can anyone please help me know how to validate if the field value entered is a phone number using php... I have used a variable $phone , datatype =varchar 10 in sql db Now i want to validate that users enter only numbers in that field..
That's it, how can I send an email in background with CakePHP, preferable using the out-of-the-box Email component?
EDIT: with in background I mean in another thread, or at least allowing the controller method to finish and send the response to the user. I want to run a function, return "OK" to the user and, after that, send an email.
If it's not possible, how could I do it using the PHP mail function? (only if it's a good approach)
Don't know if it matters, but I'm using SMTP.
Thank you in advance.
EDIT 2: I'm trying to use the CakeEmail::deliver() method, as I read from the documentation that:
Sometimes you need a quick way to fire off an email, and you don’t necessarily want do setup a bunch of configuration ahead of time. CakeEmail::deliver() is intended for that purpose.
But the mail is not actually being sent. Anyone has any hint on that method?
Answer
So "in the background" means you want to process the mail sending "out of band". This is to give the user a quick response, and to be able to process slow operations like email sending after the user has feedback (or as you say, in a separate thread).
There are a number of ways to achieve this, including:
Workers / message queues
Cron job
The simplest way is probably to use a cron job that fires off every 15 or 30 seconds.
My recommended approach is to look into workers and queues, and use something like 0mq or RabbitMQ to queue the request to send an email, and process that outside the request.
If you want to do a cron job, rather than sending the email within the request the user has initiated, you would create a new model to represent your outbound email requests, and store that data into your database. Lets call this model Message for example.
CREATE TABLE `messages` ( `id` CHAR(36) NOT NULL PRIMARY KEY,
`to` VARCHAR(255) NOT NULL, `from` VARCHAR(255) NOT NULL, `subject` VARCHAR(255) NOT NULL, `body` TEXT, `sent` TINYINT(1) NOT NULL DEFAULT 0, `created` DATETIME );
Create a Console that grabs the Message model, and does a find for "unsent" messages:
$messages = $this->Message->findAllBySent(0);
Create yourself a send() method to simplify things, and process all unsent messages:
foreach ($messages as $message) { if ($this->Message->send($message)) { // Sending was a success, update the database $this->Message->id = $message['Message']['id'];
$this->Message->saveField('sent', 1, false); } }
The implementation of the send() method on the Message model is up to you, but it would just pass the values from the passed in $message and shunt through to CakeEmail (http://api.cakephp.org/class/cake-email)
Once that is done, you can just call the console from the command line (or from your cron).
I have seen lot of java-script code,that uses call as well as apply methods to invoke the function. I am little bit confuse about the exact difference and in what which one to use in what condition.
Answer
They're not jQuery things, they're JavaScript things.
They do the same thing: They call the given function using a specific value for this within the function call. The only difference is how you specify the arguments to pass to the function. With call, you specify them as a series of discrete arguments (after the first one, which is what to use as this). With apply, you specify them as an array (again after the first arg, which is what to use as this).
I want to bind an event to a button, and execute a function whic use a 'private' var, when I click the button the function is correctly called but it can't see the var this._s (it writes 'undefined'). If I write fo.method() the string is correctly printed. here is the jsfiddle: http://jsfiddle.net/wLm1v4La/1/
Answer
you have to set the context(this) of the function manually before passing it.
Foo.prototype.setButton = function () { var tmpFunc = function(evt){ alert(this._s); } //store the function var boundFunction = tmpFunc.bind(this); //set the context manually
//pass the function now to eventlistener document.getElementById('id').addEventListener('click',boundFunction); };
Is there a simple shell command/script that supports excluding certain files/folders from being archived?
I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.
Not quite solutions:
The tar --exclude=PATTERN command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.
I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.
I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with --exclude-from=file to copy all the files to a tmp directory, and then use tar to archive that directory.
Can anybody think of a better/more efficient solution?
EDIT: Charles Ma's solution works well. The big gotcha is that the --exclude='./folder'MUST be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):
cd /folder_to_backup tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
Answer
You can have multiple exclude options for tar so
$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
etc will work. Make sure to put --excludebefore the source and destination items.
In the movie Prometheus the alien is born from the last 'human-alien' of the planet they traveled to.
But, how should it be interpreted? The alien is a mutation from the parasite inside the body of the other one? Or the alien is the real aspect of the others that is hiding inside some kind of armor?
Answer
The scene is the culmination of the movie-long reveal of the origins of the killer creatures that cause so much havoc in "Alien" and its sequels.
In "Prometheus," the creature is the result of a somewhat complicated process:
A human (Holloway) was infected by the black goo
The infected human created a new organism within a non-infected human (Shaw)
This new organism grew to be an octopus-like mutant
The octopus-like mutant created another new organism within an Engineer
The second new organism's "birth" consisted of it springing out of its host's rib cage, just like the creatures in "Alien" and its sequels -- which it also resembles physically. (Notably, the alien at the end of Prometheus looks somewhat different from the aliens in the other Alien movies. I attribute this to the fact that in Prometheus, the alien is spawned from an Engineer, while in the other movies the aliens are spawned from humans.)
One of movie's ironies is the first action on the list above was taken by an android, who was a creation of man, who in turn was a creation of the Engineers.
How much more safe is this than plain MD5? I've just started looking into password security. I'm pretty new to PHP.
$salt = 'csdnfgksdgojnmfnb';
$password = md5($salt.$_POST['password']); $result = mysql_query("SELECT id FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '$password'");
if (mysql_num_rows($result) < 1) { /* Access denied */ echo "The username or password you entered is incorrect."; } else { $_SESSION['id'] = mysql_result($result, 0, 'id'); #header("Location: ./"); echo "Hello $_SESSION[id]!"; }
I have this code which has a radio button. I want to get the value of the text box and set it as the value of the selected radio button.
HTML
onsubmit="return formValidation();"> Monthly amount of
P "text" value="">
Javascript
window.onload = function() { var promised = document.getElementsByName("amounts"); for (var i = 0; i < promised.length; i++) { promised[i].onclick = function() {
var rads = this.form[this.name]; for (var i = 0; i < rads.length; i++) { var textField = this.form[rads[i].value.toLowerCase() + "Amount"]; if (textField) textField.disabled = !rads[i].checked; } } } }
02-09 17:09:05.494 767-767/? E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.rt.droid.baseadapter01, PID: 767 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rt.droid.baseadapter01/com.rt.droid.baseadapter01.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference at com.rt.droid.baseadapter01.RT_Adapter.(MainActivity.java:71) at com.rt.droid.baseadapter01.MainActivity.onCreate(MainActivity.java:36) at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
I don't Understand how i am getting a null object when i create the new Creator object to add to the ArrayList.
Any pointers would be greatly appreciated.
Answer
You never initialize ArrayList list;. So list.add(new Creator(title[i], descs[i], icons[i])); will throw a NPE.
I have searched online for a bit with no luck in finding a way around this.
I inherited an Excel workbook where the VBA code not protected. I can view | edit the code with no problem. However, when trying to run the code I get:
Compile Error: Can't find project or library.
I then go to Tools > References in the VBE and am prompted for a VBAProject Password.
My experience tells me that there is a reference set to some other VBAProject that is password protected that is no longer relevant, or at least it's missing, but how can I bypass this password error to check on the missing project.
Answer
While the end result answer may not be that universally helpful, I thought the methodology I used to get the answer may be useful for others.
This is the code I used to compare the references in each workbook in each environment, which I decided to it when I get an error in accessing the reference name and fullpath in the workbook on my desktop:
Dim ref As Object
For Each ref In ThisWorkbook.VBProject.References Debug.Print ref.Name & " | " & ref.fullpath 'If ref.isbroken Then 'ref.Remove 'ThisWorkbook.VBProject.References.Remove ref 'End If Next
I tried using $(date) in my bash shell script, however I want the date in YYYY-MM-DD format. How do I get this?
Answer
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).
As such:
# put current date as yyyy-mm-dd in $date # -1 -> explicit current date, bash >=4.3 defaults to current time if not provided # -2 -> start time for shell printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such: printf '%(%Y-%m-%d)T\n' -1 # -> current date printed to terminal
In bash (<4.2):
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly echo $(date '+%Y-%m-%d')
Other available date formats can be viewed from the date man pages (for external non-bash specific command):
private static final int PREF_W = 600; private static final int PREF_H = 200; int b = 0; private String[][] newData = { {"", ""} }; private String[] columnName = {"S.NO", "SOLUTIONS"}; static Vector columnNames = new Vector(); static Vector data = new Vector(); static Vector columnNames56 = new Vector();
static Vector data56 = new Vector();
public static void First() {
try { DefaultTableCellRenderer cent = new DefaultTableCellRenderer(); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
for (int i = 1; i <= columns; i++) { columnNames.addElement(md.getColumnName(i)); } int columns1 = md1.getColumnCount(); for (int i = 1; i <= columns1; i++) { columnNames1.addElement(md1.getColumnName(i));
}
int columns2 = md2.getColumnCount(); for (int i = 1; i <= columns2; i++) { columnNames2.addElement(md2.getColumnName(i)); }
while (rs.next()) { Vector row = new Vector();
for (int i = 1; i <= 2; i++) { row.addElement(rs.getObject(i)); //System.out.println(row);
for (int i = 0; i < com.size(); i++) { String rr = "insert into conflictsolution values('" + com.get(i) + "')"; st1.executeUpdate(rr); } st1.close(); } catch (Exception e) { System.out.println("there was some error in establishing connection : " + e); }
try {
DefaultTableCellRenderer cent = new DefaultTableCellRenderer(); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", ""); String sql = "Select * from conflictsolution"; Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); for (int i = 1; i <= columns; i++) {
columnNames56.addElement(md.getColumnName(i)); } while (rs.next()) { Vector row = new Vector(columns); for (int i = 1; i <= columns; i++) { row.addElement(rs.getObject(i)); } data56.addElement(row); } rs.close();
stmt.close();
} catch (Exception e) { e.printStackTrace(); } } public TablePanel gregsPanel = new TablePanel("SET THE EFFECTS FOR THE RULES", data, columnNames); // line 208 private TablePanel myPanel = new TablePanel("SOLUTIONS", data56, columnNames56, b);
@Override public void mousePressed(MouseEvent e) {
fireEditingStopped(); } }); }
@Override public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column) { this.setBackground(table.getSelectionBackground()); comboBox.setSelectedItem(value);
return this; }
//Copid from DefaultCellEditor.EditorDelegate @Override public Object getCellEditorValue() { return comboBox.getSelectedItem(); }
@Override
public boolean shouldSelectCell(EventObject anEvent) { if (anEvent instanceof MouseEvent) { MouseEvent e = (MouseEvent) anEvent; return e.getID() != MouseEvent.MOUSE_DRAGGED; } return true; }
@Override public boolean stopCellEditing() {
if (comboBox.isEditable()) { comboBox.actionPerformed(new ActionEvent(this, 0, "")); } fireEditingStopped(); return true; } //Copid from AbstractCellEditor protected EventListenerList listenerList = new EventListenerList(); transient protected ChangeEvent changeEvent = null;
@Override public boolean isCellEditable(EventObject e) { return true; }
@Override public void cancelCellEditing() { fireEditingCanceled(); }
@Override public void addCellEditorListener(CellEditorListener l) { listenerList.add(CellEditorListener.class, l);
}
@Override public void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); System.out.println(listenerList);
}
public CellEditorListener[] getCellEditorListeners() { return listenerList.getListeners(CellEditorListener.class); }
protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying
// those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { // Lazily create the event: if (changeEvent == null) { changeEvent = new ChangeEvent(this); } ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent); } }
}
protected void fireEditingCanceled() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { // Lazily create the event:
if (changeEvent == null) { changeEvent = new ChangeEvent(this); } ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent); } } } }
1)when i run my derived class alone,i don't get any error. 2)when i run my base class,i get the following error,please help me
java.lang.ArrayIndexOutOfBoundsException: 1 >= 0 at java.util.Vector.elementAt(Vector.java:470) at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294) at policyreader.TablePanel.(ScrollPaneRefresh.java:279) at policyreader.ScrollPaneRefresh.(ScrollPaneRefresh.java:208) at policyreader.Hello.main(Hello.java:20)
I just finished the first season of "Game of Thrones", where one of the main themes is 'The Wall', a huge ice wall that devides the realm (Westeros) from the dangerous and winterly North.
From what I could gather this huge construct is not man-made. It was mentioned that it simply rose a few hundred years back from the ground. One of the characters says this when mentioning that they were no different than the wildlings, just happened to be on the right side of the wall. EDIT: found the quote on IMDB:
Tyrion Lannister: But... I don't believe that giants and ghouls and white walkers are lurking beyond the Wall. I believe that the only difference between us and the wildlings is that when that Wall went up, our ancestors happened to live on the right side of it.
Apparently the northern side of the Wall is extremely dangerous, hosting wildlings, dangerous animals and the mysterious "White Walkers". Therefore, the Night Watch has to constantly guard and protect the Wall from outside dangers.
What I don't understand though is: Where does the long tunnel leading through the Wall come from?
It is featured in the very first scene of the series, definitely looks man-made (it's shaped in a perfect bow form) and is covered by multiple massive gates.
Did the people from Westeros cut the tunnel into the ice? It would've certainly taken years to do this.
And if yes, what motivation could they possibly have? They probably knew before the wall came up that the north was dangerous. Why would they undertake such an effort to open a passage to this risky area?
Apart from just being not of any worth to them, it also leaves a gaping hole in the otherwise perfect defensive structure that the Wall poses.
Considering the risk they would certainly be better off to close the tunnel than to have a passage open and constantly send patrols out there. And even if they needed to go north of the Wall, they could simply let themselves from above, couldn't they?
So is the tunnel man-made and with what motivation, or is it simply a story device?
Answer
I have not yet gotten the chance to watch the series on TV but I have read the books and without any spoilers from beyond the first book here is the purpose for the tunnel in the wall.
First of all the wall is over 900 ft high that has been built by both man and some magical help. IIRC the tunnel was cut into the wall to create that path to the other side specifically so that they could chop back the forest growth. By chopping back the forest they create a lane of perfect sight to see when someone is attempting to climb the Wall and attack Westeros.
As for climbing down from the top of the wall to the northern side was not something they wished to do as it prevents a speedy return trip.
I am confuse about the function declare on head file. does this is same as java, declare function on one file,in that that file has function also has method. does in C, make the function and method in two different files? here is a example:
song.h
typedef struct { int lengthInSeconds; int yearRecorded; } Song;
Song make_song (int seconds, int year); void display_song (Song theSong);
song.c
#include #include "song.h"
Song make_song (int seconds, int year) { Song newSong;
I thought this may be a server issue but 1&1 states that it is fully supported. I've also sent emails from this server/hosting before using just a recipient, subject and body and so I'm rather unsure as to why it is not working now!
UPDATE
Sending without headers, i.e.:
mail($recipient, $subject, $message);
..does work, so it would appear to be an issue with using the headers?
Answer
There may be many reasons, for example you should study what SPF is.
The $sender_email can't be any address, for example you can't put a gmail address and send emails claiming to be that sender, without any authentication, you aren't allowed to send email on behalf on that address, because I could for example send emails putting your address in the from, pretenting to be you when I'm not (I tried to use simple words)
You should use in the From something ending in @yourdomain.com, and set up SPF to allow your server's IP to send emails for that domain. OR otherwise send emails through SMTP (with PHPmailer, for example, it's very easy)
Taking my very first babysteps with Entity Framework 5.0, I run into an exception with the very first Entity I create.
Please note that every table created after that works just fine. Also, do note that I've taken the usual steps of regenerating the database and/or restarting the Visual Studio IDE.
Using Model-First, I created a trivial table called Contacts, defined as
I then tried to run the following code (from the Page_Load of an ASP.NET page)
var contact = new DataContext.Contact { Name = aName };
System.NullReferenceException was unhandled by user code HResult=-2147467261
Message=Object reference not set to an instance of an object. Source=System.Web StackTrace: at System.Web.UI.ParseChildrenAttribute.GetHashCode() at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj) at System.Collections.Generic.HashSet`1.InternalGetHashCode(T item) at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value) at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other) at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer) at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type) at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo) at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty) at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties) at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator[T](Type clrType, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties, Func`3 validatorFactoryFunc) at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry entityEntry) at System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry entityEntry) at System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items) at System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) at System.Data.Entity.DbContext.GetValidationErrors()
at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at Contactisch._Default.AddContact(String aName) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 32 at Contactisch._Default.Page_Load(Object sender, EventArgs e) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 14 at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException:
Can someone explain the cause of this exception ? Especially, what is that call to ParseChildrenAttribute.GetHashCode doing there?
I did find someone running into the same issue here, but no satisfactory explanation was given.
Answer
Problem solved.
The cause was a bit silly. I was using the default ASP.NET Web Forms Application project from VS Web Express to perform my testing. This project contains a web form called Contact.aspx, so it already includes a partial class Contact in the same namespace as my Contact entity.
Understandably, this didn't play well with Entity Framework, leading to the rather obscure error above. Deleting the aspx page solved the problem.
try/catch doesn't work because a warning is not an exception.
I now have 2 options:
set_error_handler seems like overkill because I have to use it to filter every warning in the page (is this true?);
Adjust error reporting/display so these warnings don't get echoed to screen, then check the return value; if it's false, no records is found for hostname.
What's the best practice here?
Answer
Set and restore error handler
One possibility is to set your own error handler before the call and restore the previous error handler later with restore_error_handler().
The important thing to note when using your own error handler is that it will bypass the error_reporting setting and pass all errors (notices, warnings, etc.) to your error handler. You can set a second argument on set_error_handler() to define which error types you want to receive, or access the current setting using ... = error_reporting() inside the error handler.
Suppressing the warning
Another possibility is to suppress the call with the @ operator and check the return value of dns_get_record() afterwards. But I'd advise against this as errors/warnings are triggered to be handled, not to be suppressed.
I am trying to do something with [R] which should be extremely simple: convert values in a data.frame to numbers, as I need to test for their values and r does not recognize them as number.
When I convert a decimal number to numeric, I get the correct value:
> a <- as.numeric(1.2)
> a [1] 1.2
However, when I extract a positive value from the data.frame then use as.numeric, the number is rounded up:
I am writing a program to take input from a file and display it on the console. The problem is that the last entry is being repeated twice. The code is as follows:-
int main(void) {
string filename; int grades; cout<<"Enter the filename:"< getline(cin,filename); ifstream inFile(filename.c_str(),ios::in); if(!inFile){ cout<<"File does not exist."< exit(1); } while(!inFile.eof())
Ed Norton plays the Narrator or Jack ( due to reading a book that described someone called Jack's body parts from a 1st person perspective). Meanwhile Brad Pitt is introduced as Tyler Durden. Later on we find out that they are the same person.
So is Tyler Durden the new name he has chosen which he went and made an ID for and got various part-time jobs under or is it his original name and he somehow keeps blanking it out when he needs to tell police (things like his apartment exploded, or that other things will explode) or when he sees it on his checks from work or his work documents Id and many other things that would have his name on them?
Answer
In addition to Orion's answer, I'd add that while it's not specifically stated in the movie, I think it's implied well enough that the Narrator's name is not Tyler Durden. Tyler says at one point that the Narrator is "slowly letting himself become Tyler Durden." If his name was actually Tyler, this line wouldn't make any sense.
I suspect the movie avoids telling us his real name as a clue that he and Tyler are the same person. It was very clever indeed.
I still remember the first time I watched it and Marla is asking him his name, "What's your name? It's not on your card. Is it Radith? Corneleus? Any of the stupid names you give each night?" The bus passes in front of her, ending the scene so we don't get to hear the Narrator's answer . . . and it didn't phase me one bit. It just seemed like a neat way to end the scene.
Fight Club is definitely one of my top ten movies of all time.
How do I get the path of the directory in which a Bash script is located, inside that script?
For instance, let's say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )" SOURCE="$(readlink "$SOURCE")" [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
This last one will work with any combination of aliases, source, bash -c, symlinks, etc.
Beware: if you cd to a different directory before running this snippet, the result may be incorrect!
Also, watch out for $CDPATH gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities.
To understand how it works, try running this more verbose form:
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")" if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE="$TARGET" else DIR="$( dirname "$SOURCE" )" echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fi done
echo "SOURCE is '$SOURCE'" RDIR="$( dirname "$SOURCE" )" DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )" if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'" fi echo "DIR is '$DIR'"
And it will print something like:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.') SOURCE is './sym2/scriptdir.sh' DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2' DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
bin/ main.py user.py # where class User resides dir.py # where class Dir resides
I want to use classes from user.py and dir.py in main.py. How can I import these Python classes into main.py? Furthermore, how can I import class User if user.py is in a sub directory?
bin/
dir.py main.py usr/ user.py
Answer
Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".
Then just do...
from user import User from dir import Dir
The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.
bin/ main.py
classes/ user.py dir.py
So if the directory was named "classes", then you'd do this:
from classes.user import User from classes.dir import Dir
Same as previous, but prefix the module name with a . if not using a subdirectory:
I want to solve my AJAX cross domain problem. This is the error message I receive in Chrome:
XMLHttpRequest cannot load http://'myaddress'/TEST/user/login/testuserid . Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.
React-Router 5.1.0+ Answer (using hooks and React >16.8)
You can use the new useHistory hook on Functional Components and Programmatically navigate:
import { useHistory } from "react-router-dom"; function HomeButton() { let history = useHistory(); // use history.push('/some/path') here };
React-Router 4.0.0+ Answer
In 4.0 and above, use the history as a prop of your component.
class Example extends React.Component { // use `this.props.history.push('/some/path')` here };
NOTE: this.props.history does not exist in the case your component was not rendered by . You should use to have this.props.history in YourComponent
React-Router 3.0.0+ Answer
In 3.0 and above, use the router as a prop of your component.
class Example extends React.Component { // use `this.props.router.push('/some/path')` here };
React-Router 2.4.0+ Answer
In 2.4 and above, use a higher order component to get the router as a prop of your component.
import { withRouter } from 'react-router'; class Example extends React.Component { // use `this.props.router.push('/some/path')` here }; // Export the decorated class var DecoratedExample = withRouter(Example); // PropTypes Example.propTypes = { router: React.PropTypes.shape({ push: React.PropTypes.func.isRequired }).isRequired };
React-Router 2.0.0+ Answer
This version is backwards compatible with 1.x so there's no need to an Upgrade Guide. Just going through the examples should be good enough.
That said, if you wish to switch to the new pattern, there's a browserHistory module inside the router that you can access with
import { browserHistory } from 'react-router'
Now you have access to your browser history, so you can do things like push, replace, etc... Like:
I will not go into upgrading details. You can read about that in the Upgrade Guide
The main change about the question here is the change from Navigation mixin to History. Now it's using the browser historyAPI to change route so we will use pushState() from now on.
Here's an exemple using Mixin:
var Example = React.createClass({ mixins: [ History ], navigateToHelpPage () { this.history.pushState(null, `/help`); } })
Note that this History comes from rackt/history project. Not from React-Router itself.
If you don't want to use Mixin for some reason (maybe because of ES6 class), then you can access the history that you get from the router from this.props.history. It will be only accessible for the components rendered by your Router. So, if you want to use it in any child components it needs to be passed down as an attribute via props.
Note: if you're using Redux, there is another project called React-Router-Redux that gives you redux bindings for ReactRouter, using somewhat the same approach that React-Redux does
React-Router-Redux has a few methods available that allow for simple navigating from inside action creators. These can be particularly useful for people that have existing architecture in React Native, and they wish to utilize the same patterns in React Web with minimal boilerplate overhead.
I've been playing around with C++11 for the past few days, and I came up with something strange.
If I want to uniformly initialize an int:
int a{5};
But if I do the same thing to a std::vector:
std::vector b{2};
Does not construct a two element array, but rather an array with one element of value two. It seems like to get that effect one would need to be more explicit about it:
std::vector c{{2}}; std::vector d = {2};
But not like the declaration of b - this seems inconsistent. I have seen some other stuff to the same effect. What I'm asking - is this behavior in the final C++11 standard, or is it just in a draft that was implemented early? If so, why did the standards committee include this behavior? It seems like it defeats the whole purpose of uniform initialization, as one has to remember which classes have initializer list constructors, and to use the old () syntax instead of {} with just those classes. Or one forgoes uniform initialization altogether.
This seems like a big "gotcha". But there might be advantages to it that I am not aware of.
Edit: this code:
#include #include
int main() { std::vector a{2}; for (auto x: a) { std::cout << x << std::endl; } return 0; }
outputs "2" on gcc 4.6.2
Answer
Yes, this behaviour is intended, according to §13.3.1.7 Initialization by list-initialization
When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:
— Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of
the initializer list as a single argument.
— If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.
As to "the whole purpose of uniform intialization"... "Uniform initialization" is a marketing term, and not a very good description. The standard has all the usual forms of initialization plus list-initialization, but no "uniform initialization". List initialization is not meant to be the ultimate form of initialization, it's just another tool in the utility belt.
class Averager { public static double unlimited() { int count = 0; double sum = 0; Scanner scan = new Scanner(System.in); while(scan.hasNext()) { double d = scan.nextDouble(); sum += d; count++; } double ave = sum/count; return ave; }
public static void main(String[] args) { System.out.println(unlimited()+"\n"); } }
There is no error when I use integers but if I use numbers with point in it a error appears.
$ javac Averager.java; java Averager 0.5 Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at Averager.unlimited(Averager.java:12) at Averager.main(Averager.java:21)
To my best understanding 0.5 should be covered by double. If not please can someone correct me.
Answer
It might be locale dependent. Decimal numbers are e.g written as 0,5 in Sweden.
Change your code so that it says e.g.:
Scanner scan = new Scanner(System.in); scan.useLocale(Locale.US);
And as far as the products stuff, I remember writing it and going, “Oh man, there’s no way we’re going to clear all of this stuff.” And I had a meeting with the lawyers, who were actually really cool and really liked the script. [laughs] And in the Beavis & Butt-Head movie I couldn’t even have a bottle that was shaped like a Jack Daniel’s bottle. I couldn’t have, there was more, it was just ridiculous on that [movie].
But on Idiocracy, when we were talking about Starbucks, the lawyers said, “Well, it would help if you didn’t pick on just one company and
if you did more than one.” So, [laughs] I was like okay, and that’s why there’s the whole red light district with Starbucks and there’s an H&R Block with “Tax Return and Relief,” and all of that. But the other stuff, Carl Jr’s, that was all in the script, and I couldn’t believe it all cleared.
Second, it wasn't high profile enough to cause the companies any big issues (from the same interview):
At one point, [Fox] told me, “Hey, it’s not testing well, we’re not going to spend a lot of money promoting it.”
I have been working with android and openCV for a month and I was able to successfully implement template Matching. Now, the next task is to detect all the rectangles in the image and get the coordinates (I actually want the color of every rectangle) for research purposes. Kindly help. I tried using Hough transform with canny edge detection but unfortunately it doesn't detect the small rectangles which is the primary concern now.
Thank you!![![Have to detect all the rectangles, small and big ones
Answer
So I'm really proud to post an answer to my own question. Hope this helps someone in future. There are obviously a lot of ways to do this but the most accurate way was to use template matching on the main image to find the coordinates of the biggest rectangle and since all the other rectangles are equidistant to the corner points, center of every rectangle can be found which gives the desired colors.
The thin strip in the middle was also recognized by template matching and then a gradient operator represented the various rectangles, every peak in the gradient represents the rectangles.
Kindly comment for code. For research purposes I cannot post to anonymous.
This is the error I am getting. "Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in on line 188" What I am trying to do is connect to the database and insert data into the table, but i can't figure out this error.
My teacher said we shouldn't use EOF to read in text file or binary file information instead we should use (afile>>x). He didn't explain why, can someone explain to me. Can someone also explain what are the differences in this two different method of reading
//Assuming declaration //ifstream foobar
( ! foobar.eof() ) { foobar>>x; // This is discouraged by my teacher
}
while (foobar>>x) {
//This is encouraged by my teacher
}
Answer
Because the file is not at the end before you try to read from it.
operator>> returns a reference to the stream in the state it is after the read has been attempted and either succeeded or failed, and the stream evaluates to true if it succeeded or false if it failed. Testing for eof() first means that the file can have no useful data in it but not be at EOF yet, then when you read from it, it's at EOF and the read fails.
Another important detail is that operator>> for streams skips all leading whitespace, not trailing whitespace. This is why a file can not be at EOF before the read and be at EOF after a read.
Additionally, the former works when the next data in the file is data that cannot be read into an integer (for example, the next data is x), not just when it's at EOF, which is very important.
Example:
Consider the code:
int x, y;
f >> x;
if (!f.eof()) f >> y;
Assuming f is a file that contains the data 123␣ (the ␣ means space), the first read will succeed, but afterwards the file has no more integers in it and it is not at EOF. The second read will fail and the file will be at EOF, but you don't know because you tested for EOF before you tried reading. Then your code goes on to cause undefined behaviour because y is uninitialised.