pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
40,682,196
0
<p>To actually run your flask app in debug mode, you run this command:</p> <p><code>python /home/vagrant/PythonVision/app.py</code></p> <p>Then you can go on your browser: <a href="http://ip:5000/">http://ip:5000/</a>.</p> <p>Since I know you're running this on vagrant, the <code>ip</code> might be defined by your configs, but that's beyond the scope of this question.</p>
13,766,944
0
<p>You can also just enumerate the Items property of your DataGrid. Unlike the ItemsSource property, the Items property appears to reflect exactly what's on the screen including sorting and filtering. For example:</p> <pre><code>foreach (var item in dataGrid.Items) { // do something } </code></pre>
3,875,986
0
When does Google I/O registration open up usually? <p>I have been polishing my Java lately, and I am really starting to dig into the Android SDK. I am looking forward to attending Google's I/O conference next year, and I am nervous that I am going to miss the sign up period. Historically, when has the conference registration opened up? For those of you who went last year, do you remember when registration opened up?</p>
22,491,664
0
Adding parenthesis to a number that is binding <p>My <code>label</code> is bound to a number and for example shows <strong>72</strong> so that "72" is coming directly from binding and I can show it in label fine But I want to wrap it around parenthesis so would show as <strong>(72)</strong> I know I can use <code>StringFormat</code> but I tried and couldn't quite get the syntax right. Would you help me show how it is?</p>
27,202,080
0
Task is not waiting for completion <p>I'm trying to get my head around await and async so I wrote this little test app, but what I expected does not happen.</p> <p>Instead of waiting for the task to complete, the program continues to execute.</p> <pre><code>class Program { static void Main(string[] args) { var task = new Task(Run); task.Start(); task.Wait(); Console.WriteLine("Main finished"); Console.ReadLine(); } public async static void Run() { var task = Task.Factory.StartNew(() =&gt; { Console.WriteLine("Starting"); Thread.Sleep(1000); Console.WriteLine("End"); }); await task; Console.WriteLine("Run finished"); } } </code></pre> <p>Output</p> <pre><code>Main finished Starting End Run finished </code></pre> <p>If I swap the 'await task' for 'task.Await()' it then runs as I would have expected producing</p> <pre><code>Starting End Run finished Main finished </code></pre>
22,334,421
0
<p>I resolved the problem by using PHP EXCEL Reader because i use php 4 wich wont work with this library or with .xlsx files. now it is done , and my sheet was read , still , only one sheet is read. Thank you All !</p>
21,439,775
0
<p>You tried to multiply a string by another string.</p> <p>Try this: </p> <pre><code>output = float(user_input[0]) * float(USD[0]) </code></pre> <p>user_input[3] is 'GBP' a string, I supposed you want to say 0.60</p>
25,111,308
0
<p>You forgot to include the schema in your sql query. Write your query like this:</p> <pre><code>SELECT * FROM Tester.User </code></pre> <p>Try also to look at your server log in Netbeans, in the output window. Usually you can find their if you're doing wrong something else.</p>
31,854,252
0
<p>There are a number of reasons why decomposing a table (splitting up by columns) might be advisable. One of the first reasons a beginner should learn is data normalization. Data normalization is not directly concerned with performance, although a normalized database will sometimes outperform a poorly built one, especially under load.</p> <p>The first three steps in normalization result in 1st, 2nd, and 3rd normal forms. These forms have to do with the relationship that non-key values have to the key. A simple summary is that a table in 3rd normal form is one where all the non-key values are determined by the key, the whole key, and nothing but the key. </p> <p>There is a whole body of literature out there that will teach you how to normalize, what the benefits of normalization are, and what the drawbacks sometimes are. Once you become proficient in normalization, you may wish to learn when to depart from the normalization rules, and follow a design pattern like Star Schema, which results in a well structured, but not normalized design.</p> <p>Some people treat normalization like a religion, but that's overselling the idea. It's definitely a good thing to learn, but it's only a set of guidelines that can often (but not always) lead you in the direction of a satisfactory design.</p> <p>A normalized database tends to outperform a non normalized one at update time, but a denormalized database can be built that is extraordinarily speedy for certain kinds of retrieval.</p> <p>And, of course, all this depends on how many databases you are going to build, and their size and scope,</p>
25,621,695
0
<p>Register your route without <code>{q}</code> and with a name.</p> <p>Using closure:</p> <pre><code>Route::get('search', ['as' =&gt; 'search', function(){ $q = Input::get('q'); return $q; }]); </code></pre> <p>Using controller:</p> <pre><code>Route::get('search', ['as' =&gt; 'search', 'uses' =&gt; 'SearchController@yourMethod']); </code></pre> <p>Then call the route by its name:</p> <pre><code>route('search', ['q' =&gt; 'search query']); // /search?q=search%20query </code></pre> <p>or</p> <pre><code>URL::route('search', ['q' =&gt; 'search query']); </code></pre>
35,977,414
0
Pointer to a class's private data member <p>Consider a class <code>card</code> which has two public members, <code>int suit</code> and <code>int value</code>, and a template function that sorts an array of cards by the member I pass through a pointer-to-member, like this:</p> <pre><code>//class card with public members class card{ public: int suit; int value; }; //sorting algorithm template&lt;typename m_pointer, typename iterator, typename Functype&gt; void sort_array(m_pointer member, iterator begin, iterator end, Functype pred){ iterator iter1=begin; while(iter1!=end &amp;&amp; ++iter1!=end){ iterator iter2=iter1; while(iter2!=begin){ iterator iter3=iter2; --iter3; //here i use the pointer-to-member to sort the cards if(pred((*iter3).*member, (*iter2).*member)){ std::swap(*iter3, *iter2); } else break; --iter2; } } } int main(){ card array[3]={{3,1},{2,3},{4,5}}; //let's sort the cards by the suit value in a decreasing order sort(&amp;card::suit, array, array+3, [](int a, int b){return a&lt;b;}); } </code></pre> <p>If the card member <code>suit</code> is public there's obviously no problem, but what actually i didn't expected is that the same code doesn't give any trouble even if i declare <code>suit</code> or <code>value</code> as private members.</p> <pre><code>class card{ int suit; int value; public://adding this for clarity, read forward int* pointer_to_suit(); }; </code></pre> <p>From what I know, I shouldn't be able to access private members from outside the class, and the only way to pass a pointer-to-member to a private member is through a member function which returns the member address, like this for example:</p> <pre><code>//function member of the class card int* card::pointer_to_suit(){ return &amp;suit; } </code></pre> <p>So, why is it possible that the code above (the one with the template) works?</p> <p><strong>EDIT:</strong> Ok, the code above doesn't compile on it's own, but for some reason the following code compile fine to me. I'll post the whole code since I've no idea where the trick for it to work might be, sorry for the mess:</p> <pre><code>template&lt;typename m_pointer, typename iterator, typename Functype&gt; void sort_array(m_pointer member, iterator begin, iterator end, Functype pred){ iterator iter1=begin; while(iter1!=end &amp;&amp; ++iter1!=end){ iterator iter2=iter1; while(iter2!=begin){ iterator iter3=iter2; --iter3; if(pred((*iter3).*puntatore, (*iter2).*puntatore)){ std::swap(*iter3, *iter2); } else break; --iter2; } } } class card{ int suit; int value; public: card(): suit(0), value(0) {} card(int a, int b): suit(a), value(b){} bool operator==(card a){return (suit==a.get_s() &amp;&amp; value==a.get_v());} bool operator!= (card a){return !(*this==a);} void set_values(int a, int b){suit=a; value=b;} int get_v(){return value;} void set_v(int v){value=v;} int get_s(){return suit;} void set_s(int s){suit=s;} double points_card(); }; template&lt;typename iterator&gt; void ordina(iterator begin, iterator end, short (&amp;suit)[4]){ for(int i=0; i&lt;4; i++) suit[i]=0; iterator it1=begin; while(it1!=end){ if((*it1).get_s()==1) suit[0]+=1; else if((*it1).get_s()==2) suit[1]+=1; else if((*it1).get_s()==3) suit[2]+=1; else if((*it1).get_s()==4) suit[3]+=1; ++it1; } sort_array(&amp;carte::suit, begin, end, [](char a, char b){ if(b==0) return false; else if(a==0) return true; return (a&gt;b); }); sort_array(&amp;carte::value, begin, begin+suit[0], [](int a, int b){return (a&lt;b);}); sort_array(&amp;carte::value, begin+suit[0], begin+suit[0]+suit[1], [](int a, int b){return (a&lt;b);}); sort_array(&amp;carte::value, begin+suit[0]+suit[1], begin+suit[0]+suit[1]+suit[2], [](int a, int b){return (a&lt;b);}); sort_array(&amp;carte::value, begin+suit[0]+suit[1]+suit[2], begin+suit[0]+suit[1]+suit[2]+suit[3],[](int a, int b){return (a&lt;b);}); } int main(){ card array[5]={{2,3},{1,2},{3,4},{4,5},{3,2}}; short suits[4]={1,1,2,1}; ordina(array, array+5, suits); return 0; } </code></pre> <p><strong>EDIT 2:</strong> Yes, it runs <a href="http://coliru.stacked-crooked.com/a/d1795f0845770fcb" rel="nofollow">http://coliru.stacked-crooked.com/a/d1795f0845770fcb</a> . Please note that the code here is not translated and there are some lines i didn't add for brevity.</p> <p><strong>EDIT 3:</strong> As mentioned in Barry answer <a href="http://stackoverflow.com/a/35978073/5922196">http://stackoverflow.com/a/35978073/5922196</a>, this is a <code>gcc</code> compiler bug. I used <code>g++ 4.9.2</code> and this bug is still unresolved</p>
24,548,514
0
How to Calculate the difference between two dates <p>I have this code:</p> <pre><code>Private Sub CalculateBUT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateBUT.Click If SelectTheDateComboBox.Text = "Calculate the difference between two dates" Then FromYearTextBox.Text = FromDateTimePicker.Value.Year FromMonthTextBox.Text = FromDateTimePicker.Value.Month FromDayTextBox.Text = FromDateTimePicker.Value.Day ToYearTextBox.Text = ToDateTimePicker.Value.Year ToMonthTextBox.Text = ToDateTimePicker.Value.Month ToDayTextBox.Text = ToDateTimePicker.Value.Day Dim DaysMyString, MonthsMyString, YearsMyString As String Dim DaysDifferance, MonthsDifferance, YearsDifferance As Long DaysMyString = FromDateTimePicker.Value.Day MonthsMyString = FromDateTimePicker.Value.Month YearsMyString = FromDateTimePicker.Value.Year DaysDifferance = DateDiff(DateInterval.Day, ToDateTimePicker.Value.Day, CDate(DaysMyString)) MonthsDifferance = DateDiff(DateInterval.Month, ToDateTimePicker.Value.Month, CDate(MonthsMyString)) YearsDifferance = DateDiff(DateInterval.Year, ToDateTimePicker.Value.Year, CDate(YearsMyString)) DifferenceTextBox2.Text = DaysDifferance &amp; "Days, " &amp; MonthsDifferance &amp; "Months, " &amp; YearsDifferance &amp; "Years" End Sub </code></pre> <p>and my problem in the picture below : <img src="https://i.stack.imgur.com/fLzgA.png" alt="enter image description here"></p> <p>so, i need some help please.</p>
15,452,265
0
Unicorn doesn't run in production mode <p>I am running stack nginx+unicorn+rails 3.2</p> <p>When I am running </p> <pre><code>bundle exec unicorn_rails -c config/unicorn.rb -E development </code></pre> <p>it is ok, and site running well</p> <p>when I am trying start unicorn site in production mode</p> <pre><code>bundle exec unicorn_rails -c config/unicorn.rb -E production </code></pre> <p>I have "We're sorry, but something went wrong." error:</p> <p><img src="https://i.stack.imgur.com/0IESc.png" alt="enter image description here"></p>
10,496,754
0
Opentaps ERP- ClassNotFoundException error during running <p>Hi I am new to openTaps ERP development just a day before I started it.I have install a previously done project in my eclips.When I run it it gives me following error.I dont understand that error.</p> <p>what should be done?</p> <p>(I am using Postgresql database in it)</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory at org.hibernate.cfg.Configuration.&lt;clinit&gt;(Configuration.java:152) at org.opentaps.foundation.infrastructure.Infrastructure.getSessionFactory(Infrastructure.java:120) at org.opentaps.common.container.HibernateContainer.start(HibernateContainer.java:109) at org.ofbiz.base.container.ContainerLoader.start(ContainerLoader.java:102) at org.ofbiz.base.start.Start.startStartLoaders(Start.java:264) at org.ofbiz.base.start.Start.startServer(Start.java:313) at org.ofbiz.base.start.Start.start(Start.java:317) at org.ofbiz.base.start.Start.main(Start.java:400) Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 8 more </code></pre> <p>Anyone knows how to resolve it??</p>
23,975,558
0
<p>you need to remove this semicolon</p> <pre><code> Name = p.Attribute("Name").Value, Type = (EnvironmentType)Enum.Parse(typeof (EnvironmentType), p.Attribute("Type").Value, true), DataCenters = p.Elements("DataCenter").Select( dc =&gt; new DataCenter { Name = dc.Attribute("Name").Value, DeployEnvironmentName = dc.Attribute ("DeployEnvironmentName").Value }) }); ^^^ }); </code></pre> <p>You shouldn't use semicolons in <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="nofollow">object initializers</a>, you should separate the properties with comma.</p>
33,426,174
0
<p>I also did something similar based on this code:<br></p> <p><a href="https://github.com/royshil/FoodcamClassifier/blob/master/training_common.cpp" rel="nofollow">https://github.com/royshil/FoodcamClassifier/blob/master/training_common.cpp</a></p> <p>But the above part is after the clustering has finished. What you have to do is to train using your ML(I used SVM) and your cluster centers, the visual bag of words that you have. More, you need to find all the "closest" points to your clustered points and train them using histograms. Next, you will have a histogram of frequencies(bag of key points) that you need to train.</p> <pre><code>Ptr&lt;ifstream&gt; ifs(new ifstream("training.txt")); int total_samples_in_file = 0; vector&lt;string&gt; classes_names; vector&lt;string&gt; lines; //read from the file - ifs and put into a vector for(int i=0;i&lt;lines.size();i++) { vector&lt;KeyPoint&gt; keypoints; Mat response_hist; Mat img; string filepath; string line(lines[i]); istringstream iss(line); iss &gt;&gt; filepath; string class_to_train; iss &gt;&gt; class_to_train; class_ml = "class_" + class_to_train; if(class_ml.size() == 0) continue; img = imread(filepath); detector-&gt;detect(img,keypoints); bowide.compute(img, keypoints, response_hist); cout &lt;&lt; "."; cout.flush(); //here create the logic for the class to train(class_0, e.g) and the data you need to train. } </code></pre> <p>More you can find at this git project:<br> <a href="https://github.com/royshil/FoodcamClassifier" rel="nofollow">https://github.com/royshil/FoodcamClassifier</a> <br> Documentation here:<br> <a href="http://www.morethantechnical.com/2011/08/25/a-simple-object-classifier-with-bag-of-words-using-opencv-2-3-w-code/" rel="nofollow">http://www.morethantechnical.com/2011/08/25/a-simple-object-classifier-with-bag-of-words-using-opencv-2-3-w-code/</a></p>
2,637,940
0
<p>Trigger are no differnt from other code, there are good triggers and porly written ones. The poorly written ones cause problems in both performance and data quality. Because so few people writing the triggers have understood how to write them correctly, triggers have gotten a bad reputation since so many of them are bad. </p> <p>Developers also tend to forget about triggers and then get frustrated when they can't figure out why something they think is strange (but which is really the designed action) is happening. It is not the trigger's fault when the developers aren't competent to troubleshoot data issues.</p> <p>For updated date, it is short-sighted at best not to populate with a trigger. Data is changed from more than the application, if you need the updated date, the trigger is the appropriate place for it. Unfortunately in today's world, the great God of "easy to maintain" is crippling many of our systems from both a performance and a data quality perspective.</p>
40,887,917
0
How to define a field in elasticsearch which is aggrigatable on kibana (ELK 5.0) <p>I've defined a field as an ip in the template and checked it is defined as ip in the relevant indexes.<br> But when I open the fields in kibana it appears as non searchable and non aggregatable (so I can't use it in the visualizer).<br> I've reloaded the fields several times but it didn't change.<br> Any help will be appreciated.<br> In the index mapping: GET myindex/_mapping </p> <pre><code>"properties": { "src": { "type": "ip" } } </code></pre> <p>In kibana I see the logs and I can search based on the src field.<br> The problem is just in the fields view and visualizer.</p>
10,817,152
0
<p>To make sure an empty string is valid, add a <code>[Required]</code> attribute with <code>AllowEmptyStrings</code> set to <code>true</code>. This prevents <code>null</code> from being assigned, but allows empty strings.</p> <p>As for the regular expression, Romil's expression should work fine.</p> <pre><code>[DisplayName("Account Number:")] [Required(AllowEmptyStrings = true)] [RegularExpression(@"^1\d{7}$", ErrorMessage = "An eight digit long number starting with 1 required")] public string accountNo { get; set; } </code></pre> <p><strong>EDIT</strong> If you also want to <em>prevent</em> empty strings from being validated, simply leave out the <code>AllowEmptyStrings</code> settings (as it defaults to <code>false</code>).</p> <pre><code>[DisplayName("Account Number:")] [Required] [RegularExpression(@"^1\d{7}$", ErrorMessage = "An eight digit long number starting with 1 required")] public string accountNo { get; set; } </code></pre>
36,023,461
0
<p>How to save R objects to disk:</p> <p><a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/save.html" rel="nofollow">Save R Objects</a></p> <p>I took your example code and produced working, human readable, R-loadable output as follows:</p> <pre><code>str_url &lt;- "https://www.holidayhouses.co.nz/Browse/List.aspx?page=1" read_html_test1 &lt;- xml2::read_html(str_url) str_html &lt;- as.character(read_html_test1) x &lt;- xml2::read_html(str_html) save(x, file="c:\\temp\\text.txt",compress=FALSE,ascii=TRUE) </code></pre>
37,339,590
0
<p>You're modeling <a href="http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-many-bidirectional" rel="nofollow">bidirectional <code>@OneToMany</code></a> and as shown in the example in the documentation you're responsible for setting the <em>parent</em> value on the <em>child</em> entity:</p> <pre><code>val order = orderRepository.save(Order(...).apply{ ... route = GeoHelpers.placesListToEntities(this, data.places), ... }) fun placesListToEntities(order:Order, points: List&lt;PlaceDto&gt;) = points.map { Route( order = order, location = Helpers.geometry(it.location.latitude, it.location.longitude), title = it.title ) } </code></pre> <p>PS. Since <code>Route</code> is an <a href="http://stackoverflow.com/questions/1695930/value-object-or-entity-object-in-my-hibernate-mapping">entity</a> you could change your model a bit to enforce the constraints on the langauge level i.e:</p> <pre><code>class Route internal constructor() { lateinit var order: Order constructor(order: Order) : this() { this.order = order } } </code></pre> <p>See <a href="http://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell">this question</a> for more details.</p>
10,279,293
0
<p>How about UNION which you write as 2 separate SELECT statements</p> <p>For example: <code> SELECT * FROM User U JOIN Employee E ON E.User_Id = U.User_Id UNION SELECT * FROM User U JOIN student S ON S.User_Id = U.User_Id </code> I couldn't see why you needed the CASE statement it looked superfluous. If you wanted all Users and to show nulls then use LEFT OUTER JOIN.</p>
1,959,965
0
<p>We know what is a "site" and "application", so all we got left is <a href="http://en.wikipedia.org/wiki/World_Wide_Web" rel="nofollow noreferrer">The Web</a></p> <p>Now, a web application may be a part of a whole website. A website is comprehended of web applications. Though usually you'll see that a website has only one web application.</p> <p>For instance, you have an iPhone <em>device</em> (compared to a website) which may include different applications: playing music, videos, web browser etc.</p>
25,043,092
0
Hadoop Fail to Connect to ResourceManager <p>I am just testing out hadoop by running a wordcount example, but this error came up:</p> <pre><code>14/07/30 12:03:02 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 14/07/30 12:03:03 INFO client.RMProxy: Connecting to ResourceManager at /127.0.0.1:8032 14/07/30 12:03:04 INFO ipc.Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 0 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1 SECONDS) 14/07/30 12:03:05 INFO ipc.Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 1 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1 SECONDS) </code></pre> <p>Some people on the internet have suggested it's because of the yarn-site.xml file. Mine is:</p> <pre><code> &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services&lt;/name&gt; &lt;value&gt;mapreduce_shuffle&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services.mapreduce.shuffle.class&lt;/name&gt; &lt;value&gt;org.apache.hadoop.mapred.ShuffleHandler&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.minimum-allocation-mb&lt;/name&gt; &lt;value&gt;128&lt;/value&gt; &lt;description&gt;Minimum limit of memory to allocate to each container request at the Resource Manager.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.maximum-allocation-mb&lt;/name&gt; &lt;value&gt;1024&lt;/value&gt; &lt;description&gt;Maximum limit of memory to allocate to each container request at the Resource Manager.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.minimum-allocation-vcores&lt;/name&gt; &lt;value&gt;1&lt;/value&gt; &lt;description&gt;The minimum allocation for every container request at the RM, in terms of virtual CPU cores. Requests lower than this won't take effect, and the specified value will get allocated the minimum.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.maximum-allocation-vcores&lt;/name&gt; &lt;value&gt;2&lt;/value&gt; &lt;description&gt;The maximum allocation for every container request at the RM, in terms of virtual CPU cores. Requests higher than this won't take effect, and will get capped to this value.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.resource.memory-mb&lt;/name&gt; &lt;value&gt;2048&lt;/value&gt; &lt;description&gt;Physical memory, in MB, to be made available to running containers&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.resource.cpu-vcores&lt;/name&gt; &lt;value&gt;2&lt;/value&gt; &lt;description&gt;Number of CPU cores that can be allocated for containers.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services&lt;/name&gt; &lt;value&gt;mapreduce_shuffle&lt;/value&gt; &lt;/property&gt; </code></pre> <p>I ran programs last week and it was working fine, so I really can't figure out what is going on. Help is appreciated.</p>
9,877,155
0
Scala/Akka Socket Server IterateeRef syntax <p>Can somebody please explain to me the meaning of this line of code?</p> <pre><code>val state = IO.IterateeRef.Map.async[IO.Handle]()(context.dispatcher) </code></pre> <p>(from <a href="http://doc.akka.io/docs/akka/2.0/scala/io.html" rel="nofollow">http://doc.akka.io/docs/akka/2.0/scala/io.html</a>)</p> <p>I guess this is a partial application of the async function, which is a curried function? But I thought that async was defined in IO.IterateeRef, not IO.IterateeRef.Map.</p>
7,394,560
0
Why don't inflated views respond to click listeners? <p>I'm trying to set a click listener for a button in my layout. The click listener is only triggered when I call findViewById() directly, and not when I take the view from the inflated layout:</p> <pre><code>public class MyActivity extends Activity implements View.OnClickListener { private static final String TAG = "MyActivity"; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.test ); Button button = (Button)findViewById( R.id.mybutton ); button.setOnClickListener( this ); LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE ); ViewGroup rootLayout = (ViewGroup)inflater.inflate( R.layout.test, (ViewGroup)findViewById( R.id.myroot ), false ); rootLayout.getChildAt( 0 ).setOnClickListener( new View.OnClickListener() { @Override public void onClick( View v ) { Log.d( TAG, "Click from inflated view" ); } } ); } @Override public void onClick( View v ) { Log.d( TAG, "Click" ); } } </code></pre> <p>Here is my layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myroot" android:orientation="vertical" android:layout_width="fill_parent" android:background="#ffffff" android:layout_height="fill_parent"&gt; &lt;Button android:text="Button" android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; </code></pre> <p>Why is this? I only get the click event from the first method and not from the inflated view.</p>
25,130,700
0
<p>Add <code>&lt;base href="/demo/"&gt;</code> to your head or /demo/ to your links. The problem is, that you haven't told the browser to look in your subfolder.</p> <p>You can easily validate your links: just click on them, analyse the browser's addressbar and correct what's missing or extra in the address shown there.</p>
30,372,669
0
Add multiple images on a single page <p>How can I add multiple images on a page?</p> <p>I want to have pages with 3-4 paragraphs and under the paragraphs I want to have multiple images like a small photo gallery, I found a extension for the images in bolt lib but it is more photographic oriented and I wander if it is possible to do it simpler then using the plugin... the curiosity is if boltcms can do this with default build.</p>
30,459,865
0
<p>I finally found the answer to my issue : it is NOT possible, but it might be possible to do it one day : see documentation about that : <a href="http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication" rel="nofollow">http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication</a></p> <p>I went through this problem with this solution :</p> <pre><code>// default publication is production which will be published without env name publishNonDefault true defaultPublishConfig "productionRelease" if (android.productFlavors.size() &gt; 0) { android.libraryVariants.all { variant -&gt; // Publish a main artifact, otherwise the maven pom is not generated if (android.publishNonDefault &amp;&amp; variant.name == android.defaultPublishConfig) { def bundleTask = tasks["bundle${name.capitalize()}"] artifacts { archives(bundleTask.archivePath) { classifier null builtBy bundleTask } } } } } </code></pre> <p>I am not satisfied with it but it will do the job for now ...</p>
40,264,982
0
Indexing books with Elasticsearch: which pages contain hits? <p>I'm indexing books with Elasticsearch to search them with FTS. One of the requirements is that I have to display numbers of pages that contain hits.</p> <p>I initially planned to include page separators in indexed string, then get highlights when I search and count page separators before highlighted words. On a second thought, I'm concerned about performance issues. Some books may be up to 500 KB in size. Counting words in strings that long sounds like a <em>bad</em> idea. It would be much better to compare offsets of matched words with offsets of page separators. As I understand, <code>with_positions_offsets</code> causes ES to store these offsets, so ideally I'd like it to do the job for me.</p> <p><strong>Can this be done in ES? What are alternative solutions to finding on which page of a book a hit is?</strong></p>
38,778,703
0
<p>You will need to put the value into something so as you can compare it in the if statement. If I understand what you want then give this a try. I am also assuming you will get one result in the SQL statement.</p> <pre class="lang-vb prettyprint-override"><code> Set conn = New ADODB.Connection Set rs = New ADODB.Recordset conn.Open sConnString Set rs.ActiveConnection = conn strSQL = "SELECT [Contract Status] FROM [Investment Data] WHERE [Customer Number] =(" &amp; "SELECT [Customer Number] FROM [Excel 8.0;HDR=YES;DATABASE=" &amp; dbWb &amp; "]." &amp; dsh &amp; ")" rs.Open strSQL If Not rs.EOF Then xx = rs.GetRows Else 'do you code for not getting result rs.Close If xx(0, 0) = "Current" Then expiryPrompt = MsgBox("A previous entry from the same contract is currently active, would you like to expire current active contract?", vbYesNo, "Confirmation") Call Expiry Exit Sub Else MsgBox ("Entry has been entered into the database.") cN.Execute ssql Exit Sub End If </code></pre> <p>I also have not amended your code inside the if statement to follow my way I accessing the database.</p> <p>To answer your question in the coments. The result will be transposed into the variable. so accessing more than one row or column , you will need to do something like this.</p> <p>For getting the rows,</p> <pre class="lang-vb prettyprint-override"><code> For i = 0 To 9 Cells(i + 1, 1) = x(0, i) Next i </code></pre> <p>For getting the columns,</p> <pre class="lang-vb prettyprint-override"><code> For i = 0 To 9 Cells(1, i + 1) = x(i, 0) Next i </code></pre>
4,307,446
0
Jquery sliding gets more delayed for each click <p>If you login here <a href="http://freeri.freehostia.com/utanme/image.php" rel="nofollow">http://freeri.freehostia.com/utanme/image.php</a> Username/password:Demo123 and press any image and when it slides click the main image, do that a couple of times and suddently you'll notice that the sliding takes longer and longer for each time.</p> <p>the code im using</p> <pre><code>$(function(){ $('.slide:last-child img').live('click', function() { $('.slide:first-child').animate({ marginLeft: '0' },500); return false; }); $('.slide .img').click(function(){ var img = $(this).find('a').attr('href'); var title = $(this).find('h2').text(); var desc = $(this).find('p').text(); $('.slide:last-child img').attr('src',img); $('.slide:last-child h2').text(title); $('.slide:last-child #cont').text(desc); $('body').prepend('&lt;div id="cover"&gt;&lt;img src="./images/loader.gif"/&gt;&lt;/div&gt;'); $('.slide:last-child img').load(function(){ $('#cover').detach(); $('.slide:first-child').animate({ marginLeft: '-900px' },500); }); return false; }); }); </code></pre> <p>what am i missing here? any aid would be greatly appreciated</p>
11,495,856
0
Actionscript 3: Healthbar and Button <p>So basically I am making a game in which a button is clicked to decrease the amount of health in a healthbar. I have a button on the stage named fortyfivedown_btn, and a healthbar, which is a 101 frame (includes zero) movieclip. The health bar has an instance name of lifebar. On the stage, the button coding is:</p> <pre><code>fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick); function fortyfivedownClick(event:MouseEvent):void{ lifebar.health = lifebar.health-45; } </code></pre> <p>Inside the healthbar movieclip, I have a layer of coding that is:</p> <pre><code>var health:int = 100; gotoAndStop(health + 1); if(health &lt; 0) health = 0; else if(health &gt; 100) health = 100; gotoAndStop(health + 1); </code></pre> <p>So, there is my coding. The thing is, when the button is clicked, the healthbar does not go down. I traced the health variable in the button:</p> <pre><code> fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick); function fortyfivedownClick(event:MouseEvent):void{ lifebar.health = lifebar.health-45; } { trace(lifebar.health); } </code></pre> <p>I saw that the output is 0. For some reason the button believes the health is 0, when I declared it was 100 inside the healthbar movieclip? Any help is appreciated.</p> <p>(Edit)</p> <p>Alright, in answer to the trace question, if I don't do it like that, there is no output. I should say I'm a beginner at this all, and am learning as I go, so please bear with me. Here is my fla file:</p> <p><a href="https://skydrive.live.com/embed?cid=9AB08B59DCCDF9C6&amp;resid=9AB08B59DCCDF9C6%21107&amp;authkey=AGqFHhlHnvOXvuc" rel="nofollow">https://skydrive.live.com/embed?cid=9AB08B59DCCDF9C6&amp;resid=9AB08B59DCCDF9C6%21107&amp;authkey=AGqFHhlHnvOXvuc</a></p>
35,239,284
0
using compass mixins in scss files compiled by gulp in Laravel Elixir <p>I want to use Compass mixins and Capabilities in scss files that should compiled with <strong>Gulp</strong> tasks in <strong>laravel Elixir</strong>.</p> <p>For example , I have two scss files named <code>my-styles.css</code> and <code>app.scss</code> in <code>resource/assets/sass</code> directory :</p> <p>This is <code>my-styles.scss</code> file :</p> <pre><code>@import "compass/css3"; body{ opacity: 1.0; animation: test; color: red; text-align: center; a:link{ background-color: red; text-decoration: none ; &amp;.span{ color: red; @include border-radius(5px); } } } </code></pre> <p>And this is <code>app.scss</code> file Content :</p> <pre><code>a{ transform: scale(1.1); transform: rotate(30deg) scale(10); } </code></pre> <p>And to compile this scss files and combine them to a file name <code>all.css</code> in <code>public/css</code> directory , I write this :</p> <pre><code>var elixir = require('laravel-elixir'); var gulp = require('gulp'); var compass = require('gulp-compass'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp .src(['my-styles.scss', 'app.scss']) .pipe(sass({compass: true, sourcemap: true, style: 'compressed'})) .pipe(gulp.dest('public/css/all.css')); }); elixir.config.sourcemaps = false; elixir(function (mix) { mix.task('compile'); }); </code></pre> <p>after running <code>gulp</code> command in console this messages are shown:</p> <pre><code>D:\wamp\www\newProject&gt;gulp [12:36:48] Using gulpfile D:\wamp\www\newProject\gulpfile.js [12:36:48] Starting 'default'... [12:36:48] Starting 'task'... [12:36:48] Starting 'compile'... [12:36:48] Finished 'task' after 17 ms [12:36:48] Finished 'default' after 21 ms [12:36:48] Finished 'compile' after 26 ms </code></pre> <p>But No file is created in <code>public</code> directory. </p> <p>what is Problem ?</p>
29,627,906
0
<p>You do this by using a string:</p> <pre><code>&gt;&gt;&gt; class Node(messages.Message): ... name = messages.StringField(1) ... children = messages.MessageField('Node',2,repeated=True) </code></pre> <p>You can see an example of this in the echo service demo here:</p> <p><a href="https://github.com/google/protorpc/blob/master/demos/echo/services.py#L81" rel="nofollow">https://github.com/google/protorpc/blob/master/demos/echo/services.py#L81</a></p>
12,711,342
0
<p>Since the statements are in a try block there's a chance that they will fail, and your program has a chance of trying to use a non-initialized variable. The solution is to initialize the variables to a default value that makes sense, i.e.,</p> <pre><code>int guess = -1; // some default value </code></pre> <p>You should also wrap the while loop around the try/catch block. Don't let the program progress until inputted data is valid.</p> <pre><code>boolean validGuess = false; while (!validGuess) { // prompt user for input here try { guess = Integer.parseInt(iConsole.nextLine()); if (/* .... test if guess is valid int */ ) { validGuess = true; } } catch (NumberFormatException e) { // notify user of bad input, that he should try again } } </code></pre> <p>You could even encapsulate all of this into its own method if you need to do similar things throughout the program.</p>
20,734,837
0
<p>Welcome to Stackoverflow. </p> <p>Please download Android SDK and use adb.exe to acquire linux shell on the device and then you can do many things.</p> <p>Serial ports are for different uses dont try to use them unless you know what you are doing.</p>
2,038,752
0
<p>As you say, the PHP interpreter will cope as-is.</p> <p>However, I'd say that adding the semicolon is probably slightly better practice, but that's just a personal coding preference.</p>
8,232,852
0
<p>If you have an HTML5 DocType it should work, anything before that won't allow inline elements <code>a</code> to wrap block level elements <code>div</code>.</p> <p>Even if you use an anchor unless you do some z-indexing then your inner link likely won't be seen how you are expecting...since it's the same link it shouldn't be a problem, but that then becomes repetitive.</p>
32,249,059
0
<p><strong>Firstly,</strong> you have not measured the speed of <code>len()</code>, you have measured the speed of creating a list/set <em>together with</em> the speed of <code>len()</code>.</p> <p>Use the <code>--setup</code> argument of <code>timeit</code>:</p> <pre><code>$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "len(a)" 10000000 loops, best of 3: 0.0372 usec per loop </code></pre> <p>The statements you pass to <code>--setup</code> are run before measuring the speed of <code>len()</code>.</p> <p><strong>Secondly,</strong> you should note that <code>len(a)</code> is a pretty quick statement. The process of measuring its speed may be subject to "noise". Consider that <a href="https://hg.python.org/cpython/file/3.5/Lib/timeit.py#l70">the code executed (and measured) by timeit</a> is equivalent to the following:</p> <pre><code>for i in itertools.repeat(None, number): len(a) </code></pre> <p>Because both <code>len(a)</code> and <code>itertools.repeat(...).__next__()</code> are fast operations and their speeds may be similar, the speed of <code>itertools.repeat(...).__next__()</code> may influence the timings.</p> <p>For this reason, you'd better measure <code>len(a); len(a); ...; len(a)</code> (repeated 100 times or so) so that the body of the for loop takes a considerably higher amount of time than the iterator:</p> <pre><code>$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.2 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.3 usec per loop </code></pre> <p>(The results still says that <code>len()</code> has the same performances on lists and sets, but now you are sure that the result is correct.)</p> <p><strong>Thirdly,</strong> it's true that "complexity" and "speed" are related, but I believe you are making some confusion. The fact that <code>len()</code> has <em>O(1)</em> complexity for lists and sets does not imply that it must run with the same speed on lists and sets.</p> <p>It means that, on average, no matter how long the list <code>a</code> is, <code>len(a)</code> performs the same asymptotic number of steps. And no matter how long the set <code>b</code> is, <code>len(b)</code> performs the same asymptotic number of steps. But the algorithm for computing the size of lists and sets may be different, resulting in different performances (timeit shows that this is not the case, however this may be a possibility).</p> <p><strong>Lastly,</strong></p> <blockquote> <p>If the creation of a set object takes more time compared to creating a list, what would be the underlying reason?</p> </blockquote> <p>A set, as you know, does not allow repeated elements. Sets in CPython are implemented as hash tables (to ensure average <em>O(1)</em> insertion and lookup): constructing and maintaining a hash table is much more complex than adding elements to a list.</p> <p>Specifically, when constructing a set, you have to compute hashes, build the hash table, look it up to avoid inserting duplicated events and so on. By contrast, lists in CPython are implemented as a simple array of pointers that is <code>malloc()</code>ed and <code>realloc()</code>ed as required.</p>
9,556,511
0
When using Pick_Contact, after i choose a Contact it open ups Android Market <p>help please</p> <p>here is my code on onClick</p> <pre><code> if(v.getId()==R.id.btnContacts) { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); } </code></pre> <p>here is my code on onActivityResult</p> <pre><code> if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); if (hasPhone.equalsIgnoreCase("1")) { Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, null, null); phones.moveToFirst(); String cNumber = phones.getString(phones.getColumnIndex("data1")); TextView txtPhoneNo = (TextView) findViewById(R.id.txt_PhoneNo); txtPhoneNo.setText(cNumber); c.close(); </code></pre> <p>i dont know what's happening have tried a dozen solutions but its still the same, im running this in my Galaxy Tab</p>
4,315,822
0
Detect frequency of audio input - Java? <p>I've been researching this off-and-on for a few months. </p> <p>I'm looking for a <em>library</em> or <em>working example code</em> to detect the <strong>frequency in sound card audio input</strong>, or detect presence of a given set of frequencies. I'm leaning towards Java, but the real requirement is that it <em>should be something higher-level/simpler than C</em>, and <strong>preferably cross-platform</strong>. Linux will be the target platform but I want to leave options open for Mac or possibly even Windows. Python would be acceptable too, and if anyone knows of a language that would make this easier/has better pre-written libraries, I'd be willing to consider it.</p> <p>Essentially I have a <strong>defined set of frequency pairs</strong> that will appear in the soundcard audio input and I need to be able to detect this pair and then... do something, such as for example record the following audio up to a maximum duration, and then perform some action. <em>A potential run could feature say 5-10 pairs, defined at runtime, can't be compiled in</em>: something like frequency 1 for ~ 1 second, a maximum delay of ~1 second, frequency 2 for ~1 second.</p> <p>I found suggestions of either doing an FFT or Goertzel algorithm, but was unable to find any more than the simplest example code that seemed to give no useful results. I also found some limitations with Java audio and not being able to sample at a high enough rate to get the resolution I need.</p> <p>Any suggestions for libraries to use or maybe working code? I'll admit that I'm not the most mathematically inclined, so I've been lost in some of the more technical descriptions of how the algorithms actually work.</p>
14,867,431
0
<p>When you assign a function to a different variable, it's <code>this</code> value changes. Since <code>getElementById</code> expects <code>this</code> to be an element, you're getting an error.</p> <p>If you're in an environment where you can use <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow"><code>bind</code></a>, use it:</p> <pre><code>(function(){ var t = document.getElementById.bind(document); t('element-id'); })(); </code></pre> <p>This'll ensure that <code>t</code>'s <code>this</code> will stay the <code>document</code> object.</p> <hr> <p>If you can't use <code>bind</code>, you'll have to create an intermediary function:</p> <pre><code>(function() { function t (id) { document.getElementById(id); } t('element-id'); })(); </code></pre>
11,260,383
0
<p>If you want to create some temporary files to run tests on then you should try the JUnit Rules with <code>TemporaryFolder</code>.</p> <p><a href="http://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/" rel="nofollow">Here</a> is an example.</p> <p>That is a way to prepare your tests with necessary files.</p> <p>But it all comes down to what you actually want to do and your question is not really giving many clues...</p>
34,554,095
0
<p>Do not use destructor , because .net C# is managed language</p> <p>GC class automatically call when then any class initialized,</p> <p>use ....,</p> <pre> try{ Console.WriteLine("Exception Occurred!"); }catch(Execption ex){ return; } try{ Console.WriteLine("Exception Occurred!"); }catch{ } </pre> <p>block to solve this problem. don't use destructor. I think it may help you </p>
13,079,237
0
Magento discount to multiple categories without discounting SKU? <p>I am applying a price rule to whole categories in my Magento store but I want to leave out a few of the items within the discounted category.</p> <p>How can I do this in the price rules? I have tried everything and it just discounts all the products and still discounts the products I want to leave at full normal price.</p> <p>Thank you so much!</p>
28,901,724
0
<p>To better understand the differences between the PHP code and cURL, I created a RequestBin instance and tried both on it. They yielded drastically different results:</p> <p><img src="https://i.stack.imgur.com/py40h.png" alt="RequestBin"></p> <p>It seemed like the POST data from the PHP script yielded an incorrect result for what was sent. This can be fixed by using a built-in PHP function <a href="http://php.net/http_build_query" rel="nofollow noreferrer">http_build_query</a>.</p> <p>It will yield a more apt result:</p> <p><img src="https://i.stack.imgur.com/XnCHf.png" alt="RequestBin with fixed problem"></p>
21,870,282
0
what is Flags used for? <p>Would someone explain me the role of flags in functions like setFlags? What exactly does this word mean in that situation...?</p> <p>My example is </p> <pre><code>protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(new RenderView(this)); } </code></pre> <p>I'd like to know what is setFlags used for?</p> <p>I've read the API documentation, but I haven't understood that.</p>
26,313,936
0
Can't attach css files or image to Django template <p>Surfing the internet, I found some solutions of my problem. But it didn't help(<a href="http://stackoverflow.com/questions/15491727/include-css-and-javascript-in-my-django-template">Include CSS and Javascript in my django template</a>) last answer. I added this in <code>urls.py</code>:</p> <pre><code>urlpatterns += patterns('', url(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) </code></pre> <p>This is my <code>settings.py</code>:</p> <pre><code>CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8')) MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media') MEDIA_URL = '/media/' STATIC_ROOT = 'static/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CURRENT_PATH, 'static'), ) </code></pre> <p>And my template:</p> <pre><code>&lt;html&gt; &lt;head lang="en"&gt; &lt;meta charset="UTF-8"&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap.min.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/font-awesome.min" /&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {% load staticfiles %} &lt;div id="modal" class="modal fade"&gt; &lt;div class="modal-header"&gt; &lt;div&gt;Вхід у систему&lt;/div&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;form action = "/login/" method="post"&gt; &lt;div&gt; &lt;label for="username"&gt;Логін:&lt;/label&gt; {{form.username}} &lt;/div&gt; &lt;div&gt; &lt;label for="password"&gt;Пароль:&lt;/label&gt; {{form.password}} &lt;/div&gt; &lt;br&gt; &lt;div&gt; &lt;input type="submit" value="Submit"&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;img src="{{STATIC_URL}}ukraine.png" alt="My image"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As the result CSS files are not working and even image isn't found. I created folder for static files: <code>D:\KIT\static\css</code></p>
17,867,552
0
<p>First, add two actions for your stepper:</p> <pre><code>[theStepper addTarget:self action:@selector(stepperTapped:) forControlEvents:UIControlEventTouchDown]; [theStepper addTarget:self action:@selector(stepperValueChanged:) forControlEvents:UIControlEventValueChanged]; </code></pre> <p>Here's what those actions look like:</p> <pre><code>- (IBAction)stepperTapped:(id)sender { self.myStepper.stepValue = 1; self.myStartTime = CFAbsoluteTimeGetCurrent(); </code></pre> <p>}</p> <pre><code>- (IBAction)stepperValueChanged:(id)sender { self.myStepper.stepValue = [self stepValueForTimeSince:self.myStepperStartTime]; // handle the value change here </code></pre> <p>}</p> <p>Here's the magic code:</p> <pre><code>- (double)stepValueForTimeSince:(CFAbsoluteTime)aStartTime { double theStepValue = 1; CFAbsoluteTime theElapsedTime = CFAbsoluteTimeGetCurrent() - aStartTime; if (theElapsedTime &gt; 6.0) { theStepValue = 1000; } else if (theElapsedTime &gt; 4.0) { theStepValue = 100; } else if (theElapsedTime &gt; 2.0) { theStepValue = 10; } return theStepValue; </code></pre> <p>}</p>
9,111,904
0
<p>When doing the binomial or quasibinomial <code>glm</code>, you either supply a probability of success, a two-column matrix with the columns giving the numbers of successes and failures or a factor where the first level denotes failure and the others success on the left hand side of the equation. See details in <code>?glm</code>.</p>
7,583,042
0
<p>I had a similar problem when comparing magnetometer values with CoreMotion events. If you want to transform these NSTimeIntervals you just need to calculate the offset once:</p> <pre><code>// during initialisation // Get NSTimeInterval of uptime i.e. the delta: now - bootTime NSTimeInterval uptime = [NSProcessInfo processInfo].systemUptime; // Now since 1970 NSTimeInterval nowTimeIntervalSince1970 = [[NSDate date] timeIntervalSince1970]; // Voila our offset self.offset = nowTimeIntervalSince1970 - uptime; </code></pre>
26,362,475
0
<pre><code>DECLARE @FixedDate DATE = '2014-11-01'; DECLARE @NextYearFixed DATE = DATEADD(year, 1, @FixedDate) -- 2015-11-01 DECLARE @PreviousYearFixed DATE = DATEADD(year, -1, @FixedDate) -- 2013-11-01 </code></pre>
38,650,099
0
<p>Avoid the timer altogether.</p> <pre><code>for i as integer =0 to 100 DoSomething() next i Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick DoSomething() End Sub Sub DoSomething() ' do something End Sub </code></pre>
38,874,269
0
Laravel validator::make vs this->validate() <p>I have a validator in my controller which works fine (see below). </p> <pre><code>$this-&gt;validate($request,[ 'name' =&gt; 'required|alpha', 'sport' =&gt; 'required|alpha', 'gender' =&gt; 'required|alpha', 'age' =&gt; 'required|numeric', 'score' =&gt; 'required|numeric', ]); </code></pre> <p>When I get to my view, I just run this:</p> <pre><code>@if(count($errors) &gt; 0) &lt;div&gt; &lt;ul&gt; @foreach($errors-&gt;all() as $error) {{ $error }} @endforeach &lt;/ul&gt; &lt;/div&gt; @endif </code></pre> <p>The Laravel documentation uses <code>Validator::make($request...)</code> which one is better in terms of good practice and also performance? The method I used comes from a Laravel 5 Youtube tutorial series. </p>
38,957,921
0
<p>You can use the crate <a href="https://crates.io/crates/chrono" rel="nofollow"><code>chrono</code></a> to achieve the same result:</p> <pre><code>extern crate chrono; use chrono::Local; fn main() { let date = Local::now(); println!("{}", date.format("%Y-%m-%d][%H:%M:%S")); } </code></pre> <p><strong>Edit:</strong></p> <p>The time crate is not deprecated: it is unmaintained.</p> <p>Besides, it is not possible to format a time using only the standard library.</p>
33,771,413
0
Including a JavaScript file in another JavaScript file <p>I am a newbie in developing JavaScript libraries. I've a basic doubt on how to include a <code>js</code> file into another <code>js</code> file that is dependent on the former. For example, I'm building a javascript library that replicates the class structures present in the Server code.There are cases for example, where class <code>B</code> is contained in class <code>A</code>. I want to make a seperate js file to denote class <code>B</code> and then include this in the definition of class <code>A</code>. How do I go about this ?</p> <p>I appreciate your help.</p> <p>Thanks!</p>
9,184,301
0
<p>In standard C++ there is no such thing as a stack. The standard only differentiates between the different lifetimes of objects. In that case a variable declared as <code>T t;</code> is said to have automatic storage duration, which means it life-time ends with the end of it's surrounding scope. Most (all?) compilers implement this through a stack. It is a reasonable assumption that all objects created that way actually live on the stack.</p>
32,631,973
0
<p>You need a border because sometimes people want a visible border between elements, not white space.</p> <p>You need padding because people want space between the content and the border and between the border and the next element.</p>
10,462,409
0
What is preferable way to pass objects between server and client? <p>Good day. I develop server-client application with Glassfish+ObjectDB(embeded mode) on serverside and Android application on client side. What is prefreable way (with respect to traffic and security) to send data that stored as java objects in ObjectDB to android application? (Data must be encrypted.) I think about:</p> <ul> <li>pass serializable objects through stream input/output.</li> <li>pass data as XML/JSON format.</li> </ul> <p>Or may be there is other way?</p> <p>Thx for help.</p>
28,874,966
0
<p>Looking at you code I recommend to change the design to a dynamically rendered <code>Canvas</code>, <code>repaint</code> is not implementing multibuffering and may cause flickering. Also regarding your game is running to fast, you need to run your game in your own <code>Thread</code>(not the main Thread) then implement an <code>update</code> method and sync it to N times a second with <code>Thread.sleep</code>.</p> <p>The design can be something like:</p> <pre><code>public class Game extends Canvas implements Runnable { // resolution public static final int WIDTH = 640; public static final int HEIGHT = 480; // window title private static final String TITLE = "Title"; /** * Number of logical/physical updates per real second */ private static final int UPDATE_RATE = 60; /** * Number of rendering buffers */ private static final int BUFFERS_COUNT = 3; /** * Value of a second in NanoSeconds DO NOT CHANGE! */ private static final long NANOS_IN_SEC = 1000000000L; /** * Update interval in double precision NanoSeconds DO NOT CHANGE! */ private static final double UPDATE_SCALE = (double) NANOS_IN_SEC / UPDATE_RATE; private JFrame window; private Thread gameThread; private boolean running; // temp values int x = 0; int y = 0; //////////////// public Game(JFrame window) { this.window = window; this.running = false; setPreferredSize(new Dimension(WIDTH, HEIGHT)); this.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // properly ends the game by calling stop when window is closed this.window.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stop(); super.windowClosing(e); System.exit(0); } }); this.window.getContentPane().add(this); this.window.setResizable(false); this.window.pack(); this.window.setLocationRelativeTo(null); this.window.setVisible(true); } // starts the game public synchronized void start() { if (running) return; running = true; gameThread = new Thread(this); gameThread.start(); System.out.println("Game thread started"); System.out.println("UPDATE_RATE: " + UPDATE_RATE); } // ends the game public synchronized void stop() { if (!running) return; running = false; boolean retry = true; while (retry) { try { gameThread.join(); retry = false; System.out.println("Game thread stoped"); } catch (InterruptedException e) { System.out.println("Failed sopping game thread, retry in 1 second"); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } private void update() { // this will run UPDATE_RATE times a second x++; y++; } private void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(BUFFERS_COUNT); return; } Graphics2D g2d = (Graphics2D) bs.getDrawGraphics().create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); clear(g2d, 0); // render here g2d.setColor(Color.red); g2d.fillRect(x, y, 50, 50); ////////////// g2d.dispose(); bs.show(); } private void clear(Graphics2D g2d, int shade) { g2d.setColor(new Color(shade, shade, shade)); g2d.fillRect(0, 0, WIDTH, HEIGHT); } // game loop thread public void run() { long startTime = System.currentTimeMillis(); long tick = 1000; int upd = 0; int fps = 0; double updDelta = 0; long lastTime = System.nanoTime(); while (running) { long now = System.nanoTime(); updDelta += (now - lastTime) / UPDATE_SCALE; lastTime = now; while (updDelta &gt; 1) { update(); upd++; updDelta--; } render(); fps++; if (System.currentTimeMillis() - startTime &gt; tick) { window.setTitle(TITLE + " || Upd: " + upd + " | Fps: " + fps); upd = 0; fps = 0; tick += 1000; } try { Thread.sleep(5); // always a good idea to let is breath a bit } catch (InterruptedException e) { e.printStackTrace(); } } } } </code></pre> <p>Usage:</p> <pre><code>public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } EventQueue.invokeLater(() -&gt; { new Game(new JFrame()).start(); }); } </code></pre> <p>Obviously this is only one way of doing this(there are a lot of other ways), feel free to tweak this to your needs. It took me about 20 minutes to write so I hope it wasn't in vain and this helps, also if you find any mistakes in the code which you cant fix let me know(I kinda wrote it without checking if it works).</p>
11,893,828
0
<p>Turns out this was caused by incomplete data entered into the system. Entering a Zip Code was triggering a look-up in the Post Code table. Only this table had blank entries for County. This caused both city and state to be overridden once the user tabbed out of the field.</p> <p>The answer is to disable this functionality. Zip Codes do not respect city boundaries (i.e., there can be multiple cities in a zip code), and they don't have to respect state boundaries either. Having the system override what the user entered in makes no sense.</p>
5,970,224
0
<p>I was able to figure it out. Basically, I just needed to step through each character of the string and look for a match until once was no longer found. Thanks for the help!</p> <pre><code>/* ICD9 Lookup */ USE TSiData_Suite_LWHS_V11 DECLARE @String NVARCHAR (10) DECLARE @Match NVARCHAR(10) DECLARE @Substring NVARCHAR (10) DECLARE @Description NVARCHAR(MAX) DECLARE @Length INT DECLARE @Count INT SET @String = '309.99999999' /* Remove decimal place from string */ SET @String = REPLACE(@String,'.','') /* Get lenth of string */ SET @Length = LEN(@String) /* Initialize count */ SET @Count = 1 /* Get Substring */ SET @Substring = SUBSTRING(@String,1,@Count) /* Start processing */ IF (@Length &lt; 1 OR @String IS NULL) /* Validate @String */ BEGIN SET @Description = 'No match found for string. String is not proper length.' END ELSE IF ((SELECT COUNT(*) FROM LookupDiseases WHERE REPLACE(LookupCodeDesc,'.','') LIKE @Substring + '%') &lt; 1) /* Check for at least one match */ BEGIN SET @Description = 'No match found for string.' END ELSE /* Look for matching code */ BEGIN WHILE ((SELECT COUNT(*) FROM ICD9Lookup WHERE REPLACE(LookupCodeDesc,'.','') LIKE @Substring + '%') &lt;&gt; 1 AND (@Count &lt; @Length + 1)) BEGIN /* Update substring value */ SET @Substring = SUBSTRING(@String,1,@Count + 1) /* Increment @Count */ SET @Count += 1 /* Select the first matching code and get description */ SELECT TOP(1) @Match = LookupCodeDesc, @Description = LookupName FROM ICD9Lookup WHERE REPLACE(LookupCodeDesc,'.','') LIKE @Substring + '%' ORDER BY LookupCodeDesc ASC END END PRINT @Match PRINT @Description </code></pre>
35,481,955
0
<h3>As for IPv4 -- it's similar in IPv6</h3> <p><strong>Multicast addresses</strong> Theses correspond to the class D. The class D:</p> <ul> <li>First octet: 224 - 239</li> <li>First octet pattern: 1110*</li> <li>These IP addresses are multicast addresses.</li> </ul> <p>there are used for specific (routing protocol, service discovery, NTP), sometimes experimental, use-cases.</p> <p>Network nodes must perform a <em>join(multicast-address)</em> call in order to receive packet sent to the address <em>multicast-address</em>. There can be many multicast addresses present in a network.</p> <p><strong>Broadcast address</strong></p> <p>There is only <strong>one</strong> broadcast address in every network. This address is constructed with all its host-part IP address bits set to <strong>1</strong>.</p> <p>If the network is 192.168.0.0/24 the last octet is the host-part IP address (and the first three ones are the network-part IP address). The broadcast address is then 192.168.0.<strong>255</strong>.</p> <p>The broadcast address is used to send packet to <strong>all</strong> the nodes within the <strong>LAN</strong>, not further, not only the nodes that would had performed a <em>join(multicast-address)</em> call -- that make no sense.</p> <hr> <p><strong>More details <a href="http://stackoverflow.com/a/7781445/5321002">on this answer</a>.</strong></p>
39,909,449
0
OOP - pass one object to several others? <p>I am not quite sure if this question belongs here or to another community on stackexchange, if the latter, I could not find the right one and would be glad about a hint.</p> <p>I am at the moment programming a little game (roundbased -no threading) in Java and I am wondering: Is it bad practice if one object is known to several others?</p> <p>In my case I wonder if I should create an Object o and then pass it as a constructor argument to several other, later created objects.</p> <p>It does work, but I wonder if this should in general rather not be done?</p> <p>Does someone have an answer?</p>
14,030,985
0
<p>What I find works in these situations is toggling class names instead of directly setting 'display: block'. This prevents the need for crazy selectors or using !important.</p> <pre><code>/* the default is display:block, so all we need is this one class */ .closed { display: none; } </code></pre> <hr> <pre><code>&lt;li class="collapsable"&gt; &lt;ul class="treeview"&gt; &lt;li class="collapsable"&gt; &lt;ul class="treeview" class="closed"&gt; </code></pre>
40,935,837
0
<p>I wrote a little PHP wrapper for LIFX. <a href="https://github.com/ewkcoder" rel="nofollow noreferrer">https://github.com/ewkcoder</a></p>
17,647,325
0
<pre><code>[WebMethod] [ScriptMethod] public bool GetFarmersByName(string name) </code></pre> <p>this method must be public static method which return some data if you want to call it by ajax..</p> <p>like</p> <pre><code>[WebMethod] [ScriptMethod] public static bool GetFarmersByName(string name) </code></pre>
22,176,590
0
<p>Traditionally you would create a <code>cgi.FieldStorage</code> object, which reads stdin (usually - there are CGI standards about what it does and when). That's a bit passé nowadays. <code>Urlparse.parse_qs</code> is designed to convert from form data to dict:</p> <pre><code>&gt;&gt;&gt; import urlparse &gt;&gt;&gt; urlparse.parse_qs("prize_id=2&amp;publisher_id=32&amp;foreign_user_id=1234") {'prize_id': ['2'], 'foreign_user_id': ['1234'], 'publisher_id': ['32']} &gt;&gt;&gt; </code></pre>
22,575,795
0
<p>Once I had the same problem. You added GoogleMap fragment in XML. However, <a href="http://developer.android.com/about/versions/android-4.2.html#NestedFragments" rel="nofollow">documentation</a> says:</p> <blockquote> <p><strong>Note:</strong> You cannot inflate a layout into a fragment when that layout includes a <code>&lt;fragment&gt;</code>. Nested fragments are only supported when added to a fragment dynamically.</p> </blockquote> <p>In your case, you want to inflate a layout with GoogleMaps <code>&lt;fragment&gt;</code> into ViewPager fragment, you can't do that.</p> <p>You should add GoogleMap fragment to the ViewPager from the Java code, for example with ViewGroup's (or its subclass)<a href="http://developer.android.com/reference/android/view/ViewGroup.html#addView%28android.view.View%29" rel="nofollow"><code>addView(View v)</code></a> method.</p>
22,009,556
0
OpenCV SURFDetector Range of minHessian <p>I'm using the OpenCV SURFDetector to search for keypoints in an image. In my program I want to give the user the opportunity to set the value of the minHessian with a trackbar, but this means that I would have to know the range of the hessian-values. </p> <p>I know that the higher I set this threshold the less keypoints I get and vice versa. </p> <p>Is there a way to calculate a range of the hessian values so I can set 0 (which would be a very high minHessian threshold) on my trackbar to “no keypoints” and 100 (which is probably minHessian=1 or 0) for “all possible keypoints”?</p> <p>I’ve already taken a look at this question, but this doesn’t help me out here: <a href="http://stackoverflow.com/questions/17613723/whats-the-meaning-of-minhessian-surffeaturedetector">Whats the meaning of minHessian (Surffeaturedetector)</a></p> <p><strong>Edit:</strong> I've found a way for my application that works, but I'm not happy with this solution. This is what I am doing now: I constantly raise my minHessian and check if I still find keypoints, but this variant is neither fast nor really exact because I have to take bigger steps (in my case i+=100) to get results faster. I'm pretty sure there is another solution. What about binary search or something similar? Is it really not possible to calculate the maxHessian value?</p> <p>Here's my code:</p> <p>C#-side:</p> <pre><code>private int getMaxHessianValue() { int maxHessian = 0; for (int i = 0; i &lt; 100000; i+=100) { int numberOfKeypoints = GetNumberOfKeypoints(pathToImage, i); if (numberOfKeypoints == 0) // no keypoints found? -&gt; maxHessian { maxHessian = i; break; } } return maxHessian; } </code></pre> <p>C++-side:</p> <pre><code>int GetNumberOfKeypoints(char* path, int minHessian) { /// Load image Mat templ; templ = imread( path, CV_LOAD_IMAGE_GRAYSCALE ); // Detect the keypoints using SURF Detector SurfFeatureDetector detector( minHessian ); std::vector&lt;KeyPoint&gt; keypoints; detector.detect( templ, keypoints ); // return number of keypoints return keypoints.size(); } </code></pre>
22,886,896
0
<p>It's using recursion (of a sort) to handle one set of replacements exposing a new set characters that subsequently need replacing in the same way.</p>
4,429,205
0
Selenium / FlashSelenium calling the wrong methods? <p>Seems like sometimes when Selenium should call a certain method, it instead calls another, as pointed out by the following log:</p> <blockquote> <p>14:57:18.328 INFO - Command request: getEval[this.browserbot.findElement("someElement").doFlexClick('someIdOfAButton','');, ] on session 21708b0a4a154ebc96c9720c14578e74</p> <p>14:57:18.343 INFO - Got result: OK,Error: Cannot type text into someIdOfAButton on session 21708b0a4a154ebc96c9720c14578e74</p> </blockquote> <p>I've tried both Selenium server 1.0.3 and the 2.0 alpha 7 versions, they both display this behaviour. FlashSelenium is involved so I'm not sure where along the way lies the bug. Furthermore it's hard to reproduce as it doesn't happen only for some methods, and doesn't always happen. </p> <p>I've tried searching for issues similar to these but couldn't find any remotely similar... Anyone experienced the same behavior? And if so, is there a fix for it?</p> <p><strong>Edit:</strong> I doubt FlashSelenium is at fault for this, as the log tells that the command arrives correctly at the server... But I can't seem to be able to follow the path of execution from the moment the Selenium server gets the command and passes over to the browser, to the moment where it gets the response.</p>
38,556,594
0
<p>Hitting <code>CTRL-C</code> tells Powershell to stop the execution of the program, yielding a <code>KeyboardInterrupt</code> error.</p> <p>A comment in the program mentions the following:</p> <p><code># Keep going until they hit CTRL-D</code></p> <p>Meaning you'll have to exit with <code>CTRL-D</code>. That doesn't seem to work, so exiting with <code>CTRL-C</code> is logical. The program is broken at the line</p> <pre><code>question, answer = convert(snippet, phrase) </code></pre> <p>because we both got the same errors.</p> <p>I've personally quit following the tutorial around Ex.25. Examing projects written in Python is far more effective because you can research the functions that the programmer/developer used for the project.</p>
8,383,209
0
<p>By default find_and_modify returns the hash, check the <a href="http://api.mongodb.org/ruby/current/Mongo/Collection.html#find_and_modify-instance_method" rel="nofollow">documentation</a> </p> <p><strong>Parameters:</strong> </p> <ul> <li>opts (Hash) (defaults to: {}) — a customizable set of options</li> </ul> <p><strong>Options Hash (opts):</strong></p> <ul> <li>:query (Hash) — default: {} — a query selector document for matching the desired document.</li> <li>:update (Hash) — default: nil — the update operation to perform on the matched document.</li> <li>:sort (Array, String, OrderedHash) — default: {} — specify a sort option for the query using any of the sort options available for Cursor#sort. Sort order is important if the query will be matching multiple documents since only the first matching document will be updated and returned.</li> <li>:remove (Boolean) — default: false — If true, removes the the returned document from the collection.</li> <li>:new (Boolean) — default: false — If true, returns the updated document; otherwise, returns the document prior to update.</li> </ul> <p><strong>Returns:</strong></p> <ul> <li>(Hash) — the matched document.</li> </ul> <p>But you can convert the hash to your collection object by simply initializing the model by passing the hash as a argument</p> <pre><code> &gt;&gt; x = MyModel.collection.find_and_modify(:query =&gt; {...},:update =&gt; {...}) &gt;&gt; x.class &gt;&gt; BSON::OrderedHash &gt;&gt; obj = MyModel.new(x) &gt;&gt; obj.class &gt;&gt; MyModel </code></pre> <p>And now you can apply any mongoid operation on the converted object. It will work perfectly.</p> <p>Hope it helps</p>
30,313,901
0
<p>Follow up on this problem: It appears there was a problem in my background page code that prevented calling chrome.runtime.onConnect. I fixed it and it works now.</p>
13,770,409
0
Re-load Unloaded Projects in EnvDTE <p>I have listed all the projects in my solution, using EnvDTE, but I found a bug in my code: I can't get the projects that are Unloaded.</p> <p>I found a way to skip the Unloaded projects:</p> <pre><code>if (string.Compare(EnvDTE.Constants.vsProjectKindUnmodeled, project.Kind, System.StringComparison.OrdinalIgnoreCase) == 0) continue; </code></pre> <p>This way, my code doesn't crash - but I am unable to load the missing projects through code, since they exist already.</p> <p>How can I Load the Unloaded projects into the solution ?</p> <p>I have tried: </p> <pre><code>project.DTE.ExecuteCommand("Project.ReloadProject"); </code></pre> <p>And got error:</p> <p>System.Runtime.InteropServices.COMException (...): Command "Project.ReloadProject" is not available.</p> <p>So I tried to somehow get </p> <pre><code>application.DTE.ExecuteCommand("Project.ReloadProject"); </code></pre> <p>But before that, from every place I searched on the NET, I must pre-select the project in the solution - and for that, I need <code>project.Name</code> (which I have), and the path, which I don't (every example I have found assumes that the solution path is the same as the project path, which is highly unlikely in a generic situation).</p>
9,114,531
0
<p>A Pythonic solution might a bit like @Bogdan's, but using zip and argument unpacking</p> <pre><code>workflowname, paramname, value = zip(*[line.split(',') for line in lines]) </code></pre> <p>If you're determined to use a for construct, though, the 1st is better.</p>
40,201,415
0
Dynamically mount Carrierwave uploader on serialized field <p>I'm creating this app where users are able to dynamically add custom fields (<code>TemplateField</code>) to a template (<code>Template</code>) and use that template on a page (<code>Page</code>).</p> <p>The custom fields can have type text or image, and have custom naming. A user can for instance create at field named Profile picture of type image to their template.</p> <p>I can't however figure out how to dynamically mount a CarrierWave uploader to fields of type image, when everything is saved to an <code>hstore</code> attribute (<code>properties</code>) on the page model.</p> <p>Any help is much appreciated!</p> <pre><code>class Template &lt; ActiveRecord::Base has_many :template_fields has_many :pages end class Page &lt; ActiveRecord::Base belongs_to :template store_accessor :properties end class TemplateField &lt; ActiveRecord::Base belongs_to :template end </code></pre>
25,060,226
0
<p>Override <code>iterator</code> method in <code>ProxyNodeManager</code>. </p> <p>You can base on how <a href="https://github.com/django/django/blob/1.6.5/django/db/models/query.py#L1066" rel="nofollow">django does it</a>.</p>
30,887,633
0
<p>The first one is better because the heading should describe what to come, and is not a part of the nav. Just like h1 should not be inside p. It will probably work just fine either way though.</p>
1,823,408
0
<p>Do you really want to hide the database id from the user, as in a scenario where the user has some alternate access to the database and you want him to search for the book the hard way?</p> <p>Usually the requirement is not to keep the ID secret, but to prevent the user from figuring out IDs of other items (eg. to enforce a certain funnel of navigation to reach an item) or from sharing the ID with other users. So for example is ok to have an URL <code>http://example.com/books/0867316672289</code> where the 0867316672289 will render the <em>same</em> book to the same visitor, but the user cannot poke around the value, so 0867316672288 or 0867316672290 will land 404s. It may also be required that <em>another</em> user entering 0867316672289 gets also a 404.</p> <p>Keeping the ID truly 'secret' (ie. storing it in session and having the session state keep track of 'current book') adds little value over the scheme described above and only complicates things. </p> <p>One solution is to encrypt the IDs using a site secret key. From a int ID you get a 16 bytes encrypted block (eg if AES block size is used) that can be reverted back by the site into the original ID on subsequent visits. Visitors cannot guess other IDs due to the sheer size of the solution space (16 bytes). If you want also to make the pseudo-ids sticky to an user you can make the encryption key user specific (eg. derived from user id) or add extra information into the pseudo-id (eg. encrypt also the user-id and check it in your request handler).</p>
39,131,393
0
<p>Not sure if it's possible to load any app.config file during design time user control load. You can prevent the need to though by wrapping your user control load methods with:</p> <pre><code>private void myUserControl_Load(object sender, EventArgs e) { if (!this.DesignMode) { //....stuff } } </code></pre>
24,191,454
0
<p>The issue might be that you are trying to Uri encode an already Uri encoded string.</p> <p>As per the Intent class documentation for the toUri() method:</p> <blockquote> <p>Convert this Intent into a String holding a URI representation of it. The returned URI string has been properly URI encoded, so it can be used with <strong>Uri.parse(String)</strong>. The URI contains the Intent's data as the base URI, with an additional fragment describing the action, categories, type, flags, package, component, and extras.</p> </blockquote> <p>So try:</p> <pre><code>String finaldata = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)); </code></pre>
11,236,851
0
<p><code>Object.create()</code> and <code>new</code> are used for different purposes.</p> <p>You would use <code>Object.create()</code> to <code>inherit</code> from an existing object.<br> Where you use <code>new</code> to create a new <code>instance</code> of an object.</p> <p>See the following questions and answers for details:</p> <p><a href="http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction-in-j">Understanding the difference between Object.create() and new SomeFunction() in JavaScript</a></p> <p><a href="http://stackoverflow.com/questions/2709612/using-object-create-instead-of-new">Using &quot;Object.create&quot; instead of &quot;new&quot;</a></p>
35,578,509
0
Alias conversions <p>I have <code>struct AccessToken</code> as a part of external library and I use that library in my own. I'd like to return a value of this type but I do not see any reasons why my internal implementation should be visible from outside. Type alias looks great for this.</p> <pre><code>type AccessToken oauth.AccessToken </code></pre> <p>But I'm getting an error when trying to do next:</p> <pre><code>func Auth(key string, secret string) *AccessToken { ... var token oauth.AccessToken = AuthorizeToken(...) return AccessToken(*token) } </code></pre> <p>Error:</p> <pre><code>cannot use AccessToken(*accessToken) (type AccessToken) as type *AccessToken in return argument </code></pre> <p>It's clear that I can just copy structures field by fiend. But is there any way to use aliases?</p>
8,409,762
0
2 column floating layout, does width have to be specified for left column <p>If one uses float:left to layout two columns, does the left column have to have a width specified? Without a width assigned, when I shrink the width of the browser page, the second (main) column gets put underneath the left (navigation) column. Is there a way to avoid this, without assigning a width? If not, what is the least width spec's I need to add? I.e. can I assign a fixed pixel width to the left column, and have the right column get the rest?</p> <p>Thanks</p> <p>----- Addition -----</p> <p>After trying various answers, noting their complexity, is there any reason not to just use a two column table?</p>
35,132,355
0
<p>Try this method:</p> <p><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getObjectStorageDatacenters" rel="nofollow">http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getObjectStorageDatacenters</a></p> <p>here a rest example:</p> <pre><code>URL: https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/206/getObjectStorageDatacenters Method: Get </code></pre> <p>Regards</p>
31,669,401
0
How to get the last word of a sentence using Jquery <p>How can I get the last word of a sentence in Jquery?</p> <p><strong>Eg:</strong> <code>get the last word of a sentence</code> should return <code>sentence</code></p> <p><code>get the last word</code> should return <code>word</code></p>
1,293,607
0
<pre><code>class MyModel &lt; ActiveRecord::Base after_update :do_something attr_accessor :should_do_something def should_do_something? should_do_something != false end def do_something if should_do_something? ... end end end y = MyModel.new y.save! # callback is triggered n = MyModel.new n.should_do_something = false n.save! # callback isn't triggered </code></pre>
9,336,736
0
<p>You could set a variable outside this code:</p> <pre><code>var clickedCarousel = false; $esCarousel.show().elastislide({ imageW : 240, onClick : function( $item ) { if( anim ) return false; anim = true; // only in the FIRST CLICK click show wrapper (expected but don't work) if(!clickedCarousel) { _addImageWrapper(); clickedCarousel = true; } // on click show image _showImage($item); // change current current = $item.index(); } }); </code></pre> <p>Does this fit your need?</p> <p><strong>UPDATE:</strong> Regarding this update:</p> <p>UPDATE: When I close (close with fadeOut) It won't open again! It must be because the carousel is already been clicked… how can I “reset” the click?</p> <p><a href="http://api.jquery.com/fadeOut/" rel="nofollow">fadeOut()</a> takes a callback of this form:</p> <pre><code>obj.fadeOut( [duration] [, callback] ) </code></pre> <p>callback can be an inline function or a predefined one, so you could use this (inline):</p> <pre><code>$navClose.on('click.rgGallery', function( event ) { $('.rg-image-wrapper').fadeOut(2000,function(){ clickedCarousel = false; // reset to false after fade out is complete }); return false; }); </code></pre> <p>Does that help?</p>
8,426,952
0
<p>Please use the custom <a href="http://help.devexpress.com/#WindowsForms/CustomDocument1498" rel="nofollow">numeric mask</a> on your column editor:</p> <pre><code>this.gridColumn1.ColumnEdit = this.repositoryItemTextEdit1; //... this.repositoryItemTextEdit1.Mask.EditMask = "###,###,###,##0.0##;(###,###,###,##0.0##)"; this.repositoryItemTextEdit1.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric; this.repositoryItemTextEdit1.Mask.UseMaskAsDisplayFormat = true; </code></pre>
1,870,082
0
Really complex LINQ (to SQL) query example <p>We're thinking about adding more LINQ tests for ORMBattle.NET, but have no more ideas. All LINQ tests there are checking common LINQ functionality:</p> <ul> <li>Any test must pass on LINQ to IEnumerable</li> <li>For any test, there must be at least one ORM, on it passes (actually it doesn't matter if it is listed @ ORMBattle or not).</li> </ul> <p>Currently the goal of LINQ test sequence is to <em>automatically</em> compute LINQ implementation coverage score.</p> <p><strong>Prerequisites:</strong></p> <ul> <li><a href="http://code.google.com/p/ormbattle/source/browse/trunk/Tests/Linq/Linq2Sql.generated.cs" rel="nofollow noreferrer">Code of tests for LINQ to SQL is here</a>. This must give some imagination of what's already covered.</li> <li>Tests for other tools (actually they're generated by <a href="http://code.google.com/p/ormbattle/source/browse/trunk/Tests/Linq/LinqTests.tt" rel="nofollow noreferrer">this T4 template</a>) are <a href="http://code.google.com/p/ormbattle/source/browse/#svn/trunk/Tests/Linq" rel="nofollow noreferrer">here</a>.</li> </ul> <p>If you have any ideas on what can be added there, please share them. I'll definitely accept <em>any</em> example of LINQ query that satisfies above requirements, and possibly - some good idea related to improvement of test suite, that <em>can be implemented</em> (so e.g. if you'd suggest us to manually study the quality of translation, this won't work, because we can't automate this).</p>
9,533,542
0
<p>I'm not quite sure if I understood your question, but, can't you serialize your commands and send them through your sockets? </p> <p>An easier approach would be a <a href="http://msdn.microsoft.com/en-us/library/ms731758.aspx" rel="nofollow">self hosted wcf service</a>, as it will free you from implementing communication details.</p>
9,402,799
0
<p>The <code>JList</code> component is backed by a list model. So the only recommended way to remove an item from the list <em>view</em> is to delete it from the model (and refresh the view).</p>
27,123,183
0
<p>I tried with this and it works.</p> <p>In routes:</p> <pre><code>Route::group(array('before' =&gt; 'auth', 'after' =&gt; 'no-cache'), function() { Route::get('dashboard', array('as' =&gt; 'getDashboard', 'uses' =&gt; 'DashboardController@getIndex')); Route::get('logout', array('as' =&gt; 'getLogout', 'uses' =&gt; 'LoginController@getLogout')); Route::group(array('prefix' =&gt; 'users'), function() { Route::get('users', array('as' =&gt; 'getUsers', 'uses' =&gt; 'UsersController@getIndex', 'before' =&gt; 'hasAccess:users.index')); }); }); </code></pre> <p>In filters:</p> <pre><code>Route::filter('no-cache',function($route, $request, $response){ $response-&gt;headers-&gt;set('Cache-Control','nocache, no-store, max-age=0, must-revalidate'); $response-&gt;headers-&gt;set('Pragma','no-cache'); $response-&gt;headers-&gt;set('Expires','Fri, 01 Jan 1990 00:00:00 GMT'); }); </code></pre>
11,066,168
0
<pre><code>QMAKE_CXXFLAGS += -std=c++0x </code></pre> <p>Results in an error because you're not using the MinGW compiler. "D9002: Ignoring unknown option <code>-std=c++0x</code>" is an error from the MSVC compiler.</p> <p>In QtCreator, go to the projects tab(on the left) and change the toolchain you're using. If it hasn't auto-detected MinGW, you're going to have to add it yourself by clicking on the manage button.</p>
36,724,634
0
Need help combining SQL queries <pre><code>SELECT tableA.col1, tableA.col2, LEFT(tableB.col3, 4) as person FROM tableA LEFT JOIN tableB ON tableB.col1 = tableA.col1 AND tableB.col2 = tableA.col2 WHERE tableA.col3 = '000000' AND tableA.col4 &lt;&gt; '' AND person = 'Zeus' ORDER BY tableA.col1, tableA.col4 ASC; --- col1 col4 person 001 abc Zeus 002 abc Zeus 003 xyz Zeus 004 xyz Zeus </code></pre> <p>+</p> <pre><code>SELECT tableC.col1, SUM(tableC.col2) as cost FROM tableC WHERE tableC.col3 = 'L' GROUP BY tableC.col1, tableC.col3; --- col1 cost 001 23462 002 25215 003 92381 004 29171 </code></pre> <p>=</p> <pre><code>col1 col4 person cost 001 abc Zeus 23462 002 abc Zeus 25215 003 xyz Zeus 92381 004 xyz Zeus 29171 </code></pre> <p>How do I do this? I tried putting the second query as a nested select in the top one, but I couldn't get it to work. Both result sets share the same <code>col1</code> values, which are unique, so I guess they need to be joined on that? And ultimately the <code>person</code> is where the query will differ every time I run it.</p>
21,650,968
0
<p>It depends on the intent of <code>returns_the_hash</code></p> <p>If it changes and all of a sudden returns</p> <pre><code>{ :lorem =&gt; "ipsum", :foo =&gt; "bar", :baz =&gt; "qux", :options =&gt; { :oof =&gt; "rab", :zab =&gt; "xuq", }, } </code></pre> <p>Is that a bug that it returned lorem/ipsum or is it ok? </p> <p>If that indicates a bug, then your <strong>explicit</strong> and <strong>implicit</strong> tests wouldn't catch it, while the <strong>exact</strong> test would catch it. </p> <p>If that situation is not a bug, then you have more flexibility in deciding how important those other elements are to you and whether it makes sense for the tests to require less maintenance. </p> <p>It depends on how the data is used. For example, if all the data in the hash eventually shows up to the user, then your tests should be more stringent on what data is actually being returned (the <strong>exact</strong> test.)</p>
30,923,131
0
param is missing or the value is empty: item <p><strong>items_controller.rb</strong></p> <pre><code>class ItemsController &lt; ApplicationController def index @items = Item.all render text: @items.map{ |i| "#{i.name}: #{i.price}" }.join('&lt;br/&gt;') end def create item_params = params.require(:item).permit(:name, :description, :price, :real, :weight) @item = Item.create(item_params) render text: "#{@item.id}: #{@item.name}(#{[email protected]_record?})" end end </code></pre> <blockquote> <p>error : param is missing or the value is empty: item</p> <p>Rails.root: E:/work/my_store_2</p> <p>Application Trace | Framework Trace | Full Trace app/controllers/items_controller.rb:9:in `create' Request</p> <p>Parameters:</p> <p>{"name"=>"car1", "description"=>"good car", "price"=>"500000", "weight"=>"0", "real"=>"1"}</p> </blockquote> <p><strong>console</strong></p> <pre><code>Started GET "/items/create?name=car1&amp;description=good+car&amp;price=500000&amp;weight=0&amp;real=1" for 127.0.0.1 at 2015-06-18 21:25:39 +0300 Processing by ItemsController#create as HTML Parameters: {"name"=&gt;"car1", "description"=&gt;"good car", "price"=&gt;"500000", "weight"=&gt;"0", "real"=&gt;"1"} Completed 400 Bad Request in 2ms ActionController::ParameterMissing (param is missing or the value is empty: item): app/controllers/items_controller.rb:9:in `create' </code></pre> <p><strong>where is my mistake?</strong></p>