id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
37,124,669
Number of elements in a single dimension variant array in excel
<p>Is This code correct for determining the number of elements in a single dimension variant array in Excel VBA. Supposing I have a variant array named Array1 with k elements.</p> <pre><code>Dim n as Integer n = UBound(Array1) </code></pre>
37,124,722
2
3
null
2016-05-09 20:14:51.52 UTC
3
2022-01-18 09:44:25.11 UTC
2018-07-09 18:41:45.953 UTC
null
-1
null
6,159,217
null
1
19
excel|vba
85,262
<p>To get an accurate count, you need to do <code>UBound - LBound + 1</code>. This is because arrays don't have to go from index 1 to n, they can start at basically any index you want. Here's an example where it goes from 3 to 7, which is a total of 5 elements (3, 4, 5, 6, and 7):</p> <pre><code>Sub tgr() Dim Array1(3 To 7) As Variant Dim lNumElements As Long lNumElements = UBound(Array1) - LBound(Array1) + 1 MsgBox lNumElements End Sub </code></pre>
25,997,365
How to check a radio button with Selenium WebDriver?
<p>I want to check this radio button, but I didn't know how. My HTML is:</p> <pre><code>&lt;div class="appendContent"&gt; &lt;div&gt; id="contentContainer" class="grid_list_template"&gt; &lt;div id="routeMonitorOptions"&gt;&lt;/div&gt; &lt;/div&gt; &lt;input id="optionStopGrid" type="radio" name="gridSelector"/&gt; &lt;label for="optionStopGrid"&gt;Paradas&lt;/label&gt; &lt;/div&gt; </code></pre>
26,046,517
5
2
null
2014-09-23 14:13:00.503 UTC
null
2021-09-07 23:59:44.737 UTC
2015-11-16 06:42:31.397 UTC
user3913686
617,450
null
4,070,746
null
1
3
java|html|css|selenium
71,892
<pre><code>import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class answer { public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get("http://www.example.com/"); //If u want to know the number of radio buttons then use List List&lt;WebElement&gt;radioButton = driver.findElements(By.tagName("example")); System.out.println(radioButton.size()); //If u want to select the radio button driver.findElement(By.id("example")).click(); Thread.sleep(3000); //If u want the Text in U R console for(int i=0;i&lt;radioButton.size();i++) { System.out.println(radioButton.get(i).getText()); } //If u want to check whether the radio button is selected or not if(driver.findElement(By.id("example")).isSelected()) { System.out.println("True"); } else { System.out.println("False"); } } } </code></pre>
25,527,617
Print document value in mongodb shell
<p>I want to print the value for this JSON document in the mongo shell. Like a simple console output, without creating a new collection or document.</p> <p><img src="https://i.stack.imgur.com/6l782.png" alt="enter image description here"></p> <p>Thanks in advance</p>
25,528,322
4
3
null
2014-08-27 12:46:04.323 UTC
2
2019-08-07 09:43:23.58 UTC
null
null
null
null
2,128,765
null
1
9
mongodb|mongodb-query
43,449
<p>I found a solution, by using <code>.forEach()</code> to apply a JavaScript method:</p> <pre><code>db.widget.find( { id : "4" }, {quality_level: 1, _id:0} ).forEach(function(x) { print(x.quality_level); }); </code></pre>
9,096,137
Using ReSharper to Sort Members by Type then Name
<p>I've been trying to get ReSharpers Code Cleanup to not only sort any members alphabetically by name, but to sort them primarily by their type (whether that be a methods return type or a properties type etc.), then by their name.</p> <p>For example:</p> <pre><code>#region " Properties " public string Name { get; set; } public int Age { get; set; } #endregion #region " Instance Methods " public void SecondMethod()... public void FirstMethod()... public Post GetPost()... public List&lt;Post&gt; GetPosts()... #endregion </code></pre> <p>Would become:</p> <pre><code>#region " Properties " public int Age { get; set; } public string Name { get; set; } #endregion #region " Instance Methods " public List&lt;Post&gt; GetPosts()... public Post GetPost()... public void FirstMethod()... public void SecondMethod()... #endregion </code></pre> <p>Ideally, I would like the other default behaviours to remain the same e.g. where Constructors, Properties are positioned/grouped, and if a number of members appear within a region (as in the example above), for that group of members to be sorted independently from members outside of that group/region.</p> <p>Can anyone recommend the code necessary within the ReSharper Type Members Layout pattern editor to achieve this please?</p>
9,097,878
1
3
null
2012-02-01 12:52:09.403 UTC
7
2012-02-01 14:57:21.637 UTC
2012-02-01 13:24:58.313 UTC
null
197,415
null
197,415
null
1
30
c#|resharper
5,411
<p>Looking at the Type Member Layout in Resharper, I'm guessing this isn't possible. Here's a sample snippet for the events region:</p> <pre><code>&lt;Entry&gt; &lt;Match&gt; &lt;Kind Is="event"/&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Access Order="public internal protected-internal protected private" /&gt; &lt;Static /&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group Region="Events"/&gt; &lt;/Entry&gt; </code></pre> <p>Here's an article from JetBrains themselves: <a href="http://blogs.jetbrains.com/dotnet/2011/01/in-depth-look-at-customizing-type-layout-with-resharper/" rel="noreferrer">In-depth look at customizing type layout with resharper</a>.</p> <p>It looks like there is no qualifier for return type for sorting unfortunately. Here are the options, referenced in that post:</p> <pre><code> - &lt;Kind Is=”$val” [Order=”$val”]&gt; - &lt;Name Is="$val” [IgnoreCase=”true/false”]&gt; - &lt;HasAttribute CLRName=”$val” [Inherit=”true/false”]&gt; - &lt;Access Is=”$val”&gt; - &lt;Static/&gt; - &lt;Abstract/&gt; - &lt;Virtual/&gt; - &lt;Sealed/&gt; - &lt;Readonly/&gt; - &lt;ImplementsInterface CLRName=”$val” [Immediate=”true/false”]&gt; - &lt;HandlesEvent/&gt; </code></pre> <p>You could contact JetBrains and request that a new operand be added to the list. Seems fairly simple. Could be something like:</p> <pre><code>&lt;ReturnType="$val" [Order="$val"][AlphaOrder="true/false"]&gt; </code></pre>
23,400,204
Get facebook friends with Graph API v.2.0
<p>A while ago, I used to take the friends of mine using Graph API in this way (using Graph API Explorer):</p> <pre><code>/me/friends </code></pre> <p>Everything was perfect but now, with 2.0 version, I saw that this way does not function for friends who didn't use (via Facebook Login) the app making the request and, if I switch Graph API Explorer to 1.0 version, it functions.</p> <p>So, how can I do the same thing with the 2.0 version?</p>
23,416,859
1
16
null
2014-05-01 00:13:53.973 UTC
37
2014-09-06 16:29:20.713 UTC
2014-06-09 14:42:27.027 UTC
null
1,438,393
null
2,809,729
null
1
62
facebook|facebook-graph-api|facebook-friends|facebook-graph-api-v2.0
75,898
<p>In v2.0 of the API, <code>/me/friends</code> returns friends who also have logged into the app.</p> <p>Apps created on or after April 30th 2014 must use Graph API v2.0; they're not able to call Graph API v1.0.</p> <p>For apps which were active before April 30th, these apps can call either Graph API v2.0 or Graph API v1.0, but Graph API v1.0 will be deprecated on April 30th 2015.</p> <p>Note that if a user logs into an app via v2.0, and you call <code>/v1.0/me/friends</code>, this will still only return app-using friends.</p> <p>If you want to access non-app-using friends in the case where you want to let your users tag people in stories you publish to Facebook, you can use the <code>/me/taggable_friends</code> API.</p> <p>In the case where you want to invite people to use your app, Games can use the <code>/me/invitable_friends</code> endpoint in order to render a custom invite selector. The tokens returned by this API can then be used in the Requests Dialog. See <a href="https://developers.facebook.com/docs/games/invitable-friends/v2.0" rel="noreferrer">https://developers.facebook.com/docs/games/invitable-friends/v2.0</a> and <a href="https://developers.facebook.com/docs/games/requests/v2.0" rel="noreferrer">https://developers.facebook.com/docs/games/requests/v2.0</a></p> <p>For non-games wanting allow people to invite friends to use an app, you can still use the <a href="https://developers.facebook.com/docs/sharing/reference/send-dialog" rel="noreferrer">Send Dialog on Web</a> or the Message Dialog on <a href="https://developers.facebook.com/docs/ios/message-dialog/" rel="noreferrer">iOS</a> and <a href="https://developers.facebook.com/docs/android/message-dialog/" rel="noreferrer">Android</a></p>
20,344,378
Populate Combobox from a list
<p>Newb here, I'm currently working on a form which has a combo box, which will show several Charlie Brown TV specials which you can click on to select and see a description of, rating, runtime, etc. I'm close but I'm not there in terms of populating the combo box and i'm hoping for some help and guidance. I have looked at several things others have done but i'm not knowledgeable enough to deduce the answers from what i've been able to see so far.</p> <p>Right now i'm trying too: 1. get the listings from your load method 2. loop through them 3. Access my combo box to populate the box with the times from the listing.</p> <p>Form1.cs</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Globalization;//Used for Sting.ToUpperCase... using System.Threading; using System.Threading.Tasks;// Needed for Streaming... using System.IO;// Needed for Streaming... namespace a100___GUI___VideoStoreSelections { public partial class FormMovieLookUp : Form { private const String FILE_NAME = "txt_movieDescriptions.txt";//connect to text file in debug private List&lt;Listing&gt; films { get; set; } public FormMovieLookUp() { InitializeComponent(); } private void cmbMovieListingBox_SelectedIndexChanged(object sender, EventArgs e) { txtTitleBox.Text = cmbMovieListingBox.SelectedItem.ToString(); } //ToolBox -- my program specific tools public List&lt;Listing&gt; LoadListings()//load movie descriptions as list { StreamReader fileIn = new StreamReader(FILE_NAME); List&lt;Listing&gt; entries = new List&lt;Listing&gt;(); //loop through every line of the file while (!fileIn.EndOfStream) { String line = fileIn.ReadLine(); String[] pieces = line.Split(':'); if (pieces.Length &lt; 4) continue;//error handling - set to length of text items Listing myListing = new Listing(pieces[0], pieces[1], pieces[2], pieces[3]); entries.Add(myListing); } fileIn.Close(); return entries; } private void FormMovieLookUp_Load_1(object sender, EventArgs e) { films = LoadListings(); foreach (Listing film in films) { Console.WriteLine(film); cmbMovieListingBox.Items.Add(film.GetFilmTitle()); } } } } </code></pre> <p>Listing.CS</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace a100___GUI___VideoStoreSelections { public class Listing { private String filmTitle; private String description; private String filmRunTime; private String filmRating; public Listing(String filmTitle, String description, String filmRunTime, String filmRating) { this.filmTitle = filmTitle; this.description = description; this.filmRunTime = filmRunTime; this.filmRating = filmRating; } public String GetFilmTitle() { return filmTitle; } public String GetDescription() { return description; } public String GetFilmRunTime() { return filmRunTime; } public String GetFilmRating() { return filmRating; } } </code></pre> <p>}</p> <p>So this is what i'm trying to do to populate my combo box. Any help is thankfully received.</p>
20,344,636
7
2
null
2013-12-03 06:31:37.277 UTC
4
2021-11-08 12:39:29.49 UTC
2013-12-05 01:01:02.807 UTC
null
2,197,667
null
2,197,667
null
1
14
c#|list|class|combobox|populate
95,925
<p>I would hold <code>List&lt;Listing&gt;</code> at the class level so you can access it when a user clicks on it. I would also throw this on it's own thread and not directly in the Load event. If it's a long process you will hang the ui.</p> <pre><code>private List&lt;Listing&gt; films { get; set; } </code></pre> <p>Load</p> <pre><code>films = LoadListings(); foreach (Listing film in films) { cmbMovieListingBox.Items.Add(film.GetFilmTitle()); } </code></pre> <p>When the user selects the item</p> <pre><code>Listing film = films.Where(f =&gt; f.GetFilmTitle().Equals(cmbMovieListingBox.SelectedValue)).FistOrDefault(); if (film != null) { //do work } </code></pre>
19,929,295
Creating RadioGroup programmatically
<p>I'm getting an Error while working with the following code</p> <blockquote> <p>Error: The specified child already has a parent you must call removeView on the child's parent first</p> </blockquote> <p>Anyone please help me in resolving this Error:</p> <pre class="lang-java prettyprint-override"><code>RadioButton[] radiobutton = new RadioButton[5]; RadioGroup radiogroup = new RadioGroup(this); for (int i = 0; i &lt; 5; i++) { LinearLayout listmainLayout = (LinearLayout) findViewById(R.id.phonelist); // listmainLayout.setLayoutParams(new // ListView.LayoutParams(width, // height / 10)); listmainLayout.setGravity(Gravity.CENTER_VERTICAL); RelativeLayout mainlistLayout = new RelativeLayout(getApplicationContext()); LinearLayout.LayoutParams mainlistLayoutParams = new LinearLayout.LayoutParams( (int) (width * 0.85), LayoutParams.WRAP_CONTENT); mainlistLayout.setLayoutParams(mainlistLayoutParams); // mainlistLayout.setOrientation(LinearLayout.VERTICAL); mainlistLayout.setPadding((int) (0.03 * width), 0, 0, 0); LinearLayout.LayoutParams radiogroupparams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); radiogroup.setLayoutParams(radiogroupparams); radiobutton[i] = new RadioButton(this); radiobutton[i].setText(&quot; &quot; + ContactsActivity.phonetype.get(i) + &quot; &quot; + ContactsActivity.phone.get(i)); radiobutton[i].setId(i + 100); radiogroup.removeView(radiobutton[i]); radiogroup.addView(radiobutton[i]); mainlistLayout.addView(radiogroup); } </code></pre> <p>My logcat shows:</p> <pre><code>11-12 17:51:11.500: E/AndroidRuntime(3353): FATAL EXCEPTION: main 11-12 17:51:11.500: E/AndroidRuntime(3353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.contacts_appetite/com.example.contacts_appetite.ContactDetalisList}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.ActivityThread.access$600(ActivityThread.java:130) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.os.Handler.dispatchMessage(Handler.java:99) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.os.Looper.loop(Looper.java:137) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.ActivityThread.main(ActivityThread.java:4745) 11-12 17:51:11.500: E/AndroidRuntime(3353): at java.lang.reflect.Method.invokeNative(Native Method) 11-12 17:51:11.500: E/AndroidRuntime(3353): at java.lang.reflect.Method.invoke(Method.java:511) 11-12 17:51:11.500: E/AndroidRuntime(3353): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 11-12 17:51:11.500: E/AndroidRuntime(3353): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-12 17:51:11.500: E/AndroidRuntime(3353): at dalvik.system.NativeStart.main(Native Method) 11-12 17:51:11.500: E/AndroidRuntime(3353): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.view.ViewGroup.addViewInner(ViewGroup.java:3378) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.view.ViewGroup.addView(ViewGroup.java:3249) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.view.ViewGroup.addView(ViewGroup.java:3194) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.view.ViewGroup.addView(ViewGroup.java:3170) 11-12 17:51:11.500: E/AndroidRuntime(3353): at com.example.contacts_appetite.ContactDetalisList.getView(ContactDetalisList.java:139) 11-12 17:51:11.500: E/AndroidRuntime(3353): at com.example.contacts_appetite.ContactDetalisList.onCreate(ContactDetalisList.java:65) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.Activity.performCreate(Activity.java:5008) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 11-12 17:51:11.500: E/AndroidRuntime(3353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 11-12 17:51:11.500: E/AndroidRuntime(3353): ... 11 more </code></pre>
19,929,586
6
3
null
2013-11-12 12:33:21.46 UTC
8
2021-03-08 09:56:28.103 UTC
2021-03-08 09:56:28.103 UTC
null
10,553,536
null
2,902,777
null
1
34
android|android-view|android-radiobutton|android-radiogroup
56,876
<p>this <code>The specified child already has a parent. You must call removeView() on the child's parent first.</code> because you are adding child( radio group ) to the parent layout multiple times. </p> <p>try like this </p> <pre><code>private void createRadioButton() { final RadioButton[] rb = new RadioButton[5]; RadioGroup rg = new RadioGroup(this); //create the RadioGroup rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL for(int i=0; i&lt;5; i++){ rb[i] = new RadioButton(this); rb[i].setText(" " + ContactsActivity.phonetype.get(i) + " " + ContactsActivity.phone.get(i)); rb[i].setId(i + 100); rg.addView(rb[i]); } ll.addView(rg);//you add the whole RadioGroup to the layout } </code></pre>
27,636,373
How to make this arrow in CSS only?
<p>I'm building a wizard-like ordering process where I have this menu: <img src="https://i.stack.imgur.com/z5oaY.png" alt="menu"></p> <p>The active page is colored green (in this case, Model).</p> <p><strong>How does one make this arrow using only CSS?:</strong></p> <p><img src="https://i.stack.imgur.com/2Iu6o.png" alt="arrow"></p> <p>At the moment i'm achieving my goal by using several divs and images:</p> <pre><code>&lt;div class="menuItem"&gt; &lt;div&gt;&lt;/div&gt; &lt;!-- The left image --&gt; &lt;div&gt;Varianten&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;!-- The right image --&gt; &lt;/div&gt; </code></pre> <p>The left image: <img src="https://i.stack.imgur.com/cP7fR.png" alt="enter image description here"></p> <p>The right image:<img src="https://i.stack.imgur.com/6prAp.png" alt="enter image description here"></p> <p>I found a SO answer which does part of this: <a href="https://stackoverflow.com/questions/16180107/arrow-box-with-css">Arrow Box with CSS</a>, however i'm having trouble with the indent at the left.</p> <p>If you have a better idea about how to do this, please let me know!</p>
27,636,505
5
4
null
2014-12-24 11:41:39.06 UTC
10
2022-09-23 21:42:21.793 UTC
2017-05-23 12:26:31.28 UTC
null
-1
null
1,951,069
null
1
18
html|css|css-shapes
9,964
<p>If the space between the arrows does not need to be transparent (<em>it is solid color</em>) you can use the <code>:before</code> and <code>:after</code> to create the edges (<em>without new elements in DOM</em>)</p> <p>Basically, it creates rotated squares with the borders we want and places them accordingly</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#flowBoxes { margin:auto; padding:20px; min-width:700px; } #flowBoxes div { display:inline-block; position:relative; height:25px; line-height:25px; padding:0 20px; border:1px solid #ccc; margin-right:2px; background-color:white; } #flowBoxes div.right:after{ content:''; border-top:1px solid #ccc; border-right:1px solid #ccc; width:18px; height:18px; position:absolute; right:0; top:-1px; background-color:white; z-index:150; -webkit-transform: translate(10px,4px) rotate(45deg); -moz-transform: translate(10px,4px) rotate(45deg); -ms-transform: translate(10px,4px) rotate(45deg); -o-transform: translate(10px,4px) rotate(20deg); transform: translate(10px,4px) rotate(45deg); } #flowBoxes div.left:before{ content:''; border-top:1px solid #ccc; border-right:1px solid #ccc; width:18px; height:18px; position:absolute; left:0; top:-1px; background-color:white; z-index:50; -webkit-transform: translate(-10px,4px) rotate(45deg); -moz-transform: translate(-10px,4px) rotate(45deg); -ms-transform: translate(-10px,4px) rotate(45deg); -o-transform: translate(-10px,4px) rotate(20deg); transform: translate(-10px,4px) rotate(45deg); } #flowBoxes .active{ background-color:green; color:white; } #flowBoxes div.active:after{ background-color:green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="flowBoxes"&gt; &lt;div class="right"&gt;Diersoort / I&amp;amp;R&lt;/div&gt; &lt;div class="left right active"&gt;Model&lt;/div&gt; &lt;div class="left right"&gt;Varianten&lt;/div&gt; &lt;div class="left right"&gt;Bedrukkingen&lt;/div&gt; &lt;div class="left"&gt;Bevestiging&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
15,312,732
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
<p>The problem Im facing while trying to connect to database for mysql. I have also given the database settings that i have used.</p> <pre><code> Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line utility.execute() File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/arundhati/Desktop/test/testprac/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 8, in &lt;module&gt; from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/core/management/sql.py", line 9, in &lt;module&gt; from django.db import models File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/db/__init__.py", line 40, in &lt;module&gt; backend = load_backend(connection.settings_dict['ENGINE']) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/db/__init__.py", line 34, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/db/utils.py", line 93, in __getitem__ backend = load_backend(db['ENGINE']) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/db/utils.py", line 27, in load_backend return import_module('.base', backend_name) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 17, in &lt;module&gt; raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb </code></pre> <p>Databse Settings::</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ar_test_db', # Or path to database file if using # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } </code></pre> <p>Thanks a lot for the help !!</p>
15,312,750
27
0
null
2013-03-09 16:00:59.193 UTC
19
2022-04-16 07:02:38.77 UTC
2013-07-11 13:17:15.817 UTC
null
1,948,156
null
1,929,310
null
1
102
python|mysql|database|django
192,598
<p>It looks like you don't have the python mysql package installed, try:</p> <pre><code>pip install mysql-python </code></pre> <p>or if not using a virtual environment (on *nix hosts):</p> <pre><code>sudo pip install mysql-python </code></pre>
15,167,927
How do I log ALL exceptions globally for a C# MVC4 WebAPI app?
<h1>Background</h1> <p>I am developing an API Service Layer for a client and I have been requested to catch and log all errors globally.</p> <p>So, while something like an unknown endpoint (or action) is easily handled by using ELMAH or by adding something like this to the <code>Global.asax</code>:</p> <pre><code>protected void Application_Error() { Exception unhandledException = Server.GetLastError(); //do more stuff } </code></pre> <p>. . .unhandled errors that are not related to routing do not get logged. For example:</p> <pre><code>public class ReportController : ApiController { public int test() { var foo = Convert.ToInt32("a");//Will throw error but isn't logged!! return foo; } } </code></pre> <p>I have also tried setting the <code>[HandleError]</code> attribute globally by registering this filter:</p> <pre><code>filters.Add(new HandleErrorAttribute()); </code></pre> <p>But that also does not log all errors.</p> <h1>Problem/Question</h1> <p>How do I intercept errors like the one generated by calling <code>/test</code> above so that I can log them? It seems that this answer should be obvious, but I have tried everything I can think of so far. </p> <p>Ideally, I want to add some things to the error logging, such as the IP address of the requesting user, date, time, and so forth. I also want to be able to e-mail the support staff automatically when an error is encountered. All of this I can do if only I can intercept these errors when they happen!</p> <h1>RESOLVED!</h1> <p>Thanks to Darin Dimitrov, whose answer I accepted, I got this figured out. <em>WebAPI does <strong>not</strong> handle errors in the same way as a regular MVC controller.</em></p> <p>Here is what worked:</p> <p>1) Add a custom filter to your namespace:</p> <pre><code>public class ExceptionHandlingAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is BusinessException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(context.Exception.Message), ReasonPhrase = "Exception" }); } //Log Critical errors Debug.WriteLine(context.Exception); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An error occurred, please try again or contact the administrator."), ReasonPhrase = "Critical Exception" }); } } </code></pre> <p>2) Now register the filter globally in the <strong>WebApiConfig</strong> class:</p> <pre><code>public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }); config.Filters.Add(new ExceptionHandlingAttribute()); } } </code></pre> <p><strong>OR</strong> you can skip registration and just decorate a single controller with the <code>[ExceptionHandling]</code> attribute.</p>
15,168,120
5
5
null
2013-03-01 22:28:27.573 UTC
68
2018-05-19 12:45:50.793 UTC
2018-05-19 12:45:50.793 UTC
null
176,877
null
856,790
null
1
180
c#|asp.net-web-api|error-handling
85,452
<p><strike>If your web API is hosted inside an ASP.NET application, the <code>Application_Error</code> event will be called for all unhandled exceptions in your code, including the one in the test action you have shown. So all you have to do is handle this exception inside the Application_Error event. In the sample code you have shown you are only handling exception of type <code>HttpException</code> which is obviously not the case with the <code>Convert.ToInt32("a")</code> code. So make sure that you log and handle all exceptions in there:</p> <pre><code>protected void Application_Error() { Exception unhandledException = Server.GetLastError(); HttpException httpException = unhandledException as HttpException; if (httpException == null) { Exception innerException = unhandledException.InnerException; httpException = innerException as HttpException; } if (httpException != null) { int httpCode = httpException.GetHttpCode(); switch (httpCode) { case (int)HttpStatusCode.Unauthorized: Response.Redirect("/Http/Error401"); break; // TODO: don't forget that here you have many other status codes to test // and handle in addition to 401. } else { // It was not an HttpException. This will be executed for your test action. // Here you should log and handle this case. Use the unhandledException instance here } } } </code></pre> <p></strike></p> <p>Exception handling in the Web API could be done at various levels. Here's a <a href="http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx"><code>detailed article</code></a> explaining the different possibilities:</p> <ul> <li><p>custom exception filter attribute which could be registered as a global exception filter</p> <pre><code>[AttributeUsage(AttributeTargets.All)] public class ExceptionHandlingAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is BusinessException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(context.Exception.Message), ReasonPhrase = "Exception" }); } //Log Critical errors Debug.WriteLine(context.Exception); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An error occurred, please try again or contact the administrator."), ReasonPhrase = "Critical Exception" }); } } </code></pre></li> <li><p>custom action invoker</p> <pre><code>public class MyApiControllerActionInvoker : ApiControllerActionInvoker { public override Task&lt;HttpResponseMessage&gt; InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { var result = base.InvokeActionAsync(actionContext, cancellationToken); if (result.Exception != null &amp;&amp; result.Exception.GetBaseException() != null) { var baseException = result.Exception.GetBaseException(); if (baseException is BusinessException) { return Task.Run&lt;HttpResponseMessage&gt;(() =&gt; new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(baseException.Message), ReasonPhrase = "Error" }); } else { //Log critical error Debug.WriteLine(baseException); return Task.Run&lt;HttpResponseMessage&gt;(() =&gt; new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(baseException.Message), ReasonPhrase = "Critical Error" }); } } return result; } } </code></pre></li> </ul>
43,707,762
How to lazy load images and make them available for print
<p>Some websites have lots of images, so <strong>lazyloading</strong> seems appropiate to reduce load times and data consumption. But what if you also need to support <strong>printing</strong> for that website?</p> <p>I mean, you <em>can</em> try to detect the print event and then load the images, with something like this:</p> <h2>HTML</h2> <pre><code>&lt;img src=&quot;data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7&quot;&gt; </code></pre> <p><em>Note:</em> this is a one by one pixels gif dummy image.</p> <h2>JavaScript</h2> <pre><code>window.addEventListener('DOMContentLoaded', () =&gt; { img = document.querySelector('img'); var isPrinting = window.matchMedia('print'); isPrinting.addListener((media) =&gt; { if (media.matches) { img.src = 'http://unsplash.it/500/300/?image=705'; } }) }); </code></pre> <p><em>Note:</em> if you try this in a code playground, remove the <code>DOMContentLoaded</code> event (or simply fork these: <a href="https://jsfiddle.net/31yLp41p/" rel="noreferrer"><strong>JSFiddle</strong></a> | <a href="https://codepen.io/anon/pen/MmQgZq" rel="noreferrer"><strong>Codepen</strong></a>).</p> <p><em>Note:</em> I didn't event bother with the <code>onbeforeprint</code> and <code>onafterprint</code> for <a href="http://caniuse.com/#feat=beforeafterprint" rel="noreferrer"><strong>obvious reasons</strong></a>.</p> <p>This will work fine if the image is cached, but then again that's precisely <strong>not</strong> the point. The image/s should all load and then appear in the printing screen.</p> <p>Do you have any ideas? Has anyone successfully implemented a <strong>print-ready</strong> lazyloading plugin?</p> <h2>Update</h2> <p>I've tried <strong>redirecting</strong> the user after the print dialog is detected, to a flagged version of the website a.k.a <code>website.com?print=true</code> where lazyloading is deactivated and all images load normally.</p> <p>This method is improved by applying the <code>window.print()</code> method in this flagged print-ready version of the page, opening a new print dialog once all images are finished loading, and showing a <em>&quot;wait for it&quot;</em> message in the meantime at the top of the page.</p> <p><em>Important note:</em> this method was tested in Chrome, it does not work in Firefox nor Edge (hence why this is not an answer, but a testimony).</p> <p>It works in Chrome beacuse the print dialog closes when you redirect to another website (in this case same url but flagged). In Edge and Firefox the print dialog is an actual window and it does not close it, making it pretty unusable.</p>
43,768,465
5
6
null
2017-04-30 14:55:56.537 UTC
6
2022-06-09 17:53:23.267 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,750,762
null
1
29
javascript|html|image|printing|lazy-loading
8,331
<p>Based on your desired functionality, I'm not quite sure what you want to do is feasible. As a developer we don't really have control over a users browser. Here are my thoughts as to why this isn't fully possible.</p> <ol> <li><p>Hooking the event to go and load your missing images won't let you guarantee images will make it from the server into your page. More specifically, the PDF generated for your print preview is going to get generated before your image(s) is done loading, the <code>img.src = "..."</code> is asynchronous. You'd run into similar issues with <code>onbeforeprint</code> as well, unfortunately. Sometimes it works, sometimes it does not (example, your fiddle worked when testing in safari, but did not in Chrome)</p></li> <li><p>You cannot <a href="https://stackoverflow.com/q/6647392/1992129">stall or stop</a> the print call -- you can't force the browser to wait for your image to finish loading in the lazy loading context. (I read something about using alerts to achieve this once, but it seemed really hacky to me, was more of a deterrent to printing than stalling)</p></li> <li><p>You cannot force <code>img.src</code> to get that data synchronously in a lazy-load context. There are some methods of doing this, but they are <a href="https://stackoverflow.com/a/19973880/1992129">clever hacks -- referenced as pure evil</a> and may not work in always. I found <a href="https://stackoverflow.com/a/27131778/1992129">another link with a similar approach</a></p></li> </ol> <p>So we have a problem, if the images are not loaded by the time print event is fired, we cannot force the browser to wait until they are done. Sure, we can hook and go get those images on print, but as above points out, we cannot wait for those resources to load before the print preview pops up.</p> <h3>Potential solution (inspired by links in point three as well as <a href="https://stackoverflow.com/a/20048852/1992129">this link</a>)</h3> <p>You could almost get away with doing a synchronous XMLHttpRequest. Syncrhonous XMLHTTPRequests will not let you change the responseType, they are always strings. However, you could convert the string value to an arrayBuffer encode it to a base-64 encoded string, and set the src to a dataURL (see the link that referenced clever hacks) -- however, when I tried this I got an error in <a href="https://jsfiddle.net/31yLp41p/2/" rel="noreferrer">the jsfiddle</a> -- so it would be possible, if things were configured correctly, in theory. I'm hesitant to say yes you can, since I wasn't able to get the fiddle working with the following (but it's a route you could explore!).</p> <pre><code>var xhr = new XMLHttpRequest(); xhr.open("GET","http://unsplash.it/500/300/?image=705",false); xhr.send(null); if (request.status === 200) { //we cannot change the resposne type in synchronous XMLHTTPRequests //we can convert the string into a dataURL though var arr = new Uint8Array(this.response); // Convert the int array to a binary string // We have to use apply() as we are converting an *array* // and String.fromCharCode() takes one or more single values, not // an array. var raw = String.fromCharCode.apply(null,arr); // This is supported in modern browsers var b64=btoa(raw); var dataURL="data:image/jpeg;base64,"+b64; img.src = dataURL; } </code></pre> <h3>Work around to enhance the user experience</h3> <p>Something you could do is have some text that only displays in the print version of your page (via <code>@print</code> css media) that says "images are still loading, cancel your print request and try again" and when the images are finished loading, remove that "still waiting on resources try again message" from the DOM. Farther, you could wrap your main content inside an element that inverses the display to none when content is not loaded, so all you see is that message in the print preview dialog.</p> <p>Going off of the code you posted this could look something like the following (see updated <a href="https://jsfiddle.net/31yLp41p/1/" rel="noreferrer">jsfiddle</a>):</p> <p><strong>CSS</strong></p> <pre><code>.printing-not-ready-message{ display:none; } @media print{ .printing-not-ready-message{ display:block; } .do-not-print-content{ display:none; } } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div class="printing-not-ready-message"&gt; Images are still loading please cancel your preview and try again shortly. &lt;/div&gt; &lt;div class="do-not-print-content"&gt; &lt;h1&gt;Welcome to my Lazy Page&lt;/h1&gt; &lt;img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"&gt; &lt;p&gt;Insert some comment about picture&lt;/p&gt; &lt;/div&gt; </code></pre> <p><strong>JavaScript</strong></p> <pre><code>window.addEventListener('DOMContentLoaded', () =&gt; { img = document.querySelector('img'); var isPrinting = window.matchMedia('print'); isPrinting.addListener((media) =&gt; { if (media.matches) { img.src = 'http://unsplash.it/500/300/?image=705'; //depending on how the lazy loading is done, the following might //exist in some other call, should happen after all images are loaded. //There is only 1 image in this example so this code can be called here. img.onload = ()=&gt;{ document.querySelector(".printing-not-ready-message").remove(); document.querySelector(".do-not-print-content").className="" } } }) }); </code></pre>
7,861,886
how to get file properties?
<p>I want an application which displays the some file properties of a mediafile if available, like (don't know the exact english words used in windows for it) FileName, Length/Duration, FileType(.avi .mp3 etc.) I tried taglib and windowsapishell but I dont get a working result (references are good)</p> <pre><code>ShellFile so = ShellFile.FromFilePath(file); so.Properties.System.(everythingIwant) </code></pre> <p>shows me a lot of file properties which I want to have displayed, but I cant get it working An example of an error:</p> <p>'WindowsFormsApplication2.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. The program '[6300] WindowsFormsApplication2.vshost.exe: Program Trace' has exited with code 0 (0x0). The program '[6300] WindowsFormsApplication2.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).</p> <p>something easy like</p> <pre><code>var thing = so.Properties.System.FileName.Description; Console.WriteLine(thing); </code></pre> <p>wont work</p> <p>I do know some Java and PHP programming, but I'm totally new to C#</p> <hr> <p>Special thanks to @marr75 and @errorstacks !</p> <p>one follow up question: I made this, and it works</p> <pre><code>class Program { static void Main(string[] args) { string file = "E:/Dump/Shutter Island.avi"; FileInfo oFileInfo = new FileInfo(file); Console.WriteLine("My File's Name: \"" + oFileInfo.Name + "\""); DateTime dtCreationTime = oFileInfo.CreationTime; Console.WriteLine("Date and Time File Created: " + dtCreationTime.ToString()); Console.WriteLine("myFile Extension: " + oFileInfo.Extension); Console.WriteLine("myFile total Size: " + oFileInfo.Length.ToString()); Console.WriteLine("myFile filepath: " + oFileInfo.DirectoryName); Console.WriteLine("My File's Full Name: \"" + oFileInfo.FullName + "\""); } } </code></pre> <p>but I want it to only provide me with the info if the info exists. I saw the </p> <pre><code> **Exists** Gets a value indicating whether a file exists. (Overrides FileSystemInfo.Exists.) </code></pre> <p>But how do I use this function, I guess not like if(io.ofileinfo.FullName.exist) {Console.Write(io.ofileinfo.fullname);} ?</p>
7,861,915
2
4
null
2011-10-22 18:58:37.673 UTC
2
2020-01-28 13:17:23.707 UTC
2011-10-22 22:01:50.13 UTC
null
1,008,817
null
1,008,817
null
1
12
c#|taglib|windows-shell|windows-api-code-pack|getproperties
85,372
<p>When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property. Here is an sample code:</p> <pre><code>FileInfo oFileInfo = new FileInfo(strFilename); if (oFileInfo != null || oFileInfo.Length == 0) { MessageBox.Show("My File's Name: \"" + oFileInfo.Name + "\""); // For calculating the size of files it holds. MessageBox.Show("myFile total Size: " + oFileInfo.Length.ToString()); } </code></pre> <p>You can check like this:</p> <pre><code>if (!oFileInfo.Exists) { throw new FileNotFoundException("The file was not found.", FileName); } </code></pre> <p>To find out what those date and time values are, you can access the File System Information property using:</p> <pre><code>DateTime dtCreationTime = oFileInfo.CreationTime; MessageBox.Show("Date and Time File Created: " + dtCreationTime.ToString()); </code></pre> <p>To know the extension of the file, you can access the value of the FileSystemInfo.Extension property:</p> <pre><code>MessageBox.Show("myFile Extension: " + oFileInfo.Extension); </code></pre>
8,207,297
How to replace all double quotes to single quotes using jquery?
<p>I need to replace all double quotes to single quotes using jquery. </p> <p>How I will do that.</p> <p>I tested with this code but its not working properly.</p> <p><code>newTemp = newTemp.mystring.replace(/"/g, "'");</code></p>
8,207,316
2
0
null
2011-11-21 04:32:22.88 UTC
8
2021-01-01 16:24:40.357 UTC
2012-03-15 00:15:28.403 UTC
null
246,246
null
669,388
null
1
52
jquery|string|replace
124,022
<p>Use double quote to enclose the quote or escape it.</p> <pre><code>newTemp = mystring.replace(/"/g, "'"); </code></pre> <p>or</p> <pre><code>newTemp = mystring.replace(/"/g, '\''); </code></pre>
23,503,130
Visual Studio duplicating resource .cs file
<p>Visual Studio has begun exhibiting a rather irritating quirk. When I edit a resource file (using either the designer view or editing the XML directly), it creates a duplicate resource Designer.cs file, which causes the project to be unable to build.</p> <p>Example: Let's say my resource file is called ProjectSQL.resx. If you expand ProjectSQL.resx in the Solution Explorer, it shows ProjectSQL.Designer.cs. When I make an edit to one of the queries defined in ProjectSQL.resx, it saves fine, but creates another file called ProjectSQL1.Designer.cs.</p> <p>In that example, there's now two class files with the same class name, causing the build failure.</p> <p>Has anyone had this problem before? How did you fix it? I've tried closing the solution and reopening, as well as restarting Visual Studio. Using VS 2010 Premium on Windows 7 Ultimate for those interested.</p>
23,611,722
3
5
null
2014-05-06 19:18:04.32 UTC
6
2017-11-30 06:47:57.347 UTC
null
null
null
null
136,790
null
1
31
visual-studio-2010|resource-files
7,976
<p>In case this happens to anyone else and you find yourself here, Hans' comment above pointed me toward the project file. I had to close the solution, find the <code>LastGenOutput</code> tag in the project XML file, and change the name of the resource output back to ProjectSQL from ProjectSQL1.</p> <p>I still have no idea how this happened. But at least it's fixed now.</p>
8,981,164
self-deleting shell script
<p>I've looked around for an answer to this one but couldn't find one.</p> <p>I have written a simple script that does initial server settings and I'd like it to remove/unlink itself from the root directory on completion. I've tried a number of solutions i googled ( for example /bin/rm $test.sh) but the script always seems to remain in place. Is this possible? Below is my script so far.</p> <pre><code>#! /bin/bash cd /root/ wget -r -nH -np --cut-dirs=1 http://myhost.com/install/scripts/ rm -f index.html* *.gif */index.html* */*.gif robots.txt ls -al /root/ if [ -d /usr/local/psa ] then echo plesk &gt; /root/bin/INST_SERVER_TYPE.txt chmod 775 /root/bin/* /root/bin/setting_server_ve.sh rm -rf /root/etc | rm -rf /root/bin | rm -rf /root/log | rm -rf /root/old sed -i "75s/false/true/" /etc/permissions/jail.conf exit 1; elif [ -d /var/webmin ] then echo webmin &gt; /root/bin/INST_SERVER_TYPE.txt chmod 775 /root/bin/* /root/bin/setting_server_ve.sh rm -rf /root/etc | rm -rf /root/bin | rm -rf /root/log | rm -rf /root/old sed -i "67s/false/true/" /etc/permissions/jail.conf break exit 1; else echo no-gui &gt; /root/bin/INST_SERVER_TYPE.txt chmod 775 /root/bin/* /root/bin/setting_server_ve.sh rm -rf /root/etc | rm -rf /root/bin | rm -rf /root/log | rm -rf /root/old sed -i "67s/false/true/" /etc/permissions/jail.conf break exit 1; fi </code></pre>
8,981,233
7
4
null
2012-01-24 01:53:10.9 UTC
16
2022-05-30 16:40:10.623 UTC
2012-01-24 02:01:15.077 UTC
null
15,168
null
1,166,135
null
1
66
bash|shell
56,536
<pre><code>rm -- "$0" </code></pre> <p>Ought to do the trick. $0 is a magic variable for the full path of the executed script.</p>
5,558,118
Tabs in title bar: what's the secret?
<p>Chrome and Firefox 4, among other applications, now put some of their user interface in the title bar. In Windows, the OS normally controls the entire title bar. An application can create a custom title bar by removing the OS title bar and drawing a "fake" title bar instead (like WinAmp), but only the OS knows how to draw the non-customized elements of the title bar (e.g. Close/Minimize/Maximize), which vary by OS version.</p> <p>By what mechanism do apps like Chrome and Firefox "share" the title bar with the OS (put custom elements in the title bar while keeping the original OS visual theme)?</p> <p><img src="https://i.stack.imgur.com/bDNXW.png" alt="enter image description here"></p> <p><em>In Chrome, the tabs encroach upon the title bar so that there is not enough space for title text.</em></p>
5,587,680
4
8
null
2011-04-05 20:29:32.45 UTC
20
2014-04-04 09:38:26.55 UTC
2011-04-05 21:17:43.983 UTC
null
22,820
null
22,820
null
1
38
windows|user-interface|titlebar|custom-titlebar
11,606
<p>Microsoft has a very detailed explanation in the article <a href="http://msdn.microsoft.com/en-us/library/bb688195(v=vs.85).aspx" rel="noreferrer">Custom Window Frame Using DWM</a>.</p>
5,517,924
pip install PyQt IOError
<p>I'm trying to install PyQt package with pip, but I get this error:</p> <pre><code>~$ pip install PyQt Downloading/unpacking PyQt Downloading PyQt-x11-gpl-4.8.3.tar.gz (9.8Mb): 9.8Mb downloaded Running setup.py egg_info for package PyQt Traceback (most recent call last): File "&lt;string&gt;", line 14, in &lt;module&gt; IOError: [Errno 2] No such file or directory: '/home/john/build/PyQt/setup.py' Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 14, in &lt;module&gt; IOError: [Errno 2] No such file or directory: '/home/john/build/PyQt/setup.py ---------------------------------------- Command python setup.py egg_info failed with error code 1 Storing complete log in /home/john/.pip/pip.log </code></pre>
5,518,386
5
1
null
2011-04-01 19:28:04.143 UTC
5
2022-04-09 09:00:16.34 UTC
2012-10-02 20:51:29.413 UTC
null
15,931
null
688,172
null
1
31
python|pyqt|pip|ioerror|setup.py
16,267
<p>That's because that file has a <code>configure.py</code> not a <code>setup.py</code>. configure.py generate a make file that you use to build pyqt against the qt lib you choose by passing --qmake option to configure.py, it has different options too. I suggest filing a bug with the pip maintainer. </p>
4,898,837
How to find last merge in git?
<p>For a web site, I have master and staging, I have worked on staging for about 10 days. How do I tell for sure what has changed since my last merge, or when that merge was? Most of the merges I have done end up being FFs so I can't log them like <code>git merge branch -m 'merging staging'</code> (git reports it ignored -m). I usually merge master into staging for testing before merging staging into master for more testing and deployment.</p> <p>I could tag each one but I'm worried about the clutter of doing that for merges. What I'd like to know is "roughly, what changed since my last merge of staging into master?" Then I could make sure I spent extra time investigating those changes in the final examination. Sometimes co-workers make changes I hadn't noticed until this stage.</p> <p>I suppose since staging->into->master merges are rare, I could tag them and then do a "git whatchanged tag" but I'm hoping there is a non-tag way to do it. Thanks.</p>
4,898,869
7
6
null
2011-02-04 14:05:17.37 UTC
7
2020-01-09 20:34:00.943 UTC
null
null
null
null
289,004
null
1
30
git
26,575
<p>Try this, it will select the last branch where the commit message starts with "Merge": </p> <pre><code>git show :/^Merge </code></pre> <p><a href="http://mislav.uniqpath.com/2010/07/git-tips/" rel="noreferrer">Here</a>'s a website with a few git tips that might help you out.</p>
5,333,490
How can we restore ppc/ppc64 as well as full 10.4/10.5 SDK support to Xcode 4?
<p>Since Apple only ships SDK 10.6 with Xcode4, developing PPC applications with Xcode4 became impossible. While it is possible to develop applications with Xcode4 that can also run on 10.5 and maybe even on 10.4 systems (by selecting SDK 10.6, but deployment target 10.5 or 10.4), they will only run on Intel Macs because you need at least SDK 10.5 for building PPC applications.</p> <p>Further there are some rare cases, where you really need to build against an SDK prior to 10.6 for full platform support, e.g. if certain deprecated functionality has vanished completely from the 10.6 SDK, but you'll have to use it and dynamic linking is not always the best option in those cases. Also linking against an earlier SDK sometimes will ease development as functionality you are not supposed to use, as it would cause incompatibility to earlier OS versions, won't be available and any attempt to use it anyhow immediately leads to compiler or linker errors.</p> <p>Last but not least Apple has also removed GCC 4.0 support from Xcode4, which may be necessary for certain software to build correctly and Apple has never allowed to compile software with GCC 4.2 when using SDK 10.4, even though I hardly believe that this would really cause any issues, after all software built with GCC 4.2 and SDK 10.6 can also run on Mac OS 10.4 without any issues as long as the deployment target has been set correctly and no functionality that is unavailable under MacOS 10.4 has been used.</p> <p>Of course you can always have a parallel installation of Xcode3 next to Xcode4, but that means you must forgo all the (great?) new features of Xcode4 and keep working with the outdated Xcode3 IDE. It would certainly be much better if you could also manage all your old projects within the same IDE as your new ones and benefit from any new features available. Not all projects can be made 10.6 or Intel only in the foreseeable future. Further I'm strictly against abolishing support for older platforms earlier than would be really necessary.</p> <p><strong>Can we restore this functionality to Xcode4?</strong></p>
5,333,500
8
0
null
2011-03-17 00:37:44.587 UTC
78
2014-10-26 20:48:04.913 UTC
2011-03-17 12:14:41.613 UTC
null
15,809
null
15,809
null
1
94
xcode|xcode4|universal-binary|osx-leopard|powerpc
37,506
<p>The quick answer is: <strong>Yes, we can!</strong></p> <p>Before I get to the "<em>how it is done</em>" part, here are some notes about my patch/hack/fix. Right from the start the major goals have been:</p> <ol> <li><p>Keep all modifications to an absolute minimum.<br> We want to keep the Xcode setups as original as possible.</p></li> <li><p>By all means, try to avoid patching or modifying any files.<br> We want all files to stay untouched and keep their original content.</p></li> <li><p>Try to avoid moving or copying files around, unless absolutely necessary.</p></li> </ol> <p>I was able to keep all those goals. Almost everything is done by creating symlinks. Only a single existing symlink had to be replaced and we'll back it up before replacement, just in case.</p> <p>If you are no expert on terminal operations, I strongly advise you to copy/paste all terminal commands from my reply to your terminal, to avoid typos. Bear in mind that even spacing, quoting and especially capitalization can be important. Copy/paste them line by line, never more than one line at once and hit return after each pasted line to execute the command. Should any operation ever prompt you for a password, this will be the password of the currently logged in administrator user (your keystrokes are not displayed while typing, this is normal, don't worry, just keep typing the password and hit return; re-try if you had a typo and get prompted again).</p> <h2>Prerequisite</h2> <p>Before we can start, make sure the following conditions are true:</p> <ul> <li>You are logged in as an administrator user.</li> <li>You have started Terminal.app (Applications/Utilities) and a terminal window is open.</li> <li>You have a copy of the Xcode3 (e.g. 3.2.5) and Xcode4 disk image (DMG) or installer available.</li> <li>If you already have either Xcode version installed, <a href="http://macdevelopertips.com/xcode/how-to-uninstall-xcode.html">consider uninstalling it first</a>, so you can start with a fresh/clean setup. Uninstalling Xcode will not remove your preferences, color scheme or key binding customizations. Ideally you'd start with a system that has no Xcode version (neither 3 nor 4) currently installed.</li> </ul> <h2>Step 1: Installing Xcode3</h2> <p><strong>Important</strong>: Do not install "<em>System Tools</em>" or "<em>Unix Development</em>" package of Xcode3.<br> Whether you want to install "<em>Mac OS X 10.4 SDK</em>" and/or "<em>Documentation</em>" is up to you. If that is a Xcode3 with iOS SDKs, whether you install those or not is also up to you.</p> <p>You are free to choose any destination folder for your installation. For this guide I have chosen "<em>/Xcode3</em>", but feel free to pick a different one. Just make sure to alter all terminal commands accordingly.</p> <p>The order of the steps given here is usually not really important, but I strongly advise you to not swap step 1 and step 2. Xcode always installs a couple of files outside of the chosen destination folder and trust me, in the end you want the Xcode4 versions of those files on your disk. By installing Xcode3 before Xcode4, you can be sure that Xcode4 will overwrite those files if necessary. I once swapped steps 1 and 2 and in the end I had some rather strange issues that might have been related to the incorrect order (I cannot say for sure, but after re-installing in the correct order the issues were gone).</p> <h2>Step 2: Installing Xcode4</h2> <p>Chose any packets you like. Installing "<em>System Tools</em>" is advisable, but not strictly necessary (though most people will sooner or later miss that functionality).</p> <p>Again, feel free to pick any target folder you like. For this guide I chose the normal target folder "<em>/Developer</em>", if you take a different one, alter all terminal commands accordingly.</p> <h2>Step 3: Restoring 10.4/10.5 SDK Support</h2> <p>Switch to your terminal window and run the following commands:</p> <pre>cd /Developer/SDKs sudo ln -s /Xcode3/SDKs/MacOSX10.4u.sdk . sudo ln -s /Xcode3/SDKs/MacOSX10.5.sdk .</pre> <p>Of course only run the command for 10.4u if you also installed SDK 10.4 in step 1.</p> <p>This is enough to bring the SDKs 10.5 (and possibly 10.4) back to the selection list in Xcode4. Give it a try if you like. Fire up Xcode4, open a project, try changing the selected SDK. That was easy, huh? Be sure to close Xcode4 again (the application, not just the window) before proceeding with the next step.</p> <h2>Step 4: Restoring GCC 4.0 Support</h2> <p>If you have not installed MacOS 10.4 SDK or if you don't plan to ever use it, you can safely skip this step and proceed with step 5.</p> <p>To use SDK 10.4, you'll have to use GCC 4.0, GCC 4.2 won't work. Apple claims that GCC 4.2 is not compatible with SDK 10.4, well, if you ask me, this is a hoax. I have already overwritten this limitations more than once and there was never the tiniest issue because of it. It would be easy to modify SDK 10.4 so that Xcode will allow you to use GCC 4.2 for it, but my goal was to avoid all file modifications, so we just add GCC 4.0 support back to Xcode, which is also a good thing, because some projects really depend on GCC 4.0 (e.g. there are some bugs in GCC 4.2 that prevent valid inline assembly code to compile without errors, while the same code compiles flawlessly on GCC 4.0 and GCC 4.4).</p> <p>Back to terminal:</p> <pre>cd /Developer/usr/bin sudo ln -s /Xcode3/usr/bin/*4.0* . cd /Developer/usr/libexec/gcc/powerpc-apple-darwin10 sudo ln -s /Xcode3/usr/libexec/gcc/powerpc-apple-darwin10/4.0.1 .</pre> <p>Right now we have restored full GCC 4.0 support except for the fact that GCC 4.0 is still not selectable in Xcode4. That is because Xcode4 has no GCC 4.0 compiler plug-in any longer. Fortunately the Xcode3 plug-in also works in Xcode4, only the position has radically changed. Apple now hides those plug-ins deep within a bundle and only plug-ins there seem to work, placing them to their old position seems to have no effect.</p> <pre>cd /Developer/Library/Xcode/PrivatePlugIns cd Xcode3Core.ideplugin/Contents/SharedSupport/Developer/Library/Xcode/Plug-ins sudo ln -s "/Xcode3/Library/Xcode/Plug-ins/GCC 4.0.xcplugin" .</pre> <p>Now fire up Xcode4 again, open a project and try selecting the compiler. You should have GCC 4.0 back on the list. Now you can actually already select SDK 10.4 or 10.5, GCC 4.0 and you should have no issue to build a PPC binary. Just select "<em>Other...</em>" for the "<em>Architecture</em>" build setting and manually enter "<em>ppc</em>", then alter "<em>Valid Architectures</em>" to also include "<em>ppc</em>". We are almost done, except that trying to build a PPC binary using GCC 4.2 and SDK 10.5 will still fail.</p> <h2>Step 5: Restoring PPC Support for GCC 4.2</h2> <p>Since Apple is only supporting Intel platforms in Xcode4, not all GCC 4.2 tools have been built with PPC support. There is one important tool that has no PPC support, the tool is named "<em>as</em>" and it is the GNU Assembler. To compile ppc/ppc64 binaries with GCC 4.2 we need to use an "<em>as</em>" version with ppc/ppc64 support. This is the one and only file (actually it also a symlink) we have to first move aside (making a backup copy) before we can replace it by a symlink:</p> <pre>cd /Developer/usr/libexec/gcc/powerpc-apple-darwin10/4.2.1 sudo mv as as.bak sudo ln -s /Xcode3/usr/bin/as .</pre> <h2>Step 6: There is No Step 6</h2> <p>That's all folks. Considering how easy that was, you can imagine that Apple has certainly not dropped SDK 10.4/10.5 or ppc/ppc64 or GCC 4.0 support because this was a necessity, they dropped all that because they wanted to drop it.</p> <p>I hope this setup works as well for you as it does for me. I have been able to compile all my old projects in Xcode4 without any major changes, except for having to alter a search path here and there.</p> <p>PS:<br> It may look strange that I answer my own question here, but since I have found out how to solve this problem all by myself, I'd like to share my knowledge with the community, because I believe this is really valuable input to all MacOS developers out there. This question has been asked so many times in so many places and so far I have never seen anyone coming up with a similar fix. Share the wealth, spread the knowledge and so on, you know what I mean.</p> <h1><br>If You Still Have Issues/Questions:</h1> <p>If you have additional questions regarding this topic or if you still have problems to build your old projects correctly, please do what Stack Overflow has been designed for: Click on "Ask Question" in the upper right corner of this page and create a new question. That way the whole community can help you solving those issues, since the issues may not directly (maybe not even indirectly) be related to this hack. </p> <p>I would recommend you mention the fact that you did apply this hack at the very beginning of your question. Maybe you even want to directly link to this question, so that people, who never heard of this hack, can easily look it up. Otherwise most people will get rather confused when you mention SDK 10.4/10.5, PPC or GCC 4.0 in combination with Xcode4, which officially supports neither of these. You might get rather stupid comments instead of decent replies if you forget to mention this hack.</p> <p>Please refrain from posting your questions or issues here either as replies or as comments. Posting them as replies makes no sense because they are no replies and there is no way how people can reply back to you, other then using comments, and comments may not offer enough room for a decent reply to your question or a decent solution to your problem. And posting them as comments means you are limited to very little room and tracking reply comments will be hard as comments have no tree-like hierarchy (further they will still offer to little room for decent replies/solutions). Thank you.</p> <p>Of course other kind of comments as well as better replies to the original question are always welcome ;-)</p>
5,155,952
sorting a List of Map<String, String>
<p>I have a list variable created like this: </p> <p><code>List&lt;Map&lt;String, String&gt;&gt; list = new ArrayList&lt;Map&lt;String, String&gt;&gt;();</code></p> <p>In my Android application, this list gets populated.</p> <p>just an example:</p> <pre><code>Map&lt;String, String&gt; map1 = new HashMap&lt;String, String&gt;(); map.put("name", "Josh"); ... Map&lt;String, String&gt; map2 = new HashMap&lt;String, String&gt;(); map.put("name", "Anna"); ... Map&lt;String, String&gt; map3 = new HashMap&lt;String, String&gt;(); map.put("name", "Bernie"); ... list.add(map1); list.add(map2); list.add(map3); </code></pre> <p>I am using <code>list</code> to show results in a <code>ListView</code> by extending <code>BaseAdapter</code> and implementing the various methods.</p> <p>My problem: I need to sort <code>list</code> in alphabetical order based on the map's key <strong>name</strong></p> <p>Question: What is a simple way to sort <code>list</code> in alphabetical order based on the map's key <strong>name</strong>?</p> <p>I can't seem to wrap my head around this. I have extracted each <strong>name</strong> from each <code>Map</code> into a <code>String</code> array, and sorted it(<code>Arrays.sort(strArray);</code>). But that doesn't preserve the other data in each <code>Map</code>, so i'm not too sure how i can preserve the other mapped values</p>
5,156,015
9
5
null
2011-03-01 14:39:09.143 UTC
7
2020-11-24 08:48:01.743 UTC
null
null
null
null
416,412
null
1
28
java|android|sorting
119,921
<p>The following code works perfectly</p> <pre><code>public Comparator&lt;Map&lt;String, String&gt;&gt; mapComparator = new Comparator&lt;Map&lt;String, String&gt;&gt;() { public int compare(Map&lt;String, String&gt; m1, Map&lt;String, String&gt; m2) { return m1.get("name").compareTo(m2.get("name")); } } Collections.sort(list, mapComparator); </code></pre> <p>But your maps should probably be instances of a specific class.</p>
5,038,891
Center UIPickerView Text
<p>So I have a uipickerview with rows that only contain the number 0-24 and it looks a bit silly since the numbers are left aligned leaving a huge gap on the right of the pickerview.</p> <p>Is there an easy way to center align text in a uipickerview?</p>
5,038,994
9
2
null
2011-02-18 07:59:43.877 UTC
6
2020-03-30 15:40:23.7 UTC
null
null
null
null
482,255
null
1
38
iphone|iphone-sdk-3.0|uipickerview
26,961
<pre><code>- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)]; label.text = [NSString stringWithFormat:@"something here"]; label.textAlignment = NSTextAlignmentCenter; //Changed to NS as UI is deprecated. label.backgroundColor = [UIColor clearColor]; [label autorelease]; return label; } </code></pre> <p>or something like this.</p>
4,950,956
How would you look at developing an algorithm for this hotel problem?
<p>There is a problem I am working on for a programming course and I am having trouble developing an algorithm to suit the problem. Here it is:</p> <blockquote> <p>You are going on a long trip. You start on the road at mile post 0. Along the way there are n hotels, at mile posts a1 &lt; a2 &lt; ... &lt; an, where each ai is measured from the starting point. The only places you are allowed to stop are at these hotels, but you can choose which of the hotels you stop at. You must stop at the final hotel (at distance an), which is your destination. You'd ideally like to travel 200 miles a day, but this may not be possible (depending on the spacing of the hotels). If you travel x miles during a day, the penalty for that day is (200 - x)^2. You want to plan your trip so as to minimize the total penalty that is, the sum, over all travel days, of the daily penalties. Give an efficient algorithm that determines the optimal sequence of hotels at which to stop.</p> </blockquote> <p>So, my intuition tells me to start from the back, checking penalty values, then somehow match them going back the forward direction (resulting in an O(n^2) runtime, which is optimal enough for the situation).</p> <p>Anyone see any possible way to make this idea work out or have any ideas on possible implmentations?</p>
4,951,253
11
5
null
2011-02-09 21:53:02.167 UTC
12
2021-05-17 14:57:47.273 UTC
2021-05-17 14:57:47.273 UTC
null
2,840,103
null
610,683
null
1
20
algorithm|dynamic-programming
23,091
<p>If <code>x</code> is a marker number, <code>ax</code> is the mileage to that marker, and <code>px</code> is the minimum penalty to get to that marker, you can calculate <code>pn</code> for marker <code>n</code> if you know <code>pm</code> for all markers <code>m</code> before <code>n</code>.</p> <p>To calculate <code>pn</code>, find the minimum of <code>pm + (200 - (an - am))^2</code> for all markers <code>m</code> where <code>am &lt; an</code> and <code>(200 - (an - am))^2</code> is less than your current best for <code>pn</code> (last part is optimization).</p> <p>For the starting marker <code>0</code>, <code>a0 = 0</code> and <code>p0 = 0</code>, for marker <code>1</code>, <code>p1 = (200 - a1)^2</code>. With that starting information you can calculate <code>p2</code>, then <code>p3</code> etc. up to <code>pn</code>.</p> <p><strong>edit</strong>: Switched to Java code, using the example from OP's comment. Note that this does not have the optimization check described in second paragraph.</p> <pre><code>public static void printPath(int path[], int i) { if (i == 0) return; printPath(path, path[i]); System.out.print(i + " "); } public static void main(String args[]) { int hotelList[] = {0, 200, 400, 600, 601}; int penalties[] = {0, (int)Math.pow(200 - hotelList[1], 2), -1, -1, -1}; int path[] = {0, 0, -1, -1, -1}; for (int i = 2; i &lt;= hotelList.length - 1; i++) { for(int j = 0; j &lt; i; j++){ int tempPen = (int)(penalties[j] + Math.pow(200 - (hotelList[i] - hotelList[j]), 2)); if(penalties[i] == -1 || tempPen &lt; penalties[i]){ penalties[i] = tempPen; path[i] = j; } } } for (int i = 1; i &lt; hotelList.length; i++) { System.out.print("Hotel: " + hotelList[i] + ", penalty: " + penalties[i] + ", path: "); printPath(path, i); System.out.println(); } } </code></pre> <p>Output is:</p> <pre><code>Hotel: 200, penalty: 0, path: 1 Hotel: 400, penalty: 0, path: 1 2 Hotel: 600, penalty: 0, path: 1 2 3 Hotel: 601, penalty: 1, path: 1 2 4 </code></pre>
4,969,233
How to check if enum value is valid?
<p>I am reading an <code>enum</code> value from a binary file and would like to check if the value is really part of the <code>enum</code> values. How can I do it?</p> <pre><code>#include &lt;iostream&gt; enum Abc { A = 4, B = 8, C = 12 }; int main() { int v1 = 4; Abc v2 = static_cast&lt; Abc &gt;( v1 ); switch ( v2 ) { case A: std::cout&lt;&lt;"A"&lt;&lt;std::endl; break; case B: std::cout&lt;&lt;"B"&lt;&lt;std::endl; break; case C: std::cout&lt;&lt;"C"&lt;&lt;std::endl; break; default : std::cout&lt;&lt;"no match found"&lt;&lt;std::endl; } } </code></pre> <p>Do I have to use the <code>switch</code> operator or is there a better way?</p> <p><strong>EDIT</strong></p> <p>I have enum values set and unfortunately I can not modify them. To make things worse, they are not continuous (their values goes 0, 75,76,80,85,90,95,100, etc.)</p>
4,969,304
11
1
null
2011-02-11 12:55:51.353 UTC
6
2022-09-14 14:01:26.857 UTC
2013-04-05 22:54:40.283 UTC
null
1,438,397
null
476,681
null
1
57
c++|enums
109,200
<p><code>enum</code> value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of <code>enum X { A = 1, B = 3 }</code>, the value of <code>2</code> is considered a valid enum value.</p> <p>Consider 7.2/6 of standard:</p> <blockquote> For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax. It is possible to define an enumeration that has values not defined by any of its enumerators. </blockquote> <p>There is no retrospection in C++. One approach to take is to list enum values in an array additionally and write a wrapper that would do conversion and possibly throw an exception on failure.</p> <p>See <a href="https://stackoverflow.com/questions/4165439/generic-way-to-cast-int-to-enum-in-c">Similar Question</a> about how to cast int to enum for further details.</p>
5,377,521
Jquery Timeline plugins
<p>I am in search for jquery timeline plugin with years on the horizontal axis.</p> <p>I have seen one in the past. I am not able to find it. Did search for jquery timeline plugins.</p>
5,378,043
12
2
null
2011-03-21 12:24:05.407 UTC
11
2013-12-28 08:07:30.827 UTC
2011-11-13 23:12:06.503 UTC
null
5,640
null
613,141
null
1
12
javascript|jquery|jquery-plugins|timeline
41,446
<p>Here are 2 that I had stored in my bookmarks. They aren't jquery plugins, but they could be adapted to be jquery plugins. <a href="http://meyerweb.com/eric/thoughts/2008/01/21/structured-timeline/" rel="noreferrer">Eric Meyer's structured timeline</a> and <a href="http://www.simile-widgets.org/timeplot/?" rel="noreferrer">timeplot</a>. I also found this service called <a href="http://tiki-toki.com/" rel="noreferrer">Tiki-Toki</a> which offers timelines as a web service. </p> <p>Or you could just use something like <a href="http://highcharts.com/" rel="noreferrer">HighCharts</a> if that will work for your situation.</p>
5,164,930
Fatal error: Maximum execution time of 30 seconds exceeded
<p>I am downloading a JSON file from an online source and and when it runs through the loop I am getting this error:</p> <blockquote> <p>Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\temp\fetch.php on line 24</p> </blockquote>
5,164,954
17
2
null
2011-03-02 08:11:45.66 UTC
99
2022-04-29 09:58:40.8 UTC
2015-05-05 16:16:32.387 UTC
null
2,257,664
null
155,196
null
1
455
php|json
992,325
<p>Your loop might be endless. If it is not, you could extend the maximum execution time like this:</p> <pre><code>ini_set('max_execution_time', '300'); //300 seconds = 5 minutes</code></pre> <p>and</p> <pre><code>set_time_limit(300); </code></pre> <p>can be used to temporarily extend the time limit.</p>
5,133,516
Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?
<p>I'm trying to compile my excel addin using C# 4.0, and started to get this problem when building my project in Visual Studio. It's important to tell you that I haven't had this problem before. What could cause this to happen?</p>
5,238,737
27
6
null
2011-02-27 13:39:32.91 UTC
32
2020-01-27 08:08:50.48 UTC
2011-03-08 21:06:00.747 UTC
null
64,348
null
520,535
null
1
272
c#|visual-studio|.net-4.0
130,205
<p>My guess is that you're not working with strongly named assemblies. I've had this error when two projects reference slightly different versions of the same assembly and a more dependent project references these projects. The resolution in my case was to remove the key and version information from the assembly name in the .csproj files (it didn't matter anyway), and then do a clean build.</p> <p>Changes between the different assembly versions were compatible with the parts of the solution referring to them. If this is not the case with you, you might have to do some more work to resolve the issue.</p> <h2>NuGet</h2> <p>With NuGet it's easy to get into this situation if:</p> <ol> <li>You install a package to one project in your solution.</li> <li>A new version of that package is deployed to the package source.</li> <li>You install it to another project in the same solution.</li> </ol> <p>This results in two projects in your solution referencing different versions of that package's assemblies. If one of them references the other and is a ClickOnce app, you'll see this problem.</p> <p>To fix this, issue the <code>update-package [package name]</code> command at the Nuget Package Manager Console to bring everything up to a level playing field, at which point the problem goes away.</p> <p>You should manage NuGet packages at the solution level rather than at the project level unless there is a compelling reason not to. Solution level package management avoids the potential of multiple versions of dependencies. When using the management UI, if the <strong>Consolidated</strong> tab shows 1 or more packages have multiple versions, consider consolidating them to one.</p>
12,567,410
I need best practice in T-SQL Export data to CSV (with header)
<p><strong>What I need to do is export data into CSV file using T-SQL.</strong></p> <p>And I'm very confused about there are many ways can do it, I don't know to choose which one, please help me to confirm the bollowing:</p> <p>As I know there are about 3 methods, and I want you help me to confirm:</p> <h2>Using Microsoft.Jet.OLEDB.4.0, like this:</h2> <pre><code>INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Text;Database=C:\Temp\;HDR=Yes;', 'SELECT * FROM test.csv') (object_id, name) SELECT object_id, name FROM sys.tables; </code></pre> <p><strong>but this need the csv file is there, and with header</strong></p> <h2>using SQLCMD</h2> <p>command line. </p> <h2>using BCP</h2> <p>Use union, get data and it's column header. </p> <p>This is all my understanding about T-SQL export to CSV, please help me to confirm.</p> <p>Is there other way to export to CSV? </p> <p>Thanks!</p>
12,568,093
5
1
null
2012-09-24 14:45:39.99 UTC
2
2019-03-06 09:48:50.557 UTC
2016-01-22 08:48:36.04 UTC
null
1,419,175
null
1,583,460
null
1
9
sql|tsql|csv|sqlcmd|sql-agent-job
42,644
<p>You could use a UNION to create a header row, like this:</p> <pre><code>SELECT 'object_id', 'name' UNION ALL SELECT object_id, name FROM sys.tables </code></pre>
12,190,874
Pandas: Sampling a DataFrame
<p>I'm trying to read a fairly large CSV file with Pandas and split it up into two random chunks, one of which being 10% of the data and the other being 90%.</p> <p>Here's my current attempt:</p> <pre><code>rows = data.index row_count = len(rows) random.shuffle(list(rows)) data.reindex(rows) training_data = data[row_count // 10:] testing_data = data[:row_count // 10] </code></pre> <p>For some reason, <code>sklearn</code> throws this error when I try to use one of these resulting DataFrame objects inside of a SVM classifier:</p> <pre><code>IndexError: each subindex must be either a slice, an integer, Ellipsis, or newaxis </code></pre> <p>I think I'm doing it wrong. Is there a better way to do this?</p>
12,192,021
5
1
null
2012-08-30 06:12:46.203 UTC
30
2016-04-26 15:52:39.28 UTC
null
null
null
null
464,744
null
1
69
python|partitioning|pandas
80,397
<p>What version of pandas are you using? For me your code works fine (i`m on git master).</p> <p>Another approach could be:</p> <pre><code>In [117]: import pandas In [118]: import random In [119]: df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD')) In [120]: rows = random.sample(df.index, 10) In [121]: df_10 = df.ix[rows] In [122]: df_90 = df.drop(rows) </code></pre> <p>Newer version (from 0.16.1 on) supports this directly: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html</a></p>
19,070,290
pyaudio - "Listen" until voice is detected and then record to a .wav file
<p>I'm having some problems and I cannot seem to get my head around the concept.</p> <p>What I am trying to do is this:</p> <p>Have the microphone "listen" for voiced (above a particular threshold) and then start recording to a .wav file until the person has stopped speaking / the signal is no longer there. For example:</p> <pre><code>begin: listen() -&gt; nothing is being said listen() -&gt; nothing is being said listen() -&gt; VOICED - _BEGIN RECORDING_ listen() -&gt; VOICED - _BEGIN RECORDING_ listen() -&gt; UNVOICED - _END RECORDING_ end </code></pre> <p>I want to do this also using "threading" so a thread would be created that "listens" to the file constantly, and, another thread will begin when there is voiced data.. But, I cannot for the life of me figure out how I should go about it.. Here is my code so far:</p> <pre><code>import wave import sys import threading from array import array from sys import byteorder try: import pyaudio CHECK_PYLIB = True except ImportError: CHECK_PYLIB = False class Audio: _chunk = 0.0 _format = 0.0 _channels = 0.0 _rate = 0.0 record_for = 0.0 stream = None p = None sample_width = None THRESHOLD = 500 # initial constructor to accept params def __init__(self, chunk, format, channels, rate): #### set data-types self._chunk = chunk self.format = pyaudio.paInt16, self.channels = channels self.rate = rate self.p = pyaudio.PyAudio(); def open(self): # print "opened" self.stream = self.p.open(format=pyaudio.paInt16, channels=2, rate=44100, input=True, frames_per_buffer=1024); return True def record(self): # create a new instance/thread to record the sound threading.Thread(target=self.listen).start(); def is_silence(snd_data): return max(snd_data) &lt; THRESHOLD def listen(self): r = array('h') while True: snd_data = array('h', self.stream.read(self._chunk)) if byteorder == 'big': snd_data.byteswap() r.extend(snd_data) return sample_width, r </code></pre> <p>I'm guessing that I could record "5" second blocks, and, then if the block is deemed as "voiced" then it the thread should be started until all the voice data has been captured. However, because at current it's at <code>while True:</code> i don't want to capture all of the audio up until there are voiced commands, so e.g. "no voice", "no voice", "voice", "voice", "no voice", "no voice" i just want the "voice" inside the wav file.. Anyone have any suggestions?</p> <p>Thank you</p> <p>EDIT:</p> <pre><code>import wave import sys import time import threading from array import array from sys import byteorder from Queue import Queue, Full import pyaudio CHUNK_SIZE = 1024 MIN_VOLUME = 500 BUF_MAX_SIZE = 1024 * 10 process_g = 0 def main(): stopped = threading.Event() q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK_SIZE))) listen_t = threading.Thread(target=listen, args=(stopped, q)) listen_t.start() process_g = threading.Thread(target=process, args=(stopped, q)) process_g.start() try: while True: listen_t.join(0.1) process_g.join(0.1) except KeyboardInterrupt: stopped.set() listen_t.join() process_g.join() def process(stopped, q): while True: if stopped.wait(timeout = 0): break print "I'm processing.." time.sleep(300) def listen(stopped, q): stream = pyaudio.PyAudio().open( format = pyaudio.paInt16, channels = 2, rate = 44100, input = True, frames_per_buffer = 1024 ) while True: if stopped and stopped.wait(timeout=0): break try: print process_g for i in range(0, int(44100 / 1024 * 5)): data_chunk = array('h', stream.read(CHUNK_SIZE)) vol = max(data_chunk) if(vol &gt;= MIN_VOLUME): print "WORDS.." else: print "Nothing.." except Full: pass if __name__ == '__main__': main() </code></pre> <p>Now, after every 5 seconds, I need the "process" function to execute, and then process the data (time.delay(10) whilst it does this and then start the recording back up.. </p>
20,132,455
2
6
null
2013-09-28 18:28:19.43 UTC
8
2019-10-05 08:42:11.35 UTC
2013-09-29 16:32:12.82 UTC
null
1,326,876
null
1,326,876
null
1
3
python|multithreading|audio|pyaudio
25,275
<p>Look here:</p> <p><a href="https://github.com/jeysonmc/python-google-speech-scripts/blob/master/stt_google.py" rel="noreferrer">https://github.com/jeysonmc/python-google-speech-scripts/blob/master/stt_google.py</a></p> <p>It even converts Wav to flac and sends it to the google Speech api , just delete the stt_google_wav function if you dont need it ;)</p>
3,236,194
Defining "method_called".. How do I make a hook method which gets called every time any function of a class gets called?
<p>I want to make a hook method which gets called everytime any function of a class gets called. I have tried method_added, but it executes only once at the time of class definition,</p> <pre><code>class Base def self.method_added(name) p "#{name.to_s.capitalize} Method's been called!!" end def a p "a called." end def b p "b called." end end t1 = Base.new t1.a t1.b t1.a t1.b Output: "A Method's been called!!" "B Method's been called!!" "a called." "b called." "a called." "b called." </code></pre> <p>but my requirement is that any function of a class that gets called anywhere in the program triggers the "method_called", hook method.</p> <pre><code>Expected Output: "A Method's been called!!" "a called." "B Method's been called!!" "b called." "A Method's been called!!" "a called." "B Method's been called!!" "b called." </code></pre> <p>If there is any defined existing hook method that works just the same, then please tell about it.</p> <p>Thanks in advance..</p>
3,236,342
3
2
null
2010-07-13 10:26:38.99 UTC
12
2014-01-26 14:14:16.61 UTC
2010-07-13 11:11:55.067 UTC
null
63,034
null
362,271
null
1
13
ruby|metaprogramming|hook
6,521
<p>Take a look at <a href="http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-set_trace_func" rel="noreferrer"><code>Kernel#set_trace_func</code></a>. It lets you specify a proc which is invoked whenever an event (such as a method call) occurs. Here's an example:</p> <pre><code>class Base def a puts "in method a" end def b puts "in method b" end end set_trace_func proc { |event, file, line, id, binding, classname| # only interested in events of type 'call' (Ruby method calls) # see the docs for set_trace_func for other supported event types puts "#{classname} #{id} called" if event == 'call' } b = Base.new b.a b.b </code></pre> <p>Outputs:</p> <pre><code>Base a called in method a Base b called in method b </code></pre>
3,601,106
How to terminate a program in Perl - exit or die?
<p>I am using syntax checking to see whether my Perl script is being used in the correct way. If the syntax is not correct, I display a message saying what the correct syntax is, and then end the execution of the program.</p> <p>Between:</p> <pre><code>print "Please use the following syntax: ..."; exit 1; </code></pre> <p>and:</p> <pre><code>die("Please use the following syntax: ..."); </code></pre> <p>Which one should I use? I know <code>die</code> would have been the answer if exception handling was in place, but that is not the case.</p> <p>Which one is the better choice for program termination without exception handling? Please also say why.</p>
3,601,259
3
1
null
2010-08-30 14:10:12.523 UTC
5
2017-08-11 19:20:17.15 UTC
2017-08-11 19:20:17.15 UTC
null
3,474,146
null
113,124
null
1
32
perl
86,836
<p>It depends on what you want to have happen with STDERR and STDOUT. I prefer to send error and warning type messages to STDERR so that when someone is trying to redirect output to a file they still see the error messages; However, there are times though when STDOUT is used to communicate status to the user so he or she can <code>tail -f</code> or paginate it, and at those times writing to STDERR causes them pain (they have to redirect STDERR back into STDOUT with <code>2&gt;&amp;1</code>, and not everyone knows how to do that). So which to use, <code>die</code> or <code>print</code> and <code>exit</code>, depends heavily on what type of program you are writing.</p> <p>There are other benefits/drawbacks to using <code>die</code>:</p> <ul> <li>You can trap <code>die</code> with an <code>eval</code>, but not exit</li> <li>You can run code when the program calls <code>die</code> by installing a signal handler for the <code>__DIE__</code> signal</li> <li>You can easily override the <code>die</code> function</li> </ul> <p>Each of those has times where it is handy to be able to do them, and times when it is a pain that they can be done.</p>
3,339,798
What does contentOffset do in a UIScrollView?
<p>What is the use of the <code>contentOffset</code> property in <code>UIScrollView</code>?</p>
3,339,830
3
0
null
2010-07-26 23:47:27.55 UTC
15
2019-11-09 18:48:54.513 UTC
2014-05-16 02:33:29.763 UTC
user3404653
null
null
375,786
null
1
67
iphone|uiscrollview
47,143
<p>According to the <strong><a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html" rel="noreferrer">documentation</a></strong>, the <code>contentOffset</code> property represents:</p> <blockquote> <p>The point at which the origin of the content view is offset from the origin of the scroll view.</p> </blockquote> <p>In plain speak, it's how far the view has moved in each direction (vertical and horizontal). You can unpack vertical and horizontal distance by accessing the <code>x</code> and <code>y</code> properties of the <code>CGPoint</code>:</p> <pre><code>CGFloat xOffset = _myScrollView.contentOffset.x; CGFloat yOffset = _myScrollView.contentOffset.y; </code></pre>
11,262,817
Learn about android internals(dive deep into the system)
<p>Ok, guys, I think that's the right place to ask a question, because it's all about development(if I'm wrong or it's duplicate question, please tell me).</p> <p>So, I want to <strong>dive deep in Android</strong>, understand how system works down to the kernel(and also learn what's behind rooting and other hacking stuff). Where should I go from here? Linux book? VM architecture?</p> <p>Just downloading the source code didn't help as I don't understand how <em>all that</em> works.</p>
11,263,032
3
5
null
2012-06-29 13:36:08.88 UTC
11
2015-09-20 06:52:04.023 UTC
null
null
null
user468311
null
null
1
15
android|linux|architecture|systems-programming
12,793
<blockquote> <p>Where should I go from here?</p> </blockquote> <p>There are two books on Android internals that I am aware of:</p> <ul> <li><p>One, <a href="https://rads.stackoverflow.com/amzn/click/com/1119951380" rel="noreferrer" rel="nofollow noreferrer">XDA Developers' Android Hacker's Toolkit</a>, is getting lousy reviews, but that may be because it does not cover much ground beyond what's found on XDA itself. However, if you're not super-familiar with the subject, it may still be worthwhile.</p></li> <li><p>The other, <a href="https://rads.stackoverflow.com/amzn/click/com/1449308295" rel="noreferrer" rel="nofollow noreferrer">Embedded Android: Porting, Extending, and Customizing</a>, was supposed to be out in July, but it looks like the publication date got pushed out to August. I think that there is an early-access edition on the O'Reilly site for purchase.</p></li> </ul> <p>Marakana's <a href="http://marakana.com/techtv/about.html" rel="noreferrer">TechTV</a> series includes a number of videos (e.g., conference presentations) on firmware mods. They, and a couple of other firms, also offer training on the subject.</p> <p>You are certainly welcome to poke around <a href="http://www.xda-developers.com/" rel="noreferrer">XDA</a> and its forum posts on firmware mods, but it's definitely more of a community site than a reference guide to the subject.</p> <p>Beyond that, learning how the Linux OS works (kernel, drivers, etc.) would certainly help, as Android is based on that stuff.</p>
11,351,183
How to get XML tag value in Python
<p>I have some XML in a unicode-string variable in Python as follows:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;results preview='0'&gt; &lt;meta&gt; &lt;fieldOrder&gt; &lt;field&gt;count&lt;/field&gt; &lt;/fieldOrder&gt; &lt;/meta&gt; &lt;result offset='0'&gt; &lt;field k='count'&gt; &lt;value&gt;&lt;text&gt;6&lt;/text&gt;&lt;/value&gt; &lt;/field&gt; &lt;/result&gt; &lt;/results&gt; </code></pre> <p>How do I extract the <code>6</code> in <code>&lt;value&gt;&lt;text&gt;6&lt;/text&gt;&lt;/value&gt;</code> using Python?</p>
11,351,312
2
2
null
2012-07-05 19:25:34.39 UTC
2
2016-12-06 10:38:40.803 UTC
null
null
null
null
608,259
null
1
20
python|xml|parsing|dom|xml-parsing
61,739
<p><a href="http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html" rel="noreferrer">BeautifulSoup</a> is the most simple way to parse XML as far as I know...</p> <p>And assume that you have read the introduction, then just simply use:</p> <pre><code>soup = BeautifulSoup('your_XML_string') print soup.find('text').string </code></pre>
11,441,084
Makefile with multiples rules sharing same recipe
<p>I'd like to know if it's possible to write a Makefile with several rules, each one defining its own prerequisites and executing all of them the same recipe without duplicating the recipe. Example:</p> <pre><code>TARGETS= file1 file2 file3 all: $(TARGETS) file1: dep1 dep2 file2: dep2 dep3 dep4 file3: dep2 dep1 cat $^ &gt; $@ </code></pre> <p>Thanks!</p>
11,441,134
1
0
null
2012-07-11 20:37:29.09 UTC
14
2014-07-22 08:49:49.623 UTC
2012-07-11 21:55:33.777 UTC
null
545,027
null
548,825
null
1
41
makefile|rules
22,237
<p>Yes, it is written in a rather obvious way:</p> <pre><code>TARGETS= file1 file2 file3 all: $(TARGETS) file1: dep1 dep2 file2: dep2 dep3 dep4 file3: dep2 dep1 $(TARGETS): cat $^ &gt; $@ </code></pre> <h2>UPD.</h2> <p>Just to clarify.</p> <p>Generic <a href="http://www.gnu.org/software/make/manual/make.html#Rule-Syntax">make rule</a> looks like this:</p> <pre><code>targets... : prerequisites... recipe ... </code></pre> <p>Any part of the rule can be omitted. Without the recipe, one can populate the list of prerequisites anywhere in the makefile, a target can occur in the left hand side of multiple rule statements.</p> <p>For example, the following is equivalent to the example above (well, assuming that the Makefile is properly designed so that the order of prerequisites does not matter):</p> <pre><code>file1 file3 : dep1 file1 file2 file3 : dep2 file2 : dep3 dep4 </code></pre> <p>Unlike listing prerequisites, there can be at most one explicit recipe for each target. Inside the recipe you can use <a href="http://www.gnu.org/software/make/manual/make.html#Automatic-Variables">automatic variables</a> to get the target name, the list of prerequisites, etc.</p> <h2>UPD. 2</h2> <p>As @Calmarius mentions in comments this doesn't apply to <a href="http://www.gnu.org/software/make/manual/make.html#Pattern-Rules">pattern rules</a>, like <code>%.txt: %.foo</code>. Multiple patterns within targets mean that the rule produces all these targets <strong>at once</strong>.</p> <blockquote> <p>This pattern rule has two targets:</p> <pre><code>%.tab.c %.tab.h: %.y bison -d $&lt; </code></pre> <p>This tells make that the recipe <code>bison -d x.y</code> will make both <code>x.tab.c</code> and <code>x.tab.h</code>. If the file foo depends on the files <code>parse.tab.o</code> and <code>scan.o</code> and the file scan.o depends on the file <code>parse.tab.h</code>, when <code>parse.y</code> is changed, the recipe <code>bison -d parse.y</code> will be executed only once, and the prerequisites of both <code>parse.tab.o</code> and <code>scan.o</code> will be satisfied.</p> </blockquote> <p>One may define multiple prerequisites in a pattern rule though (that is, provided that its targets contain a <code>%</code> stem, otherwise it would be a regular rule).</p>
10,903,077
Calling a Fragment method from a parent Activity
<p>I see in the <a href="http://developer.android.com/guide/topics/fundamentals/fragments.html" rel="noreferrer">Android Fragments Dev Guide</a> that an "activity can call methods in a fragment by acquiring a reference to the Fragment from FragmentManager, using <code>findFragmentById()</code> or <code>findFragmentByTag()</code>."</p> <p>The example that follows shows how to get a fragment reference, but not how to call specific methods in the fragment.</p> <p>Can anyone give an example of how to do this? I would like to call a specific method in a Fragment from the parent Activity. Thanks.</p>
10,903,140
14
0
null
2012-06-05 18:47:52.37 UTC
35
2022-09-21 06:33:32.433 UTC
2014-11-26 06:28:35.32 UTC
null
1,318,946
null
1,322,527
null
1
134
android|android-fragments
204,449
<p>not get the question exactly as it is too simple :</p> <pre><code>ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); fragment.&lt;specific_function_name&gt;(); </code></pre>
12,706,463
How can I find the current language in a Laravel view?
<p>I'm using the Laravel Lang class for localization of my web app. I've added two languages to the languages array in <code>application/config/application.php</code>. This changes the default language it uses for localization to whatever the first part of the URI indicates (e.g. bla.com/en/bla and bla.com/co/bla). Now I need to be able to check what the current default language is in my view. However, the Lang class provides no way of checking this as far as I've been able to figure out, as the <code>Lang::$language</code> variable is protected. Is there any way of checking this apart from manually parsing the URI?</p>
13,495,416
11
0
null
2012-10-03 10:20:34.25 UTC
4
2020-06-18 05:16:40.47 UTC
null
null
null
null
941,158
null
1
20
localization|laravel
63,462
<p>BenjaminRH's answer is very good, and his suggested approach works perfectly. I've improved the snippet a bit. Now it detects the browser language and checks if that language is supported according to the application's config file.</p> <p>It's a quick hack, but it works on my app. Note that the application language is also set now. Feel free to use ore improve it.</p> <pre class="lang-php prettyprint-override"><code>Route::filter('before', function() { // current uri language ($lang_uri) $lang_uri = URI::segment(1); // Set default session language if none is set if(!Session::has('language')) { // use lang in uri, if provided if(in_array($lang_uri, Config::get('application.languages'))) { $lang = $lang_uri; } // detect browser language elseif(isset(Request::server('http_accept_language'))) { $headerlang = substr(Request::server('http_accept_language'), 0, 2); if(in_array($headerlang, Config::get('application.languages'))) { // browser lang is supported, use it $lang = $headerlang; } // use default application lang else { $lang = Config::get('application.language'); } } // no lang in uri nor in browser. use default else { // use default application lang $lang = Config::get('application.language'); } // set application language for that user Session::put('language', $lang); Config::set('application.language', $lang); } // session is available else { // set application to session lang Config::set('application.language', Session::get('language')); } // prefix is missing? add it if(!in_array($lang_uri, Config::get('application.languages'))) { return Redirect::to(URI::current()); } // a valid prefix is there, but not the correct lang? change app lang elseif(in_array($lang_uri, Config::get('application.languages')) AND $lang_uri != Config::get('application.language')) { Session::put('language', $lang_uri); Config::set('application.language', $lang_uri); } }); </code></pre>
12,721,864
"binary was not built with debug information " warning meaning in mfc application?
<p>I am getting the following <strong>Warning</strong> when i run my Windows Application(MFC) in Windows 7.</p> <p><code>'XXX.exe': Loaded 'C:\2010\Debug\bin\plugins\control\libhotkeys_plugin.dll', Binary was not built with debug information.</code></p> <p>Please Help Me out.Thank You</p>
12,722,176
5
1
null
2012-10-04 06:58:49.917 UTC
10
2020-10-13 10:16:04.13 UTC
2013-08-02 07:39:33.153 UTC
null
1,710,877
null
1,710,877
null
1
26
windows|visual-studio-2010|visual-c++|mfc|media-player
30,353
<p>It seems that your binary was build in Release mode</p> <p>Now there are two ways which you can follow....</p> <ul> <li>build the binary with "Debug" configuration</li> <li><p>change the project settings so that a Program Database file (PDB) is generated in the release mode.</p> <p>Now you can generate PDB from the property window...</p></li> </ul> <p><img src="https://i.stack.imgur.com/Al6Oi.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/lOdL1.png" alt="enter image description here"></p>
12,938,067
How clear gdb command screen?
<p>Is it possible to clear the command window of gdb? I mean, is there a command in gdb that do the same (for the command windows) as the <code>clear</code> command in a bash terminal?</p>
12,938,086
2
0
null
2012-10-17 15:41:12.193 UTC
10
2015-06-09 00:13:42.017 UTC
2012-10-17 20:32:19.457 UTC
null
275,567
null
973,795
null
1
56
c++|c|gcc|gdb|binutils
25,831
<p>Hit <code>Control + L</code>. Works for me in Linux and Mac OS X as well with recent versions of GDB.</p>
12,972,434
restart mysql server on windows 7
<p>How do I restart MySQL on Windows 7? </p> <p>I'm using HeidiSql as a front end and there's no option in there.</p> <p>The only other things I have is the MySQL 5.5 command line client.</p>
12,972,467
9
0
null
2012-10-19 10:33:24.367 UTC
12
2021-03-16 13:46:47.123 UTC
2015-12-09 10:01:28.497 UTC
null
1,245,190
null
407,503
null
1
66
mysql|windows
147,038
<p>Open the command prompt and enter the following commands:</p> <pre><code>net stop MySQL net start MySQL </code></pre> <p>the MySQL service name maybe changes based on the version you installed. In my situation, MySQL version is MySQL Server 5.7. So I use the following command </p> <pre><code>net stop MySQL57 net start MySQL57 </code></pre>
17,080,018
Use and Access Existing SQLite Database on iOS
<p>I have a fully populated database in SQLite that I'd like to use in my new app. It's rather large, so I'd like to avoid changing it to another format if possible. How can I use this database in such a way that it ships with my app?</p> <p>EDIT: If I just drop the file into my Supported Files directory, for example, how can I access it? How do I reference it?</p>
17,268,032
5
4
null
2013-06-13 05:47:34.377 UTC
16
2021-10-29 15:27:46.76 UTC
2018-07-09 09:45:56.103 UTC
null
3,350,628
null
386,869
null
1
18
ios|objective-c|swift|sqlite
25,276
<p>SQLite database interaction can be made simple and clean by using <code>FMDB Framework</code>. FMDB is an Objective-C wrapper for the SQLite C interface.</p> <p>Reference worth reading:</p> <p><a href="https://github.com/ccgus/fmdb" rel="nofollow noreferrer">FMDB Framework Docs</a></p> <p><a href="https://www.dropbox.com/s/1weu3wq2qn70dt8/FMDB-Demo-Storyboard.zip" rel="nofollow noreferrer"><strong>Sample Project With Storyboard</strong></a></p> <h2>Initial Setup</h2> <p>Add the <code>SQLite DB</code> like any other file in your application's bundle then copy the database to documents directory using the following code then <strong>use the database from the documents directory</strong></p> <ol> <li>First download the <a href="https://github.com/ccgus/fmdb" rel="nofollow noreferrer">FMDB framework</a></li> <li>Extract the framework now copy all the file from <code>src/fmdb</code> folder (not the <code>src/sample</code> or <code>src/extra</code> folders).</li> <li>Click your project in the left column of Xcode.</li> <li>Click the main target in the middle column.</li> <li>Click the “Build Phases” tab.</li> <li>Expand the arrow next to “Link Binary With Libraries”.</li> <li>Click the “+” button.</li> <li>Search for libsqlite3.0.dylib and double click it.</li> </ol> <p><strong>Copying your <code>existing database</code> into <code>app's document</code> in <code>didFinishLaunchingWithOptions:</code> and maintain the database path through out the application.</strong></p> <p>In your AppDelegate add the following code.</p> <p><strong>AppDelegate.m</strong></p> <pre><code>#import &quot;AppDelegate.h&quot; @implementation AppDelegate // Application Start - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Function called to create a copy of the database if needed. [self createCopyOfDatabaseIfNeeded]; return YES; } #pragma mark - Defined Functions // Function to Create a writable copy of the bundled default database in the application Documents directory. - (void)createCopyOfDatabaseIfNeeded { // First, test for existence. BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // Database filename can have extension db/sqlite. NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@&quot;database-name.sqlite&quot;]; success = [fileManager fileExistsAtPath:appDBPath]; if (success) { return; } // The writable database does not exist, so copy the default to the appropriate location. NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@&quot;database-name.sqlite&quot;]; success = [fileManager copyItemAtPath:defaultDBPath toPath:appDBPath error:&amp;error]; NSAssert(success, @&quot;Failed to create writable database file with message '%@'.&quot;, [error localizedDescription]); } </code></pre> <p><strong>YourViewController.m</strong></p> <h2>Select Query</h2> <pre><code>#import &quot;FMDatabase.h&quot; - (void)getAllData { // Getting the database path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@&quot;database-name.sqlite&quot;]; FMDatabase *database = [FMDatabase databaseWithPath:dbPath]; [database open]; NSString *sqlSelectQuery = @&quot;SELECT * FROM tablename&quot;; // Query result FMResultSet *resultsWithNameLocation = [database executeQuery:sqlSelectQuery]; while([resultsWithNameLocation next]) { NSString *strID = [NSString stringWithFormat:@&quot;%d&quot;,[resultsWithNameLocation intForColumn:@&quot;ID&quot;]]; NSString *strName = [NSString stringWithFormat:@&quot;%@&quot;,[resultsWithNameLocation stringForColumn:@&quot;Name&quot;]]; NSString *strLoc = [NSString stringWithFormat:@&quot;%@&quot;,[resultsWithNameLocation stringForColumn:@&quot;Location&quot;]]; // loading your data into the array, dictionaries. NSLog(@&quot;ID = %d, Name = %@, Location = %@&quot;,strID, strName, strLoc); } [database close]; } </code></pre> <h2>Insert Query</h2> <pre><code>#import &quot;FMDatabase.h&quot; - (void)insertData { // Getting the database path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@&quot;database-name.sqlite&quot;]; FMDatabase *database = [FMDatabase databaseWithPath:dbPath]; [database open]; NSString *insertQuery = [NSString stringWithFormat:@&quot;INSERT INTO user VALUES ('%@', %d)&quot;, @&quot;Jobin Kurian&quot;, 25]; [database executeUpdate:insertQuery]; [database close]; } </code></pre> <h2>Update Query</h2> <pre><code>- (void)updateDate { // Getting the database path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@&quot;fmdb-sample.sqlite&quot;]; FMDatabase *database = [FMDatabase databaseWithPath:dbPath]; [database open]; NSString *insertQuery = [NSString stringWithFormat:@&quot;UPDATE users SET age = '%@' WHERE username = '%@'&quot;, @&quot;23&quot;, @&quot;colin&quot; ]; [database executeUpdate:insertQuery]; [database close]; } </code></pre> <h2>Delete Query</h2> <pre><code>#import &quot;FMDatabase.h&quot; - (void)deleteData { // Getting the database path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@&quot;database-name.sqlite&quot;]; FMDatabase *database = [FMDatabase databaseWithPath:dbPath]; [database open]; NSString *deleteQuery = @&quot;DELETE FROM user WHERE age = 25&quot;; [database executeUpdate:deleteQuery]; [database close]; } </code></pre> <h2>Addition Functionality</h2> <p><strong>Getting the row count</strong></p> <p>Make sure to include the <code>FMDatabaseAdditions.h</code> file to use <code>intForQuery:</code>.</p> <pre><code>#import &quot;FMDatabase.h&quot; #import &quot;FMDatabaseAdditions.h&quot; - (void)gettingRowCount { // Getting the database path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@&quot;database-name.sqlite&quot;]; FMDatabase *database = [FMDatabase databaseWithPath:dbPath]; [database open]; NSUInteger count = [database intForQuery:@&quot;SELECT COUNT(field_name) FROM table_name&quot;]; [database close]; } </code></pre>
17,020,393
ASP.NET MVC 4, Migrations - How to run 'update-database' on a production server
<p>I can use package manager to run 'update-database -verbose' locally.</p> <p>Probably a stupid question but I can't find it online - once my website is deployed - how can I run this manually on the server?</p> <p>Secondarily - what other strategies would you recommend for deploying database migrations to production - and how would they be preferable?</p> <p>Thanks</p>
17,024,918
7
2
null
2013-06-10 09:10:32.937 UTC
12
2016-11-09 12:49:33.123 UTC
null
null
null
null
2,254,951
null
1
30
asp.net-mvc|entity-framework|asp.net-mvc-4|entity-framework-5|entity-framework-migrations
29,790
<p>You have a couple of options:</p> <ul> <li>You could use <code>update-database -script</code> to generate the SQL commands to update the database on the server</li> <li>You could use the <a href="https://stackoverflow.com/questions/9705241/what-is-the-correct-format-for-running-entity-framework-migrate-exe-tool-without">migrate.exe</a> executable file that resides in the package folder on <code>/packages/EntityFramework5.0.0/tools/migrate.exe</code>. I've used it successfully in the past with Jet Brains' Team City Build Server to setup the migrations with my deploy scripts.</li> <li>If you're using IIS Web Deploy you can tell the server to perform the migrations after publish (see pic below)</li> <li>You could setup automatic migrations, but I prefer to be in control of when things happen :)</li> </ul> <p><strong>Update:</strong> Also, check out <a href="http://sedodream.com/2012/08/06/PlansRegardingWebsiteProjectsAndWebDeploymentProjects.aspx" rel="noreferrer">Sayed Ibrahim's blog</a>, he works on the MsBuild Team at Microsoft and has some great insights on deployments </p> <p><img src="https://i.stack.imgur.com/1p4gN.png" alt="enter image description here"></p>
16,932,825
Why can't non-default arguments follow default arguments?
<p>Why does this piece of code throw a SyntaxError?</p> <pre><code>&gt;&gt;&gt; def fun1(a=&quot;who is you&quot;, b=&quot;True&quot;, x, y): ... print a,b,x,y ... File &quot;&lt;stdin&gt;&quot;, line 1 SyntaxError: non-default argument follows default argument </code></pre> <p>While the following piece of code runs without visible errors:</p> <pre><code>&gt;&gt;&gt; def fun1(x, y, a=&quot;who is you&quot;, b=&quot;True&quot;): ... print a,b,x,y ... </code></pre>
16,933,624
4
2
null
2013-06-05 06:17:41.527 UTC
64
2022-05-09 20:28:42.48 UTC
2022-05-09 20:28:42.48 UTC
null
4,518,341
null
2,268,849
null
1
169
python
205,090
<p>All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be <em>impossible</em> for the interpreter to decide which values match which arguments if mixed modes were allowed. A <code>SyntaxError</code> is raised if the arguments are not given in the correct order:</p> <p>Let us take a look at keyword arguments, using your function.</p> <pre><code>def fun1(a="who is you", b="True", x, y): ... print a,b,x,y </code></pre> <p>Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:</p> <pre><code>func1("ok a", "ok b", 1) # Is 1 assigned to x or ? func1(1) # Is 1 assigned to a or ? func1(1, 2) # ? </code></pre> <p>How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.</p> <pre><code>&gt;&gt;&gt; def fun1(x, y, a="who is you", b="True"): ... print a,b,x,y ... </code></pre> <p><em>Reference O'Reilly - Core-Python</em><br> Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.</p>
4,606,207
Using datetime to compare with dates in Django
<p>I have a question in Django on how you can compare dates to solve some solutions. For example I have a datefield in my models.py Like below.</p> <pre><code>class Invoice(models.Model): payment_date = models.DateTimeField() </code></pre> <p>What I want to be able to do is ask if the is a way to compare a datetime.now with a DateTimeField. For example, if I had a list of payment dates and I wanted to compare with datetime now. Thhe payment_date's that are late with their payments are shown in owing. Otherwise, it the value is zero.</p> <p>Here is my views to show whats going on. I have tried so far but I get a 0 value for payment_date's which are later than the payment date.</p> <p>Edit here is my latest views. Funny thing is that I seem to be getting the owing = invoice_gross for all results - unlike before when I was getting all 0s. So it is still not working properly.</p> <pre><code>@login_required def homepage(request): invoices_list = Invoice.objects.all() invoice_name = invoices_list[0].client_contract_number.client_number.name invoice_gross = invoices_list[0].invoice_gross payment_date = invoices_list[0].payment_date if payment_date &lt;= datetime.now(): owing = invoice_gross if payment_date &gt; datetime.now(): owing = 0 return render_to_response(('index.html', locals()), {'invoices_list': invoices_list ,'invoice_name':invoice_name, 'invoice_gross':invoice_gross,'payment_date':payment_date,'owing':owing}, context_instance=RequestContext(request)) </code></pre> <p>Oh and my table is basically doing something like this.</p> <pre><code>ID Owing 1 100 (All the same value) 2 100 3 100 . . . . . . </code></pre>
4,606,277
2
0
null
2011-01-05 16:03:35.097 UTC
6
2011-01-06 16:03:07.417 UTC
2011-01-06 16:03:07.417 UTC
null
512,002
null
512,002
null
1
11
django|datetime|views|models|datefield
47,918
<p>I think the problem is in the line</p> <pre><code>if datetime.now() == payment_date: </code></pre> <p>That will literally see if the <code>payment_date</code> is <em>right now</em>. I think you want to see if now is greater than or equal to the <code>payment_date</code>, in which case you should use</p> <pre><code>if datetime.now() &gt;= payment_date: </code></pre> <p>You can also just filter the invoices when you query the database:</p> <pre><code>invoices_list = Invoice.objects.filter(payment_date__lte=datetime.now()) </code></pre> <h1>Update</h1> <p>Your code is wrong because you have mutually exclusive conditionals. Look:</p> <pre><code>if payment_date &lt;= datetime.now(): owing = invoice_gross if payment_date &gt; datetime.now(): owing = 0 </code></pre> <p>That first checks to see if <code>payment_date</code> is before now. Then it sets <code>owing</code> to <code>invoice_gross</code>. <em>Then</em>, <em>in the same conditional</em>, it checks to see if <code>payment_date</code> is after now. But that can't be! You are only in this block of code if <code>payment_date</code> is <em>before</em> now!</p> <p>I think you have an indentation error, and want this instead:</p> <pre><code>if payment_date &lt;= datetime.now(): owing = invoice_gross if payment_date &gt; datetime.now(): owing = 0 </code></pre> <p>Which, of course, is the same as:</p> <pre><code>if payment_date &lt;= datetime.now(): owing = invoice_gross else: owing = 0 </code></pre>
4,266,448
Reading stream twice?
<p>When I have uploaded an image from my website I need to do 2 things: </p> <ol> <li>read the image dimensions</li> <li>save the image to the database</li> </ol> <p>the first thing I do is reading the image stream into an Image object, like so:</p> <pre><code>var file = Request.Files["logo"]; Image FullsizeImage = Image.FromStream(file.InputStream); </code></pre> <p>the next thing I do is to save the "file" object to the database (LINQ to SQL). BUT, when I try to save the image to database, the stream from the file has it's postion at the end of the stream, and it seems no data is present.</p> <p>I know I should somwhow reset the stream and put it back into position 0, but how do I do that the most effiecent and correct way ?</p>
4,266,487
2
0
null
2010-11-24 11:56:03.563 UTC
10
2021-03-08 07:57:52.933 UTC
2020-12-15 13:44:11.55 UTC
null
1,016,343
null
76,152
null
1
38
c#|.net|.net-core|stream
26,461
<p>Well, the simplest way is:</p> <pre><code>file.InputStream.Position = 0; </code></pre> <p>... assuming the stream supports seeking. However, That may do interesting things to the <code>Image</code> if you're not careful - because it will have retained a reference to the stream.</p> <p>You may be best off loading the data into a byte array, and then creating two separate <code>MemoryStream</code> objects from it if you still need to. If you're using .NET 4, it's easy to copy one stream to another:</p> <pre><code>MemoryStream ms = new MemoryStream(); Request.Files["logo"].InputStream.CopyTo(ms); byte[] data = ms.ToArray(); </code></pre>
4,416,983
Get java.util.Date out from Joda-Time DateTime
<p>I have code like this:</p> <pre><code>// old_api(Date date) old_api(calendar.getTime()); </code></pre> <p>Currently, I need to replace <code>Calendar</code> with Joda-Time <code>DateTime</code>. I was wondering how I can get <code>java.util.Date</code> out from Joda-Time <code>DateTime</code>?</p>
4,417,000
2
0
null
2010-12-11 13:39:57.59 UTC
6
2017-12-22 10:20:24.817 UTC
2016-11-30 16:12:04.85 UTC
null
157,882
null
72,437
null
1
47
java|jodatime
35,686
<p>Use <a href="http://joda-time.sourceforge.net/apidocs/org/joda/time/base/AbstractInstant.html#toDate%28%29" rel="noreferrer"><code>DateTime#toDate()</code></a>.</p> <pre><code>Date date = dateTime.toDate(); </code></pre>
26,924,618
How can incoming calls be answered programmatically in Android 5.0 (Lollipop)?
<p>As I am trying to create a custom screen for incoming calls I am trying to programatically answer an incoming call. I am using the following code but it is not working in Android 5.0.</p> <pre><code>// Simulate a press of the headset button to pick up the call Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED"); // froyo and beyond trigger on buttonUp instead of buttonDown Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK)); context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED"); </code></pre>
27,084,305
10
9
null
2014-11-14 06:59:54.16 UTC
90
2019-08-05 10:57:24.283 UTC
2017-08-18 11:58:34.81 UTC
null
1,000,551
null
1,075,218
null
1
94
android|android-5.0-lollipop|phone-call|incoming-call
84,806
<h1>Update with Android 8.0 Oreo</h1> <p>Even though the question was originally asked for Android L support, people still seem to be hitting this question and answer, so it is worth describing the improvements introduced in Android 8.0 Oreo. The backward compatible methods are still described below.</p> <h2>What changed?</h2> <p>Starting with <a href="https://developer.android.com/about/versions/oreo/android-8.0.html#perms" rel="noreferrer">Android 8.0 Oreo</a>, the <a href="https://developer.android.com/reference/android/Manifest.permission_group.html#PHONE" rel="noreferrer"><em>PHONE</em> permission group</a> also contains the <a href="https://developer.android.com/reference/android/Manifest.permission.html#ANSWER_PHONE_CALLS" rel="noreferrer"><em>ANSWER_PHONE_CALLS</em> permission</a>. As the name of permission suggests, holding it allows your app to programmatically accept incoming calls through a proper API call without any hacking around the system using reflection or simulating the user.</p> <h2>How do we utilize this change?</h2> <p>You should <a href="https://developer.android.com/training/basics/supporting-devices/platforms.html#version-codes" rel="noreferrer">check system version at runtime</a> if you are supporting older Android versions so that you can encapsulate this new API call while maintaining support for those older Android versions. You should follow <a href="https://developer.android.com/training/permissions/requesting.html" rel="noreferrer">requesting permissions at run time</a> to obtain that new permission during run-time, as is standard on the newer Android versions.</p> <p>After having obtained the permission, your app just has to simply call the <a href="https://developer.android.com/reference/android/telecom/TelecomManager.html#acceptRingingCall()" rel="noreferrer">TelecomManager's <em>acceptRingingCall</em></a> method. A basic invocation looks as follows then:</p> <pre><code>TelecomManager tm = (TelecomManager) mContext .getSystemService(Context.TELECOM_SERVICE); if (tm == null) { // whether you want to handle this is up to you really throw new NullPointerException("tm == null"); } tm.acceptRingingCall(); </code></pre> <hr> <h1>Method 1: TelephonyManager.answerRingingCall()</h1> <p><em>For when you have unlimited control over the device.</em></p> <h2>What is this?</h2> <p>There is TelephonyManager.answerRingingCall() which is a hidden, internal method. It works as a bridge for ITelephony.answerRingingCall() which has been discussed on the interwebs and seems promising at the start. It is <strong>not</strong> available on <a href="https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/telephony/java/android/telephony/TelephonyManager.java" rel="noreferrer">4.4.2_r1</a> as it was introduced only in commit <a href="https://android.googlesource.com/platform/frameworks/base/+/83da75d938d519bbcffb9c3b52802fd2daad4aee" rel="noreferrer">83da75d</a> for Android 4.4 KitKat (<a href="https://android.googlesource.com/platform/frameworks/base/+/android-4.4.3_r1/telephony/java/android/telephony/TelephonyManager.java#1535" rel="noreferrer">line 1537 on 4.4.3_r1</a>) and later "reintroduced" in commit <a href="https://android.googlesource.com/platform/frameworks/base/+/f1e1e7714375b3b83f2cc3956b112293face56a1" rel="noreferrer">f1e1e77</a> for Lollipop (<a href="https://android.googlesource.com/platform/frameworks/base/+/android-5.0.0_r1/telephony/java/android/telephony/TelephonyManager.java#3136" rel="noreferrer">line 3138 on 5.0.0_r1</a>) due to how the Git tree was structured. This means that unless you only support devices with Lollipop, which is probably a bad decision based on the tiny market share of it as of right now, you still need to provide fallback methods if going down this route.</p> <h2>How would we use this?</h2> <p>As the method in question is hidden from the SDK applications use, you need to use <a href="http://en.wikipedia.org/wiki/Reflection_(computer_programming)" rel="noreferrer">reflection</a> to dynamically examine and use the method during runtime. If you are not familiar with reflection, you can quickly read <a href="https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful">What is reflection, and why is it useful?</a>. You can also dig deeper into the specifics at <a href="https://docs.oracle.com/javase/tutorial/reflect/" rel="noreferrer">Trail: The Reflection API</a> if you are interested in doing so.</p> <h3>And how does that look in code?</h3> <pre><code>// set the logging tag constant; you probably want to change this final String LOG_TAG = "TelephonyAnswer"; TelephonyManager tm = (TelephonyManager) mContext .getSystemService(Context.TELEPHONY_SERVICE); try { if (tm == null) { // this will be easier for debugging later on throw new NullPointerException("tm == null"); } // do reflection magic tm.getClass().getMethod("answerRingingCall").invoke(tm); } catch (Exception e) { // we catch it all as the following things could happen: // NoSuchMethodException, if the answerRingingCall() is missing // SecurityException, if the security manager is not happy // IllegalAccessException, if the method is not accessible // IllegalArgumentException, if the method expected other arguments // InvocationTargetException, if the method threw itself // NullPointerException, if something was a null value along the way // ExceptionInInitializerError, if initialization failed // something more crazy, if anything else breaks // TODO decide how to handle this state // you probably want to set some failure state/go to fallback Log.e(LOG_TAG, "Unable to use the Telephony Manager directly.", e); } </code></pre> <h2>This is too good to be true!</h2> <p>Actually, there is one slight problem. This method should be fully functional, but the security manager wants callers to hold <a href="http://developer.android.com/reference/android/Manifest.permission.html#MODIFY_PHONE_STATE" rel="noreferrer">android.permission.MODIFY_PHONE_STATE</a>. This permission is in the realm of only partially documented features of the system as 3rd parties are not expected to touch it (as you can see from the documentation for it). You can try adding a <a href="http://developer.android.com/guide/topics/manifest/uses-permission-element.html" rel="noreferrer"><code>&lt;uses-permission&gt;</code></a> for it but that will do no good because the protection level for this permission is <em>signature|system</em> (<a href="https://android.googlesource.com/platform/frameworks/base/+/android-5.0.0_r1/core/res/AndroidManifest.xml#1198" rel="noreferrer">see line 1201 of core/AndroidManifest on 5.0.0_r1</a>).</p> <p>You can read <a href="https://code.google.com/p/android/issues/detail?id=34785" rel="noreferrer">Issue 34785: Update android:protectionLevel documentation</a> which was created back in 2012 to see that we are missing details about the specific "pipe syntax", but from experimenting around, it appears it must function as an 'AND' meaning all the specified flags have to be fulfilled for the permission to be granted. Working under that assumption, it would mean you must have your application:</p> <ol> <li><p><strong>Installed as a system application.</strong></p> <p>This should be fine and could be accomplished by asking the users to install using a ZIP in recovery, such as when rooting or installing Google apps on custom ROMs that don't have them already packaged.</p></li> <li><p><strong>Signed with the same signature as frameworks/base aka the system, aka the ROM.</strong></p> <p>This is where the problems pop up. To do this, you need to have your hands on the keys used for signing frameworks/base. You would not only have to get access to Google's keys for Nexus factory images, but you would also have to get access to all other OEMs' and ROM developers' keys. This does not seem plausible so you can have your application signed with the system keys by either making a custom ROM and asking your users to switch to it (which might be hard) or by finding an exploit with which the permission protection level can be bypassed (which might be hard as well).</p></li> </ol> <p>Additionally, this behavior appears to be related to <a href="https://code.google.com/p/android/issues/detail?id=34792" rel="noreferrer">Issue 34792: Android Jelly Bean / 4.1: android.permission.READ_LOGS no longer works</a> which utilizes the same protection level along with an undocumented development flag as well.</p> <p><strong>Working with the TelephonyManager sounds good, but will not work unless you get the appropriate permission which is not that easy to do in practice.</strong></p> <h2>What about using TelephonyManager in other ways?</h2> <p>Sadly, it appears to require you to hold the <a href="http://developer.android.com/reference/android/Manifest.permission.html#MODIFY_PHONE_STATE" rel="noreferrer">android.permission.MODIFY_PHONE_STATE</a> to use the cool tools which in turn means you are going to have a hard time getting access to those methods.</p> <hr> <h1>Method 2: service call SERVICE CODE</h1> <p><em>For when you can test that the build running on the device will work with the specified code.</em></p> <p>Without being able to interact with the TelephonyManager, there is also the possibility of interacting with the service through the <code>service</code> executable.</p> <h2>How does this work?</h2> <p>It is fairly simple, but there is even less documentation about this route than others. We know for sure the executable takes in two arguments - the service name and the code.</p> <ul> <li><p>The <strong>service name</strong> we want to use is <em>phone</em>.</p> <p>This can be seen by running <code>service list</code>.</p></li> <li><p>The <strong>code</strong> we want to use appears to have been <em>6</em> but seems to now be <em>5</em>.</p> <p>It looks like it has been based on <a href="http://developer.android.com/reference/android/os/IBinder.html#FIRST_CALL_TRANSACTION" rel="noreferrer">IBinder.FIRST_CALL_TRANSACTION</a> + 5 for many versions now (from <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/com/android/internal/telephony/ITelephony.java#ITelephony.Stub.0TRANSACTION_answerRingingCall" rel="noreferrer">1.5_r4</a> to <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/com/android/internal/telephony/ITelephony.java#ITelephony.Stub.0TRANSACTION_answerRingingCall" rel="noreferrer">4.4.4_r1</a>) but during local testing the code 5 worked to answer an incoming call. As Lollipo is a massive update all around, it is understandable internals changed here as well.</p></li> </ul> <p>This results with a command of <code>service call phone 5</code>.</p> <h2>How do we utilize this programmatically?</h2> <h3>Java</h3> <p><em>The following code is a rough implementation made to function as a proof of concept. If you actually want to go ahead and use this method, you probably want to check out <a href="http://su.chainfire.eu/" rel="noreferrer">guidelines for problem-free su usage</a> and possibly switch to the more fully developed <a href="https://github.com/Chainfire/libsuperuser/tree/master/libsuperuser" rel="noreferrer">libsuperuser</a> by <a href="https://twitter.com/ChainfireXDA" rel="noreferrer">Chainfire</a>.</em></p> <pre><code>try { Process proc = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(proc.getOutputStream()); os.writeBytes("service call phone 5\n"); os.flush(); os.writeBytes("exit\n"); os.flush(); if (proc.waitFor() == 255) { // TODO handle being declined root access // 255 is the standard code for being declined root for SU } } catch (IOException e) { // TODO handle I/O going wrong // this probably means that the device isn't rooted } catch (InterruptedException e) { // don't swallow interruptions Thread.currentThread().interrupt(); } </code></pre> <h3>Manifest</h3> <pre><code>&lt;!-- Inform the user we want them root accesses. --&gt; &lt;uses-permission android:name="android.permission.ACCESS_SUPERUSER"/&gt; </code></pre> <h2>Does this really require root access?</h2> <p>Sadly, it seems so. You can try using <a href="http://developer.android.com/reference/java/lang/Runtime.html#exec(java.lang.String)" rel="noreferrer">Runtime.exec</a> on it, but I was not able to get any luck with that route.</p> <h2>How stable is this?</h2> <p>I'm glad you asked. Due to not being documented, this can break across various versions, as illustrated by the seeming code difference above. The service name should probably stay <em>phone</em> across various builds, but for all we know, the code value can change across multiple builds of the same version (internal modifications by, say, the OEM's skin) in turn breaking the method used. It is therefore worth mentioning the testing took place on a Nexus 4 (mako/occam). I would personally advise you against using this method, but as I am not able to find a more stable method, I believe this is the best shot.</p> <hr> <h1>Original method: Headset keycode intents</h1> <p><em>For times when you have to settle.</em></p> <p><em>The following section was strongly influenced by <a href="https://stackoverflow.com/a/27137442">this answer</a> by <a href="https://stackoverflow.com/users/1990699/riley-c">Riley C</a>.</em></p> <p>The simulated headset intent method as posted in the original question seems to be broadcast just as one would expect, but it doesn't appear to accomplish the goal of answering the call. While there appears to be code in place that should handle those intents, they simply aren't being cared about, which has to mean there must be some kind of new countermeasures in place against this method. The log doesn't show anything of interest either and I don't personally believe digging through the Android source for this will be worthwhile just due to the possibility of Google introducing a slight change that easily breaks the method used anyway.</p> <h2>Is there anything we can do right now?</h2> <p>The behavior can be consistently reproduced using the input executable. It takes in a keycode argument, for which we simply pass in <a href="http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_HEADSETHOOK" rel="noreferrer">KeyEvent.KEYCODE_HEADSETHOOK</a>. The method doesn't even require root access making it suitable for common use cases in the general public, but there is a small drawback in the method - the headset button press event cannot be specified to require a permission, meaning it works like a real button press and bubbles up through the whole chain, which in turn means you have to be cautious about when to simulate the button press as it could, for example, trigger the music player to start playback if nobody else of higher priority is ready to handle the event.</p> <h3>Code?</h3> <pre><code>new Thread(new Runnable() { @Override public void run() { try { Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK)); } catch (IOException e) { // Runtime.exec(String) had an I/O problem, try to fall back String enforcedPerm = "android.permission.CALL_PRIVILEGED"; Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra( Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra( Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK)); mContext.sendOrderedBroadcast(btnDown, enforcedPerm); mContext.sendOrderedBroadcast(btnUp, enforcedPerm); } } }).start(); </code></pre> <hr> <h1>tl;dr</h1> <p>There is a nice public API for Android 8.0 Oreo and later.</p> <p>There is no public API prior to Android 8.0 Oreo. The internal APIs are off-limits or simply without documentation. You should proceed with caution.</p>
41,408,025
react-native .toLocaleString() not working on android
<p>I'm using <code>.toLocaleString()</code> on react-native for my number output. All work on IOS but seems not working on Android. This is normal or? Do I need to use a function for the decimal?</p> <p><a href="https://i.stack.imgur.com/sdA8f.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/sdA8f.jpg" alt="enter image description here"></a></p>
45,084,376
13
5
null
2016-12-31 11:47:31.757 UTC
2
2022-08-23 07:22:47.267 UTC
null
null
null
null
5,670,861
null
1
58
react-native
28,153
<p>You can use </p> <pre><code>number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") </code></pre>
9,701,276
OpenCV tracking using optical flow
<p>I use this to functions as a base of my tracking algorithm.</p> <pre><code> //1. detect the features cv::goodFeaturesToTrack(gray_prev, // the image features, // the output detected features max_count, // the maximum number of features qlevel, // quality level minDist); // min distance between two features // 2. track features cv::calcOpticalFlowPyrLK( gray_prev, gray, // 2 consecutive images points_prev, // input point positions in first im points_cur, // output point positions in the 2nd status, // tracking success err); // tracking error </code></pre> <p><code>cv::calcOpticalFlowPyrLK</code> takes vector of points from the previous image as input, and returns appropriate points on the next image. Suppose I have random pixel (x, y) on the previous image, how can I calculate position of this pixel on the next image using OpenCV optical flow function?</p>
9,702,540
2
0
null
2012-03-14 11:42:00.72 UTC
19
2016-06-20 23:51:32.027 UTC
2016-06-20 23:51:32.027 UTC
null
4,904,417
null
1,149,797
null
1
18
c++|opencv|computer-vision|tracking
56,124
<p>As you write, <code>cv::goodFeaturesToTrack</code> takes an image as input and produces a vector of points which it deems "good to track". These are chosen based on their ability to stand out from their surroundings, and are based on Harris corners in the image. A tracker would normally be initialised by passing the first image to goodFeaturesToTrack and obtaining a set of features to track. These features could then be passed to <code>cv::calcOpticalFlowPyrLK</code> as the previous points, along with the next image in the sequence and it will produce the next points as output, which then become input points in the next iteration.</p> <p>If you want to try to track a different set of pixels (rather than features generated by <code>cv::goodFeaturesToTrack</code> or a similar function), then simply provide these to <code>cv::calcOpticalFlowPyrLK</code> along with the next image.</p> <p>Very simply, in code:</p> <pre><code>// Obtain first image and set up two feature vectors cv::Mat image_prev, image_next; std::vector&lt;cv::Point&gt; features_prev, features_next; image_next = getImage(); // Obtain initial set of features cv::goodFeaturesToTrack(image_next, // the image features_next, // the output detected features max_count, // the maximum number of features qlevel, // quality level minDist // min distance between two features ); // Tracker is initialised and initial features are stored in features_next // Now iterate through rest of images for(;;) { image_prev = image_next.clone(); feature_prev = features_next; image_next = getImage(); // Get next image // Find position of feature in new image cv::calcOpticalFlowPyrLK( image_prev, image_next, // 2 consecutive images points_prev, // input point positions in first im points_next, // output point positions in the 2nd status, // tracking success err // tracking error ); if ( stopTracking() ) break; } </code></pre>
10,154,227
Django ORM, group by day
<p>I am trying to group products by DAY, however date_created is a datetime field.</p> <pre><code>Product.objects.values('date_created') \ .annotate(available=Count('available_quantity')) </code></pre> <p>returns:</p> <pre><code>[ {'date_created': datetime.datetime(2012, 4, 14, 13, 3, 6), 'available': 1}, {'date_created': datetime.datetime(2012, 4, 14, 17, 12, 9), 'available': 1}, ... ] </code></pre> <p>I want:</p> <pre><code>[ {'date_created': datetime.datetime(2012, 4, 14), 'available': 2}, ... ] </code></pre> <p><strong>edit:</strong> database backend MYSQL</p>
10,154,412
5
1
null
2012-04-14 14:00:02.783 UTC
5
2021-01-04 11:19:04.857 UTC
2014-01-15 08:04:24.93 UTC
null
911,519
null
911,519
null
1
33
python|mysql|django|django-orm
13,548
<p>Inspired by <a href="https://stackoverflow.com/questions/3543379/django-annotate-groupings-by-month">this question</a> try this for MySQL</p> <pre><code>from django.db.models import Count Product.objects.extra(select={'day': 'date( date_created )'}).values('day') \ .annotate(available=Count('date_created')) </code></pre>
10,158,849
Android ProGuard return Line Number
<p>Is there a way to get ProGuard to return a line number where the crash happened? I can use <code>retrace</code> to get to the method, but often for things like <code>NullPointerException</code> there are too many possibilities and in a large piece of code its extremely hard to determine the underlying cause as you have to check every object and it's life cycle to make sure nothing is wrong. It would really help if ProGuard could narrow this down to a line number for me.</p>
10,159,080
2
0
null
2012-04-15 01:24:18.273 UTC
13
2020-11-18 12:42:57.067 UTC
null
null
null
null
611,600
null
1
40
java|android|apk|proguard
7,900
<p>Add this line to your proguard-project.txt file.</p> <pre><code># will keep line numbers and file name obfuscation -renamesourcefileattribute SourceFile -keepattributes SourceFile,LineNumberTable </code></pre> <p><a href="https://www.guardsquare.com/en/products/proguard/manual/usage" rel="nofollow noreferrer">https://www.guardsquare.com/en/products/proguard/manual/usage</a></p>
9,705,078
Are there any knockoutjs page/routing frameworks?
<p>Coming from asp.net MVC 3. In MVC4 they introduced WebAPI's. It would be nice to be able to do all view/routes code in javascript and just rely on MVC for API. Heck it's really cool that webapi's can be run independent of IIS!</p> <p>That being said:</p> <p>Are there any page frameworks that can leverage KnockoutJS which are similar to my mock-up below:</p> <pre><code>Framework.RegisterRoutes(..,mainViewModel);//sets the CurrentViewModel? </code></pre> <p>Each route being a separate file of a viewModel, and a view to be injected into the master view</p> <pre><code>var mainviewModel= function(){ var self = this; self.CurrentViewModel = ko.observable(); ... return self; } &lt;div id="mainPageContent" data-bind:'html:CurrentViewModel.Render'&gt; &lt;/div&gt; </code></pre> <p>I know that a lot of this can be achieved by self, but not sure how to achieve the register routes/ loading separate files</p> <p>I feel like knockoutjs's main strengths is the ability to not intrude into the way you code js (ie build an object/framework how you want so long as the interacting objects are observable)</p>
14,631,837
6
1
null
2012-03-14 15:38:28.663 UTC
20
2016-05-08 02:01:22.77 UTC
2013-10-08 05:42:48.81 UTC
null
106,224
null
51,841
null
1
42
knockout.js|javascript-framework
43,172
<p><a href="http://pagerjs.com/">Pager.js</a> is a URL routing framework built specifically for use with Knockout.js. Make sure you go through the entire <a href="http://pagerjs.com/demo/">Demo</a> to see its full power and flexibility. IMHO, it far exceeds PathJS and Sammy.</p>
44,096,708
How to debug spring-boot application with IntelliJ IDEA community Edition?
<p>I'm having difficulties in debugging a Java spring-boot application on IntelliJ IDEA community Edition. The main problem is, that the IDE won't stop on a breakpoint, even the program surely executes through it. How can I make the the IntelliJ IDEA to stop on the breakpoint?</p> <p>As additional information, here is my run configurations:</p> <p>Maven configuration with a command as: spring-boot:run. Before launch I build the project.</p>
44,446,503
11
9
null
2017-05-21 12:13:16.153 UTC
41
2022-08-31 14:07:39.653 UTC
2017-05-21 12:15:45.793 UTC
null
4,662,347
null
4,662,347
null
1
122
java|intellij-idea|spring-boot
131,571
<p>The only way I got it working was by creating a separate, remote debug configuration.</p> <p>So go to edit configurations-&gt; Remote -&gt; +. Then start your application normally through intelliJ. Then switch to the newly created remote configuration. Instead of running it, press debug. Now debugger should be ready, and you can set breakpoints and the debugger will stop to them.</p> <p>EDIT: For me the debug port was already enabled, but I see that this is not the case for everyone. If you get an error like</p> <pre><code>'Unable to open debugger port (localhost:5005): java.net.ConnectException &quot;Connection refused: connect&quot; </code></pre> <p>Then you need to enable port on your app's pom.xml. Copied from @Gianluca Musa answer:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;configuration&gt; &lt;jvmArguments&gt; -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005 &lt;/jvmArguments&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>Kudos for @Gianluca Musa for pointing this out in his answer</p>
28,340,920
how to make my phonegap android app crash?
<p>I am developing a crash reporter plugin for phonegap android apps. For the testing purpose, I have to make my application crash &amp; "Unfortunately, application has stopped" window has to be invoked. When I make an unhandled exception in the javascript, the app is not crashing. Instead its showing the same screen. I made the app screen stop respond to user input by executing some infinite loop in javascript &amp; waited around 1 hour, still the app was not crashing. Is the phonegap library by default handling the exceptions ? how I can make my app crash by making exception in javascript level ?</p> <p>I tried the below code,added a java method to generate crash in the 'CordovaActivity' class. </p> <pre><code>public static void generateCrash() { int a = 0; int b = 10; int c = b/a ; } </code></pre> <p>The app is crashing when I call this method from java (from the 'onCreate' in the activity class) . But when I invoke the same method from the javascript using plugin, the app is not crashing. I want my app to crash by calling/invoking some function from the javascript. </p>
29,875,804
9
16
null
2015-02-05 09:55:48.817 UTC
6
2015-04-28 11:37:48.233 UTC
2015-04-21 09:20:01.19 UTC
null
2,797,795
null
2,797,795
null
1
29
javascript|cordova
4,394
<p><strong><em>Crash by pressing menu button:</em></strong></p> <p>You cannot make the app crash from a plugin or javascript call as the exceptions are handled internally. If you want to make the app crash in android you can edit CordovaActivity.java in Android platform. Change onCreateOptionsMenu as shown:</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); throw new RuntimeException(); } </code></pre> <p>Press the <strong>menu button</strong> and app will crash &amp; "Unfortunately, application has stopped" window will be displayed. </p> <p><strong><em>Crash by calling some native function from Javascript:</em></strong></p> <p>Write an Android native plugin for Phonegap. Refer <a href="http://docs.phonegap.com/en/3.0.0/guide_platforms_android_plugin.md.html#Android%20Plugins">http://docs.phonegap.com/en/3.0.0/guide_platforms_android_plugin.md.html#Android%20Plugins</a> for plugin creation. Throw exception inside execute method. This will be handled in the parent layer(Thats why you can see logs about crash in the console), So please do following changes to make the app <strong>crash</strong>.(Both the classes belong to org.apache.cordova package)</p> <ul> <li>Remove <code>catch (Exception e){}</code> block in <strong>execHelper</strong> method of <strong>pluginManager</strong> classs.</li> <li><p>Remove <code>catch (Throwable e) {}</code> block in <strong>exec</strong> method of <strong>ExposedJsApi</strong> class.</p> <p>With this change I am able to crash the application from javascript call.</p></li> </ul>
9,907,161
commons httpclient - Adding query string parameters to GET/POST request
<p>I am using commons HttpClient to make an http call to a Spring servlet. I need to add a few parameters in the query string. So I do the following:</p> <pre><code>HttpRequestBase request = new HttpGet(url); HttpParams params = new BasicHttpParams(); params.setParameter("key1", "value1"); params.setParameter("key2", "value2"); params.setParameter("key3", "value3"); request.setParams(params); HttpClient httpClient = new DefaultHttpClient(); httpClient.execute(request); </code></pre> <p>However when i try to read the parameter in the servlet using</p> <pre><code>((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getParameter("key"); </code></pre> <p>it returns null. In fact the parameterMap is completely empty. When I manually append the parameters to the url before creating the HttpGet request, the parameters are available in the servlet. Same when I hit the servlet from the browser using the URL with queryString appended. </p> <p>What's the error here? In httpclient 3.x, GetMethod had a setQueryString() method to append the querystring. What's the equivalent in 4.x?</p>
14,690,178
7
0
null
2012-03-28 12:08:15.733 UTC
11
2021-08-05 21:26:00.73 UTC
2012-05-18 18:02:38.073 UTC
null
21,234
null
818,713
null
1
86
java|apache-httpclient-4.x
182,818
<p>Here is how you would add query string parameters using HttpClient 4.2 and later:</p> <pre><code>URIBuilder builder = new URIBuilder("http://example.com/"); builder.setParameter("parts", "all").setParameter("action", "finish"); HttpPost post = new HttpPost(builder.build()); </code></pre> <p>The resulting URI would look like:</p> <pre><code>http://example.com/?parts=all&amp;action=finish </code></pre>
9,695,329
C++: How to round a double to an int?
<p>I have a double (call it x), meant to be 55 but in actuality stored as 54.999999999999943157 which I just realised.</p> <p>So when I do </p> <pre><code>double x = 54.999999999999943157; int y = (int) x; </code></pre> <p>y = 54 instead of 55!</p> <p>This puzzled me for a long time. How do I get it to correctly round? </p>
9,695,341
5
10
null
2012-03-14 03:01:18.293 UTC
27
2020-02-02 13:30:55.85 UTC
2020-02-02 13:30:55.85 UTC
null
584,192
null
1,255,592
null
1
145
c++|floating-point|rounding
505,248
<p>add 0.5 before casting (if x > 0) or subtract 0.5 (if x &lt; 0), because the compiler will always truncate.</p> <pre><code>float x = 55; // stored as 54.999999... x = x + 0.5 - (x&lt;0); // x is now 55.499999... int y = (int)x; // truncated to 55 </code></pre> <p>C++11 also introduces <a href="http://en.cppreference.com/w/cpp/numeric/math/round" rel="noreferrer">std::round</a>, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.</p> <p>A follow up question might be <em>why</em> the float isn't stored as exactly 55. For an explanation, see <a href="https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate">this</a> stackoverflow answer.</p>
11,750,041
How to create a named pipe in node.js?
<p>How to create a named pipe in node.js?</p> <p>P.S.: For now I'm creating a named pipe as follows. But I think this is not best way</p> <pre><code>var mkfifoProcess = spawn('mkfifo', [fifoFilePath]); mkfifoProcess.on('exit', function (code) { if (code == 0) { console.log('fifo created: ' + fifoFilePath); } else { console.log('fail to create fifo with code: ' + code); } }); </code></pre>
18,226,566
3
1
null
2012-07-31 22:36:50.117 UTC
16
2015-08-23 22:23:40.707 UTC
2012-08-01 11:44:50.857 UTC
null
386,578
null
386,578
null
1
36
node.js|pipe|named-pipes
36,281
<p>Looks like name pipes aren't and won't be supported in Node core - from Ben Noordhuis 10/11/11:</p> <blockquote> <p>Windows has a concept of named pipes but since you mention <code>mkfifo</code> I assume you mean UNIX FIFOs.</p> <p>We don't support them and probably never will (FIFOs in non-blocking mode have the potential to deadlock the event loop) but you can use UNIX sockets if you need similar functionality.</p> </blockquote> <p><a href="https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ" rel="noreferrer">https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ</a></p> <p>Named pipes and sockets are very similar however, the <code>net</code> module implements local sockets by specifying a <code>path</code> as opposed to a <code>host</code> and <code>port</code>:</p> <ul> <li><a href="http://nodejs.org/api/net.html#net_server_listen_path_callback" rel="noreferrer">http://nodejs.org/api/net.html#net_server_listen_path_callback</a></li> <li><a href="http://nodejs.org/api/net.html#net_net_connect_path_connectlistener" rel="noreferrer">http://nodejs.org/api/net.html#net_net_connect_path_connectlistener</a></li> </ul> <p>Example:</p> <pre><code>var net = require('net'); var server = net.createServer(function(stream) { stream.on('data', function(c) { console.log('data:', c.toString()); }); stream.on('end', function() { server.close(); }); }); server.listen('/tmp/test.sock'); var stream = net.connect('/tmp/test.sock'); stream.write('hello'); stream.end(); </code></pre>
11,607,465
Need good example: Google Calendar API in Javascript
<p>What I'm trying to do: Add events to a google calendar from my site using javascript.</p> <p>What I can't do: Find a good tutorial/walk through/example for the google calendar api. All the documentation I've been able to find links back and forth between v1 and v2 api's, or the v3 api doesn't seem to be client based.</p> <p>For those that are curious, the site I'm developing this for: <a href="http://infohost.nmt.edu/~bbean/banweb/index.php" rel="noreferrer">http://infohost.nmt.edu/~bbean/banweb/index.php</a></p>
11,622,475
2
2
null
2012-07-23 06:32:08.25 UTC
15
2021-07-07 23:24:59.98 UTC
2013-12-29 01:41:48.863 UTC
null
881,229
null
1,545,084
null
1
44
google-calendar-api
84,090
<p>Google provides a great JS client library that works with all of Google's discovery-based APIs (such as Calendar API v3). I've written a <a href="http://googleappsdeveloper.blogspot.com/2011/12/using-new-js-library-to-unlock-power-of.html">blog post</a> that covers the basics of setting up the JS client and authorizing a user.</p> <p>Once you have the basic client enabled in your application, you'll need to get familiar with the specifics of Calendar v3 to write your application. I suggest two things:</p> <ul> <li>The <a href="https://developers.google.com/apis-explorer/#p/calendar/v3/">APIs Explorer</a> will show you which calls are available in the API.</li> <li>The Chrome developer tools' Javascript console will automatically suggest method names when you are manipulating <code>gapi.client</code>. For example, begin typing <code>gapi.client.calendar.events.</code> and you should see a set of possible completions (you'll need the <code>insert</code> method).</li> </ul> <p>Here's an example of what inserting an event into JS would look like:</p> <pre><code>var resource = { "summary": "Appointment", "location": "Somewhere", "start": { "dateTime": "2011-12-16T10:00:00.000-07:00" }, "end": { "dateTime": "2011-12-16T10:25:00.000-07:00" } }; var request = gapi.client.calendar.events.insert({ 'calendarId': 'primary', 'resource': resource }); request.execute(function(resp) { console.log(resp); }); </code></pre> <p>Hopefully this is enough to get you started.</p>
3,526,386
How to prepend # at the head of multiple lines with emacs?
<p>I need to comment out some blocks of code in Python. How can I do that with emacs? How can I prepend # character at the start of each line of a block?</p>
3,526,422
4
1
null
2010-08-19 21:26:43.483 UTC
11
2014-02-12 10:44:24.63 UTC
null
null
null
null
260,127
null
1
27
emacs
20,642
<p>You can use the comment-region command using</p> <pre><code>M-x comment-region </code></pre> <p>Edit: And as suggested by @Gilles in comment you can use <code>M-;</code> which according to the help is</p> <blockquote> <p>Call the comment command you want (Do What I Mean).</p> <p>If the region is active and 'transient-mark-mode' is on, call 'comment-region' (unless it only consists of comments, in which case it calls 'uncomment-region'). Else, if the current line is empty, call 'comment-insert-comment-function' if it is defined, otherwise insert a comment and indent it. Else if a prefix arg is specified, call 'comment-kill'. Else, call 'comment-indent'.</p> </blockquote> <p>which is probably easier on the long run. :-) Remember that this is "mode-dependant", so you need to set python-mode before you comment using <code>M-x python-mode</code></p> <p>Or if you want to prefix every line with any type of character, select the text you want to comment and type</p> <pre><code>C-x r t </code></pre> <p>and type the character you want to prefix with. Remember that the caret must be on the first column on the last line that you select, or your text would be replaced.</p> <p><em>You select text by pressing C-space and moving your caret around btw.</em></p>
3,512,202
GitHub - HTTPS access
<p>I am unable to clone my repository via HTTPS:</p> <pre><code>$ git clone https://github.com/walterjwhite/project.configuration.git Initialized empty Git repository in ./project.configuration/.git/ error: Failed connect to github.com:443; Connection refused while accessing https://github.com/walterjwhite/project.configuration.git/info/refs fatal: HTTP request failed </code></pre> <p>I have configured .netrc with my login and password as well as the machine or server I am connecting to.</p>
3,514,762
4
1
null
2010-08-18 12:48:15.127 UTC
18
2020-03-18 20:23:04.703 UTC
2014-07-29 18:15:01.123 UTC
null
113,632
Walter White
null
null
1
43
git|https|github
99,766
<p>As you did saw yourself in <a href="http://github.com/blog/642-smart-http-support#comment-8469" rel="noreferrer">GitHub support</a>, <a href="http://github.com/schacon" rel="noreferrer">Scott Schacon</a> himself suggested:</p> <blockquote> <p>So I guess your <code>.netrc</code> is incorrect or something?<br> Try removing the info from your <code>.netrc</code> and cloning first (since it's a public repo).</p> </blockquote> <p>If it isn't a GitHub server issue, it could be your firewall.<br> And/or your proxy (<code>git config --global http.proxy http://user:password@proxy:xxx</code>).</p>
3,580,068
Is setTimeout with no delay the same as executing the function instantly?
<p>I am looking at some existing code in a web application. I saw this:</p> <p><code>window.setTimeout(function () { ... })</code></p> <p>Is this the same as just executing the function content right away?</p>
3,580,703
4
1
null
2010-08-26 22:29:54.583 UTC
9
2021-08-12 00:39:36.227 UTC
2010-08-26 22:38:37.217 UTC
null
92,313
null
195,486
null
1
54
javascript|delay|settimeout|timing
22,666
<p>It won't necessarily run right away, neither will explicitly setting the delay to 0. The reason is that setTimeout removes the function from the execution queue and it will only be invoked after JavaScript has finished with the current execution queue. </p> <pre><code>console.log(1); setTimeout(function() {console.log(2)}); console.log(3); console.log(4); console.log(5); //console logs 1,3,4,5,2 </code></pre> <p>for more details see <a href="http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/" rel="noreferrer">http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/</a></p>
8,101,178
How do I apply mathematical operations to Android dimensions?
<p>How do I avoid this hardcoded math...</p> <pre><code>&lt;resources&gt; &lt;dimen name="uno"&gt;10dip&lt;/dimen&gt; &lt;dimen name="dos"&gt;6dip&lt;/dimen&gt; &lt;dimen name="uno_plus_dos"&gt;16dip&lt;/dimen&gt; &lt;/resources&gt; &lt;Button android:layout_marginTop="@dimen/uno_plus_dos" /&gt; </code></pre> <p>...and covert it to something like this?</p> <pre><code>&lt;Button android:layout_marginTop="@dimin/uno + @dimen/dos" /&gt; </code></pre>
8,101,549
4
2
null
2011-11-11 23:27:35.597 UTC
12
2017-08-16 12:30:32.327 UTC
null
null
null
null
459,987
null
1
57
android|xml|android-layout
15,001
<p>You don't, sorry. Layout XML files do not support expressions. You either:</p> <ul> <li>Leave it as <code>@dimen/uno_plus_dos</code>, or</li> <li>Set your margins in Java code, where you can replace a single resource with a bunch of extra lines of code, or</li> <li>Write your own layout preprocessor that handles expressions like this</li> </ul> <p><strong>UPDATE</strong> The <a href="https://developer.android.com/topic/libraries/data-binding/index.html" rel="noreferrer">data binding library</a> supports some operations in its expressions. I am uncertain if it can handle this specific scenario. </p>
7,887,867
Binding the Loaded event?
<p>I am trying to display a login window once my MainWindow loads while sticking to the MVVM pattern. So I am trying to Bind my main windows Loaded event to an event in my viewmodel. Here is what I have tried:</p> <p>MainWindowView.xaml</p> <pre><code> &lt;Window x:Class="ScrumManagementClient.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" DataContext="ViewModel.MainWindowViewModel" Loaded="{Binding ShowLogInWindow}"&gt; &lt;Grid&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>MainWindowViewModel.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ScrumManagementClient.ViewModel { class MainWindowViewModel : ViewModelBase { public void ShowLogInWindow(object sender, EventArgs e) { int i = 0; } } } </code></pre> <p>The error message I am getting is "Loaded="{Binding ShowLogInWindow}" is not valid. '{Binding ShowLogInWindow}' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid."</p>
7,887,936
5
1
null
2011-10-25 10:25:31.597 UTC
13
2016-10-05 15:49:49.61 UTC
null
null
null
null
588,734
null
1
19
c#|wpf|data-binding|mvvm|loaded
50,005
<p>You're going to have to use the System.Windows.Interactivity dll.</p> <p>Then add the namespace in your XAML:</p> <pre><code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" </code></pre> <p>Then you can do stuff like:</p> <pre><code>&lt;i:Interaction.Triggers&gt; &lt;i:EventTrigger EventName="Loaded"&gt; &lt;i:InvokeCommandAction Command="{Binding MyICommandThatShouldHandleLoaded}" /&gt; &lt;/i:EventTrigger&gt; &lt;/i:Interaction.Triggers&gt; </code></pre> <p>Please note that you will have to use an <code>ICommand</code> (or DelegateCommand is you use Prism, or RelayCommand if you use MVVMLight), and the DataContext of your Window must hold that ICommand.</p>
7,859,623
How do I use CMake?
<p>I am trying to use CMake in order to compile opencv.</p> <p>I am reading the <a href="http://www.cmake.org/cmake/help/cmake_tutorial.html#s3">tutorial</a> but can't understand what is CMakeLists files and how is it connected to the gui of CMake?</p> <p>Also couldn't understand what are makefiles, are they the same is CMakeLists? </p> <p>And which file is it which I in the end open with visual-studio?</p>
7,859,700
6
2
null
2011-10-22 12:46:03.947 UTC
42
2020-11-08 11:36:31.273 UTC
2014-11-27 15:17:43.427 UTC
null
492,336
null
591,005
null
1
126
c++|visual-studio|cmake
179,752
<p>CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.</p> <p>You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.</p>
8,110,934
Direct vs. Delegated - jQuery .on()
<p>I am trying to understand this particular difference between the <em>direct</em> and <em>delegated</em> event handlers using the <a href="http://api.jquery.com/on/" rel="noreferrer">jQuery <em>.on()</em> method</a>. Specifically, the last sentence in this paragraph:</p> <blockquote> <p>When a <code>selector</code> is provided, the event handler is referred to as <em>delegated</em>. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.</p> </blockquote> <p>What does it mean by "runs the handler for any elements"? I made a <a href="http://labs.siku-siku.com/jquery/on/" rel="noreferrer">test page</a> to experiment with the concept. But both following constructs lead to the same behavior:</p> <pre><code>$("div#target span.green").on("click", function() { alert($(this).attr("class") + " is clicked"); }); </code></pre> <p>or,</p> <pre><code>$("div#target").on("click", "span.green", function() { alert($(this).attr("class") + " is clicked"); }); </code></pre> <p>Maybe someone could refer to a different example to clarify this point? Thanks.</p>
8,111,171
6
3
null
2011-11-13 10:26:54.693 UTC
63
2021-01-11 16:21:06.653 UTC
2016-09-06 14:13:24.95 UTC
null
5,885,146
null
583,539
null
1
167
javascript|jquery|event-bubbling|jquery-events|event-binding
44,696
<p><strong>Case 1 (direct):</strong></p> <pre><code>$("div#target span.green").on("click", function() {...}); </code></pre> <p>== Hey! I want every span.green inside div#target to listen up: when you get clicked on, do X.</p> <p><strong>Case 2 (delegated):</strong></p> <pre><code>$("div#target").on("click", "span.green", function() {...}); </code></pre> <p>== Hey, div#target! When any of your child elements which are "span.green" get clicked, do X with them.</p> <p><strong>In other words...</strong></p> <p>In case 1, each of those spans has been individually given instructions. If new spans get created, they won't have heard the instruction and won't respond to clicks. Each span is <strong>directly responsible</strong> for its own events.</p> <p>In case 2, only the container has been given the instruction; it is responsible for noticing clicks <em>on behalf of</em> its child elements. The work of catching events has been <strong>delegated</strong>. This also means that the instruction will be carried out for child elements that are created in future.</p>
8,322,849
Mysql order by specific ID values
<p>Is it possible to sort in mysql by "order by" using predefined set of column values (ID) like: order by (ID=1,5,4,3) so I would get record 1, 5, 4, 3 in that order out?</p> <p><strong>UPDATE:</strong> About abusing mysql ;-) I have to explain why I need this...</p> <p>I want my records change sort randomly every 5 minutes. I have a cron task to do the update table to put different, random sort order in it. There is just one problem! PAGINATION. I will have a visitor who comes to my page and I give him first 20 results. He will wait 6 minutes and go to page 2 and he will have wrong results as the sort order had allready changed.</p> <p>So I thought that if he comes to my site I put all the ID's to a session and when he is in page 2 he get's the correct records out even if the sorting allready changed.</p> <p>Is there any other way, better, to do this?</p>
8,322,898
8
2
null
2011-11-30 08:09:36.84 UTC
33
2020-07-07 07:34:00.56 UTC
2011-11-30 08:58:46.14 UTC
null
413,178
null
413,178
null
1
120
mysql|sorting
107,423
<p>You can use ORDER BY and FIELD function. See <a href="http://lists.mysql.com/mysql/209784" rel="noreferrer">http://lists.mysql.com/mysql/209784</a></p> <pre><code>SELECT * FROM table ORDER BY FIELD(ID,1,5,4,3) </code></pre> <p>It uses <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field" rel="noreferrer">Field()</a> function, Which "Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found" according to the documentation. So actually you sort the result set by the return value of this function which is the index of the field value in the given set.</p>
4,624,113
Start a .Net Process as a Different User
<p>I want to start a Process with Admin rights. When I run the code below the Process complains saying it needs Admin rights:</p> <pre><code>public class ImpersonationHelper : IDisposable { IntPtr m_tokenHandle = new IntPtr(0); WindowsImpersonationContext m_impersonatedUser; #region Win32 API Declarations const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; //This parameter causes LogonUser to create a primary token. [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); #endregion /// &lt;summary&gt; /// Constructor. Impersonates the requested user. Impersonation lasts until /// the instance is disposed. /// &lt;/summary&gt; public ImpersonationHelper(string domain, string user, string password) { // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref m_tokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } // Impersonate m_impersonatedUser = new WindowsIdentity(m_tokenHandle).Impersonate(); } #region IDisposable Pattern /// &lt;summary&gt; /// Revert to original user and cleanup. /// &lt;/summary&gt; protected virtual void Dispose(bool disposing) { if (disposing) { // Revert to original user identity if (m_impersonatedUser != null) m_impersonatedUser.Undo(); } // Free the tokens. if (m_tokenHandle != IntPtr.Zero) CloseHandle(m_tokenHandle); } /// &lt;summary&gt; /// Explicit dispose. /// &lt;/summary&gt; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// &lt;summary&gt; /// Destructor /// &lt;/summary&gt; ~ImpersonationHelper() { Dispose(false); } #endregion } using (new ImpersonationHelper("xxx.blabla.com", "xxxx", "xxxx")) { if (!string.IsNullOrEmpty(txtFilename.Text)) Process.Start(txtFilename.Text); } </code></pre>
4,624,413
3
0
null
2011-01-07 09:32:09.78 UTC
9
2022-06-17 16:54:04.087 UTC
2014-10-28 18:33:03.14 UTC
null
176,877
null
50,985
null
1
28
c#|impersonation
79,809
<p>Can you try something like this: <a href="http://weblogs.asp.net/hernandl/archive/2005/12/02/startprocessasuser.aspx" rel="noreferrer">Start a new Process as another user</a></p> <p>Code sample:</p> <pre><code>System.Diagnostics.Process proc = new System.Diagnostics.Process(); System.Security.SecureString ssPwd = new System.Security.SecureString(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = "filename"; proc.StartInfo.Arguments = "args..."; proc.StartInfo.Domain = "domainname"; proc.StartInfo.UserName = "username"; string password = "user entered password"; for (int x = 0; x &lt; password.Length; x++) { ssPwd.AppendChar(password[x]); } password = ""; proc.StartInfo.Password = ssPwd; proc.Start(); </code></pre>
4,633,493
Nested content_tag throws undefined method `output_buffer=` in simple helper
<p>I'm trying to create a simple view helper but as soon as I try nest a couple of content tags it will throw <pre>NoMethodError: undefined method `output_buffer=' for</pre></p> <pre><code>def table_for(list, &amp;proc) t = Table.new proc.call(t) t.render_column(list) end class Table include ActionView::Helpers::TagHelper attr_accessor :columns, :block def initialize @columns = Array.new end def col(name) @columns &lt;&lt; name end def render_column(list) content_tag :table do list.each do |c| content_tag :td, c end end end end </code></pre> <p>Any hints of what's wrong? I've also seen that there's a XmlBuilder is that one better for my purpose? </p>
4,660,644
3
0
null
2011-01-08 10:45:21.947 UTC
7
2011-09-26 22:39:04.297 UTC
null
null
null
null
191,975
null
1
35
ruby-on-rails-3
12,427
<p>With help from <a href="https://stackoverflow.com/questions/4633493/nested-content-tag-throws-undefined-method-output-buffer-in-simple-helper/4633685#4633685">Nested content_tag throws undefined method `output_buffer=` in simple helper</a> I ended up with the following solution inspired by the API for Formtastic.</p> <pre><code>&lt;%= table_for(@users) do |t| %&gt; &lt;% t.col :name %&gt; &lt;% t.col :email %&gt; &lt;% t.col :test, :value =&gt; lambda { |u| u.email }, :th =&gt; 'Custom column name' %&gt; &lt;% t.col :static, :value =&gt; 'static value' %&gt; &lt;% end %&gt; </code></pre> <p>Using the output_buffer directly and probably reinventing the wheel the code looks like</p> <pre><code>module ApplicationHelper def table_for(list, &amp;block) table = Table.new(self) block.call(table) table.show(list) end class Column include ActiveSupport::Inflector attr_accessor :name, :options def initialize(name, options = {}) @name = name @options = options end def td_value(item) value = options[:td] if (value) if (value.respond_to?('call')) value.call(item) else value end else item[name] end end def th_value options[:th] ||= humanize(name) end end class Table include ActionView::Helpers::TagHelper attr_accessor :template, :columns def initialize(temp) @columns = Array.new @template = temp end def col(name, options = {}) columns &lt;&lt; Column.new(name, options) end def show(list) template.content_tag(:table) do template.output_buffer &lt;&lt; template.content_tag(:tr) do columns.collect do |c| template.output_buffer &lt;&lt; content_tag(:th, c.th_value) end end list.collect do |item| template.output_buffer &lt;&lt; template.content_tag(:tr) do columns.collect do |c| template.output_buffer &lt;&lt; template.content_tag(:td, c.td_value(item)) end end end end end end end </code></pre>
14,763,702
how to move this navigation bar to the right
<p>I'm new to CSS and I'm trying to experiment with this code - if you want to see what it looks like go to this link: <a href="https://www.servage.net/blog/wp-content/uploads/2009/03/css-menu.html" rel="nofollow noreferrer">https://www.servage.net/blog/wp-content/uploads/2009/03/css-menu.html</a> Here's the code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;CSS based drop-down menu&lt;/title&gt; &lt;style type="text/css"&gt; ul { font-family: Arial, Verdana; font-size: 14px; margin: 0; padding: 0; list-style: none; } ul li { display: block; position: relative; float: left; } li ul { display: none; } ul li a { display: block; text-decoration: none; color: #ffffff; border-top: 1px solid #ffffff; padding: 5px 15px 5px 15px; background: #2C5463; margin-left: 1px; white-space: nowrap; } ul li a:hover { background: #617F8A; } li:hover ul { display: block; position: absolute; } li:hover li { float: none; font-size: 11px; } li:hover a { background: #617F8A; } li:hover li a:hover { background: #95A9B1; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt;&lt;a href=""&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;About&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=""&gt;The Team&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;History&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Vision&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Products&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=""&gt;Cozy Couch&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Great Table&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Small Chair&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Shiny Shelf&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Invisible Nothing&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Contact&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=""&gt;Online&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Right Here&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Somewhere Else&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I have 2 questions about this: How do I make this navigation bar on the right side of the page ? Some of the tabs have drop down lists, when I add this margin-top: 50px to change the position of the navigation bar the dropdown lists move down like this <img src="https://i.stack.imgur.com/RTplO.png" alt="enter image description here"></p>
14,763,841
4
0
null
2013-02-08 00:26:52.5 UTC
5
2017-07-24 06:04:12.36 UTC
null
null
null
null
1,985,349
null
1
4
html|css
83,990
<p>To move the <code>#menu</code> to the right and <code>50px</code> down, add these properties </p> <pre><code>#menu { position: absolute; top: 50px; right: 0px; } </code></pre> <p><a href="http://jsfiddle.net/hnCaz/" rel="noreferrer">JSFiddle</a></p> <p>If you want to use <code>float</code> and <code>margin-top</code> instead, you must restrict the margin to the <code>#menu</code> </p> <pre><code>#menu { float: right; margin-top: 50px; } </code></pre> <p><a href="http://jsfiddle.net/zCcV4/" rel="noreferrer">JSFiddle</a></p>
14,376,577
Clear combobox datasource items
<p>Combobox datasource has been assigned with</p> <pre><code>cmbCombobox.DataSource = myCollection </code></pre> <p>where myCollection has type MyCollection: List</p> <p>How can I clear items in combobox?</p>
14,418,786
5
0
null
2013-01-17 10:06:43.43 UTC
2
2015-11-16 20:21:48.19 UTC
2013-07-04 15:02:30.373 UTC
null
1,085,940
null
444,079
null
1
6
.net|winforms|compact-framework
44,467
<p>When you data bind a control, it will synchronize with that collection. In order to clear the items in your ComboBox set it's DataSource to null.</p> <pre><code>cmbComboBox.DataSource = null; </code></pre> <p>If your combobox is <strong>not</strong> databound (no DataSource) then you can do</p> <pre><code>cmbComboBox.Items.Clear(); </code></pre>
14,503,225
change font colour in textbox with CSS when value is typed into box
<p>I have a text box, which acts as a search box on my page. I pre-populate the field with the word 'SEARCH' which has a default text colour of #D6D6D0.</p> <p>Using CSS, is it possible to change the text colour to #FFFFFF when someone enters text in the box?</p> <pre><code>&lt;input type="text" name="q" value="SEARCH" id="searchFieldText"&gt; #searchFieldText { background: url("/images/crmpicco/search_bg3.png") no-repeat scroll 0 0 #000000; border: medium none; color: #D6D6D0; float: left; font-family: Arial,Helvetica,sans-serif; font-size: 10px; height: 21px; padding-left: 0; padding-top: 3px; width: 168px; } </code></pre>
14,503,266
5
0
null
2013-01-24 14:05:49.667 UTC
1
2013-01-25 09:11:16.017 UTC
null
null
null
null
691,505
null
1
6
html|forms|css|textbox
45,008
<p>The focus pseudo class should work</p> <pre><code>#searchFieldText:focus { color: #fff; } </code></pre>
4,556,397
SQL: Is it possible to add a dummy column in a select statement?
<p>I need to add a dummy column to a simple select statement in certain circumstances:</p> <p><code>Select Id, EndOfcol default '~' from Main where id &gt; 40</code></p>
4,556,405
4
0
null
2010-12-29 17:46:58.297 UTC
4
2015-07-10 09:32:19.99 UTC
2010-12-29 17:49:28.893 UTC
null
142,129
null
557,382
null
1
29
sql|tsql|sql-server-2008
82,613
<p>Yes, it's actually a constant value.</p> <pre><code>SELECT id, '~' AS EndOfcol FROM Main WHERE id &gt; 40 </code></pre>
4,372,197
MySQL returns only one row
<p>I have this simple PHP code:</p> <pre><code>$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); $query2 = mysql_fetch_assoc($quer); print_r($query2); </code></pre> <p>It only returns this:</p> <pre><code>Array ( [title] =&gt; Kill Bill Vol 1. [url_title] =&gt; kill_bill_vol_1 ) </code></pre> <p>I have 3500+ rows in the table, and running the SQL in PhpMyAdmin works perfectly.</p>
4,372,215
5
0
null
2010-12-07 00:00:49.7 UTC
1
2018-02-15 09:38:57.517 UTC
null
null
null
null
499,501
null
1
6
php|mysql
38,824
<pre><code>$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); while ($row = mysql_fetch_assoc($query)) { print_r($row); } </code></pre> <ul> <li>You misspelled <code>$query</code> in your example</li> <li><code>mysql_fetch_assoc()</code> will return a row each time it is called, and <code>FALSE</code> when out of rows. Use that to your advantage, by assigning a variable to it in the condition. Within the <code>while()</code> loop, <code>$row</code> will be the current row.</li> </ul>
4,533,636
How to implement iterator as an attribute of a class in Java
<p>let's say I have this simple MyArray class, with two simple methods: add, delete and an iterator. In the main method we can see how it is supposed to be used:</p> <pre><code>public class MyArray { int start; int end; int[] arr; myIterator it; public MyArray(){ this.start=0; this.end=0; this.arr=new int[500]; it=new myIterator(); } public void add(int el){ this.arr[this.end]=el; this.end++; } public void delete(){ this.arr[this.start]=0; this.start++; } public static void main(String[] args){ MyArray m=new MyArray(); m.add(3); m.add(299); m.add(19); m.add(27); while(m.it.hasNext()){ System.out.println(m.it.next()); } } </code></pre> <p>And then MyIterator should be implemented somehow:</p> <pre><code>import java.util.Iterator; public class myIterator implements Iterator{ @Override public boolean hasNext() { // TODO Auto-generated method stub return false; } @Override public Object next() { // TODO Auto-generated method stub return null; } @Override public void remove() { // TODO Auto-generated method stub } </code></pre> <p>}</p> <p>MyIterator should iterate <em>arr</em> from <em>MyArray</em> class, from <em>start</em> to <em>end</em> values; both are also attributes of <em>MyArray</em>. So, as <em>MyIterator</em> should use <em>MyArray</em> attributes, how should MyIterator be implemented? Perhaps I can send the current object in the initialization:</p> <pre><code>it=new myIterator(this); </code></pre> <p>But I guess it's not the best soultion. Or maybe MyArray itself should implement Iterator interface? How is this solved?</p> <p>EDIT:</p> <p>Ok, thanks to everybody. This was a simple example of what I wnat to do, so don't care about fixed length array. Waht I really want to do is a circular FIFO, that's why <code>start</code> and <code>end</code> are the cursors.</p> <p>This circular FIFO will be an array of pairs of ints with, e.g., size 300: <code>int[][] arr=new int[300][2]</code>.</p> <p>When iterating a circular array I have to take care if the counter arrives to the end and make it start from the beginning, so this is how I have solved it:</p> <pre><code>if (this.start &gt;= this.end ) temp_end=this.end+this.buff.length; else temp_end=this.end; int ii; int j=0; int[] value=new int[2]; for(int i=this.start; i&lt;temp_end; i++){ ii=i% this.arr.length; value=this.buff[ii]; //do anything with value </code></pre> <p>}</p> <p>But I would like to avoid worrying about these things and just iterate in a simple way, I can do this with iterator interface, but then I have 2 problems: the first one I already explained and has been solved by many answers, and the second one is that my array is made of pairs of ints, and I can't use iterator with primitive types. </p>
4,533,698
6
0
null
2010-12-26 11:18:59.79 UTC
3
2013-03-08 17:02:51.977 UTC
2010-12-26 17:42:17.18 UTC
null
527,706
null
527,706
null
1
4
java|iterator
47,585
<p>Its very unusual to maintain an iterator as an instance variable of the class. You can only traverse the array once - probably not what you want. More likely, you want your class to provide an iterator to anyone that wants to traverse your array. A more traditional iterator is below.</p> <p>Java 5+ code - I haven't tried to compile or run, so it may be contain errors (not near a dev machine right now). It also uses autobox'ing for converting <code>Integer</code> to <code>int</code>. </p> <pre><code>public class MyArray implements Iterable&lt;Integer&gt; { public static class MyIterator implements Iterator&lt;Integer&gt; { private final MyArray myArray; private int current; MyIterator(MyArray myArray) { this.myArray = myArray; this.current = myArray.start; } @Override public boolean hasNext() { return current &lt; myArray.end; } @Override public Integer next() { if (! hasNext()) throw new NoSuchElementException(); return myArray.arr[current++]; } @Override public void remove() { // Choose exception or implementation: throw new OperationNotSupportedException(); // or //// if (! hasNext()) throw new NoSuchElementException(); //// if (currrent + 1 &lt; myArray.end) { //// System.arraycopy(myArray.arr, current+1, myArray.arr, current, myArray.end - current-1); //// } //// myArray.end--; } } .... // Most of the rest of MyArray is the same except adding a new iterator method .... public Iterator&lt;Integer&gt; iterator() { return new MyIterator(); } // The rest of MyArray is the same .... } </code></pre> <hr> <p>Also note: be careful of not hitting that 500 element limit on your static array. Consider using the ArrayList class instead if you can.</p>
4,500,932
Devise within namespace
<p>I'm trying to split my rails project in a front-end for regular users and a back-end for admins. Therefore i have created a namespace 'admin' so that i can easily control admin specific controller methods/layouts/authentication in the map admin.</p> <p>I'm using Devise to register/authenticate my admins only. Because it is only used for admins only i'm trying to move Devise to the admin namespace.</p> <p>I could not find exactly what i was looking for in the <a href="https://github.com/plataformatec/devise" rel="noreferrer">documentation</a> of Devise but i tried something like this in routes.rb:</p> <pre><code>namespace 'admin'do devise_for :admins end </code></pre> <p>I also tried to make a custom Devise::Sessions controller but that too didn't seem to work out.</p> <p>Does anyone know how to do this? Should i just use the regular routes for devise with a custom(admin) layout?</p>
4,502,272
6
0
null
2010-12-21 15:33:38.99 UTC
21
2016-06-04 06:36:06.637 UTC
null
null
null
null
521,259
null
1
38
ruby-on-rails|namespaces|ruby-on-rails-plugins|devise
28,431
<p>Simply "moving" Devise to the admin namespace is wrong. Devise uses controllers like <code>Devise::SessionsController</code> and that cannot be "moved".</p> <p>I usually create my own controllers and inherit them from Devise:</p> <pre><code>class Admin::SessionsController &lt; ::Devise::SessionsController layout "admin" # the rest is inherited, so it should work end </code></pre> <p>And configure this in <code>config/routes.rb</code>:</p> <pre><code>devise_for :admins, :controllers =&gt; { :sessions =&gt; "admin/sessions" } </code></pre> <p><strong>Or</strong> you could change the layout only, by making the layout a bit more complex:</p> <pre><code>class ApplicationController &lt; ActionController::Base layout :layout private def layout if devise_controller? &amp;&amp; devise_mapping.name == :admin "admin" else "application" end end end </code></pre>
4,185,282
Is there a way of having something like jUnit Assert message argument in Mockito's verify method?
<p>Let's assume a snippet of testing code:</p> <pre><code>Observable model = Class.forName(fullyQualifiedMethodName).newInstance(); Observer view = Mockito.mock(Observer.class); model.addObserver(view); for (Method method : Class.forName(fullyQualifiedMethodName).getDeclaredMethods()) { method.invoke(model, composeParams(method)); model.notifyObservers(); Mockito.verify( view, Mockito.atLeastOnce() ).update(Mockito.&lt;Observable&gt;any(), Mockito.&lt;Object&gt;any()); } </code></pre> <p><code>Mockito.verify</code> method throws an exception if a method in a model hasn't invoked <code>Observable.setChanged()</code> method.</p> <p>Problem: without adding <code>loggers/System.print.out</code> I can't realize what's the current method that has failed the test. Is there a way of having something similar to <code>jUnit Assert</code> methods:</p> <pre><code>Assert.assertEquals( String.format("instances %s, %s should be equal", inst1, inst2), inst1.getParam(), inst2.getParam() ); </code></pre> <hr> <p><strong>SOLUTION:</strong></p> <pre><code>verify(observer, new VerificationMode() { @Override public void verify(VerificationData data) { assertTrue( format( "method %s doesn't call Observable#setChanged() after changing the state of the model", method.toString() ), data.getAllInvocations().size() &gt; 0); } }).update(Mockito.&lt;Observable&gt;any(), Mockito.&lt;Object&gt;any()); </code></pre>
58,686,499
7
0
null
2010-11-15 14:29:57.117 UTC
2
2021-12-25 00:32:59.253 UTC
2010-12-01 11:19:48.353 UTC
null
32,090
null
32,090
null
1
35
java|junit|assert|mockito|verify
13,822
<p>This question is ancient, but Mockito v2.1.0+ now has a built-in feature for this.</p> <pre><code>verify(mock, description(&quot;This will print on failure&quot;)).someMethod(&quot;some arg&quot;); </code></pre> <p>More examples included from <a href="https://stackoverflow.com/users/1339923/lambart">@Lambart</a>'s comment below:</p> <pre><code>verify(mock, times(10).description(&quot;This will print if the method isn't called 10 times&quot;)).someMethod(&quot;some arg&quot;); verify(mock, never().description(&quot;This will print if someMethod is ever called&quot;)).someMethod(&quot;some arg&quot;); verify(mock, atLeastOnce().description(&quot;This will print if someMethod is never called with any argument&quot;)).someMethod(anyString()); </code></pre>
4,607,991
JavaScript, transform object into array
<p>I've got an object:</p> <pre><code>var obj = { "Mike": 24, "Peter": 23, "Simon": 33, "Tom": 12, "Frank": 31 }; </code></pre> <p>I want to create an array that holds the values of the object. The keys (key names) can be disregarded:</p> <pre><code>[24, 23, 33, 12, 31] </code></pre> <p><strong>The order of the values is NOT important!</strong> </p> <p>One solution (obviously) would be do have a function that takes the values and puts them into an array:</p> <pre><code>var arr = valuesToArray(obj); </code></pre> <p>I will accept such a function as the answer. However, I would be more pleased if there would be an API function (ECMAScript, jQuery, browser-specific, ...) that could do this. Is there such a thing? </p>
50,039,247
9
0
null
2011-01-05 18:48:25.74 UTC
10
2019-12-06 02:54:25.353 UTC
null
null
null
null
425,275
null
1
33
javascript|jquery
65,257
<p>Use <strong>Object.values</strong> it will return array.</p> <pre><code>Object.values(obj) // [24, 23, 33, 12, 31] </code></pre>
4,142,203
Does .NET have icon collections?
<p>Does .NET framework have a collection of icons for use in Windows Forms or WPF application somewhere? How does one use it? For example, how do I use it as an application window icon? </p> <p>I recall, if you want to display a message box there is a choice to show different icons, I suppose there are more icons in the framework?</p>
4,142,304
10
0
null
2010-11-10 07:39:49.473 UTC
35
2022-04-18 12:39:37.45 UTC
2010-11-10 07:46:25.987 UTC
null
446,261
null
385,387
null
1
70
.net|wpf|winforms|icons
98,615
<p>If you're using a full edition (not Express) of Visual Studio, an image library is included for you to use freely in your applications (including commercial products!). The primary advantage of using icons from this library is that they are very similar or identical to those that are used in Windows and other Microsoft products, such as Office and Visual Studio, so your users will find them very familiar. This library includes images, icons, and animations and is installed on your computer when you install Visual Studio. For example, if you're using VS 2010, the image library is located here:</p> <blockquote> <p>..\Program Files\Microsoft Visual Studio 10.0\Common7\VS2010ImageLibrary\1033</p> </blockquote> <p>To use the files, you first need to extract them from the zip file.</p> <p>See <a href="https://devblogs.microsoft.com/visualstudio/tips-and-tricks-visual-studio-2010-image-library/" rel="nofollow noreferrer">this entry</a> on th Visual Studio Team Blog site for more information. As the page explains, the one caveat to using the images is that they must be consistent with their specified usage (&quot;In other words, don't use the 'Cut' image for a 'Copy' command.&quot;), but this really just makes sense.</p> <hr /> <p>If you can't find the icons you're looking for included with Visual Studio's image library, there are plenty of free icon packs available on the Internet. Several of the other posts mention their picks, but I'm a huge fan of <a href="https://p.yusukekamiyamane.com/" rel="nofollow noreferrer">Fugue Icons</a>. Similar to the Silk icons, they're free for use in your applications as long as you provide attribution. Otherwise, you can purchase a royalty-free license for a very reasonable price.</p> <p>If you have money to spend, <a href="http://www.glyfx.com/-" rel="nofollow noreferrer">GlyFX</a> sells high quality icons and graphics, many of which have a similar style as those found in Windows or other Microsoft products.</p> <p>And finally, if you're just looking for a particular icon, you can use one of these free icon search engines:</p> <ul> <li><p><a href="http://www.findicons.com" rel="nofollow noreferrer">http://www.findicons.com</a></p> </li> <li><p><a href="http://www.iconfinder.net" rel="nofollow noreferrer">http://www.iconfinder.net</a></p> </li> <li><p><a href="http://www.iconlet.com" rel="nofollow noreferrer">http://www.iconlet.com</a></p> </li> </ul>
4,647,301
Rolling back local and remote git repository by 1 commit
<p>I've read the similar posts on this topic, and can't for the life of me figure out how to do this properly.</p> <p>I checked in about 1000 files that I don't want, and I'd rather not have to go through 1by1 and remove them all from the repo.</p> <ul> <li>I have a remote <strong><code>master</code></strong> Branch.</li> <li>I have the local <strong><code>master</code></strong> Branch.</li> </ul> <p>They are both at the same revision.</p> <p><strong>I want to rollback my remote by 1 commit.</strong></p> <p>Say my history on <code>master</code> is <code>A--B--C--D--E</code>.<br> I want to rollback my local to <code>D</code>.<br> Then push it to remote so my current hash will be D both remote and local. </p> <p>I'm having issues doing this.<br> I'm using Git Tower but am comfortable with the command line. Any help?</p> <p><strong>UPDATE:</strong> Great comments below. Using a reset seems to be partially discouraged especially if the repository is shared with other users. <strong>What's the best way to undo the previous commit's changes without using a hard reset</strong>? Is there a way?</p>
4,647,362
15
4
null
2011-01-10 13:25:16.023 UTC
103
2022-04-08 12:25:44.46 UTC
2011-01-10 17:07:32.233 UTC
null
95,175
null
95,175
null
1
253
git
151,127
<p>If nobody has pulled your remote repo yet, you can change your branch HEAD and force push it to said remote repo:</p> <pre><code>git reset --hard HEAD^ git push -f </code></pre> <p>(or, if you have direct access to the remote repo, you can change its <a href="https://stackoverflow.com/questions/4624881/how-can-i-uncommit-the-last-commit-in-a-git-bare-repository/4625424#4625424">HEAD reference even though it is a bare repo</a>)</p> <p>Note, as commented by <a href="https://stackoverflow.com/users/1116812/alien-technology">alien-technology</a> in <a href="https://stackoverflow.com/questions/4647301/rolling-back-local-and-remote-git-repository-by-1-commit/4647362#comment64375482_4647362">the comments below</a>, on Windows (CMD session), you would need <code>^^</code>:</p> <pre><code>git reset --hard HEAD^^ git push -f </code></pre> <p>And? as noted in <a href="https://stackoverflow.com/questions/4647301/rolling-back-local-and-remote-git-repository-by-1-commit/4647362?noredirect=1#comment122971508_4647362">the comments</a> by <a href="https://stackoverflow.com/users/12484/jon-schneider">Jon Schneider</a>:</p> <blockquote> <p>If the command with &quot;<code>HEAD^</code>&quot; results in <code>error no matches found: HEAD^</code>, see &quot;<a href="https://stackoverflow.com/q/6091827/6309"><code>git show HEAD^</code> doesn't seem to be working. Is this normal?</a>&quot;</p> </blockquote> <p>Update since 2011:<br /> Using <strong><code>git push --force-with-lease</code></strong> (<a href="https://stackoverflow.com/a/52937476/6309">that I present here</a>, introduced in 2013 with Git 1.8.5) is safer.</p> <p>See <a href="https://stackoverflow.com/users/14660/schwern">Schwern</a>'s <a href="https://stackoverflow.com/a/59994138/6309">answer</a> for illustration.</p> <hr /> <blockquote> <p>What if somebody has already pulled the repo? What would I do then?</p> </blockquote> <p>Then I would suggest something that doesn't rewrite the history:</p> <ul> <li><strong><a href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html" rel="noreferrer"><code>git revert</code></a></strong> locally your last commit (creating a new commit that reverses what the previous commit did)</li> <li>push the 'revert' generated by <code>git revert</code>.</li> </ul>
14,407,007
Best way to check for mongoose validation error
<p>I've got two <a href="http://mongoosejs.com/docs/validation.html">validation</a> functions for my usermodel</p> <pre><code>User.schema.path('email').validate(function(value, respond) { User.findOne({email: value}, function(err, user) { if(err) throw err; if(user) return respond(false); respond(true); }); }, 'EMAIL_EXISTS'); </code></pre> <p>and the same for <code>username</code></p> <pre><code>User.schema.path('username').validate(function(value, respond) { User.findOne({username: value}, function(err, user) { if(err) throw err; if(user) return respond(false); respond(true); }); }, 'USERNAME_TAKEN'); </code></pre> <p>They return errors in the following format</p> <pre><code>{ message: 'Validation failed', name: 'ValidationError', errors: { username: { message: 'Validator "USERNAME_TAKEN" failed for path username', name: 'ValidatorError', path: 'username', type: 'USERNAME_TAKEN' } } } </code></pre> <p>The error for the <code>email</code> path is similar. Is there a smarter way to check for those errors than the following?</p> <pre><code>if (err &amp;&amp; err.errors &amp;&amp; err.errors.username) { ... } </code></pre> <p>This is kind of ugly.</p>
14,642,233
8
0
null
2013-01-18 20:20:43.487 UTC
13
2021-06-03 10:01:01.223 UTC
null
null
null
null
1,256,496
null
1
35
node.js|mongoose
56,808
<p>Technically you must check first the error name because not all errors are handled the same way. Then, based on the error name you must check for particular properties, as the errors property that comes with a ValidationError.</p> <p>Also you put the field name in the error type and this is redundant, it's better to use the same error type because in the error checking procedure you will get the field name also.</p> <p>So your code can be something like:</p> <pre><code>User.schema.path('email').validate(function(value, respond) { User.findOne({email: value}, function(err, user) { if(err) throw err; if(user) return respond(false); respond(true); }); }, 'exists'); User.schema.path('username').validate(function(value, respond) { User.findOne({username: value}, function(err, user) { if(err) throw err; if(user) return respond(false); respond(true); }); }, 'exists'); </code></pre> <p>And then, the error checking procedure:</p> <pre><code>if (err) { switch (err) { case err instanceof mongoose.Error.ValidationError: for (field in err.errors) { switch (err.errors[field].type) { case 'exists': ... break; case 'invalid': ... break; ... } } break; default: ... } } </code></pre> <p>If you want to shorten this, you have various options. If you only have one type of validation you can do it like this:</p> <pre><code>if (err) { if (err instanceof mongoose.Error.ValidationError) { for (field in err.errors) { ... } } else { // A general error (db, crypto, etc…) ... } } </code></pre> <p>The minimal expression of the error check procedure would be similar to what you've wrote in your post:</p> <pre><code>if (err) { for (field in err.errors) { ... } } </code></pre> <p>This will work because if errors is not defined it will just ignore the for. But you're ignoring all other error types here.</p> <p>I also think that these error layouts are a bit messing, but don't expect for this to change in a near future.</p>
14,847,760
Ruby idiom for substring from index until end of string
<p>Just wondering if there's a Ruby idiom for extracting a substring from an index until the end of the string. I know of <code>str[index..-1]</code> which works by passing in a range object to the <code>String</code>'s <code>[]</code> method but it's a little clunky. In python, for example, you could write <code>str[index:]</code> which would implicitly get you the rest of the string.</p> <p>Example:</p> <pre><code>s = "hello world" s[6..-1] # &lt;-- "world" </code></pre> <p>Is there anything nicer than <code>s[6..-1]</code>? </p>
14,847,879
6
7
null
2013-02-13 06:28:48.757 UTC
3
2019-07-03 13:54:31.59 UTC
null
null
null
null
1,164,573
null
1
43
ruby|string|substring|slice|idioms
34,128
<p>I think it isn't.</p> <p>It seems that <code>Range</code> is better way to do it.</p>
2,652,935
Internal phone storage in Android
<p>How can you retrieve your phone internal storage from an app? I found MemoryInfo, but it seems that returns information on how much memory use your currently running tasks. </p> <p>I am trying to get my app to retrieve how much internal phone storage is available.</p>
2,653,121
2
0
null
2010-04-16 12:37:05.21 UTC
10
2019-01-08 13:36:52.243 UTC
2019-01-08 13:36:52.243 UTC
null
469,983
null
274,365
null
1
7
android
12,311
<p>Use <code>android.os.Environment</code> to find the internal directory, then use <code>android.os.StatFs</code> to call the Unix <code>statfs</code> system call on it. Shamelessly <a href="https://github.com/android/platform_packages_apps_settings/blob/gingerbread/src/com/android/settings/deviceinfo/Memory.java#L335" rel="noreferrer">stolen</a> from the Android settings app:</p> <pre><code>File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return Formatter.formatFileSize(this, availableBlocks * blockSize); </code></pre>
2,731,894
What happens if you kill a long-running alter query?
<p>What happens if you kill a long-running alter query? Will the alter query simply revert? How long could that take (as a proportion of the time it has already been running)?</p> <p>What if that query is being replicated onto another server? Will killing the process on the other server revert the original server's alter query?</p> <p>We're running mysql</p>
2,732,646
2
3
null
2010-04-28 17:47:54.397 UTC
2
2016-01-26 10:14:29.14 UTC
null
null
null
null
122,422
null
1
32
mysql|kill|alter
26,412
<p>It depends what you're doing. If you're running <code>an alter table...add index</code> command on an <code>InnoDB</code> table (not so sure about <code>MyISAM</code>), then it will just run and run as it copies the whole darn table lock-stock-and-barrel first: if it's in the middle of "copy to temp table" then it's pretty much unstoppable.</p> <p><a href="http://dev.mysql.com/doc/refman/5.5/en/alter-table.html" rel="noreferrer">See here:</a></p> <blockquote> <p>In most cases, ALTER TABLE works by making a temporary copy of the original table. The alteration is performed on the copy, and then the original table is deleted and the new one is renamed. While ALTER TABLE is executing, the original table is readable by other sessions. Updates and writes to the table are stalled until the new table is ready, and then are automatically redirected to the new table without any failed updates.</p> </blockquote>
2,982,376
Why is Serializable Attribute required for an object to be serialized
<p>Based on my understanding, SerializableAttribute provides no compile time checks, as it's all done at runtime. If that's the case, then why is it required for classes to be marked as serializable?</p> <p>Couldn't the serializer just try to serialize an object and then fail? Isn't that what it does right now? When something is marked, it tries and fails. Wouldn't it be better if you had to mark things as unserializable rather than serializable? That way you wouldn't have the problem of libraries not marking things as serializable?</p>
2,982,534
2
2
null
2010-06-05 22:33:51.82 UTC
5
2012-07-11 01:19:36.89 UTC
2012-07-11 01:19:36.89 UTC
null
79,646
null
98,970
null
1
40
c#|.net|serialization
19,436
<p>As I understand it, the idea behind the <code>SerializableAttribute</code> is to create an <strong>opt-in</strong> system for binary serialization.</p> <p>Keep in mind that, unlike XML serialization, which uses public properties, binary serialization grabs all the private fields by default.</p> <p>Not only this could include operating system structures and private data that is not supposed to be exposed, but <strong>deserializing</strong> it could result in corrupt state that can crash an application (silly example: a handle for a file open in a different computer).</p>
2,634,043
svn diff: file marked as binary type
<p>I'm doing an <code>svn diff</code> on one of my files and svn is detecting it as a binary type. The file is readable plain text and I would like to be able to get a diff of this file. How do I tell SVN that this is not a binary file?</p> <pre><code>Cannot display: file marked as a binary type. svn:mime-type = application/octet-stream </code></pre>
2,634,053
2
0
null
2010-04-14 00:03:25.107 UTC
18
2013-11-14 20:47:36.067 UTC
2013-11-14 20:47:36.067 UTC
null
2,390,083
null
11,708
null
1
85
svn|file-type
40,598
<p>You can use the <a href="http://svnbook.red-bean.com/en/1.5/svn.ref.properties.html" rel="noreferrer">Subversion property</a> svn:mime-type to set an explicit mimetype on the file:</p> <pre> svn propset svn:mime-type 'text/plain' <i>path/to/file</i> </pre> <p>Alternatively, you can delete this property (since Subversion assumes plaintext, otherwise) using:</p> <pre> svn propdel svn:mime-type <i>path/to/file</i> </pre>
2,178,301
linenumbering with listings package in latex
<p>I am trying to insert a code snippet with the listingspackage, and want the lines numbered. However I would like only every 5th line and the first to be numbered (numbers beeing(1,5,10,15,...)) according to the manual:</p> <pre><code>stepnumber=5 </code></pre> <p>should do the trick, however using my minimal example (see bottom), I get the line numbers 1,6,11,16,...</p> <p>May be I misinterpreted he manual 8did that once before), however I am clueless.</p> <p>If a real latex guru is around, there would be something I would like even more, having every linenumber printed however every fifth in bold/ a different style numbers than beeing: 1 2 3 4 <strong>5</strong> 6 7 8 9 <strong>10</strong> 11 ... however since this is not in the doku I am sure it requires some deeper latex/listings knowledge.</p> <p>P.S.: There is one more oddity, eventhough I put "numberfirstline=false" I get the line number 1 ( I get that linenumber as well without setting numberfirstline, which should default to false), it is jsu in there to point out that something is wrong.</p> <p>I am using miktex for compilation, if that helps.</p> <p>Thanks in advance.</p> <pre><code>\documentclass{scrreprt} %[twoside,headings=openright] %Sourcecode formatting \usepackage{listings} \lstset{ numbers=left, % Ort der Zeilennummern stepnumber=5, % Abstand zwischen den Zeilennummern numberfirstline=false } \begin{document} \lstinputlisting{sourcecode/AES/lookupSoftcoded.S} %codefile with 15 lines or so... \end{document} </code></pre>
2,178,419
1
0
null
2010-02-01 16:34:22.62 UTC
3
2010-02-01 16:51:22.647 UTC
null
null
null
null
258,418
null
1
29
latex|listings
37,094
<p>You can get the desired numbering like this:</p> <pre><code>\lstset{ numbers=left, stepnumber=5, firstnumber=1, numberfirstline=true } </code></pre>
30,411,060
AngularJS browser cache issues
<p>Good morning, I have a web application in production environement. The users are using it every day, when I publish an update and a user comes back to the web application he views the old version of the web application. He needs to refresh the browser to load the new version. How can I solve this problem? I cannot tell hundreds of users to refresh the page every time I publish an update (3-4 times a week).</p>
30,411,090
5
0
null
2015-05-23 09:27:28.853 UTC
9
2019-09-09 06:33:14.773 UTC
null
null
null
null
2,100,125
null
1
21
angularjs|caching
40,810
<p>A simple solution would be to add <strong>query strings representing timestamp or session id</strong> to your files. </p> <p>For e.g., in our spring applications, we simply use : </p> <pre><code>&lt;script src="js/angular/lib/app.js?r=&lt;%= session.getId()%&gt;"&gt;&lt;/script&gt; </code></pre> <p>You can implement the same solution in your server specific implementation too.</p>
34,611,919
How to package a portable .NET library targeting .NET Core?
<p>How do I package a portable .NET library in a modern general-purpose way? Let's assume I have a single AnyCPU assembly that I wish to make available to any .NET platform that supports the .NET Core API surface, for example .NET Framework 4.6 and the Universal Windows Platform.</p> <blockquote> <p>This is a series of questions and answers that document my findings on the topic of modern NuGet package authoring, focusing especially on the changes introduced with NuGet 3. You may also be interested in some related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/34611829/how-to-package-a-net-framework-library">How to package a .NET Framework library?</a></li> <li><a href="https://stackoverflow.com/questions/34611882/how-to-package-a-net-library-targeting-the-universal-windows-platform">How to package a .NET library targeting the Universal Windows Platform?</a></li> <li><a href="https://stackoverflow.com/questions/34611968/how-to-package-a-net-library-targeting-net-framework-and-universal-windows-pla">How to package a .NET library targeting .NET Framework and Universal Windows Platform and include platform-specific functionality?</a></li> <li><a href="https://stackoverflow.com/questions/34611991/how-to-package-a-multi-architecture-net-library-that-targets-the-universal-wind">How to package a multi-architecture .NET library that targets the Universal Windows Platform?</a></li> <li><a href="https://stackoverflow.com/questions/34612015/how-to-package-a-net-library-that-targets-the-universal-windows-platform-and-de">How to package a .NET library that targets the Universal Windows Platform and depends on Visual Studio extension SDKs?</a></li> </ul> </blockquote>
34,611,920
2
0
null
2016-01-05 12:38:09.447 UTC
11
2017-03-08 19:53:32.41 UTC
2016-01-05 12:44:32.793 UTC
null
2,928
null
2,928
null
1
21
.net|nuget|uwp|nuget-package|.net-core
6,369
<p>This answer builds upon the <a href="https://stackoverflow.com/questions/34611829/how-to-package-a-net-framework-library">principles used to package libraries targeting the .NET Framework</a>. Read the linked answer first to better understand the following.</p> <p>To publish the portable .NET library, you will need to create a NuGet package with the following structure:</p> <pre><code>\---lib \---dotnet MyPortableLibrary.dll MyPortableLibrary.pdb MyPortableLibrary.XML </code></pre> <p>All three files will come from your project's build output directory under the Release build configuration.</p> <p>The <code>dotnet</code> directory in the structure above has a special meaning - it indicates to NuGet that the files in the directory are to be used on any platform that all your package's dependencies are compatible with. Therefore, your package is automatically usable on any .NET platform that supports all your dependencies (e.g. .NET Core).</p> <p>The crucial next step is to determine the list of dependencies. Due to <a href="https://github.com/NuGet/Home/issues/1883">a package management issue</a> it is not possible to simply declare a dependency on .NET Core itself (.NET Core is the API surface shared by all the .NET platforms). Instead, you must manually determine each .NET Core component dependency and add it to the nuspec file.</p> <p>The dependency detection process for .NET Core packages consists of two steps:</p> <ol> <li>Determine the .NET Core assemblies referenced by your library.</li> <li>Determine the NuGet packages that contain these assemblies.</li> </ol> <p>Visual Studio does not provide the information you need. Instead, you need to build your library and inspect the resulting DLL file. The following PowerShell script will display the references of a .NET assembly:</p> <pre><code>Get-ChildItem MyPortableLibrary.dll | % { [Reflection.Assembly]::LoadFile($_.FullName).GetReferencedAssemblies() | % { $_.Name + ".dll" } } </code></pre> <p>The output of this command will be a list of assembly names, for example:</p> <pre><code>System.Runtime.dll System.Resources.ResourceManager.dll System.Numerics.Vectors.dll </code></pre> <p>Once you have obtained the list, open the project.lock.json file in your project directory. This file contains information about all NuGet packages used by your project. You will find, among other data, various blocks of JSON such as the following:</p> <pre><code>"System.Numerics.Vectors/4.1.0": { "dependencies": { "System.Globalization": "[4.0.10, )", "System.Resources.ResourceManager": "[4.0.0, )", "System.Runtime": "[4.0.20, )", "System.Runtime.Extensions": "[4.0.10, )" }, "frameworkAssemblies": [ "mscorlib", "System.Numerics" ], "compile": { "ref/net46/System.Numerics.Vectors.dll": {} }, "runtime": { "lib/net46/System.Numerics.Vectors.dll": {} } }, </code></pre> <p>This block of JSON indicates that the assembly files listed under "compile" are provided by the package listed in the top level value (System.Numerics.Vectors version 4.1.0). Use this information to map every referenced assembly to a NuGet package. Note that while the package and assembly names are often the same, this is not always the case!</p> <p>For any NuGet packages that are not part of .NET Core, you can skip the above process as you already know the exact package you have a dependency on. The dependency detection logic described here is only required because you cannot declare a dependency directly on .NET Core (the Microsoft.NETCore package) due to the issue linked above.</p> <p>Now simply list all the dependencies in your nuspec file, based on the following example:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"&gt; &lt;metadata minClientVersion="3.2"&gt; &lt;id&gt;Example.MyPortableLibrary&lt;/id&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;authors&gt;Firstname Lastname&lt;/authors&gt; &lt;description&gt;Example of a portable library with NuGet package dependencies.&lt;/description&gt; &lt;dependencies&gt; &lt;dependency id="System.Numerics.Vectors" version="4.1.0" /&gt; &lt;dependency id="System.Resources.ResourceManager" version="4.0.0" /&gt; &lt;dependency id="System.Runtime" version="4.0.20" /&gt; &lt;/dependencies&gt; &lt;/metadata&gt; &lt;files&gt; &lt;file src="..\bin\Release\MyPortableLibrary.*" target="lib\dotnet" /&gt; &lt;/files&gt; &lt;/package&gt; </code></pre> <p>That's it! The resulting package is usable on any compatible .NET platform, such as .NET Framework 4.6 or Universal Windows Platform. Remember to build your solution using the Release configuration before creating the NuGet package.</p> <p>A sample library and the relevant packaging files are <a href="https://github.com/sandersaares/nuget-package-authoring">available on GitHub</a>. The solution corresponding to this answer is PortableLibrary.</p> <p>Refer to <a href="http://blogs.msdn.com/b/lucian/archive/2015/09/15/writing-a-nuget-package-for-vs2015-rtm-repost.aspx">Lucian Wischik's blog</a> for a deeper dive into the logic that operates on such NuGet packages.</p>
31,362,044
Anonymous interface implementation in Golang
<p>In Go, is there a way to satisfy an interface anonymously? It doesn't seem like there is, but this was my best attempt.</p> <p>(In the <a href="http://play.golang.org/p/4i-8o087dg" rel="noreferrer">Playground</a>)</p> <pre><code>package main import "fmt" type Thing interface { Item() float64 SetItem(float64) } func newThing() Thing { item := 0.0 return struct { Item (func() float64) SetItem (func(float64)) }{ Item: func() float64 { return item }, SetItem: func(x float64) { item = x }, } } func main() { thing := newThing() fmt.Println("Hello, playground") fmt.Println(thing) } </code></pre>
31,362,378
4
0
null
2015-07-11 21:30:52.033 UTC
16
2021-04-27 21:34:18.087 UTC
null
null
null
null
97,964
null
1
72
go|anonymous-types
50,505
<p>Go uses <a href="http://golang.org/ref/spec#Method_sets">method sets</a> to declare which methods belong to a type. There is only one way to declare functions with receiver types (methods):</p> <pre><code>func (v T) methodName(...) ... { } </code></pre> <p>Since nested functions are forbidden, there is no way to define a method set on anonymous structs.</p> <p>The second thing that will not allow this is that methods are read-only. <a href="http://golang.org/ref/spec#Method_values">Method values</a> were introduced to allow to pass methods around and use them in goroutines but not to manipulate the method set.</p> <p>What you can do instead is to provide a ProtoThing and refer to underlying implementations of your anonymous struct (<a href="http://play.golang.org/p/k0lCJqyF6p">on play</a>):</p> <pre><code>type ProtoThing struct { itemMethod func() float64 setItemMethod func(float64) } func (t ProtoThing) Item() float64 { return t.itemMethod() } func (t ProtoThing) SetItem(x float64) { t.setItemMethod(x) } // ... t := struct { ProtoThing }{} t.itemMethod = func() float64 { return 2.0 } t.setItemMethod = func(x float64) { item = x } </code></pre> <p>This works because by embedding <code>ProtoThing</code> the method set is inherited. Thus the anonymous struct also satisfies the <code>Thing</code> interface.</p>
50,115,416
get height of a Widget using its GlobalKey in flutter
<p>I am struggling getting the height of a Widget using its GlobalKey. the function that is getting the height is called after the Layout is rendered to make sure the context is available but key.currentState and also key.currentContext still returns null.</p> <pre><code>import 'package:flutter/material.dart'; class TestPage extends StatefulWidget{ @override State&lt;StatefulWidget&gt; createState() =&gt; new TestPageState(); } class TestPageState extends State&lt;TestPage&gt;{ final TestWidget testWidget = new TestWidget(); @override initState() { //calling the getHeight Function after the Layout is Rendered WidgetsBinding.instance .addPostFrameCallback((_) =&gt; getHeight()); super.initState(); } void getHeight(){ final GlobalKey key = testWidget.key; //returns null: final State state = key.currentState; //returns null: final BuildContext context = key.currentContext; //Error: The getter 'context' was called on null. final RenderBox box = state.context.findRenderObject(); print(box.size.height); print(context.size.height); } @override Widget build(BuildContext context) { return new Scaffold( body: testWidget, ); } } class TestWidget extends StatefulWidget{ @override Key get key =&gt; new GlobalKey&lt;TestWidgetState&gt;(); @override State&lt;StatefulWidget&gt; createState() =&gt; new TestWidgetState(); } class TestWidgetState extends State&lt;TestWidget&gt;{ @override Widget build(BuildContext context) { return new Container( child: new Text("Test", style: const TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold),), ); } } </code></pre>
50,115,927
3
0
null
2018-05-01 11:08:23.933 UTC
11
2022-01-18 10:40:38.64 UTC
null
null
null
null
5,955,776
null
1
15
dart|flutter
22,648
<p>You need to assign that key to a widget using <code>super</code> in the widget constructor. Not add it as a field. That <code>Key</code> also must be constant.</p> <pre><code>import 'package:flutter/material.dart'; class TestPage extends StatefulWidget { @override State&lt;StatefulWidget&gt; createState() =&gt; new TestPageState(); } class TestPageState extends State&lt;TestPage&gt; { final key = new GlobalKey&lt;TestWidgetState&gt;(); @override initState() { //calling the getHeight Function after the Layout is Rendered WidgetsBinding.instance.addPostFrameCallback((_) =&gt; getHeight()); super.initState(); } void getHeight() { //returns null: final State state = key.currentState; //returns null: final BuildContext context = key.currentContext; //Error: The getter 'context' was called on null. final RenderBox box = state.context.findRenderObject(); print(box.size.height); print(context.size.height); } @override Widget build(BuildContext context) { return new Scaffold( body: new TestWidget(key: key), ); } } class TestWidget extends StatefulWidget { TestWidget({Key key}) : super(key: key); @override State&lt;StatefulWidget&gt; createState() =&gt; new TestWidgetState(); } class TestWidgetState extends State&lt;TestWidget&gt; { @override Widget build(BuildContext context) { return new Container( child: new Text( "Test", style: const TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold), ), ); } } </code></pre>
48,714,879
Error parsing header X-XSS-Protection - Google Chrome
<p>I upgraded Google Chrome to <code>Version 64.0.3282.140 (Official Build) (64-bit)</code> on a Windows 10 machine. Once I did, I am getting this error on my site within the developer tools console. Not real sure where to start. I did see a similar issue last year that was an issue with youtube (also in the url), but I haven't seen any solutions. </p> <pre><code>Error parsing header X-XSS-Protection: 1; mode=block; report=https://www.google.com/appserve/security-bugs/log/youtube: insecure reporting URL for secure page at character position 22. The default protections will be applied. 16:07:31.905 </code></pre> <p>I'm also seeing the issue when I go directly to youtube via the embedded url so it's not just on my site. </p> <p>UPDATE </p> <p>I've attached a photo of the headers in the response that indicate the google.com url that appears to be generating the issue. </p> <p><a href="https://i.stack.imgur.com/QsvVy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QsvVy.png" alt="enter image description here"></a></p>
48,745,051
2
0
null
2018-02-09 22:14:42.88 UTC
16
2019-10-04 16:11:20.713 UTC
2018-02-12 08:36:28.67 UTC
null
6,849,716
null
7,426,461
null
1
86
javascript|html|google-chrome|youtube|youtube-api
55,668
<p>It's a known bug in the current Google Chrome and Chromium:<br> <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=807304" rel="noreferrer">https://bugs.chromium.org/p/chromium/issues/detail?id=807304</a></p> <p>In the current version of their browser, the Chrome developers had restricted the X-XSS-Protection's report field URL to the same domain origin for some security reasons. So, when you embed a video with some embed code, as it downloads from another server where the header "report=<a href="https://www.google.com/" rel="noreferrer">https://www.google.com/</a>" is set, and while your page is not hosted at the google.com domain - the error message occurs. </p> <p>Yet, all minor sites (including youtube.com) are sending report URL with different origin domains in it. Probably, they are not even aware of this recent change in Chrome. So either YouTube will change their headers or Chrome developers will revert this. There's nothing that we, as end users, can do. Just wait till they sort this out.</p> <p>UPDATE:</p> <p>The issue has been fixed in <code>Version 66.0.3359.117 (Official Build) (64-bit)</code></p>
35,268,940
How to force telegram to update link preview?
<p>Telegram show description meta tag as link preview. I changed the description meta tag but the link preview of my website didn't changed. How to force telegram to update link preview?</p>
35,793,374
4
0
null
2016-02-08 11:48:33.84 UTC
27
2022-07-15 16:59:23.34 UTC
null
null
null
null
2,254,990
null
1
103
seo|telegram
77,056
<p>Go to <a href="https://telegram.me/webpagebot" rel="noreferrer">@webpagebot</a> and send the link (up to 10) you want to update. Automatically will scan your site and generate the new image thumbnail, site name and description.</p> <p>Remember to have og prefix in your <code>html</code> tag as: <code>&lt;html prefix="og: http://ogp.me/ns#"&gt;</code> or telegram bot will not update the graph cache.</p> <p><a href="http://telegramgeeks.com/2016/03/you-can-update-link-preview-telegram/" rel="noreferrer">via telegramgeeks</a></p>
34,987,509
TensorFlow: Max of a tensor along an axis
<p>My question is in two connected parts:</p> <ol> <li><p>How do I calculate the max along a certain axis of a tensor? For example, if I have</p> <pre><code>x = tf.constant([[1,220,55],[4,3,-1]]) </code></pre> <p>I want something like </p> <pre><code>x_max = tf.max(x, axis=1) print sess.run(x_max) output: [220,4] </code></pre> <p>I know there is a <code>tf.argmax</code> and a <code>tf.maximum</code>, but neither give the maximum value along an axis of a single tensor. For now I have a workaround:</p> <pre><code>x_max = tf.slice(x, begin=[0,0], size=[-1,1]) for a in range(1,2): x_max = tf.maximum(x_max , tf.slice(x, begin=[0,a], size=[-1,1])) </code></pre> <p>But it looks less than optimal. Is there a better way to do this?</p></li> <li><p>Given the indices of an <code>argmax</code> of a tensor, how do I index into another tensor using those indices? Using the example of <code>x</code> above, how do I do something like the following:</p> <pre><code>ind_max = tf.argmax(x, dimension=1) #output is [1,0] y = tf.constant([[1,2,3], [6,5,4]) y_ = y[:, ind_max] #y_ should be [2,6] </code></pre> <p>I know slicing, like the last line, does not exist in TensorFlow yet (<a href="https://github.com/tensorflow/tensorflow/issues/206" rel="noreferrer">#206</a>). </p> <p>My question is: <em>what is the best workaround for my specific case (maybe using other methods like gather, select, etc.)?</em></p> <p>Additional information: I know <code>x</code> and <code>y</code> are going to be two dimensional tensors only!</p></li> </ol>
34,988,069
2
0
null
2016-01-25 07:49:27.57 UTC
7
2018-10-12 18:11:31.34 UTC
2018-10-12 18:11:31.34 UTC
null
2,956,066
null
5,813,490
null
1
34
python|tensorflow|deep-learning|max|tensor
66,124
<p>The <a href="https://www.tensorflow.org/versions/0.6.0/api_docs/python/math_ops.html#reduce_max"><code>tf.reduce_max()</code></a> operator provides exactly this functionality. By default it computes the global maximum of the given tensor, but you can specify a list of <code>reduction_indices</code>, which has the same meaning as <code>axis</code> in NumPy. To complete your example:</p> <pre><code>x = tf.constant([[1, 220, 55], [4, 3, -1]]) x_max = tf.reduce_max(x, reduction_indices=[1]) print sess.run(x_max) # ==&gt; "array([220, 4], dtype=int32)" </code></pre> <p>If you compute the argmax using <a href="https://www.tensorflow.org/versions/0.6.0/api_docs/python/math_ops.html#argmax"><code>tf.argmax()</code></a>, you could obtain the the values from a different tensor <code>y</code> by flattening <code>y</code> using <a href="https://www.tensorflow.org/versions/0.6.0/api_docs/python/array_ops.html#reshape"><code>tf.reshape()</code></a>, converting the argmax indices into vector indices as follows, and using <a href="https://www.tensorflow.org/versions/0.6.0/api_docs/python/array_ops.html#gather"><code>tf.gather()</code></a> to extract the appropriate values:</p> <pre><code>ind_max = tf.argmax(x, dimension=1) y = tf.constant([[1, 2, 3], [6, 5, 4]]) flat_y = tf.reshape(y, [-1]) # Reshape to a vector. # N.B. Handles 2-D case only. flat_ind_max = ind_max + tf.cast(tf.range(tf.shape(y)[0]) * tf.shape(y)[1], tf.int64) y_ = tf.gather(flat_y, flat_ind_max) print sess.run(y_) # ==&gt; "array([2, 6], dtype=int32)" </code></pre>
28,875,514
Adding content after add to cart button on woocommerce single page
<p>I have successfully added a content after short description on single product page with </p> <pre><code>if (!function_exists('my_content')) { function my_content( $content ) { $content .= '&lt;div class="custom_content"&gt;Custom content!&lt;/div&gt;'; return $content; } } add_filter('woocommerce_short_description', 'my_content', 10, 2); </code></pre> <p>I saw that in <code>short-description.php</code> there was <code>apply_filters( 'woocommerce_short_description', $post-&gt;post_excerpt )</code></p> <p>so I hooked to that.</p> <p>In the same way, I'd like to add a content after the add to cart button, so I found <code>do_action( 'woocommerce_before_add_to_cart_button' )</code>, and now I am hooking to <code>woocommerce_before_add_to_cart_button</code>. I'm using</p> <pre><code>if (!function_exists('my_content_second')) { function my_content_second( $content ) { $content .= '&lt;div class="second_content"&gt;Other content here!&lt;/div&gt;'; return $content; } } add_action('woocommerce_after_add_to_cart_button', 'my_content_second'); </code></pre> <p>But nothing happens. Can I only hook to hooks inside <code>apply_filters</code>? From what I've understood so far by working with hooks is that you only need a hook name to hook to and that's it. The first one was a filter hook, so I used <code>add_filter</code>, and the second one is action hook so I should use <code>add_action</code>, and all should work. So why doesn't it?</p>
28,875,852
3
0
null
2015-03-05 10:25:37.897 UTC
3
2021-09-15 11:52:41.473 UTC
2015-03-05 10:46:40.887 UTC
null
629,127
null
629,127
null
1
6
php|wordpress|woocommerce|hook
38,207
<p>Here, you need to echo content as it is add_action hook.</p> <pre><code>add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' ); /* * Content below "Add to cart" Button. */ function add_content_after_addtocart_button_func() { // Echo content. echo '&lt;div class="second_content"&gt;Other content here!&lt;/div&gt;'; } </code></pre>
29,346,935
Elasticsearch: nested object under path is not of nested type
<p>I've been trying to search on my document which contains a nested field. I created the nested mapping like this: </p> <pre><code>{ "message": { "properties": { "messages": { "type": "nested", "properties": { "message_id": { "type": "string" }, "message_text": { "type": "string" }, "message_nick": { "type": "string" } } } } } } </code></pre> <p>My search looks like this: </p> <pre><code>curl -XGET 'localhost:9200/thread_and_messages/thread/_search' \ -d '{"query": {"bool": {"must": [{"match": {"thread_name": "Banana"}}, {"nested": {"path": "messages", "query": {"bool": {"must": [{"match": {"messages.message_text": "Banana"}}]}}}]}}}}' </code></pre> <p>Yet I am receiving this error message: </p> <pre><code>QueryParsingException[[thread_and_messages] [nested] nested object under path [messages] is not of nested type] </code></pre> <p><strong>EDIT</strong></p> <p>I am still receiving this error. I am doing this via Java so this is the document I am trying to create:</p> <pre><code>{ "_id": { "path": "3", "thread_id": "3", "thread_name": "Banana", "created": "Wed Mar 25 2015", "first_nick": "AdminTech", "messages": [ { "message_id": "9", "message_text": "Banana", "message_nick": "AdminTech" } ] } } </code></pre> <p>Creating the index like so:</p> <pre><code>CreateIndexRequestBuilder indexRequest = client.admin().indices().prepareCreate(INDEX).addMapping("message", mapping); </code></pre> <p>I think I am possibly indexing the document incorrectly.</p>
29,749,186
3
0
null
2015-03-30 13:01:34.953 UTC
6
2022-03-29 03:07:30.96 UTC
2017-07-13 10:27:50.51 UTC
null
1,058,028
null
2,387,293
null
1
33
elasticsearch|nested
41,805
<p>TLDR: Put <code>"type": "nested",</code> in your nested type.</p> <p>Say we have a normal type, and another type nested in it:</p> <pre><code>{ "some_index": { "mappings": { "normal_type": { "properties": { "nested_type": { "type": "nested", "properties": { "address": { "type": "string" }, "country": { "type": "string" } } }, "first_name": { "type": "string" }, "last_name": { "type": "string" } } } } } } </code></pre> <p>The <code>"type": "nested",</code> line is required for the nested queries to work which have <code>"path":</code> assigned to <code>nested_type</code>, like this:</p> <pre><code>GET /some_index/normal_type/_search { "query": { "nested": { "query": { "bool": {} }, "path": "nested_type" } } } </code></pre> <p>The <code>"type": "nested",</code> line seems to be required in newer Elasticsearch versions only (since 1.1.1 ?).</p>
49,947,592
Replace NA with Zero in dplyr without using list()
<p>In dplyr I can replace NA with 0 using the following code. The issue is this inserts a list into my data frame which screws up further analysis down the line. I don't even understand lists or atomic vectors or any of that at this point. I just want to pick certain columns, and replace all occurrences of NA with zero. And maintain the columns integer status.</p> <pre><code>library(dplyr) df &lt;- tibble(x = c(1, 2, NA), y = c("a", NA, "b"), z = list(1:5, NULL, 10:20)) df df %&gt;% replace_na(list(x = 0, y = "unknown")) </code></pre> <p>That works but transforms the column into a list. How do I do it without transforming the column into a list?</p> <p>And here's how to do it in base R. But not sure how to work this into a mutate statement:</p> <pre><code>df$x[is.na(df$x)] &lt;- 0 </code></pre>
49,947,633
5
0
null
2018-04-20 18:17:34.227 UTC
11
2022-09-06 12:21:55.333 UTC
null
null
null
null
8,495,608
null
1
43
r|dplyr|na
79,593
<p>What version of <code>dplyr</code> are you using? It might be an old one. The <code>replace_na</code> function now seems to be in <code>tidyr</code>. This works</p> <pre><code>library(tidyr) df &lt;- tibble::tibble(x = c(1, 2, NA), y = c("a", NA, "b"), z = list(1:5, NULL, 10:20)) df %&gt;% replace_na(list(x = 0, y = "unknown")) %&gt;% str() # Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 3 variables: # $ x: num 1 2 0 # $ y: chr "a" "unknown" "b" # $ z:List of 3 # ..$ : int 1 2 3 4 5 # ..$ : NULL # ..$ : int 10 11 12 13 14 15 16 17 18 19 ... </code></pre> <p>We can see the NA values have been replaced and the columns <code>x</code> and <code>y</code> are still atomic vectors. Tested with <code>tidyr_0.7.2</code>.</p>
45,160,055
Unit Testing in Retrofit for Callback
<p>Here i got a sample of code in presenter. How do i make write a test for onSuccess and onFailure in retrofit call</p> <pre><code>public void getNotifications(final List&lt;HashMap&lt;String,Object&gt;&gt; notifications){ if (!"".equalsIgnoreCase(userDB.getValueFromSqlite("email",1))) { UserNotifications userNotifications = new UserNotifications(userDB.getValueFromSqlite("email",1),Integer.parseInt(userDB.getValueFromSqlite("userId",1).trim())); Call call = apiInterface.getNotifications(userNotifications); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { UserNotifications userNotifications1 = (UserNotifications) response.body(); if(userNotifications1.getNotifications().isEmpty()){ view.setListToAdapter(notifications); onFailure(call,new Throwable()); } else { for (UserNotifications.Datum datum:userNotifications1.getNotifications()) { HashMap&lt;String,Object&gt; singleNotification= new HashMap&lt;&gt;(); singleNotification.put("notification",datum.getNotification()); singleNotification.put("date",datum.getDate()); notifications.add(singleNotification); } view.setListToAdapter(notifications); } } @Override public void onFailure(Call call, Throwable t) { call.cancel(); } }); } } } </code></pre> <p>How do i write unittesting to cover all cases for this piece of code.</p> <p>Thanks</p>
45,166,524
2
0
null
2017-07-18 07:18:30.533 UTC
11
2021-05-04 13:56:06.787 UTC
2017-07-18 07:21:48.31 UTC
null
2,062,634
null
8,118,272
null
1
15
android|unit-testing|junit|mockito|retrofit2
12,325
<p>When you want to test different responses from service (API) it's probably best to mock it and return what you need.</p> <pre><code> @Test public void testApiResponse() { ApiInterface mockedApiInterface = Mockito.mock(ApiInterface.class); Call&lt;UserNotifications&gt; mockedCall = Mockito.mock(Call.class); Mockito.when(mockedApiInterface.getNotifications()).thenReturn(mockedCall); Mockito.doAnswer(new Answer() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Callback&lt;UserNotifications&gt; callback = invocation.getArgumentAt(0, Callback.class); callback.onResponse(mockedCall, Response.success(new UserNotifications())); // or callback.onResponse(mockedCall, Response.error(404. ...); // or callback.onFailure(mockedCall, new IOException()); return null; } }).when(mockedCall).enqueue(any(Callback.class)); // inject mocked ApiInterface to your presenter // and then mock view and verify calls (and eventually use ArgumentCaptor to access call parameters) } </code></pre>
65,638,840
How do I pass an href to an onClick function in nextjs?
<p>In the following code</p> <pre><code>import Link from &quot;next/link&quot;; export default function IndexPage() { const handleClick = (path) =&gt; { if (path === &quot;/about&quot;) { console.log(&quot;I clicked on the About Page&quot;); } if (path === &quot;/posts&quot;) { console.log(&quot;I clicked on the Posts Page&quot;); } }; return ( &lt;div&gt; Hello World.{&quot; &quot;} &lt;Link onClick={() =&gt; handleClick(&quot;/about&quot;)} href=&quot;/about&quot;&gt; &lt;a&gt;About&lt;/a&gt; &lt;/Link&gt; &lt;Link onClick={() =&gt; handleClick(&quot;/posts&quot;)} href=&quot;/posts&quot;&gt; &lt;a&gt;Posts&lt;/a&gt; &lt;/Link&gt; &lt;/div&gt; ); </code></pre> <p>Whenever the about or posts page is clicked, I'd like to <code>console.log</code> that I clicked on the page name. Right now, my current implementation does not <code>console.log</code> anything. What is wrong with my code?</p>
66,947,080
5
0
null
2021-01-09 02:39:50.917 UTC
0
2022-05-22 11:21:32.1 UTC
2021-11-05 05:06:34.66 UTC
null
12,146,388
null
12,146,388
null
1
12
reactjs|next.js
42,341
<p>You can move the onClick handler to the <code>&lt;a&gt; tag</code>.</p> <pre class="lang-js prettyprint-override"><code>import { useRouter } from &quot;next/router&quot;; import Link from &quot;next/link&quot;; export default function IndexPage() { const router = useRouter(); const handleClick = (e, path) =&gt; { if (path === &quot;/about&quot;) { console.log(&quot;I clicked on the About Page&quot;); } if (path === &quot;/posts&quot;) { console.log(&quot;I clicked on the Posts Page&quot;); } }; return ( &lt;div&gt; Hello World.{&quot; &quot;} &lt;Link href=&quot;/&quot;&gt; &lt;a onClick={(e) =&gt; handleClick(e, &quot;/about&quot;)}&gt;About&lt;/a&gt; &lt;/Link&gt;{&quot; &quot;} &lt;Link href=&quot;/&quot;&gt; &lt;a onClick={(e) =&gt; handleClick(e, &quot;/posts&quot;)}&gt;Posts&lt;/a&gt; &lt;/Link&gt; &lt;/div&gt; ); } </code></pre>
27,991,964
freemarker templates check if sequence is empty
<p>I would like to check if a sequence is empty in a freemarker template.</p> <p>This snippet works to check if a sequence <strong><em>contains</em></strong> a value:</p> <pre><code>&lt;#if node.attachments?seq_contains("blue")&gt; &lt;pre&gt;hello&lt;/pre&gt; &lt;/#if&gt; </code></pre> <p>However, if <code>node.attachments</code> is empty i would like to do something else.</p> <p>That is the syntax for this?</p>
27,992,179
1
0
null
2015-01-16 20:05:57.547 UTC
null
2018-06-11 22:07:13.027 UTC
null
null
null
null
1,322,427
null
1
31
java|freemarker
28,983
<p>Try:</p> <pre><code>&lt;#if node.attachments?size != 0&gt; </code></pre> <p>Or:</p> <pre><code>&lt;#if node.attachments?has_content&gt; </code></pre>
22,799,648
Convert curl example to pycurl
<p>Could someone convert the following PostMark curl example to pycurl?</p> <pre><code>curl -X POST &quot;http://api.postmarkapp.com/email&quot; \ -H &quot;Accept: application/json&quot; \ -H &quot;Content-Type: application/json&quot; \ -H &quot;X-Postmark-Server-Token: ed742D75-5a45-49b6-a0a1-5b9ec3dc9e5d&quot; \ -v \ -d &quot;{From: '[email protected]', To: '[email protected]', Subject: 'Postmark test', HtmlBody: '&lt;html&gt;&lt;body&gt;&lt;strong&gt;Hello&lt;/strong&gt; dear Postmark user.&lt;/body&gt;&lt;/html&gt;'}&quot; </code></pre>
22,814,075
1
0
null
2014-04-02 00:58:34.167 UTC
8
2022-09-20 05:18:19.92 UTC
2022-09-20 05:18:19.92 UTC
null
3,064,538
null
2,557,050
null
1
17
python|curl|pycurl|postmark
33,564
<p>You can use something like this. It's a basic implementation but it should work.</p> <pre><code>import pycurl, json postmark_url = 'https://api.postmarkapp.com/email' data = json.dumps({"From": "[email protected]", "To": "[email protected]", "Subject": "Pycurl", "TextBody": "Some text"}) c = pycurl.Curl() c.setopt(pycurl.URL, github_url) c.setopt(pycurl.HTTPHEADER, ['X-Postmark-Server-Token: API_TOKEN_HERE','Accept: application/json']) c.setopt(pycurl.POST, 1) c.setopt(pycurl.POSTFIELDS, data) c.perform() </code></pre>