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
16,268,693
Running code on the main thread from a secondary thread?
<p>This is a general Java question and not an Android one first off!</p> <p>I'd like to know how to run code on the main thread, from the context of a secondary thread. For example:</p> <pre><code>new Thread(new Runnable() { public void run() { //work out pi to 1,000 DP (takes a while!) //print the result on the main thread } }).start(); </code></pre> <p>That sort of thing - I realise my example is a little poor since in Java you don't need to be in the main thread to print something out, and that Swing has an event queue also - but the generic situation where you might need to run say a Runnable on the main thread while in the context of a background thread.</p> <p>EDIT: For comparison - here's how I'd do it in Objective-C:</p> <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0UL), ^{ //do background thread stuff dispatch_async(dispatch_get_main_queue(), ^{ //update UI }); }); </code></pre> <p>Thanks in advance!</p>
16,268,778
6
0
null
2013-04-28 22:28:05.187 UTC
8
2021-08-07 09:15:04.983 UTC
null
null
null
null
390,924
null
1
30
java|multithreading|concurrency|synchronization
36,071
<p>There is no universal way to just send some code to another running thread and say "Hey, you, do this." You would need to put the main thread into a state where it has a mechanism for receiving work and is waiting for work to do.</p> <p>Here's a simple example of setting up the main thread to wait to receive work from other threads and run it as it arrives. Obviously you would want to add a way to actually end the program and so forth...!</p> <pre><code>public static final BlockingQueue&lt;Runnable&gt; queue = new LinkedBlockingQueue&lt;Runnable&gt;(); public static void main(String[] args) throws Exception { new Thread(new Runnable(){ @Override public void run() { final int result; result = 2+3; queue.add(new Runnable(){ @Override public void run() { System.out.println(result); } }); } }).start(); while(true) { queue.take().run(); } } </code></pre>
12,695,232
Using native functions in Android with OpenCV
<p>I want to use OpenCV+Android, using native functions. However I am a little confused how to use bitmaps as parameters and how to return a value of an edited bitmap (or Mat).</p> <p>So for example I have a native function:</p> <pre><code>#include &lt;jni.h&gt; #include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; JNIEXPORT ??? JNICALL Java_com_my_package_name_and_javaclass_myFunction(JNIEnv* env, jobject javaThis, cv::Mat mat1){ //here will be code to perform filtering, blurring, canny edge detection or similar things. //so I want to input a bitmap, edit it and send it back to the Android class. return ??? } </code></pre> <p>So here I am using cv::Mat as a parameter. I know this is wrong, but I am unsure what it should be, and what should be in the correpsonding java class. Should it be a ByteArray? And then in the above native function the parameter would be jByteArray (or similar)?</p> <p>And for the return object, what should I put? Should this be an array?</p> <p>Basically what I am looking for is in the Java class I have a Mat (or Bitmap) I send it to the native function for editing and return a nicely edited bitmap.</p>
12,699,835
2
2
null
2012-10-02 17:29:15.227 UTC
9
2012-10-03 00:20:47.347 UTC
null
null
null
user485498
null
null
1
3
java|android|c++|opencv|java-native-interface
7,219
<p>This is the OpenCV Tutorial code for Android. I remember that it took a while for me to understand the JNI convention. Just look into JNI code first </p> <pre><code>#include &lt;jni.h&gt; #include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;opencv2/features2d/features2d.hpp&gt; #include &lt;vector&gt; using namespace std; using namespace cv; extern "C" { JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial3_Sample3View_FindFeatures(JNIEnv* env, jobject thiz, jint width, jint height, jbyteArray yuv, jintArray bgra) { jbyte* _yuv = env-&gt;GetByteArrayElements(yuv, 0); jint* _bgra = env-&gt;GetIntArrayElements(bgra, 0); Mat myuv(height + height/2, width, CV_8UC1, (unsigned char *)_yuv); Mat mbgra(height, width, CV_8UC4, (unsigned char *)_bgra); Mat mgray(height, width, CV_8UC1, (unsigned char *)_yuv); //Please make attention about BGRA byte order //ARGB stored in java as int array becomes BGRA at native level cvtColor(myuv, mbgra, CV_YUV420sp2BGR, 4); vector&lt;KeyPoint&gt; v; FastFeatureDetector detector(50); detector.detect(mgray, v); for( size_t i = 0; i &lt; v.size(); i++ ) circle(mbgra, Point(v[i].pt.x, v[i].pt.y), 10, Scalar(0,0,255,255)); env-&gt;ReleaseIntArrayElements(bgra, _bgra, 0); env-&gt;ReleaseByteArrayElements(yuv, _yuv, 0); } } </code></pre> <p>and then Java code</p> <pre><code>package org.opencv.samples.tutorial3; import android.content.Context; import android.graphics.Bitmap; class Sample3View extends SampleViewBase { public Sample3View(Context context) { super(context); } @Override protected Bitmap processFrame(byte[] data) { int frameSize = getFrameWidth() * getFrameHeight(); int[] rgba = new int[frameSize]; FindFeatures(getFrameWidth(), getFrameHeight(), data, rgba); Bitmap bmp = Bitmap.createBitmap(getFrameWidth(), getFrameHeight(), Bitmap.Config.ARGB_8888); bmp.setPixels(rgba, 0/* offset */, getFrameWidth() /* stride */, 0, 0, getFrameWidth(), getFrameHeight()); return bmp; } public native void FindFeatures(int width, int height, byte yuv[], int[] rgba); static { System.loadLibrary("native_sample"); } } </code></pre>
12,694,785
Get Time Difference between two datetime in stored procedure
<p>I want to get Get Time Difference between two datetime in stroed procedure. then i need to cast that answer to varchar. i don't know how to get that value. i am a new one for stroed procedure. i am using sql server 2008</p> <pre><code>declare @tdate1 datetime declare @date2 datetime declare @finaltime varchar set @enddate = '2004-10-18 07:53:35.000' set @startdate = '2004-10-18 15:28:57.000' if @startdate &gt;= @enddate // This is what i want to do.. else </code></pre>
12,694,910
5
1
null
2012-10-02 16:56:25.433 UTC
1
2017-03-21 15:40:42.05 UTC
2012-10-02 17:08:13.317 UTC
null
137,508
null
1,312,250
null
1
3
sql-server|stored-procedures
56,760
<pre><code>SELECT DATEDIFF(year, @startdate, @enddate) </code></pre> <p>try this to start you in the right direction.</p> <p><code>year</code> represents the period of measure you want to return</p> <p><a href="https://msdn.microsoft.com/en-us/library/ms189794.aspx" rel="noreferrer">Here</a> is a link to an MSDN Article that may be helpful</p> <p><code>DATEDIFF</code> (Transact-SQL)</p> <p>Other Versions </p> <p><em>Updated: December 2, 2015</em></p> <p><strong>THIS TOPIC APPLIES TO:</strong></p> <p>yesSQL Server (starting with 2008) yesAzure SQL Database yesAzure SQL Data Warehouse yesParallel Data Warehouse Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. For larger differences, see DATEDIFF_BIG (Transact-SQL). For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL). Topic link icon Transact-SQL Syntax Conventions Syntax</p> <pre><code>DATEDIFF ( datepart , startdate , enddate ) </code></pre> <p>-- Azure SQL Data Warehouse and Parallel Data Warehouse</p> <pre><code>DATEDIFF (datepart ,startdate ,enddate ) </code></pre> <p><strong>Arguments</strong></p> <p><em>datepart</em></p> <p>Is the part of startdate and enddate that specifies the type of boundary crossed. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid.</p> <p><strong>datepart</strong></p> <p><em>Abbreviations</em></p> <pre><code>year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, ww hour hh minute mi, n second ss, s millisecond ms microsecond mcs nanosecond ns startdate </code></pre> <p>Is an expression that can be resolved to a <code>time, date, smalldatetime, datetime, datetime2</code>, or datetimeoffset value. date can be an expression, column expression, user-defined variable or string literal. startdate is subtracted from enddate.</p> <p>To avoid ambiguity, use four-digit years. For information about two digits years, see Configure the two digit year cutoff Server Configuration Option. enddate</p> <p>See <strong>startdate</strong>. <em>Return Type int</em> Return Value Each datepart and its abbreviations return the same value. If the return value is out of range for int (-2,147,483,648 to +2,147,483,647), an error is returned. For millisecond, the maximum difference between startdate and enddate is 24 days, 20 hours, 31 minutes and 23.647 seconds. For second, the maximum difference is 68 years. If startdate and enddate are both assigned only a time value and the datepart is not a time datepart, 0 is returned. A time zone offset component of startdate or endate is not used in calculating the return value. Because smalldatetime is accurate only to the minute, when a smalldatetime value is used for startdate or enddate, seconds and milliseconds are always set to 0 in the return value. If only a time value is assigned to a variable of a date data type, the value of the missing date part is set to the default value: 1900-01-01. If only a date value is assigned to a variable of a time or date data type, the value of the missing time part is set to the default value: 00:00:00. If either startdate or enddate have only a time part and the other only a date part, the missing time and date parts are set to the default values. If startdate and enddate are of different date data types and one has more time parts or fractional seconds precision than the other, the missing parts of the other are set to 0. datepart Boundaries The following statements have the same startdate and the same endate. Those dates are adjacent and differ in time by .0000001 second. The difference between the startdate and endate in each statement crosses one calendar or time boundary of its datepart. Each statement returns 1. If different years are used for this example and if both startdate and endate are in the same calendar week, the return value for week would be 0.</p> <pre><code>SELECT DATEDIFF(year, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(quarter, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(dayofyear, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(week, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(hour, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(minute, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(second, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999' , '2006-01-01 00:00:00.0000000'); </code></pre> <p>Remarks DATEDIFF can be used in the select list, WHERE, HAVING, GROUP BY and ORDER BY clauses. DATEDIFF implicitly casts string literals as a datetime2 type. This means that DATEDIFF does not support the format YDM when the date is passed as a string. You must explicitly cast the string to a datetime or smalldatetime type to use the YDM format. Specifying SET DATEFIRST has no effect on DATEDIFF. DATEDIFF always uses Sunday as the first day of the week to ensure the function is deterministic. Examples The following examples use different types of expressions as arguments for the startdate and enddate parameters. A. Specifying columns for startdate and enddate The following example calculates the number of day boundaries that are crossed between dates in two columns in a table.</p> <pre><code>CREATE TABLE dbo.Duration ( startDate datetime2 ,endDate datetime2 ); INSERT INTO dbo.Duration(startDate,endDate) VALUES('2007-05-06 12:10:09','2007-05-07 12:10:09'); SELECT DATEDIFF(day,startDate,endDate) AS 'Duration' FROM dbo.Duration; </code></pre> <p>-- Returns: 1 B. Specifying user-defined variables for startdate and enddate The following example uses user-defined variables as arguments for startdate and enddate.</p> <pre><code>DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722'; DECLARE @enddate datetime2 = '2007-05-04 12:10:09.3312722'; SELECT DATEDIFF(day, @startdate, @enddate); </code></pre> <p>C. Specifying scalar system functions for startdate and enddate The following example uses scalar system functions as arguments for startdate and enddate.</p> <pre><code>SELECT DATEDIFF(millisecond, GETDATE(), SYSDATETIME()); </code></pre> <p>D. Specifying scalar subqueries and scalar functions for startdate and enddate The following example uses scalar subqueries and scalar functions as arguments for startdate and enddate. USE AdventureWorks2012; GO</p> <pre><code>SELECT DATEDIFF(day,(SELECT MIN(OrderDate) FROM Sales.SalesOrderHeader), (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader)); </code></pre> <p>E. Specifying constants for startdate and enddate The following example uses character constants as arguments for startdate and enddate.</p> <pre><code>SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635' , '2007-05-08 09:53:01.0376635'); </code></pre> <p>F. Specifying numeric expressions and scalar system functions for enddate The following example uses a numeric expression, (GETDATE ()+ 1), and scalar system functions, GETDATE and SYSDATETIME, as arguments for enddate.</p> <pre><code>USE AdventureWorks2012; GO SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635', GETDATE()+ 1) AS NumberOfDays FROM Sales.SalesOrderHeader; GO USE AdventureWorks2012; GO SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635', DATEADD(day,1,SYSDATETIME())) AS NumberOfDays FROM Sales.SalesOrderHeader; GO G. Specifying ranking functions for startdate The following example uses a ranking function as an argument for startdate. USE AdventureWorks2012; GO SELECT p.FirstName, p.LastName ,DATEDIFF(day,ROW_NUMBER() OVER (ORDER BY a.PostalCode),SYSDATETIME()) AS 'Row Number' FROM Sales.SalesPerson s INNER JOIN Person.Person p ON s.BusinessEntityID = p.BusinessEntityID INNER JOIN Person.Address a ON a.AddressID = p.BusinessEntityID WHERE TerritoryID IS NOT NULL AND SalesYTD &lt;&gt; 0; </code></pre> <p>H. Specifying an aggregate window function for startdate The following example uses an aggregate window function as an argument for startdate.</p> <pre><code>USE AdventureWorks2012; GO SELECT soh.SalesOrderID, sod.ProductID, sod.OrderQty,soh.OrderDate ,DATEDIFF(day,MIN(soh.OrderDate) OVER(PARTITION BY soh.SalesOrderID),SYSDATETIME() ) AS 'Total' FROM Sales.SalesOrderDetail sod INNER JOIN Sales.SalesOrderHeader soh ON sod.SalesOrderID = soh.SalesOrderID WHERE soh.SalesOrderID IN(43659,58918); GO </code></pre> <p>Examples: Azure SQL Data Warehouse Public Preview and Parallel Data Warehouse The following examples use different types of expressions as arguments for the startdate and enddate parameters. I. Specifying columns for startdate and enddate The following example calculates the number of day boundaries that are crossed between dates in two columns in a table.</p> <pre><code>CREATE TABLE dbo.Duration ( startDate datetime2 ,endDate datetime2 ); INSERT INTO dbo.Duration(startDate,endDate) VALUES('2007-05-06 12:10:09','2007-05-07 12:10:09'); SELECT TOP(1) DATEDIFF(day,startDate,endDate) AS Duration FROM dbo.Duration; </code></pre> <p>-- Returns: 1 J. Specifying scalar subqueries and scalar functions for startdate and enddate The following example uses scalar subqueries and scalar functions as arguments for startdate and enddate. -- Uses AdventureWorks</p> <pre><code>SELECT TOP(1) DATEDIFF(day,(SELECT MIN(HireDate) FROM dbo.DimEmployee), (SELECT MAX(HireDate) FROM dbo.DimEmployee)) FROM dbo.DimEmployee; </code></pre> <p>K. Specifying constants for startdate and enddate The following example uses character constants as arguments for startdate and enddate.</p> <pre><code>-- Uses AdventureWorks SELECT TOP(1) DATEDIFF(day, '2007-05-07 09:53:01.0376635' , '2007-05-08 09:53:01.0376635') FROM DimCustomer; </code></pre> <p>L. Specifying ranking functions for startdate The following example uses a ranking function as an argument for startdate. -- Uses AdventureWorks</p> <pre><code>SELECT FirstName, LastName ,DATEDIFF(day,ROW_NUMBER() OVER (ORDER BY DepartmentName),SYSDATETIME()) AS RowNumber FROM dbo.DimEmployee; </code></pre> <p>M. Specifying an aggregate window function for startdate The following example uses an aggregate window function as an argument for startdate. -- Uses AdventureWorks</p> <pre><code>SELECT FirstName, LastName, DepartmentName ,DATEDIFF(year,MAX(HireDate) OVER (PARTITION BY DepartmentName),SYSDATETIME()) AS SomeValue FROM dbo.DimEmployee </code></pre>
37,263,124
Which Enum constant will I get if the Enum values are same
<p>Is there a logic to which constant I get if there are more than one enum constant that has the same value?</p> <p>I tried the variations below, but couldn't get a reasonable logic.</p> <h3>Main Method:</h3> <pre><code>public class Program { public static void Main(string[] args) { Test a = 0; Console.WriteLine(a); } } </code></pre> <h3>First try:</h3> <pre><code>enum Test { a1=0, a2=0, a3=0, a4=0, } </code></pre> <p>Output:</p> <pre><code>a2 </code></pre> <h3>Second try:</h3> <pre><code>enum Test { a1=0, a2=0, a3, a4=0, } </code></pre> <p>Output:</p> <pre><code>a4 </code></pre> <h3>Third try:</h3> <pre><code>enum Test { a1=0, a2=0, a3, a4, } </code></pre> <p>Output:</p> <pre><code>a2 </code></pre> <h3>Fourth try:</h3> <pre><code>enum Test { a1=0, a2=0, a3, a4 } </code></pre> <p>Output:</p> <pre><code>a1 </code></pre>
37,263,227
2
4
null
2016-05-16 20:55:56.613 UTC
1
2017-01-14 21:24:35.043 UTC
2017-01-14 21:24:35.043 UTC
null
3,729,695
null
3,729,695
null
1
58
c#|.net|enums
2,714
<p>The <a href="https://msdn.microsoft.com/en-us/library/a0h36syw(v=vs.110).aspx">documentation</a> actually addresses this:</p> <blockquote> <p>If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, <strong>your code should not make any assumptions about which name the method will return</strong>.</p> </blockquote> <p>(emphasis added)</p> <p>However, this does not mean that the result is <em>random</em>. What that means it that <em>it's an implementation detail that is subject to change</em>. The implementation could completely change with just a patch, could be different across compilers (MONO, Roslyn, etc.), and be different on different platforms. </p> <p>If your system is designed that it <em>requires</em> that the reverse-lookup for enums is consistent over time and platforms, then <em>don't use</em> <code>Enum.ToString</code>. Either change your design so it's not dependent on that detail, or write your <em>own</em> method that <em>will</em> be consistent. </p> <p>So you should not write code that depends on that implementation, or you are taking a risk that it will change without your knowledge in a future release.</p>
27,058,649
How to animate UITableViewCell height using auto-layout?
<p>There are lot of similar questions on Stack Overflow about <code>UITableViewCell</code> height animation, but nothing works for new iOS8 auto-layout driven table view. My issue:</p> <p>Custom cell:</p> <pre><code>@property (weak, nonatomic) IBOutlet iCarousel *carouselView; @property (weak, nonatomic) IBOutlet UIPageControl *pageControl; @property (weak, nonatomic) IBOutlet UIButton *seeAllButton; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *carouselHeightConstraint; </code></pre> <p>Note <code>carouselHeightConstraint</code>. This is height constraint for content view's subview (the only subview).</p> <p>Height is set to <code>230.0f</code> for example. On first load it looks like: <img src="https://i.stack.imgur.com/hkP5X.png" alt="enter image description here" /></p> <p>Then, on <strong>See All</strong> action I want to <strong>expand</strong> cell, my code:</p> <pre><code>- (IBAction)seeAllButtonAction:(id)sender { BOOL vertical = !self.carouselCell.carouselView.vertical; self.carouselCell.carouselView.type = vertical ? iCarouselTypeCylinder : iCarouselTypeLinear; self.carouselCell.carouselView.vertical = vertical; [UIView transitionWithView:self.carouselCell.carouselView duration:0.2 options:0 animations:^{ self.carouselCell.carouselHeightConstraint.constant = vertical ? CGRectGetHeight(self.tableView.frame) : 230; [self.carouselCell setNeedsUpdateConstraints]; [self.carouselCell updateConstraintsIfNeeded]; [self.tableView beginUpdates]; [self.tableView endUpdates]; completion:^(BOOL finished) { }]; } </code></pre> <p>As you can see, I try to use this good old solution:<br /> <a href="https://stackoverflow.com/questions/460014/can-you-animate-a-height-change-on-a-uitableviewcell-when-selected">Can you animate a height change on a UITableViewCell when selected?</a></p> <p>And the result:</p> <p><img src="https://i.stack.imgur.com/jnHVS.png" alt="enter image description here" /></p> <p>My cell <strong>shrinks</strong> to <code>44.0f</code> height.</p> <h1>Question:</h1> <p>Why this happens? I expect to see my cell smoothly expanded with magic of auto-layot.</p> <p><strong>Note:</strong><br /> I dont't want to use <code>-tableView:heightForRowAtIndexPath:</code>. It's auto-layout era, right?</p>
28,517,242
2
7
null
2014-11-21 10:00:01.757 UTC
11
2016-09-09 10:44:13.907 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,469,060
null
1
21
ios|objective-c|uitableview|ios8|autolayout
14,015
<p>The following worked for me:</p> <p><strong>Preparation:</strong></p> <ol> <li><p>On <code>viewDidLoad</code> tell the table view to use self-sizing cells:</p> <pre><code>tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 44; // Some average height of your cells </code></pre></li> <li><p>Add the constraints as you normally would, but add them to the cell's <code>contentView</code>!</p></li> </ol> <p><strong>Animate height changes:</strong></p> <p>Say you change a constraint's <code>constant</code>:</p> <pre><code>myConstraint.constant = newValue; </code></pre> <p>...or you add/remove constraints.</p> <p>To animate this change, proceed as follows:</p> <ol> <li><p>Tell the contentView to animate the change:</p> <pre><code>[UIView animateWithDuration: 0.3 animations: ^{ [cell.contentView layoutIfNeeded] }]; // Or self.contentView if you're doing this from your own cell subclass </code></pre></li> <li><p>Then tell the table view to react to the height change with an animation</p> <pre><code>[tableView beginUpdates]; [tableView endUpdates]; </code></pre></li> </ol> <p>The duration of 0.3 on the first step is what seems to be the duration UITableView uses for its animations when calling begin/endUpdates.</p> <p><strong>Bonus - change height without animation and without reloading the entire table:</strong></p> <p>If you want to do the same thing as above, but without an animation, then do this instead:</p> <pre><code>[cell.contentView layoutIfNeeded]; [UIView setAnimationsEnabled: FALSE]; [tableView beginUpdates]; [tableView endUpdates]; [UIView setAnimationsEnabled: TRUE]; </code></pre> <p><strong>Summary:</strong></p> <pre><code>// Height changing code here: // ... if (animate) { [UIView animateWithDuration: 0.3 animations: ^{ [cell.contentView layoutIfNeeded]; }]; [tableView beginUpdates]; [tableView endUpdates]; } else { [cell.contentView layoutIfNeeded]; [UIView setAnimationsEnabled: FALSE]; [tableView beginUpdates]; [tableView endUpdates]; [UIView setAnimationsEnabled: TRUE]; } </code></pre> <hr> <p>You can check out my implementation of a cell that expands when the user selects it <a href="https://github.com/truppelito/SwiftUtils">here</a> (pure Swift &amp; pure autolayout - truly the way of the future).</p>
21,891,605
Getting IIS to impersonate the windows user to SQL server in an intranet environment
<p>I am developing an intranet site using C# and ASP.NET MVC. I have SQL Server on one machine and IIS running on a separate machine. I would like a user to visit the intranet site and without prompting the user internet explorer sends the users windows credentials to IIS and these are then passed to sql server meaning sql server can see the user accessing the database.</p> <p>I am aware of the Kerberos double hop issue and it is this I am trying to get around. At present I can get IE to pass the windows credentials to IIS and authenticate fine. I just cannot get IIS to pass on those credentials to SQL Server and instead the request currently runs under the app pool identity which is set to a domain service account "htu\srv-htu-iis".</p> <p>My setup is as follows:</p> <p><strong>Web.Config</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;system.web&gt; &lt;authentication mode="Windows" /&gt; &lt;authorization&gt; &lt;deny users="?" /&gt; &lt;/authorization&gt; &lt;identity impersonate="true" /&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;validation validateIntegratedModeConfiguration="false" /&gt; &lt;/system.webServer&gt; </code></pre> <p><strong>Connection String</strong></p> <pre><code>connection string=&amp;quot;data source=hturesbsqlp01;initial catalog=R2_Dev;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&amp;quot;" </code></pre> <p><strong>IIS Authentication Settings</strong></p> <pre class="lang-none prettyprint-override"><code>Anonymous Authentication = Disabled ASP.NET Impersonation = Enabled Forms Authentication = Disabled Windows Authentication = Enabled </code></pre> <p><strong>IIS App Pool Settings</strong></p> <pre class="lang-none prettyprint-override"><code>Managed Pipeline = Integrated Identity = htu\srv-htu-iis (domain service account) </code></pre> <p><strong>Active Directory Settings</strong></p> <p>The domain service account htu\srv-htu-iis has had a service principal name set which associates our site with the account. </p> <p>Active directory has </p> <pre class="lang-none prettyprint-override"><code>Allow Delagation to any service </code></pre> <p>SQL Server is running under its own SQL Domain Service account.</p> <p><strong>Tests</strong></p> <p>I ran the following code tests:</p> <pre><code>System.Web.HttpContext.Current.User.Identity.Name </code></pre> <p>this correctly return the windows credentials of the user accessing the site</p> <pre><code>System.Security.Principal.WindowsIdentity.GetCurrent().Name </code></pre> <p>return the domain service account "htu\srv-htu-iis" which is what the app pool identity is running under.</p> <p>Can anyone provide direction as to where I might be going wrong?</p>
21,909,518
1
5
null
2014-02-19 20:23:53.577 UTC
7
2017-05-14 14:56:55.093 UTC
2014-09-23 14:06:15.76 UTC
null
1,366,033
null
2,414,446
null
1
30
sql-server|asp.net-mvc|authentication|iis|kerberos
27,473
<p>Well to anyone visiting this question in the future. I resolved this by restarting the IIS Service...doh! Seems my settings were fine just need a full restart of the service!</p>
26,871,866
print highest value in dict with key
<p>My dict is like,</p> <pre><code>{'A':4,'B':10,'C':0,'D':87} </code></pre> <p>I want to find max value with its key and min value with its key.</p> <p>Output will be like ,</p> <p>max : 87 , key is D</p> <p>min : 0 , key is C</p> <p>I know how to get min and max values from dict. Is there is any way to get value and key in one statement?</p> <pre><code>max([i for i in dic.values()]) min([i for i in dic.values()]) </code></pre>
26,871,933
3
2
null
2014-11-11 18:28:38.31 UTC
9
2020-12-11 21:34:44.24 UTC
null
null
null
null
1,246,764
null
1
16
python|python-2.7|dictionary
122,340
<p>You could use use <a href="https://docs.python.org/2/library/functions.html#max"><code>max</code></a> and <a href="https://docs.python.org/2/library/functions.html#min"><code>min</code></a> with <a href="https://docs.python.org/2/library/stdtypes.html#dict.get"><code>dict.get</code></a>:</p> <pre><code>maximum = max(mydict, key=mydict.get) # Just use 'min' instead of 'max' for minimum. print(maximum, mydict[maximum]) # D 87 </code></pre>
17,290,114
AttributeError: 'tuple' object has no attribute
<p>I'm a beginner in python. I'm not able to understand what the problem is?</p> <pre><code>def list_benefits(): s1 = "More organized code" s2 = "More readable code" s3 = "Easier code reuse" s4 = "Allowing programmers to share and connect code together" return s1,s2,s3,s4 def build_sentence(): obj=list_benefits() print obj.s1 + " is a benefit of functions!" print obj.s2 + " is a benefit of functions!" print obj.s3 + " is a benefit of functions!" print build_sentence() </code></pre> <p>The error I'm getting is:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): Line 15, in &lt;module&gt; print build_sentence() Line 11, in build_sentence print obj.s1 + " is a benefit of functions!" AttributeError: 'tuple' object has no attribute 's1' </code></pre>
17,290,166
7
4
null
2013-06-25 05:57:06.98 UTC
6
2022-04-09 22:42:55.237 UTC
2014-03-03 10:23:38.437 UTC
null
2,276,527
null
2,276,527
null
1
49
python|python-2.7
385,451
<p>You return four variables s1,s2,s3,s4 and receive them using a single variable <code>obj</code>. This is what is called a <code>tuple</code>, <code>obj</code> is associated with 4 values, the values of <code>s1,s2,s3,s4</code>. So, use index as you use in a list to get the value you want, in order.</p> <pre><code>obj=list_benefits() print obj[0] + " is a benefit of functions!" print obj[1] + " is a benefit of functions!" print obj[2] + " is a benefit of functions!" print obj[3] + " is a benefit of functions!" </code></pre>
17,450,861
add scroll bar to table body
<p>I want to do this as easily as possible with out any additional libraries.</p> <p>In my very long table I want to add a scrollbar to the <code>&lt;tbody&gt;</code> tag so that the head is always visible but it wont work. can you please help.</p> <p>fiddle : <a href="http://jsfiddle.net/Hpx4L/">http://jsfiddle.net/Hpx4L/</a></p> <pre><code>&lt;table border="1"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Month&lt;/th&gt; &lt;th&gt;Savings&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;td&gt;Sum&lt;/td&gt; &lt;td&gt;$180&lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;tbody style="overflow-y:scroll; height:100px;"&gt; &lt;!-- wont work --&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
17,451,132
4
4
null
2013-07-03 14:33:27.013 UTC
15
2021-04-19 20:38:46.163 UTC
null
null
null
null
1,477,816
null
1
51
html|css
251,045
<p>you can wrap the content of the <code>&lt;tbody&gt;</code> in a scrollable <code>&lt;div&gt;</code> :</p> <p>html</p> <pre><code>.... &lt;tbody&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;div class="scrollit"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;January&lt;/td&gt; &lt;td&gt;$100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;February&lt;/td&gt; &lt;td&gt;$80&lt;/td&gt; &lt;/tr&gt; ... </code></pre> <p>css</p> <pre><code>.scrollit { overflow:scroll; height:100px; } </code></pre> <p>see my jsfiddle, forked from yours: <a href="http://jsfiddle.net/VTNax/2/">http://jsfiddle.net/VTNax/2/</a></p>
5,221,524
Idiomatic way to convert an InputStream to a String in Scala
<p>I have a handy function that I've used in Java for converting an InputStream to a String. Here is a direct translation to Scala:</p> <pre><code> def inputStreamToString(is: InputStream) = { val rd: BufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8")) val builder = new StringBuilder() try { var line = rd.readLine while (line != null) { builder.append(line + "\n") line = rd.readLine } } finally { rd.close } builder.toString } </code></pre> <p>Is there an idiomatic way to do this in scala?</p>
5,221,595
3
0
null
2011-03-07 15:31:27.73 UTC
19
2017-10-08 13:15:50.163 UTC
2011-07-13 12:36:15.92 UTC
null
505,893
null
312,057
null
1
117
string|scala|inputstream
69,039
<p>For Scala >= 2.11</p> <pre><code>scala.io.Source.fromInputStream(is).mkString </code></pre> <p>For Scala &lt; 2.11:</p> <pre><code>scala.io.Source.fromInputStream(is).getLines().mkString("\n") </code></pre> <p>does pretty much the same thing. Not sure why you want to get lines and then glue them all back together, though. If you can assume the stream's nonblocking, you could just use <code>.available</code>, read the whole thing into a byte array, and create a string from that directly.</p>
62,003,082
ElementNotInteractableException: element not interactable: element has zero size appears since upgrade to chromedriver 83
<p>I use the following docker image to run my cucumber tests:</p> <p><a href="https://hub.docker.com/r/selenium/standalone-chrome/" rel="noreferrer">https://hub.docker.com/r/selenium/standalone-chrome/</a></p> <p>Unfortunately, starting from today it seems that whenever I run my tests I get the errors below. They appear at the start of each test. It does not matter what I do on the page.</p> <p>**13:38:26 [exec] org.openqa.selenium.ElementNotInteractableException: element not interactable: element has zero size</p> <p>13:38:26 [exec] (Session info: chrome=83.0.4103.61)**</p> <p>I did some digging and I noticed the chromedriver version was updated from 81 to 83. I managed to fix this issue by using an older docker image from that docker hub link which has chromedriver 81. But if I attempt to use chromedriver 83 again it will not work. </p> <p>Has anyone else encountered this? Is there a new chrome option I need to add because of the update? </p>
62,137,766
9
3
null
2020-05-25 13:08:56.183 UTC
2
2021-09-21 13:25:32.21 UTC
2020-05-25 13:39:26.85 UTC
null
6,337,474
null
6,337,474
null
1
20
docker|selenium-chromedriver
42,135
<p>The root cause of that issue is that Chrome doesn't scroll to the element outside of the viewport. Instead of it, Chrome tries to click on it outside of the viewing area. That's why the issue appears. It is definitely an issue with Chrome 83 because I didn't face it on Chrome 81.</p> <p>Moreover, I have no such issue on Windows machine, it reproduced only on Linux (I'm using selenoid docker images).</p> <p>Solution with a click via JS is not the best option, because via JS you can click anywhere even for unclickable elements (e.g. overlapped by other objects). It's an unsafe operation.</p> <p>Instead of this, I would suggest scrolling to the element before click and after native click(); it will work just perfectly.</p> <pre><code>JavascriptExecutor executor = (JavascriptExecutor) driver; executor.executeScript(&quot;arguments[0].scrollIntoView(true);&quot;, element); element.click(); </code></pre>
9,601,707
How to set property value using Expressions?
<p>Given the following method:</p> <pre><code>public static void SetPropertyValue(object target, string propName, object value) { var propInfo = target.GetType().GetProperty(propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); if (propInfo == null) throw new ArgumentOutOfRangeException("propName", "Property not found on target"); else propInfo.SetValue(target, value, null); } </code></pre> <p>How would you go about writing it's expression enabled equivalent without needing to pass in an extra parameter for target? </p> <p>Why do this instead of setting the property directly I can hear you say. For example suppose we have the following class with a property that has a public getter but private setter: </p> <pre><code>public class Customer { public string Title {get; private set;} public string Name {get; set;} } </code></pre> <p>I would like to be able to call: </p> <pre><code>var myCustomerInstance = new Customer(); SetPropertyValue&lt;Customer&gt;(cust =&gt; myCustomerInstance.Title, "Mr"); </code></pre> <p>Now here is some sample code. </p> <pre><code>public static void SetPropertyValue&lt;T&gt;(Expression&lt;Func&lt;T, Object&gt;&gt; memberLamda , object value) { MemberExpression memberSelectorExpression; var selectorExpression = memberLamda.Body; var castExpression = selectorExpression as UnaryExpression; if (castExpression != null) memberSelectorExpression = castExpression.Operand as MemberExpression; else memberSelectorExpression = memberLamda.Body as MemberExpression; // How do I get the value of myCustomerInstance so that I can invoke SetValue passing it in as a param? Is it possible } </code></pre> <p>Any pointers? </p>
9,601,914
1
3
null
2012-03-07 12:39:58.71 UTC
18
2017-05-24 15:25:00.08 UTC
2013-03-31 11:25:46.333 UTC
null
661,933
null
138,767
null
1
76
c#|linq|expression
51,541
<p>You could cheat and make life easier with an extension method:</p> <pre><code>public static class LambdaExtensions { public static void SetPropertyValue&lt;T, TValue&gt;(this T target, Expression&lt;Func&lt;T, TValue&gt;&gt; memberLamda, TValue value) { var memberSelectorExpression = memberLamda.Body as MemberExpression; if (memberSelectorExpression != null) { var property = memberSelectorExpression.Member as PropertyInfo; if (property != null) { property.SetValue(target, value, null); } } } } </code></pre> <p>and then:</p> <pre><code>var myCustomerInstance = new Customer(); myCustomerInstance.SetPropertyValue(c =&gt; c.Title, "Mr"); </code></pre> <p>The reason why this is easier is because you already have the target on which the extension method is invoked. Also the lambda expression is a simple member expression without closures. In your original example the target is captured in a closure and it could be a bit tricky to get to the underlying target and <code>PropertyInfo</code>.</p>
9,335,015
Find() vs. Where().FirstOrDefault()
<p>I often see people using <code>Where.FirstOrDefault()</code> to do a search and grab the first element. Why not just use <code>Find()</code>? Is there an advantage to the other? I couldn't tell a difference.</p> <pre><code>namespace LinqFindVsWhere { class Program { static void Main(string[] args) { List&lt;string&gt; list = new List&lt;string&gt;(); list.AddRange(new string[] { "item1", "item2", "item3", "item4" }); string item2 = list.Find(x =&gt; x == "item2"); Console.WriteLine(item2 == null ? "not found" : "found"); string item3 = list.Where(x =&gt; x == "item3").FirstOrDefault(); Console.WriteLine(item3 == null ? "not found" : "found"); Console.ReadKey(); } } } </code></pre>
9,335,036
6
3
null
2012-02-17 20:35:28.477 UTC
35
2022-08-10 10:21:07.757 UTC
2015-12-15 09:15:06.543 UTC
null
1,364,007
null
659,858
null
1
194
c#|linq|linq-to-objects
146,698
<p>Where is the <code>Find</code> method on <code>IEnumerable&lt;T&gt;</code>? (Rhetorical question.)</p> <p>The <code>Where</code> and <code>FirstOrDefault</code> methods are applicable against multiple kinds of sequences, including <code>List&lt;T&gt;</code>, <code>T[]</code>, <code>Collection&lt;T&gt;</code>, etc. Any sequence that implements <code>IEnumerable&lt;T&gt;</code> can use these methods. <code>Find</code> is available only for the <code>List&lt;T&gt;</code>. Methods that are generally more applicable, are then more <em>reusable</em> and have a greater impact.</p> <blockquote> <p>I guess my next question would be why did they add the find at all. That is a good tip. The only thing I can think of is that the FirstOrDefault could return a different default value other than null. Otherwise it just seems like a pointless addition</p> </blockquote> <p><code>Find</code> on <code>List&lt;T&gt;</code> predates the other methods. <code>List&lt;T&gt;</code> was added with generics in .NET 2.0, and <code>Find</code> was part of the API for that class. <code>Where</code> and <code>FirstOrDefault</code> were added as extension methods for <code>IEnumerable&lt;T&gt;</code> with Linq, which is a later .NET version. I cannot say with certainty that if Linq existed with the 2.0 release that <code>Find</code> would never have been added, but that is arguably the case for many other features that came in earlier .NET versions that were made obsolete or redundant by later versions. </p>
9,245,656
Is Celery as efficient on a local system as python multiprocessing is?
<p>I'm having a bit of trouble deciding whatever to use python multiprocessing or celery or pp for my application. </p> <p>My app is very CPU heavy but currently uses only one cpu so, I need to spread it across all available cpus(which caused me to look at python's multiprocessing library) but I read that this library doesn't scale to other machines if required. Right now I'm not sure if I'll need more than one server to run my code but I'm thinking of running celery locally and then scaling would only require adding new servers instead of refactoring the code(as it would if I used multiprocessing).</p> <p>My question: is this logic correct? and is there any negative(performance) with using celery locally(if it turns out a single server with multiple cores can complete my task)? or is it more advised to use multiprocessing and grow out of it into something else later?</p> <p>Thanks!</p> <p>p.s. this is for a personal learning project but I would maybe one day like to work as a developer in a firm and want to learn how professionals do it.</p>
9,246,968
2
4
null
2012-02-12 01:32:12.857 UTC
12
2018-11-20 05:30:59.773 UTC
2018-11-20 05:30:59.773 UTC
null
1,270,789
null
640,558
null
1
28
python|parallel-processing|multiprocessing|celery
9,213
<p>I have actually never used Celery, but I have used multiprocessing.</p> <p>Celery seems to have several ways to pass messages (tasks) around, including ways that you should be able to run workers on different machines. So a downside might be that message passing could be slower than with multiprocessing, but on the other hand you could spread the load to other machines.</p> <p>You are right that multiprocessing can only run on one machine. But on the other hand, communication between the processes can be very fast, for example by using shared memory. Also if you need to process very large amounts of data, you could easily read and write data from and to the local disk, and just pass filenames between the processes.</p> <p>I don't know how well Celery would deal with task failures. For example, task might never finish running, or might crash, or you might want to have the ability to kill a task if it did not finish in certain time limit. I don't know how hard it would be to add support for that if it is not there.</p> <p>multiprocessing does not come with fault tolerance out of the box, but you can build that yourself without too much trouble.</p>
18,548,157
C header files and compilation/linking
<p>I know that header files have forward declarations of various functions, structs, etc. that are used in the <code>.c</code> file that 'calls' the <code>#include</code>, right? As far as I understand, the "separation of powers" occurs like this:</p> <p>Header file: <code>func.h</code></p> <ul> <li><p>contains forward declaration of function </p> <pre><code>int func(int i); </code></pre></li> </ul> <p>C source file: <code>func.c</code></p> <ul> <li><p>contains actual function definition</p> <pre><code>#include "func.h" int func(int i) { return ++i ; } </code></pre></li> </ul> <p>C source file <code>source.c</code> (the "actual" program): </p> <pre><code>#include &lt;stdio.h&gt; #include "func.h" int main(void) { int res = func(3); printf("%i", res); } </code></pre> <p>My question is: seeing that the <code>#include</code> is simply a compiler directive that copies the contents of the <code>.h</code> in the file that <code>#include</code> is in, how does the <code>.c</code> file know how to actually execute the function? All it's getting is the <code>int func(int i);</code>, so how can it actually perform the function? How does it gain access to the actual definition of <code>func</code>? Does the header include some sort of 'pointer' that says "that's my definition, over there!"?</p> <p>How does it work? </p>
18,548,353
5
5
null
2013-08-31 12:31:53.69 UTC
19
2017-08-26 20:39:26.1 UTC
2017-08-26 20:39:26.1 UTC
null
15,168
null
2,373,239
null
1
47
c|linker
81,418
<p>Uchia Itachi gave the answer. It's the <strong>linker</strong>.</p> <p>Using GNU C compiler <code>gcc</code> you would compile a one-file program like </p> <pre><code>gcc hello.c -o hello # generating the executable hello </code></pre> <p>But compiling the two (or more) file program as described in your example, you would have to do the following:</p> <pre><code>gcc -c func.c # generates the object file func.o gcc -c main.c # generates the object file main.o gcc func.o main.o -o main # generates the executable main </code></pre> <p>Each object file has external symbols (you may think of it as public members). Functions are by default external while (global) variables are by default internal. You could change this behavior by defining </p> <pre><code>static int func(int i) { # static linkage return ++i ; } </code></pre> <p>or</p> <pre><code>/* global variable accessible from other modules (object files) */ extern int global_variable = 10; </code></pre> <p>When encountering a call to a function, not defined in the main module, the linker searches all the object files (and libraries) provided as input for the module where the called function is defined. By default you probably have some libraries linked to your program, that's how you can use <code>printf</code>, it's already compiled into a library.</p> <p>If you are really interested, try some assembly programming. These names are the equivalent of labels in assembly code.</p>
18,741,334
How do I view grants on Redshift
<p>I'd like to view grants on redshifts.</p> <p>I found <a href="http://postgresql.1045698.n5.nabble.com/quot-SHOW-GRANTS-FOR-username-quot-or-why-z-is-not-enough-for-me-td5714952.html">this view for postgres</a>:</p> <pre><code>CREATE OR REPLACE VIEW view_all_grants AS SELECT use.usename as subject, nsp.nspname as namespace, c.relname as item, c.relkind as type, use2.usename as owner, c.relacl, (use2.usename != use.usename and c.relacl::text !~ ('({|,)' || use.usename || '=')) as public FROM pg_user use cross join pg_class c left join pg_namespace nsp on (c.relnamespace = nsp.oid) left join pg_user use2 on (c.relowner = use2.usesysid) WHERE c.relowner = use.usesysid or c.relacl::text ~ ('({|,)(|' || use.usename || ')=') ORDER BY subject, namespace, item </code></pre> <p>Which doesn't work because the <code>::text</code> cast of <code>relacl</code> fails with the following:</p> <pre><code>ERROR: cannot cast type aclitem[] to character varying [SQL State=42846] </code></pre> <p>Modifying the query to</p> <pre><code>CREATE OR REPLACE VIEW view_all_grants AS SELECT use.usename as subject, nsp.nspname as namespace, c.relname as item, c.relkind as type, use2.usename as owner, c.relacl -- , (use2.usename != use.usename and c.relacl::text !~ ('({|,)' || use.usename || '=')) as public FROM pg_user use cross join pg_class c left join pg_namespace nsp on (c.relnamespace = nsp.oid) left join pg_user use2 on (c.relowner = use2.usesysid) WHERE c.relowner = use.usesysid -- or c.relacl::text ~ ('({|,)(|' || use.usename || ')=') ORDER BY subject, namespace, item </code></pre> <p>Allows the view to be created, but I'm concerned that this is not showing all relevant data.</p> <p>How can I modify the view to work on redshift or is there an better/alternative way to view grants on redshift ?</p> <p><strong>UPDATE:</strong> Redshift has the HAS_TABLE_PRIVILEGE function to check grants. (see <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_HAS_TABLE_PRIVILEGE.html">here</a>)</p>
36,530,337
7
6
null
2013-09-11 12:31:50.07 UTC
24
2022-09-06 13:08:33.633 UTC
2017-05-04 13:54:40.993 UTC
null
330,315
null
808,653
null
1
39
sql|amazon-redshift
76,729
<p>Another variation be like:</p> <pre><code>SELECT * FROM ( SELECT schemaname ,objectname ,usename ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'select') AND has_schema_privilege(usrs.usename, schemaname, 'usage') AS sel ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'insert') AND has_schema_privilege(usrs.usename, schemaname, 'usage') AS ins ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'update') AND has_schema_privilege(usrs.usename, schemaname, 'usage') AS upd ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'delete') AND has_schema_privilege(usrs.usename, schemaname, 'usage') AS del ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'references') AND has_schema_privilege(usrs.usename, schemaname, 'usage') AS ref FROM ( SELECT schemaname, 't' AS obj_type, tablename AS objectname, schemaname + '.' + tablename AS fullobj FROM pg_tables WHERE schemaname not in ('pg_internal','pg_automv') UNION SELECT schemaname, 'v' AS obj_type, viewname AS objectname, schemaname + '.' + viewname AS fullobj FROM pg_views WHERE schemaname not in ('pg_internal','pg_automv') ) AS objs ,(SELECT * FROM pg_user) AS usrs ORDER BY fullobj ) WHERE (sel = true or ins = true or upd = true or del = true or ref = true) and schemaname='&lt;opt schema&gt;' and usename = '&lt;opt username&gt;'; </code></pre>
14,933,929
PHP: Converting UTF-8 string to Ansi?
<p>I build a csv string from values I have in my DB. The final string is stored in my $csv variable.</p> <p>Now I offer this string for download, like this:</p> <pre><code>header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=whatever.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo $csv; </code></pre> <p>When I open this in Notepad++ for example, it says <em>Ansi as UTF-8</em>. How can I chnage that to Ansi only?</p> <p>I tried:</p> <pre><code>$csv = iconv("ISO-8859-1", "WINDOWS-1252", $csv); </code></pre> <p>That did not change anything.</p> <p>Thanks!</p> <p><strong>Solution:</strong> $csv = iconv("UTF-8", "WINDOWS-1252", $csv);</p>
14,934,118
3
6
null
2013-02-18 10:17:51.017 UTC
1
2019-04-16 19:25:17.993 UTC
2013-02-18 10:31:13.86 UTC
null
1,856,596
null
1,856,596
null
1
9
php|ansi
68,579
<p>Try:</p> <pre><code>$csv = iconv("UTF-8", "Windows-1252", $csv); </code></pre> <p>But you will eventually lose data because ANSI can only encode a small subset of UTF-8. If you don't have a very strong reason against it, serve your files UTF-8 encoded.</p>
15,285,687
How to position UITableViewCell at bottom of screen?
<p>There are one to three <code>UITableViewCell</code>s in a <code>UITableViewView</code>. Is there a way to always position the cell(s) at the bottom of screen after <code>reloadData</code>?</p> <pre><code>+----------------+ +----------------+ +----------------+ | | | | | | | | | | | | | | | | | | | | | | | +------------+ | | | | | | | cell 1 | | | | | | | +------------+ | | | | +------------+ | | +------------+ | | | | | cell 1 | | | | cell 2 | | | | | +------------+ | | +------------+ | | +------------+ | | +------------+ | | +------------+ | | | cell 1 | | | | cell 2 | | | | cell 3 | | | +------------+ | | +------------+ | | +------------+ | +----------------+ +----------------+ +----------------+ </code></pre>
32,233,834
14
5
null
2013-03-08 02:28:56.637 UTC
12
2018-03-29 12:45:36.1 UTC
null
null
null
null
88,597
null
1
26
ios|cocoa-touch|uitableview
12,726
<p>I've create a new sample solution since the previous answer is not outdated for modern use.</p> <p>The latest technique uses autolayout and self-sizing cells so the previous answer would no longer work. I reworked the solution to work with the modern features and created a sample project to put on GitHub.</p> <p>Instead of counting up the height of each row, which is causes additional work, this code instead gets the frame for the last row so that the content inset from the top can be calculated. It leverages what the table view is already doing so no additional work is necessary.</p> <p>This code also only sets the top inset in case the bottom inset is set for the keyboard or another overlay. </p> <p>Please report any bugs or submit improvements on GitHub and I will update this sample.</p> <p>GitHub: <a href="https://github.com/brennanMKE/BottomTable">https://github.com/brennanMKE/BottomTable</a></p> <pre><code>- (void)updateContentInsetForTableView:(UITableView *)tableView animated:(BOOL)animated { NSUInteger lastRow = [self tableView:tableView numberOfRowsInSection:0]; NSUInteger lastIndex = lastRow &gt; 0 ? lastRow - 1 : 0; NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:lastIndex inSection:0]; CGRect lastCellFrame = [self.tableView rectForRowAtIndexPath:lastIndexPath]; // top inset = table view height - top position of last cell - last cell height CGFloat topInset = MAX(CGRectGetHeight(self.tableView.frame) - lastCellFrame.origin.y - CGRectGetHeight(lastCellFrame), 0); UIEdgeInsets contentInset = tableView.contentInset; contentInset.top = topInset; UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState; [UIView animateWithDuration:animated ? 0.25 : 0.0 delay:0.0 options:options animations:^{ tableView.contentInset = contentInset; } completion:^(BOOL finished) { }]; } </code></pre>
15,024,933
Why equal operator works for Integer value until 128 number?
<p>Why Integer <code>==</code> operator does not work for 128 and after Integer values? Can someone explain this situation?</p> <p>This is my Java environment:</p> <pre class="lang-none prettyprint-override"><code>java version &quot;1.6.0_37&quot; Java(TM) SE Runtime Environment (build 1.6.0_37-b06) Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01, mixed mode) </code></pre> <p>Sample Code:</p> <pre class="lang-java prettyprint-override"><code>Integer a; Integer b; a = 129; b = 129; for (int i = 0; i &lt; 200; i++) { a = i; b = i; if (a != b) { System.out.println(&quot;Value:&quot; + i + &quot; - Different values&quot;); } else { System.out.println(&quot;Value:&quot; + i + &quot; - Same values&quot;); } } </code></pre> <p>Some part of console output:</p> <pre><code>Value:124 - Same values Value:125 - Same values Value:126 - Same values Value:127 - Same values Value:128 - Different values Value:129 - Different values Value:130 - Different values Value:131 - Different values Value:132 - Different values </code></pre>
15,024,977
7
0
null
2013-02-22 13:04:16.253 UTC
8
2021-06-14 19:27:05.683 UTC
2021-06-14 08:53:38.343 UTC
null
-1
null
889,556
null
1
27
java|integer|equals-operator
18,606
<p>Check out <a href="https://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/Integer.java#l596" rel="nofollow noreferrer" title="public static Integer valueOf(int i) {...}">the source code of Integer</a> . You can see the caching of values there.</p> <p>The caching happens only if you use <code>Integer.valueOf(int)</code>, not if you use <code>new Integer(int)</code>. The autoboxing used by you uses <code>Integer.valueOf</code>.</p> <p>According to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7" rel="nofollow noreferrer">JLS</a>, you can always count on the fact that for values between -128 and 127, you get the identical Integer objects after autoboxing, and on some implementations you might get identical objects even for higher values.</p> <p>Actually in Java 7 (and I think in newer versions of Java 6), the <a href="http://www.docjar.com/html/api/java/lang/Integer.java.html" rel="nofollow noreferrer">implementation</a> of the IntegerCache class has changed, and the upper bound is no longer hardcoded, but it is configurable via the property &quot;java.lang.Integer.IntegerCache.high&quot;, so if you run your program with the VM parameter <code>-Djava.lang.Integer.IntegerCache.high=1000</code>, you get &quot;Same values&quot; for all values.</p> <p>But the JLS still guarantees it only until 127:</p> <blockquote> <p>Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly.</p> <p>For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.</p> <p>This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all characters and shorts, as well as integers and longs in the range of -32K - +32K.</p> </blockquote>
15,346,863
Windows Batch Script: Redirect ALL output to a file
<p>I am running various Java benchmarks and would like to archive the results. I execute the (dacapo) benchmark like this:</p> <pre><code>C:\VM\jre\bin\java -jar C:\benchmarks\dacapo-9.12-bach.jar %arg1% &gt; %time::=% </code></pre> <p>I pass the type of benchmark in over a parameter, thats what %arg1% is.</p> <p>You can see that I am redirecting the output to a textfile. Unfortunately, the first and last line of the output is still printed in the console and not into the textfile:</p> <pre><code>===== DaCapo 9.12 luindex starting ===== ===== DaCapo 9.12 luindex PASSED in 2000 msec ===== </code></pre> <p>Especially the last line would be important to have in the text file :)</p> <p>Is there a trick to force this behavior?</p>
15,346,929
2
0
null
2013-03-11 19:24:53.283 UTC
14
2018-05-14 20:39:47.207 UTC
2014-07-23 14:53:39.24 UTC
null
3,558,960
null
497,393
null
1
45
windows|batch-file|dacapo
47,940
<p>You must redirect <em>STDOUT</em> and <em>STDERR</em>.</p> <p><code>command &gt; logfile 2&gt;&amp;1</code></p> <p><em>STDIN</em> is file descriptor #0, <em>STDOUT</em> is file descriptor #1 and <em>STDERR</em> is file descriptor #2.<br> Just as "command > file" redirects <em>STDOUT</em> to a file, you may also redirect arbitrary file descriptors to each other. The <code>&gt;&amp;</code> operator redirects between file descriptors. So, <code>2 &gt;&amp; 1</code> redirects all <em>STDERR</em> output to <em>STDOUT</em>. </p> <p>Furthermore, take care to add <code>2&gt;&amp;1</code> at the end of the instruction because on Windows, the order of redirection is important as <code>command 2&gt;&amp;1 &gt; logfile</code> will produce an empty file, as Dawid added in the comments.</p>
15,208,615
Using .pth files
<p>I am trying to make a module discoverable on a system where I don't have write access to the global <code>site-packages</code> directory, and without changing the environment (<code>PYTHONPATH</code>). I have tried to place a <code>.pth</code> file in the same directory as a script I'm executing, but it seems to be ignored. E.g., I created a file <code>extras.pth</code> with the following content: </p> <pre><code>N:\PythonExtras\lib\site-packages </code></pre> <p>But the following script, placed and run in the same directory, prints <code>False</code>.</p> <pre><code>import sys print r"N:\PythonExtras\lib\site-packages" in sys.paths </code></pre> <p>The only directory in <code>sys.path</code> to which I have write access is the directory containing the script. Is there another (currently non-existent) directory where I could place <code>extras.pth</code> and have it be seen? Is there a better way to go about this?</p> <p>I'm using python 2.7 on Windows. All <code>.pth</code> questions I could find here use the system module directories.</p> <p><strong>Edit:</strong> I've tracked down the Windows per-user installation directory, at <code>%APPDATA%\Python\Python27\site-packages</code>. I can place a module there and it will be imported, but if I put a <code>.pth</code> file there, it has no effect. Is this really not supposed to work, or am I doing something wrong?</p>
15,209,116
2
0
null
2013-03-04 18:37:07.677 UTC
18
2019-01-05 19:14:04.353 UTC
2013-03-04 19:45:39.133 UTC
null
699,305
null
699,305
null
1
53
python
104,125
<p>As described in <a href="http://docs.python.org/2/library/site.html">the documentation</a>, PTH files are only processed if they are in the site-packages directory. (More precisely, they are processed if they are in a "site directory", but "site directory" itself is a setting global to the Python installation and does not depend on the current directory or the directory where the script resides.)</p> <p>If the directory containing your script is on <code>sys.path</code>, you could create a <code>sitecustomize.py</code> in that directory. This will be loaded when Python starts up. Inside <code>sitecustomize.py</code>, you can do:</p> <pre><code>import site site.addsitedir('/some/dir/you/want/on/the/path') </code></pre> <p>This will not only add that directory, but will add it as a "site directory", causing PTH files there to be processed. This is handy if you want to create your own personal <code>site-packages</code>-like-directory.</p> <p>If you only need to add one or two directories to the path, you could do so more simply. Just create a tiny Python library that manipulates <code>sys.path</code>, and then import that library from your script. Something like:</p> <pre><code># makepath.py import sys sys.path.append('/whatever/dir/you/want') # script.py import makepath </code></pre> <p>Edit: Again, according to <a href="http://docs.python.org/2/library/site.html#site.USER_SITE">the documentation</a>, there is the possibility of a site-specific directory in <code>%APPDATA%\Python\PythonXY\site-packages</code> (on Windows). You could try that, if in fact you have write access to that (and not just to your script directory).</p>
15,134,199
How to split and modify a string in NodeJS?
<p>I have a string :</p> <pre><code>var str = "123, 124, 234,252"; </code></pre> <p>I want to parse each item after split and increment 1. So I will have:</p> <pre><code>var arr = [124, 125, 235, 253 ]; </code></pre> <p>How can I do that in NodeJS?</p>
15,134,505
3
0
null
2013-02-28 11:20:37.23 UTC
13
2017-04-04 11:07:41.38 UTC
2013-02-28 11:22:16.537 UTC
null
1,003,994
null
594,781
null
1
54
javascript|node.js
186,748
<p>Use <code>split</code> and <code>map</code> function:</p> <pre><code>var str = "123, 124, 234,252"; var arr = str.split(","); arr = arr.map(function (val) { return +val + 1; }); </code></pre> <p>Notice <code>+val</code> - string is casted to a number.</p> <p>Or shorter:</p> <pre><code>var str = "123, 124, 234,252"; var arr = str.split(",").map(function (val) { return +val + 1; }); </code></pre> <h3>edit 2015.07.29</h3> <p>Today I'd advise <strong>against</strong> using <code>+</code> operator to cast variable to a number. Instead I'd go with a more explicit but also more readable <code>Number</code> call:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var str = "123, 124, 234,252"; var arr = str.split(",").map(function (val) { return Number(val) + 1; }); console.log(arr);</code></pre> </div> </div> </p> <h3>edit 2017.03.09</h3> <p>ECMAScript 2015 introduced <em>arrow function</em> so it could be used instead to make the code more concise:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var str = "123, 124, 234,252"; var arr = str.split(",").map(val =&gt; Number(val) + 1); console.log(arr);</code></pre> </div> </div> </p>
28,106,872
how to post json object array to a web api
<p>How can I post a JSON array to a Web API? It's working for single object.</p> <p>This is what I've tried, but the controller seems to be returning <code>0</code> rather than the expected <code>3</code>.</p> <p>This is my JSON:</p> <pre><code>var sc = [{ "ID": "5", "Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a", "Table_ID": "Allergy_Trns", "Checksum": "-475090533", "LastModified": "2015-01-22T20:08:52.013" }, { "ID": "5", "Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a", "Table_ID": "Allergy_Trns", "Checksum": "-475090533", "LastModified": "2015-01-22T20:08:52.013" }, { "ID": "5", "Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a", "Table_ID": "Allergy_Trns", "Checksum": "-475090533", "LastModified": "2015-01-22T20:08:52.013" }]; </code></pre> <p>AJAX call:</p> <pre><code>$.ajax({ url: urlString, type: 'POST', data: sc, dataType: 'json', crossDomain: true, cache: false, success: function (data) { console.log(data); } }); </code></pre> <p>Web API controller:</p> <pre><code>[HttpPost] public string PostProducts([FromBody]List&lt;SyncingControl&gt; persons) { return persons.Count.ToString(); // 0, expected 3 } </code></pre>
28,107,144
3
3
null
2015-01-23 09:37:27.093 UTC
4
2016-01-08 13:46:17.057 UTC
2015-01-23 10:59:25.743 UTC
null
1,833,612
null
2,471,038
null
1
18
c#|jquery|asp.net|json|asp.net-web-api
42,805
<p>There is an error in the json <code>Table_ID": "Allergy_Trns"</code> should be <code>"Table_ID": "Allergy_Trns"</code>.</p> <p>Missing double quote.</p> <p><strong>Update</strong></p> <p>You need to make sure that you are sending your parameters as json as follows:</p> <pre><code> $.ajax({ url: urlString, type: 'POST', data: JSON.stringify(sc), dataType: 'json', contentType: 'application/json', crossDomain: true, cache: false, success: function (data) { console.log(data); } }); </code></pre> <p>Notice the <code>JSON.stringify(sc)</code>, @herbi is partly correct too about specifying a content type.</p> <p><strong>Screen grab</strong></p> <p><img src="https://i.stack.imgur.com/XpKAU.png" alt="**Screen grab**"></p>
28,221,555
How does OkHttp get Json string?
<p><strong><em>Solution</em></strong>: It was a mistake on my side.</p> <p>The right way is <strong>response.body().string()</strong> other than <strong>response.body.toString()</strong></p> <p>Im using Jetty servlet, the URL is<code>http://172.16.10.126:8789/test/path/jsonpage</code>, every time request this URL it will return </p> <pre><code>{"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} </code></pre> <p>It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with <code>Okhttp</code>.</p> <pre><code>TestActivity﹕ com.squareup.okhttp.internal.http.RealResponseBody@537a7f84 </code></pre> <p>The Okhttp code Im using:</p> <pre><code>OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } </code></pre> <p>Can anyone helpe?</p>
29,680,883
6
3
null
2015-01-29 18:04:54.79 UTC
22
2022-03-22 09:59:36.683 UTC
2017-01-22 22:30:23.893 UTC
null
399,576
null
1,735,756
null
1
73
java|http|okhttp|embedded-jetty
125,153
<pre><code>try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(urls[0]) .build(); Response responses = null; try { responses = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } String jsonData = responses.body().string(); JSONObject Jobject = new JSONObject(jsonData); JSONArray Jarray = Jobject.getJSONArray("employees"); for (int i = 0; i &lt; Jarray.length(); i++) { JSONObject object = Jarray.getJSONObject(i); } } </code></pre> <p>Example add to your columns:</p> <pre><code>JCol employees = new employees(); colums.Setid(object.getInt("firstName")); columnlist.add(lastName); </code></pre>
48,012,663
how to define a static property in the ES6 classes
<p>I want to have a static property in an ES6 class. This property value is initially an empty array.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> class Game{ constructor(){ // this.cards = []; } static cards = []; } Game.cards.push(1); console.log(Game.cards);</code></pre> </div> </div> </p> <p>How can I do it?</p>
48,034,996
2
4
null
2017-12-28 18:38:25.1 UTC
6
2018-07-24 10:29:45.07 UTC
2018-03-15 14:16:13.63 UTC
null
65,732
null
9,150,399
null
1
46
javascript|ecmascript-6|static|es6-class
41,213
<p>One way of doing it could be like this:</p> <pre><code>let _cards = []; class Game{ static get cards() { return _cards; } } </code></pre> <p>Then you can do:</p> <pre><code>Game.cards.push(1); console.log(Game.cards); </code></pre> <p>You can find some useful points in this <a href="https://esdiscuss.org/topic/define-static-properties-and-prototype-properties-with-the-class-syntax" rel="noreferrer">discussion</a> about including static properties in es6.</p>
45,194,598
using process.env in TypeScript
<p>How do I read node environment variables in TypeScript? </p> <p>If i use <code>process.env.NODE_ENV</code> I have this error :</p> <pre><code>Property 'NODE_ENV' does not exist on type 'ProcessEnv' </code></pre> <p>I have installed <code>@types/node</code> but it didn't help.</p>
45,195,359
19
8
null
2017-07-19 15:11:22.96 UTC
38
2022-07-25 21:36:32.087 UTC
null
null
null
null
990,193
null
1
190
node.js|typescript
248,129
<p>There's no guarantee of what (if any) environment variables are going to be available in a Node process - the <code>NODE_ENV</code> variable is just a convention that was popularised by Express, rather than something built in to Node itself. As such, it wouldn't really make sense for it to be included in the type definitions. Instead, <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts#L408" rel="noreferrer">they define <code>process.env</code> like this</a>:</p> <pre><code>export interface ProcessEnv { [key: string]: string | undefined } </code></pre> <p>Which means that <code>process.env</code> can be indexed with a string in order to get a string back (or <code>undefined</code>, if the variable isn't set). To fix your error, you'll have to use the index syntax:</p> <pre><code>let env = process.env["NODE_ENV"]; </code></pre> <p>Alternatively, as jcalz pointed out in the comments, if you're using TypeScript 2.2 or newer, you can access indexable types like the one defined above using the dot syntax - in which case, your code should just work as is.</p>
9,498,877
How is TeamViewer so fast?
<p>Sorry about the length, it's kinda necessary.</p> <p><strong>Introduction</strong></p> <p>I'm developing a remote desktop software (just for fun) in C# 4.0 for Windows Vista/7. I've gotten through basic obstacles: I have a robust UDP messaging system, relatively clean program design, I've got a mirror driver (the free DFMirage mirror driver from DemoForge) up and running, and I've implemented NAT traversal for all NAT types except Symmetric NATs (present in corporate firewall situations).</p> <p>Regarding screen transfer/sharing, thanks to the mirror driver, I'm automatically notified of changed screen regions and I can simply marshal the mirror driver's ever-changing screen bitmap to my own bitmap. Then I compress the screen region as a PNG and send it off from the server to my client. Things are looking pretty good, but it's not fast enough. It's just as slow as VNC (btw, I don't use the VNC protocol, just a custom amateur protocol).</p> <p>From the slowest remote desktop software to the fastest, the list usually begins at all VNC-like implementations, then climbs up to Microsoft Windows Remote Desktop...and then...TeamViewer. Not quite sure about CrossLoop, LogMeIn - I haven't used them, but TeamViewer is <em>insanely</em> fast. It's quite literally live. I ran a <code>tree</code> command on Command Prompt and it updated with 20 ms delay. I can browse the web just a few milliseconds slower than on my laptop. Scrolling code vertically in Visual Studio has 50 ms lag time. Think about how robust TeamViewer's screen-transfer solution must be to accomplish all this.</p> <p>VNCs use poll-based hooks for detecting screen change and brute force screen capturing/comparing at their worst. At their best, they use a mirror driver like DFMirage. I'm at this level. And they use something called the RFB protocol.</p> <p>Microsoft Windows Remote Desktop apparently goes one step higher than VNC. I heard, from somewhere on StackOverflow, that Windows Remote Desktop doesn't send screen bitmaps, but actual drawing commands. That's quite brilliant, because it can just send simple text (draw this rectangle at this coordinate and color it with this gradient)! Remote Desktop really is pretty fast - and it's the standard way of working from home. And it uses something called the RDP protocol.</p> <p>Now TeamViewer is a complete mystery to me. Apparently, they released their source code for Version 2 (TeamViewer is Version 7 as of February 2012). People have read it and said that Version 2 is useless - that it's just a few improvements over VNC with automatic NAT traversal. </p> <p>But Version 7...it's ridiculously fast now. I mean, it's actually faster than Windows Remote Desktop. I've streamed DirectX 3D games with TeamViewer (at 1 fps, but Windows Remote Desktop doesn't even allow DirectX to run).</p> <p>By the way, TeamViewer does all this <em>without</em> a mirror driver. There is an option to install one, and it gets just a bit faster.</p> <p><strong>The Question</strong></p> <p><strong>My question is, how is TeamViewer so fast?</strong> It must not be possible. If you've got 1920 by 1080 resolution at even 24 bit depth (16 bit depth would be noticeably ugly), thats still 6,220,800 bytes raw. Even using libjpeg-turbo (one of the fastest JPG compression libraries used by large corporations), compressing it down to 30KB (let's be extremely generous), would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers). And that libjpeg-turbo compression would take time to compress. High-quality JPG compression takes 175 milliseconds for a full 1920 by 1080 screenshot for me. And that number goes up if the host's computer runs an Atom processor. I simply don't understand how TeamViewer has optimized their screen transfer so well. Again, small-size images might be highly compressed, but take at least tens of milliseconds to compress. Large-size images take no time to compress, but take a long time to get through. Somehow, TeamViewer completes this entire process to get roughly 20-25 frames per second. I've used a network monitor, and TeamViewer is still lagless at speeds of 500 Kbps and 1 Mbps (VNC software lag for a few seconds at that transfer rate). During my <code>tree</code> Command Prompt test, TeamViewer was receiving inbound data at a rate of 1 Mbps and still running 5-6 fps. VNC and remote desktop don't do that. So, how?</p> <p>The answers will be somewhat complicated and intricate, so <em>please don't post your $0.02 if you're only going to say it's because they use UDP instead of TCP</em> (would you believe they actually do use TCP just as successfully though).</p> <p>I'm hoping there's a TeamViewer developer somewhere here on StackOverflow.</p> <p><strong>Potential Answers</strong></p> <p>Will update this once people reply.</p> <ol> <li>My thoughts are, first of all, that TeamViewer has very fine network control. For example, they split large packets to just under the MTU size and never waste a trip. They probably have all sorts of fancy hooks to detect screen changes along with extremely fast XOR image comparisons.</li> </ol>
9,499,435
5
7
null
2012-02-29 12:06:48.66 UTC
99
2019-10-30 23:24:15.84 UTC
null
null
null
null
555,547
null
1
167
performance|network-programming|operating-system|udp|remote-desktop
154,868
<p>The most fundamental thing here probably is that you don't want to transmit static images but only <em>changes</em> to the images, which essentially is analogous to <strong>video stream</strong>.</p> <p>My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is <em>linear</em> movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).</p> <p>The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.</p>
8,461,636
Real World Functional Programming in Scala
<p>Soooo...</p> <p>Semigroups, Monoids, Monads, Functors, Lenses, Catamorphisms, Anamorphisms, Arrows... These all sound good, and after an exercise or two (or ten), you can grasp their essence. And with <code>Scalaz</code>, you get them for free...</p> <p>However, in terms of real-world programming, I find myself struggling to find usages to these notions. Yes, of course I always find someone on the web using Monads for IO or Lenses in Scala, but... still... </p> <p>What I am trying to find is something along the "prescriptive" lines of a pattern. Something like: "here, you are trying to solves <em>this</em>, and one good way to solve it is by using lenses <em>this way</em>!"</p> <p>Suggestions?</p> <hr> <p>Update: Something along these lines, with a book or two, would be great (thanks Paul): <a href="https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns">Examples of GoF Design Patterns in Java&#39;s core libraries</a></p>
8,466,077
5
3
null
2011-12-11 02:52:50.923 UTC
11
2011-12-19 01:27:15.02 UTC
2017-05-23 12:33:33.567 UTC
null
-1
null
41,652
null
1
35
scala|functional-programming|design-patterns|scalaz
4,033
<p>I gave <a href="http://skillsmatter.com/podcast/scala/practical-scalaz-2518">a talk back in September</a> focused on the practical application of monoids and applicative functors/monads via <em>scalaz.Validation</em>. I gave another version of the same talk <a href="http://skillsmatter.com/podcast/scala/scalaz">at the scala Lift Off</a>, where the emphasis was more on the validation. I would watch the first talk until I start on validations and then skip to the second talk (27 minutes in).</p> <p>There's also <a href="https://gist.github.com/970717">a gist I wrote</a> which shows how you might use <em>Validation</em> in a "practical" application. That is, if you are designing software for nightclub bouncers.</p>
5,320,814
Order of rows in heatmap?
<p>Take the following code:</p> <pre><code> heatmap(data.matrix(signals),col=colors,breaks=breaks,scale="none",Colv=NA,labRow=NA) </code></pre> <p>How can I extract, pre-calculate or re-calculate the order of the rows in the heatmap produced? Is there a way to inject the output of <code>hclust(dist(signals))</code> into the heatmap function?</p>
5,329,590
5
1
null
2011-03-16 03:42:41.73 UTC
6
2017-10-24 16:15:57.33 UTC
2012-07-02 11:26:50.65 UTC
null
97,160
null
114,307
null
1
9
r|cluster-analysis|heatmap
43,944
<p>Thanks for the feedback, Jesse and Paolo. I wrote the following ordering function which will hopefully be useful to others:</p> <pre><code>data = data.matrix(data) distance = dist(data) cluster = hclust(distance, method="ward") dendrogram = as.dendrogram(cluster) Rowv = rowMeans(data, na.rm = T) dendrogram = reorder(dendrogram, Rowv) ## Produce the heatmap from the calculated dendrogram. ## Don't allow it to re-order rows because we have already re-ordered them above. reorderfun = function(d,w) { d } png("heatmap.png", res=150, height=22,width=17,units="in") heatmap(data,col=colors,breaks=breaks,scale="none",Colv=NA,Rowv=dendrogram,labRow=NA, reorderfun=reorderfun) dev.off() ## Re-order the original data using the computed dendrogram rowInd = rev(order.dendrogram(dendrogram)) di = dim(data) nc = di[2L] nr = di[1L] colInd = 1L:nc data_ordered &lt;- data[rowInd, colInd] write.table(data_ordered, "rows.txt",quote=F, sep="\t",row.names=T, col.names=T) </code></pre>
4,854,947
Android Microsoft Office Library (.doc, .docx, .xls, .ppt, etc.)
<p>Does anyone know of a good Java Microsoft Office API capable or running on an Android? I know there is an OpenOffice Java API, but I haven't heard of anyone using it on Android.</p> <p>I know that using intents is another option, but how common are pre-installed office viewers on the varying Android distributions? Would it be reasonable for a developer to expect the user to have one of these viewers installed? Is it reasonable to request that they install one of these applications if they don't already have one?</p>
5,266,527
5
1
null
2011-01-31 19:07:40.64 UTC
10
2019-02-07 17:13:53.827 UTC
2011-10-28 13:21:31.453 UTC
null
496,830
null
313,207
null
1
28
java|android|ms-office|openoffice.org
34,353
<p>Since most of the documents we need to display are already hosted on the web, we opted to use an embedded web view that opens the document using <a href="http://docs.google.com/viewer" rel="noreferrer">google docs viewer</a>. </p> <p>We still have a few locally stored documents though that this approach doesn't work with. For these, our solution was to rely on the support of existing apps. After spending some more time with Android, It seems that most devices come equipped with some sort of document/pdf reading capability installed fresh out of the box. In the event that they don't have a capable app, we direct them to a market search for a free reader. </p>
5,407,421
Design a Hashtable
<p>I was asked this question in an Interview and was left stumped, even though i came up with an answer I didn't feel comfortable with my solution. I wanted to see how experts here feel about this question.</p> <p>I am exactly quoting the question as it came out of the Interviewer. "Design a Hash-table, You can use any data-structure you can want. I would like to see how you implement the O(1) look up time". Finally he said It's more like simulating a Hash-table via another Data-structure.</p> <p>Can anyone light me with more information on this question. Thanks!</p> <p>PS: Main reason for me putting this question is to know how an expert designer would start off with the Design for this problem &amp;&amp; one more thing I cleared the interview somehow based on the other questions that were asked but this question was in my mind and I wanted to find out the answer!</p>
5,407,639
6
13
null
2011-03-23 15:14:57.31 UTC
9
2014-10-14 21:20:35.063 UTC
2011-03-23 15:22:51.703 UTC
user645466
null
user645466
null
null
1
22
algorithm|hashtable
18,685
<p>It's a fairly standard interview question that shows you understand the underlying concepts being useful Java data structures, like <strong>HashSet</strong>s and <strong>HashMap</strong>s.</p> <p>You would use an array of lists, these are normally referred to as <strong><em>buckets</em></strong>. You start your hashtable with a given capacity <em>n</em> meaning you have a array of 10 lists (all empty). </p> <p>To add an object to your hastable you call the objects <code>hashCode</code> function which gives you an int (a number in a pretty big range). So you then have to modulo the hashCode wrt to <em>n</em> to give you the bucket it lives in. Add the object to the end of the list in that bucket.</p> <p>To find an object you again use the hashCode and mod function to find the bucket and then need to iterate through the list using <code>.equals()</code> to find the correct object.</p> <p>As the table gets fuller, you will end up doing more and more linear searching, so you will eventually need to re-hash. This means building an entirely new, larger table and putting the objects into it again.</p> <p>Instead of using a List in each array position you can recalulate a different bucket position if the one you want is full, a common method is <a href="http://en.wikipedia.org/wiki/Quadratic_probing" rel="noreferrer">quadratic probing</a>. This has the advantage of not needed any dynamic data structures like lists but is more complicated.</p>
5,440,168
Exception: There is already an open DataReader associated with this Connection which must be closed first
<p>I have below code and I am getting exception:</p> <blockquote> <p>There is already an open <code>DataReader</code> associated with this <code>Connection</code> which must be closed first.</p> </blockquote> <p>I am using Visual Studio 2010/.Net 4.0 and MySQL for this project. Basically I am trying to run another SQL statement while using data reader to do my other task. I am getting exception at line <code>cmdInserttblProductFrance.ExecuteNonQuery();</code></p> <pre><code>SQL = "Select * from tblProduct"; //Create Connection/Command/MySQLDataReader MySqlConnection myConnection = new MySqlConnection(cf.GetConnectionString()); myConnection.Open(); MySqlCommand myCommand = new MySqlCommand(SQL, myConnection); MySqlDataReader myReader = myCommand.ExecuteReader(); myCommand.Dispose(); if (myReader.HasRows) { int i = 0; // Always call Read before accessing data. while (myReader.Read()) { if (myReader["frProductid"].ToString() == "") //there is no productid exist for this item { strInsertSQL = "Insert Into tblProduct_temp (Productid) Values('this istest') "; MySqlCommand cmdInserttblProductFrance = new MySqlCommand(strInsertSQL, myConnection); cmdInserttblProductFrance.ExecuteNonQuery(); //&lt;=====THIS LINE THROWS "C# mySQL There is already an open DataReader associated with this Connection which must be closed first." } } } </code></pre>
7,404,092
9
1
null
2011-03-26 03:19:44.247 UTC
10
2022-08-26 13:17:25.01 UTC
2014-08-02 11:11:38.097 UTC
null
2,642,204
null
552,918
null
1
47
c#|mysql
162,102
<p>You are using the same connection for the <code>DataReader</code> and the <code>ExecuteNonQuery</code>. This is not supported, <a href="http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.80).aspx" rel="noreferrer">according to MSDN</a>:</p> <blockquote> <p>Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.</p> </blockquote> <p><strong>Updated 2018</strong>: link to <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader" rel="noreferrer">MSDN</a></p>
5,410,820
How can I show all the localStorage saved variables?
<p>I want to acess all the localStorage variables saved on a specific page. How do I do that? I want to show it like I would show an array with the join() function</p>
5,410,874
9
1
null
2011-03-23 19:51:24.52 UTC
20
2022-07-01 21:46:56.903 UTC
2012-02-21 18:41:48.68 UTC
null
357,641
null
652,170
null
1
77
javascript|html|local-storage
98,700
<p>You could try iterating through all of the items in the localStorage object:</p> <pre><code>for (var i = 0; i &lt; localStorage.length; i++){ // do something with localStorage.getItem(localStorage.key(i)); } </code></pre>
4,873,607
How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5
<p>I have a stored procedure that has three parameters and I've been trying to use the following to return the results:</p> <pre><code>context.Database.SqlQuery&lt;myEntityType&gt;("mySpName", param1, param2, param3); </code></pre> <p>At first I tried using <code>SqlParameter</code> objects as the params but this didn't work and threw a <code>SqlException</code> with the following message:</p> <blockquote> <p>Procedure or function 'mySpName' expects parameter '@param1', which was not supplied.</p> </blockquote> <p>So my question is how you can use this method with a stored procedure that expects parameters?</p> <p>Thanks.</p>
4,874,600
10
2
null
2011-02-02 11:01:51.4 UTC
62
2019-10-03 17:37:41.8 UTC
2014-01-29 13:50:35.767 UTC
null
13,302
null
333,943
null
1
268
c#|sql|ado.net|linq-to-entities|entity-framework-ctp5
353,167
<p>You should supply the SqlParameter instances in the following way: </p> <pre><code>context.Database.SqlQuery&lt;myEntityType&gt;( "mySpName @param1, @param2, @param3", new SqlParameter("param1", param1), new SqlParameter("param2", param2), new SqlParameter("param3", param3) ); </code></pre>
5,497,064
How to get the full path of running process?
<p>I am having an application that is changing some settings of another application (it is a simple C# application that run by double clicking (no setup required)).</p> <p>After changing the settings I need to restart the other application so that it reflects the changed settings.</p> <p>So to do, I have to kill the running process and start the process again, But the problem is after killing I am not able to find the process. (Reason is system do not know where the exe file is..)</p> <p><strong>Is there any way to find out the path of running process or exe, if it is running?</strong></p> <p>I do not want to give path manually, i.e. if it is running get the path, kill the process and start again else .... I will handle later</p>
5,497,123
14
0
null
2011-03-31 08:23:52.373 UTC
30
2022-08-24 09:56:36.187 UTC
2020-10-07 11:41:59.65 UTC
null
9,139,384
null
503,110
null
1
125
c#
171,472
<pre><code> using System.Diagnostics; var process = Process.GetCurrentProcess(); // Or whatever method you are using string fullPath = process.MainModule.FileName; //fullPath has the path to exe. </code></pre> <p>There is one catch with this API, if you are running this code in 32 bit application, you'll not be able to access 64-bit application paths, so you'd have to compile and run you app as 64-bit application (Project Properties → Build → Platform Target → x64).</p>
12,132,260
What is the difference between Shell, Kernel and API
<p>I want to understand how this applies to an operating system and also to those things that are not infact operating systems. I can't understand the difference between the three and their essence. API is the functions we can call but what is Shell? If we have an API than what exactly is the Kernel of the operating system? I understand the an operating system has a Core that is not going to change and this core does the fundamental Job of a typical OS while we may have different user interfaces like GUI or command line with the same Kernel. So the problem is I am confused how these things are different. Aaaaaaarhg!</p> <p>Can the functions like printf and fopen in C be called API calls?</p>
12,134,430
4
0
null
2012-08-26 17:19:59.527 UTC
21
2020-05-30 04:01:53.807 UTC
null
null
null
null
854,183
null
1
26
api|shell|operating-system|kernel
52,246
<ul> <li><p>A <strong>command-line interface (CLI) shell</strong> is a command interpreter, i.e. the program that either processes the command you enter in your command line (aka terminal) or processes shell scripts (text files containing commands) (batch mode). In early Unix times, it used to be the unique way for users to interact with their machines. Nowadays, graphical user interfaces (GUIs) are becoming the preferred type of shell for most users.</p></li> <li><p>A <strong>kernel</strong> is a low level program interfacing with the hardware (CPU, RAM, disks, network, ...) on top of which applications are running. It is the lowest level program running on computers although with virtualization you can have multiple kernels running on top of virtual machines which themselves run on top of another operating system.</p></li> <li><p>An <strong>API</strong> is a generic term defining the interface developers have to use when writing code using libraries and a programming language. <strong>Kernels have no APIs</strong> as they are not libraries. They do have an <strong>ABI</strong>, which, beyond other things, define how do applications interact with them through system calls. Unix application developers use the standard C library (eg: <code>libc</code>, <code>glibc</code>) to build ABI compliant binaries. <code>printf(3)</code> and <code>fopen(3)</code> are not wrappers to system calls but <code>(g)libc</code> standard facilities. The low level system calls they eventually use are <code>write(2)</code> and <code>open(2)</code> and possibly others like <code>brk</code>, <code>mmap</code>. The number in parentheses is a convention to tell in what manual the command is to be found.</p></li> </ul> <p>The first volume of the Unix manual pages contains the <strong>shell</strong> commands.</p> <p>The second one contains the system call <strong>wrappers</strong> like <code>write</code> and <code>open</code>. They form the interface to the <strong>kernel</strong>.</p> <p>The third one contains the standard library (including the Unix standard <strong>API</strong>) functions (excluding system calls) like <code>fopen</code> and <code>printf</code>. These are <strong>not</strong> wrappers to specific system calls but just code using system calls when required.</p>
12,566,023
Sharing rerere cache
<p>I've seen people recommend that all developers set up a symlink on their machine from <code>C:\project\.git\rr-cache</code> to a shared folder <code>\\server\rr-cache</code>.</p> <p>However, it would seem more convenient to share the folder by including it in the git repository itself, if that is possible. I've seen people mention this solution, but not actually how to do it.</p> <p>Any ideas?</p>
12,590,387
2
3
null
2012-09-24 13:26:04.973 UTC
15
2014-05-09 09:59:36.633 UTC
2013-07-06 01:21:34.197 UTC
null
1,864,976
user479911
null
null
1
28
git|version-control|git-merge|merge-conflict-resolution|git-rerere
5,832
<p>It can be shared via a dedicated branch. You want to stop if there is a conflict on that branch and resolve it as it means that there were attempts to solve the same conflict in 2 different ways. Needless to say, that will be the exception to the rule.</p> <p>For the others on this question, google "Branch per Feature" to see where this is useful.</p> <p>Hooks can automate syncing the common rr-cache branch.</p> <p>Here is what you need to automate. rereresharing is an example branch that you are merging to, rr-cache is a branch that stores the resolutions; all these steps worked without issue:</p> <pre><code>git checkout --orphan rereresharing start-sprint-1 git --git-dir=.git --work-tree=.git/rr-cache checkout -b rr-cache git --git-dir=.git --work-tree=.git/rr-cache add -A git --git-dir=.git --work-tree=.git/rr-cache commit -m "initial cache" git clean -xdf git checkout rereresharing git merge --no-ff FTR-1 git merge --no-ff FTR-2 vim opinion.txt # resolve conflict git add -A git commit git checkout rr-cache git --git-dir=.git --work-tree=.git/rr-cache add -A git --git-dir=.git --work-tree=.git/rr-cache commit -m "resolution" git remote add origin ../bpf-central git push origin rereresharing rr-cache cd - # assumes you were previously in the other local repo git remote add origin ../bpf-central git fetch git branch rr-cache origin/rr-cache ls .git/rr-cache git --git-dir=.git --work-tree=.git/rr-cache checkout rr-cache -- . ls .git/rr-cache </code></pre> <p>You are now ready to do the same merge and you will have your conflict resolved.</p>
12,501,331
How does long to int cast work in Java?
<p>This question is <strong>not</strong> about how a <a href="https://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java">long should be correctly cast to an int</a>, but rather what happens when we incorrectly cast it to an int. </p> <p>So consider this code -</p> <pre><code> @Test public void longTest() { long longNumber = Long.MAX_VALUE; int intNumber = (int)longNumber; // potentially unsafe cast. System.out.println("longNumber = "+longNumber); System.out.println("intNumber = "+intNumber); } </code></pre> <p>This gives the output - </p> <pre><code>longNumber = 9223372036854775807 intNumber = -1 </code></pre> <p>Now suppose I make the following change-</p> <pre><code>long longNumber = Long.MAX_VALUE - 50; </code></pre> <p>I then get the output - </p> <pre><code>longNumber = 9223372036854775757 intNumber = -51 </code></pre> <p>The question is, <strong>how</strong> is the long's value being converted to an int?</p>
12,501,360
1
0
null
2012-09-19 19:12:03.257 UTC
6
2012-09-19 19:30:38.153 UTC
2017-05-23 12:17:44.467 UTC
null
-1
null
1,199,882
null
1
29
java|casting
15,421
<p>The low 32 bits of the <code>long</code> are taken and put into the <code>int</code>.</p> <p>Here's the math, though:</p> <ol> <li>Treat negative <code>long</code> values as <code>2^64</code> plus that value. So <code>-1</code> is treated as 2^64 - 1. (This is the <em>unsigned</em> 64-bit value, and it's how the value is actually represented in binary.)</li> <li>Take the result and mod by 2^32. (This is the <em>unsigned</em> 32-bit value.)</li> <li>If the result is >= 2^31, subtract 2^32. (This is the signed 32-bit value, the Java <code>int</code>.)</li> </ol>
12,223,529
Create Globally Unique ID in JavaScript
<p>I have a script that, when a user loads, creates a unique id. Which is then saved in <code>localStorage</code> and used for tracking transactions. Sort of like using a cookie, except since the browser is generating the unique id there might be collisions when sent to the server. Right now I'm using the following code:</p> <pre class="lang-js prettyprint-override"><code>function genID() { return Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2); } </code></pre> <p>I realize this is a super basic implementation, and want some feedback on better ways to create a "more random" id that will prevent collisions on the server. Any ideas?</p>
12,223,573
1
5
null
2012-08-31 23:16:39.447 UTC
6
2015-09-30 19:05:05.06 UTC
2015-09-30 19:05:05.06 UTC
null
591,166
null
591,166
null
1
38
javascript
24,888
<p>I've used this in the past. Collision odds should be very low.</p> <pre><code>var generateUid = function (separator) { /// &lt;summary&gt; /// Creates a unique id for identification purposes. /// &lt;/summary&gt; /// &lt;param name="separator" type="String" optional="true"&gt; /// The optional separator for grouping the generated segmants: default "-". /// &lt;/param&gt; var delim = separator || "-"; function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } return (S4() + S4() + delim + S4() + delim + S4() + delim + S4() + delim + S4() + S4() + S4()); }; </code></pre>
12,174,947
Removing part of a filename for multiple files on Linux
<p>I want to remove <strong>test.extra</strong> from all of my file names in current directory </p> <pre><code>for filename in *.fasta;do echo $filename | sed \e 's/test.extra//g' done </code></pre> <p>but it complains about not founding file.echo is to be sure it list correctly. </p>
12,175,160
7
3
null
2012-08-29 09:38:56.733 UTC
31
2019-09-02 08:03:10.59 UTC
2018-12-15 15:32:44.167 UTC
null
608,639
null
1,571,792
null
1
58
linux|bash|shell
103,306
<p>First of all use 'sed -e' instead of '\e'</p> <p>And I would suggest you do it this way in bash </p> <pre><code>for filename in *.fasta; do [ -f "$filename" ] || continue mv "$filename" "${filename//test.extra/}" done </code></pre>
43,121,340
Why is the use of len(SEQUENCE) in condition values considered incorrect by Pylint?
<p>Considering this code snippet:</p> <pre><code>from os import walk files = [] for (dirpath, _, filenames) in walk(mydir): # More code that modifies files if len(files) == 0: # &lt;-- C1801 return None </code></pre> <p>I was alarmed by Pylint with this message regarding the line with the if statement:</p> <blockquote> <p>[pylint] C1801:Do not use <code>len(SEQUENCE)</code> as condition value</p> </blockquote> <p>The rule C1801, at first glance, did not sound very reasonable to me, and the <a href="https://pylint.readthedocs.io/en/latest/reference_guide/features.html#id19" rel="noreferrer">definition on the reference guide</a> does not explain why this is a problem. In fact, it downright calls it an <em>incorrect use</em>.</p> <blockquote> <p><strong>len-as-condition (C1801)</strong>: <em>Do not use <code>len(SEQUENCE)</code> as condition value Used when Pylint detects incorrect use of len(sequence) inside conditions.</em></p> </blockquote> <p>My search attempts have also failed to provide me a deeper explanation. I do understand that a sequence's length property may be lazily evaluated, and that <code>__len__</code> can be programmed to have side effects, but it is questionable whether that alone is problematic enough for Pylint to call such a use incorrect. Hence, before I simply configure my project to ignore the rule, I would like to know whether I am missing something in my reasoning.</p> <p>When is the use of <code>len(SEQ)</code> as a condition value problematic? What major situations is Pylint attempting to avoid with C1801?</p>
43,476,778
4
7
null
2017-03-30 14:52:30.96 UTC
19
2022-08-30 12:37:59.323 UTC
2021-01-20 10:01:20.323 UTC
null
63,550
null
1,233,251
null
1
235
python|conditional-statements|pylint
94,267
<blockquote> <p>When is the use of <code>len(SEQ)</code> as a condition value problematic? What major situations is Pylint attempting to avoid with C1801?</p> </blockquote> <p>It’s not <em>really</em> problematic to use <code>len(SEQUENCE)</code> – though it may not be as efficient (see <a href="https://stackoverflow.com/questions/43121340/why-is-the-use-of-lensequence-in-condition-values-considered-incorrect-by-pyli#comment73322508_43121340">chepner’s comment</a>). Regardless, Pylint checks code for compliance with the <a href="https://www.python.org/dev/peps/pep-0008" rel="noreferrer">PEP 8 style guide</a> which states that</p> <blockquote> <p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.</p> <pre><code><b>Yes:</b> if not seq: if seq: <b>No:</b> if len(seq): if not len(seq): </code></pre> </blockquote> <p>As an occasional Python programmer, who flits between languages, I’d consider the <code>len(SEQUENCE)</code> construct to be more readable and explicit (“Explicit is better then implicit”). However, using the fact that an empty sequence evaluates to <code>False</code> in a Boolean context is considered more “Pythonic”.</p>
3,668,128
How to create a boost ssl iostream?
<p>I'm adding HTTPS support to code that does input and output using boost tcp::iostream (acting as an HTTP server).</p> <p>I've found examples (and have a working toy HTTPS server) that do SSL input/output using boost::asio::read/boost::asio::write, but none that use iostreams and the &lt;&lt; >> operators. How do I turn an ssl::stream into an iostream?</p> <p>Working code:</p> <pre><code>#include &lt;boost/asio.hpp&gt; #include &lt;boost/asio/ssl.hpp&gt; #include &lt;boost/foreach.hpp&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; using namespace std; using namespace boost; using boost::asio::ip::tcp; typedef boost::asio::ssl::stream&lt;boost::asio::ip::tcp::socket&gt; ssl_stream; string HTTPReply(int nStatus, const string&amp; strMsg) { string strStatus; if (nStatus == 200) strStatus = "OK"; else if (nStatus == 400) strStatus = "Bad Request"; else if (nStatus == 404) strStatus = "Not Found"; else if (nStatus == 500) strStatus = "Internal Server Error"; ostringstream s; s &lt;&lt; "HTTP/1.1 " &lt;&lt; nStatus &lt;&lt; " " &lt;&lt; strStatus &lt;&lt; "\r\n" &lt;&lt; "Connection: close\r\n" &lt;&lt; "Content-Length: " &lt;&lt; strMsg.size() &lt;&lt; "\r\n" &lt;&lt; "Content-Type: application/json\r\n" &lt;&lt; "Date: Sat, 09 Jul 2009 12:04:08 GMT\r\n" &lt;&lt; "Server: json-rpc/1.0\r\n" &lt;&lt; "\r\n" &lt;&lt; strMsg; return s.str(); } int main() { // Bind to loopback 127.0.0.1 so the socket can only be accessed locally boost::asio::io_service io_service; tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 1111); tcp::acceptor acceptor(io_service, endpoint); boost::asio::ssl::context context(io_service, boost::asio::ssl::context::sslv23); context.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2); context.use_certificate_chain_file("server.cert"); context.use_private_key_file("server.pem", boost::asio::ssl::context::pem); for(;;) { // Accept connection ssl_stream stream(io_service, context); tcp::endpoint peer_endpoint; acceptor.accept(stream.lowest_layer(), peer_endpoint); boost::system::error_code ec; stream.handshake(boost::asio::ssl::stream_base::server, ec); if (!ec) { boost::asio::write(stream, boost::asio::buffer(HTTPReply(200, "Okely-Dokely\n"))); // I really want to write: // iostream_object &lt;&lt; HTTPReply(200, "Okely-Dokely\n") &lt;&lt; std::flush; } } } </code></pre> <p>It seems like the ssl::stream_service would be the answer, but that is a dead end.</p> <p>Using boost::iostreams (as suggested by accepted answer) is the right approach; here's the working code I've ended up with:</p> <pre><code>#include &lt;boost/asio.hpp&gt; #include &lt;boost/asio/ssl.hpp&gt; #include &lt;boost/iostreams/concepts.hpp&gt; #include &lt;boost/iostreams/stream.hpp&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;iostream&gt; using namespace boost::asio; typedef ssl::stream&lt;ip::tcp::socket&gt; ssl_stream; // // IOStream device that speaks SSL but can also speak non-SSL // class ssl_iostream_device : public boost::iostreams::device&lt;boost::iostreams::bidirectional&gt; { public: ssl_iostream_device(ssl_stream &amp;_stream, bool _use_ssl ) : stream(_stream) { use_ssl = _use_ssl; need_handshake = _use_ssl; } void handshake(ssl::stream_base::handshake_type role) { if (!need_handshake) return; need_handshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (use_ssl) return stream.read_some(boost::asio::buffer(s, n)); return stream.next_layer().read_some(boost::asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (use_ssl) return boost::asio::write(stream, boost::asio::buffer(s, n)); return boost::asio::write(stream.next_layer(), boost::asio::buffer(s, n)); } private: bool need_handshake; bool use_ssl; ssl_stream&amp; stream; }; std::string HTTPReply(int nStatus, const std::string&amp; strMsg) { std::string strStatus; if (nStatus == 200) strStatus = "OK"; else if (nStatus == 400) strStatus = "Bad Request"; else if (nStatus == 404) strStatus = "Not Found"; else if (nStatus == 500) strStatus = "Internal Server Error"; std::ostringstream s; s &lt;&lt; "HTTP/1.1 " &lt;&lt; nStatus &lt;&lt; " " &lt;&lt; strStatus &lt;&lt; "\r\n" &lt;&lt; "Connection: close\r\n" &lt;&lt; "Content-Length: " &lt;&lt; strMsg.size() &lt;&lt; "\r\n" &lt;&lt; "Content-Type: application/json\r\n" &lt;&lt; "Date: Sat, 09 Jul 2009 12:04:08 GMT\r\n" &lt;&lt; "Server: json-rpc/1.0\r\n" &lt;&lt; "\r\n" &lt;&lt; strMsg; return s.str(); } void handle_request(std::iostream&amp; s) { s &lt;&lt; HTTPReply(200, "Okely-Dokely\n") &lt;&lt; std::flush; } int main(int argc, char* argv[]) { bool use_ssl = (argc &lt;= 1); // Bind to loopback 127.0.0.1 so the socket can only be accessed locally io_service io_service; ip::tcp::endpoint endpoint(ip::address_v4::loopback(), 1111); ip::tcp::acceptor acceptor(io_service, endpoint); ssl::context context(io_service, ssl::context::sslv23); context.set_options( ssl::context::default_workarounds | ssl::context::no_sslv2); context.use_certificate_chain_file("server.cert"); context.use_private_key_file("server.pem", ssl::context::pem); for(;;) { ip::tcp::endpoint peer_endpoint; ssl_stream _ssl_stream(io_service, context); ssl_iostream_device d(_ssl_stream, use_ssl); boost::iostreams::stream&lt;ssl_iostream_device&gt; ssl_iostream(d); // Accept connection acceptor.accept(_ssl_stream.lowest_layer(), peer_endpoint); std::string method; std::string path; ssl_iostream &gt;&gt; method &gt;&gt; path; handle_request(ssl_iostream); } } </code></pre>
3,693,387
3
7
null
2010-09-08 13:20:12.503 UTC
13
2015-10-06 21:58:28.513 UTC
2010-09-15 01:29:36.947 UTC
null
58,359
null
58,359
null
1
24
c++|boost|openssl|boost-asio|iostream
11,326
<p><a href="https://stackoverflow.com/users/441099/guy">@Guy</a>'s suggestion (using <code>boost::asio::streambuf</code>) should work, and it's probably the easiest to implement. The main drawback to that approach is that everything you write to the iostream will be buffered in memory until the end, when the call to <code>boost::asio::write()</code> will dump the entire contents of the buffer onto the ssl stream at once. (I should note that this kind of buffering can actually be desirable in many cases, and in your case it probably makes no difference at all since you've said it's a low-volume application). </p> <p>If this is just a "one-off" I would probably implement it using @Guy's approach.</p> <p>That being said -- there are a number of good reasons that you might rather have a solution that allows you to use iostream calls to write directly into your <code>ssl_stream</code>. If you find that this is the case, then you'll need to build your own wrapper class that extends <code>std::streambuf</code>, overriding <code>overflow()</code>, and <code>sync()</code> (and maybe others depending on your needs).</p> <p>Fortunately, <a href="http://www.boost.org/doc/libs/1_44_0/libs/iostreams/doc/index.html" rel="nofollow noreferrer"><code>boost::iostreams</code></a> provides a relatively easy way to do this without having to mess around with the std classes directly. You just build your own class that implements the appropriate <a href="http://www.boost.org/doc/libs/1_44_0/libs/iostreams/doc/concepts/device.html" rel="nofollow noreferrer"><code>Device</code></a> contract. In this case that's <a href="http://www.boost.org/doc/libs/1_44_0/libs/iostreams/doc/concepts/sink.html" rel="nofollow noreferrer"><code>Sink</code></a>, and the <code>boost::iostreams::sink</code> class is provided as a convenient way to get most of the way there. Once you have a new Sink class that encapsulates the process of writing to your underlying ssl_stream, all you have to do is create a <code>boost::iostreams::stream</code> that is templated to your new device type, and off you go.</p> <p>It will look something like the following (this example is adapted from <a href="http://www.boost.org/doc/libs/1_44_0/libs/iostreams/doc/tutorial/container_sink.html" rel="nofollow noreferrer">here</a>, see also <a href="https://stackoverflow.com/questions/533038/redirect-stdcout-to-a-custom-writer">this related stackoverflow post</a>):</p> <pre><code>//---this should be considered to be "pseudo-code", //---it has not been tested, and probably won't even compile //--- #include &lt;boost/iostreams/concepts.hpp&gt; // other includes omitted for brevity ... typedef boost::asio::ssl::stream&lt;boost::asio::ip::tcp::socket&gt; ssl_stream; class ssl_iostream_sink : public sink { public: ssl_iostream_sink( ssl_stream *theStream ) { stream = theStream; } std::streamsize write(const char* s, std::streamsize n) { // Write up to n characters to the underlying // data sink into the buffer s, returning the // number of characters written boost::asio::write(*stream, boost::asio::buffer(s, n)); } private: ssl_stream *stream; }; </code></pre> <p>Now, your accept loop might change to look something like this:</p> <pre><code>for(;;) { // Accept connection ssl_stream stream(io_service, context); tcp::endpoint peer_endpoint; acceptor.accept(stream.lowest_layer(), peer_endpoint); boost::system::error_code ec; stream.handshake(boost::asio::ssl::stream_base::server, ec); if (!ec) { // wrap the ssl stream with iostream ssl_iostream_sink my_sink(&amp;stream); boost::iostream::stream&lt;ssl_iostream_sink&gt; iostream_object(my_sink); // Now it works the way you want... iostream_object &lt;&lt; HTTPReply(200, "Okely-Dokely\n") &lt;&lt; std::flush; } } </code></pre> <p>That approach hooks the ssl stream into the iostream framework. So now you should be able to do anything to <code>iostream_object</code> in the above example, that you would normally do with any other <code>std::ostream</code> (like stdout). And the stuff that you write to it will get written into the ssl_stream behind the scenes. Iostreams has built-in buffering, so some degree of buffering will take place internally -- but this is a good thing -- it will buffer until it has accumulated some reasonable amount of data, then it will dump it on the ssl stream, and go back to buffering. The final std::flush, <em>should</em> force it to empty the buffer out to the ssl_stream.</p> <p>If you need more control over internal buffering (or any other advanced stuff), have a look at the other cool stuff available in <code>boost::iostreams</code>. Specifically, you might start by looking at <a href="http://www.boost.org/doc/libs/1_44_0/libs/iostreams/doc/guide/generic_streams.html#stream_buffer" rel="nofollow noreferrer"><code>stream_buffer</code></a>. </p> <p>Good luck!</p>
3,751,661
what is the meaning of Broken pipe Exception?
<p>what is the meaning of broken pipe exception and when it will come?</p>
3,751,722
3
0
null
2010-09-20 12:57:14.993 UTC
5
2016-11-22 10:01:07.14 UTC
2016-11-22 10:01:07.14 UTC
null
1,439,305
null
449,281
null
1
28
java
63,147
<p>A pipe is a data stream, typically data being read from a file or from a network socket. A broken pipe occurs when this pipe is suddenly closed from the other end. For a flie, this could be if the file is mounted on a disc or a remote network which has become disconnected. For a network socket, it could be if the network gets unplugged or the process on the other end crashes.</p> <p>In Java, there is no <code>BrokenPipeException</code> specifically. This type of error will be found wrapped in a different exception, such as a <code>SocketException</code> or <code>IOException</code>.</p>
38,466,276
Why is `row.names` preferred over `rownames`?
<p>There are two functions in the R core library.</p> <ul> <li><a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/row.names.html">row.names</a> <em>Get and Set Row Names for Data Frames</em></li> <li><a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/colnames.html">rownames</a> <em>Retrieve or set the row names of a matrix-like object.</em></li> </ul> <p>However the docs for <code>row.names</code> specifies <em>For a data frame, ‘rownames’ and ‘colnames’ eventually call ‘row.names’ and ‘names’ respectively, but the latter are preferred.</em> Why are is <code>row.names</code> preferred? Wouldn't it be easier to just ignore <code>row.names</code> and just call <code>rownames</code>?</p>
39,179,031
1
7
null
2016-07-19 18:47:18.313 UTC
8
2021-11-17 06:45:38.697 UTC
2016-07-19 19:03:04.967 UTC
null
124,486
null
124,486
null
1
32
r
6,682
<p><code>row.names()</code> is an S3 generic function whereas <code>rownames()</code> is a lower level non-generic function. <code>rownames()</code> is in effect the default method for <code>row.names()</code> that is applied to any object in the absence of a more specific method.</p> <p>If you are operating on a data frame <code>x</code>, then it is more efficient to use <code>row.names(x)</code> because there is a specific <code>row.names()</code> method for data frames. The <code>row.names()</code> method for data frames simply extracts the <code>&quot;row.names&quot;</code> attribute that is already stored in <code>x</code>. By contrast, because of the definition of <code>rownames()</code> and the inter-relationships between the functions, <code>rownames(x)</code> has to extract all the dimension names of <code>x</code>, then drop the column names, then combine with <code>names(x)</code>, then drop <code>names(x)</code> again. This process even involves a call to <code>row.names(x)</code> as an intermediate step. This will all usually happen so quickly that you don't notice it, but just extracting the attribute is obviously more efficient.</p> <p>It would be logical to just use the generic version <code>row.names()</code> all the time, since it always dispatches the appropriate method. There is no practical advance in using <code>rownames(x)</code> over <code>row.names(x)</code>. For object classes that have a defined <code>row.names</code> method, then <code>rownames(x)</code> is wrong because it bypasses that method. For object classes with no defined row.names method, then the two functions are equivalent because <code>row.names(x)</code> simply calls <code>rownames(x)</code>.</p> <p>The reason why both functions exist is historical. <code>rownames()</code> is the older function and was part of the R language before generic functions and methods were introduced. It was intended only for use on matrices, but it will work fine on any data object that has a <code>dimnames</code> attribute. I personally use <code>rownames(x)</code> when <code>x</code> is a matrix and <code>row.names(x)</code> otherwise but, as I have said, one could just as well use <code>row.names(x)</code> all the time.</p>
22,689,122
Why is Haskell unable to read "7e7" but able to read "7a7"?
<p>Try to do:</p> <pre><code>Prelude&gt; reads "7a7" :: [(Int, String)] [(7,"a7")] Prelude&gt; reads "7e7" :: [(Int, String)] [] </code></pre> <p>I tested this for all possible characters in the middle. They all work except for <code>'e'</code>. It seems as if <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29">Haskell</a> tries to interpret the number in scientific notation, but it can't because I'm asking for <code>Int</code>.</p> <p>It seems like a bug to me. </p>
22,689,863
3
6
null
2014-03-27 13:28:42.267 UTC
1
2014-04-09 23:05:17.473 UTC
2014-03-27 19:09:45.38 UTC
null
467,090
null
600,545
null
1
49
string|haskell
2,119
<p>GHC is indeed buggy. Its implementation of <a href="http://hackage.haskell.org/package/base-4.6.0.1/docs/src/Numeric.html#readSigned"><code>Numeric.readSigned</code></a> uses the following:</p> <pre><code>read'' r = do (str,s) &lt;- lex r (n,"") &lt;- readPos str return (n,s) </code></pre> <p>The <code>lex</code> call will try to parse any lexeme, and this means that for "7e7" it yields <code>[("7e7", "")]</code>, because "7e7" is a whole lexeme for a floating point literal. Then it tries to get a complete parse out of <code>readPos</code>, which in this case is an argument for which <code>Numeric.readDec</code> was passed in, and <code>readDec</code> will yield, correctly, <code>[(7, "e7")]</code> for the string "7e7". That fails pattern matching against <code>(n, "")</code>, and ends up as <code>[]</code>.</p> <p>I <em>think</em> it should be simply as follows:</p> <pre><code>read'' = readPos </code></pre>
26,246,867
'ping' is not recognized as an internal or external command operable program or batch file error
<p>When I do <code>ping www.google.com</code> I get the error message</p> <blockquote> <p>'ping' is not recognized as an internal or external command operable program or batch file.</p> </blockquote> <p>Here is an example:</p> <p><img src="https://i.stack.imgur.com/NTKsO.png" alt="Command Prompt Ping" /></p> <p>Then:</p> <p><img src="https://i.stack.imgur.com/B05Kn.png" alt="Error Command Prompt" /></p> <p>What could I be doing wrong?</p> <p>I'm using Windows 7, 64 bit</p> <p>There was some tutorial online that said to look up Systems32. And that didnt even show up. In the search at the image there</p> <p><img src="https://i.stack.imgur.com/Ux3GY.png" alt="Windows menu button" /></p> <p>I have also restarted my computer</p> <p>I've had this for over 6 months and its really beginning to cause me problems.</p> <p>Also if you believe this is off topic please explain first :P</p>
26,246,992
2
7
null
2014-10-07 23:24:39.69 UTC
1
2021-06-21 23:03:26.497 UTC
2021-06-21 23:03:26.497 UTC
null
3,204,869
null
3,204,869
null
1
10
windows|batch-file|command-prompt|ping|system32
53,944
<p>Most likely something has removed the system32 directory from your path. Have you installed the Java SDK? It has a reputation for doing that.</p> <p>To check this, at the command prompt type <code>path</code> (followed by enter)</p> <p>If c:\windows\system32 isn't there, it needs to be added back in. To do this:</p> <pre><code>From the desktop, Right click 'Computer', click 'Properties' then click 'Advanced system settings' - this should bring up the System Properties - Advanced tab Click 'Enviornment Variables' Select the system variables 'PATH' Edit PATH and add this line to the front c:\windows\system32; or to be generic (in case you've installed windows on a different drive) %SystemRoot%\system32 Start a new command window to check if this has worked (or reboot) existing command windows will use the old path </code></pre>
11,245,062
How can we get exact time to load a page using Selenium WebDriver?
<p>How can we get exact time to load a page using Selenium WebDriver?</p> <p>We use Thread.sleep</p> <p>We use implicitlyWait</p> <p>we use WebDriverWait</p> <p>but How can we get exact time to load a page using Selenium WebDriver?</p>
11,248,246
5
3
null
2012-06-28 12:51:01.457 UTC
5
2020-09-02 16:43:40.907 UTC
2016-12-15 08:20:56.283 UTC
null
1,515,052
null
1,015,801
null
1
9
java|selenium|selenium-webdriver|webdriver
63,134
<p>If you are trying to find out how much time does it take to load a page completely using Selenium WebDriver (a.k.a Selenium 2).</p> <p>Normally WebDriver should return control to your code only after the page has loaded completely.</p> <p>So the following Selenium Java code might help you to find the time for a page load - </p> <pre><code>long start = System.currentTimeMillis(); driver.get("Some url"); long finish = System.currentTimeMillis(); long totalTime = finish - start; System.out.println("Total Time for page load - "+totalTime); </code></pre> <p>If this does not work then you will have to wait till some element is displayed on the page - </p> <pre><code> long start = System.currentTimeMillis(); driver.get("Some url"); WebElement ele = driver.findElement(By.id("ID of some element on the page which will load")); long finish = System.currentTimeMillis(); long totalTime = finish - start; System.out.println("Total Time for page load - "+totalTime); </code></pre>
11,189,021
Reports in Codeigniter
<p>What is the most simplist way to generate reports in Codeigniter framework? Is there any library available to do this task? Except charting what are the other resources to do this.</p>
11,189,368
3
2
null
2012-06-25 12:04:04.613 UTC
15
2017-03-01 08:02:34.98 UTC
2013-09-13 08:05:09 UTC
null
713,141
null
713,141
null
1
14
php|codeigniter|csv|report|codeigniter-2
35,395
<p>Found a nice solution myself. If you want to generate reports in csv format it is very easy with codeigniter. Your model function </p> <pre><code>function index(){ return $query = $this-&gt;db-&gt;get('my_table'); /* Here you should note i am returning the query object instead of $query-&gt;result() or $query-&gt;result_array() */ } </code></pre> <p>Now in controller</p> <pre><code>function get_report(){ $this-&gt;load-&gt;model('my_model'); $this-&gt;load-&gt;dbutil(); $this-&gt;load-&gt;helper('file'); /* get the object */ $report = $this-&gt;my_model-&gt;index(); /* pass it to db utility function */ $new_report = $this-&gt;dbutil-&gt;csv_from_result($report); /* Now use it to write file. write_file helper function will do it */ write_file('csv_file.csv',$new_report); /* Done */ } </code></pre> <p>No externals are required everything is available in codeigntier. Cheers! If you want to write xml file it is easy too.<br> Just use <code>xml_from_result()</code> method of dbutil and use <code>write_file('xml_file.xml,$new_report)</code> Visit these links they will help. </p> <p><a href="http://codeigniter.com/user_guide/database/utilities.html" rel="noreferrer">Database Utility Class</a> </p> <p>And </p> <p><a href="http://codeigniter.com/user_guide/helpers/file_helper.html" rel="noreferrer">File Helper</a></p>
11,395,180
VBA Reference counting - Object destruction
<p>Lately I've bumped into a question that made me pounder; it kept me busy and I couldn't find a transparent explanation for it on the net.<br> It is related to the destruction of Excel objects (which I use all the time and never <em>really</em> questioned before). </p> <p>Background leading to my question:<br> With regular objects, you can instantiate an object using the keywords SET and NEW. For example: </p> <pre><code>Set classInstance = New className </code></pre> <p>Whenever we instantiate this way, the object is created in the heap memory and the reference counter is increased by 1.<br> In case I don't add more references, the following statement would bring the reference count back to zero: </p> <pre><code>Set classInstance = Nothing </code></pre> <p>When the reference count goes to 0, the object is destroyed and cleared from memory and the "classInstance" points to . </p> <p>What I've read:<br> When we use the "CREATEOBJECT" function, it returns a reference to a COM object. </p> <pre><code>Set oApp = CreateObject("Excel.Application") </code></pre> <p>Even though we could say: </p> <pre><code>Set oApp = nothing </code></pre> <p>The objects' reference count will go to 0, and oApp will not point to the object anymore. </p> <p><strong>My questions</strong>:<br> 1) Why is it that this type of object requires to call the method .Quit before the object is actually being removed from memory?<br> The same goes when adding a reference to a workbook object (workbooks.add or workbook.open) which requires the .close method. Why can't these objects be automatically destroyed when bringing the reference count to zero?<br> Which is the case when we say for example: </p> <pre><code>set oRange = nothing </code></pre> <p>2) And is there a need to say: </p> <pre><code>oApp.Quit set oApp = nothing </code></pre> <p>Since the Application object is already cleared from memory when applying .Quit, there is no object to be released anymore.<br> The only reason I could come up with, why oApp would be set to Nothing after Quit, would be because it could be pointing to an unused memory location (on the heap) and could lead to confusion later if this memory would be re-assigned (although in VBA I find this hard to imagine). I was questioning myself if this conclusion is correct and I would like to receive confirmation for that from someone who knows the answer.<br> Please, tell me if I see this wrongly. </p> <p>3) What they call in VBA "a reference to an object" (such as oApp in the code above), I see them as pointer variables in C. Would it be safe to use this statement or again, am I seeing this wrongly? </p> <p>Generally is not hard to apply .Quit and set to nothing, but it would be nice to receive some accurate information on the topic. So that I know for 100% percent why I am doing it. </p>
11,396,211
2
2
null
2012-07-09 12:38:40.043 UTC
9
2017-08-30 20:00:43.697 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
917,467
null
1
25
excel|vba
21,827
<p>Good Question :)</p> <p>Excel controls the creation of its objects. Likewise it also controls their destruction.</p> <p>Setting <code>oApp = Nothing</code> just destroys the object reference. It doesn't remove the Application. To destroy an Excel object, you have to use it's <code>.Quit</code> method.</p> <p>Whenever you do, <code>Set x = Nothing</code>, the reference(pointer) named <code>x</code> to its relevant object is removed. This doesn't mean that the object itself will be removed from the memory. Whether the object will be removed from memory or not, depends on various factors.</p> <ol> <li>Whether there are more references pointing towards the same object. If there are, the object will not be removed. The reference count must be zero.</li> <li>The internal implementation of the destructor of that object.</li> </ol> <p>The <code>.Quit</code> method is defined to graciously remove all the memory objects excel has allocated, and close itself. </p> <p>It is similar to calling <code>Close</code> on a form in VB6. Take for example, a form in vb6.</p> <pre><code>Dim f As Form Set f = Form1 f.Show ' '~~&gt; Rest of the code ' Set f = Nothing </code></pre> <p>Will this destroy the form? :)</p> <p><strong>FOLLOWUP</strong></p> <blockquote> <p>How about question 2? Thanks – Kim Gysen 14 mins ago</p> </blockquote> <p><img src="https://i.stack.imgur.com/r58OO.png" alt="enter image description here"></p> <p>It might not be exactly as shown here, and compiler optimizations may make things behave differently... but this is the basic concept that is at work.</p>
10,893,302
What's the difference between $.add and $.append JQuery
<p>I was wondering and couldn't get any best documentation that what's the difference between $.add and $.append when we have single element to add or append to a container.</p> <p>Thanks in Advance</p>
10,893,354
6
5
null
2012-06-05 07:29:08.45 UTC
6
2021-10-12 01:48:30.867 UTC
null
null
null
null
936,217
null
1
39
javascript|jquery
26,222
<p>Given a jQuery object that represents a set of DOM elements, the <a href="https://api.jquery.com/add/" rel="noreferrer"><code>.add()</code></a> method constructs a new jQuery object from the union of those elements and the ones passed into the method. But it does not insert the element into the DOM, i.e using <code>.add()</code> the element will be added to the DOM but to see it in the page you have to insert it in the page using some <a href="http://api.jquery.com/category/manipulation/dom-insertion-outside/" rel="noreferrer">insertion</a>/<a href="http://api.jquery.com/category/manipulation/dom-insertion-inside/" rel="noreferrer">append</a> method.</p>
11,421,048
Android / iOS - Custom URI / Protocol Handling
<p>Is there a way to define some kind of handling mechanism in Android <strong>and</strong> iOS that would allow me to do intercept either of the following:</p> <pre><code>myapp:///events/3/ - or - http://myapp.com/events/3/ </code></pre> <p>I'd like to 'listen' for either the protocol or the host, and open a corresponding Activity / ViewController.</p> <p>I'd like too if these could be as system wide as possible. I imagine this will be more of an issue on iOS, but I'd ideally be able to click either of those two schemes, as hyperlinks, from any app. Gmail, Safari, etc.</p>
11,421,402
3
0
null
2012-07-10 20:03:24.397 UTC
42
2018-06-08 12:31:45.013 UTC
2016-01-13 15:52:03.38 UTC
null
518,530
null
420,001
null
1
51
android|ios|protocols|manifest|custom-url-protocol
49,318
<p><strong>Update:</strong> This is a very old question, and things have changed a lot on both iOS and Android. I'll leave the original answer below, but anyone working on a new project or updating an old one should instead consider using <a href="https://medium.com/@ageitgey/everything-you-need-to-know-about-implementing-ios-and-android-mobile-deep-linking-f4348b265b49" rel="noreferrer">deep links</a>, which are supported on both platforms.</p> <p>On iOS, deep links are called <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html" rel="noreferrer">universal links</a>. You'll need to create a JSON file on your web site that associates your app with URLs that point to parts of your web site. Next, update your app to accept a <code>NSUserActivity</code> object and set up the app to display the content that corresponds to the given URL. You also need to add an entitlement to the app listing the URLs that the app can handle. In use, the operating system takes care of downloading the association file from your site and starting your app when someone tries to open one of the URLs your app handles.</p> <p>Setting up <a href="https://developer.android.com/training/app-links/#app-links-vs-deep-links" rel="noreferrer">app links on Android</a> works similarly. First, you'll set up an association between your web site(s) and your app, and then you'll add <a href="https://developer.android.com/training/app-links/deep-linking" rel="noreferrer">intent filters</a> that let your app intercept attempts to open the URLs that your app can handle.</p> <p>Although the details are obviously different, the approach is pretty much the same on both platforms. It gives you the ability to insert your app into the display of your web site's content no matter what app tries to access that content.</p> <hr> <p><strong>Original answer:</strong></p> <p>For iOS, yes, you can do two things:</p> <ol> <li><p>Have your app advertise that it can handle URL's with a given scheme.</p></li> <li><p>Install a protocol handler to handle whatever scheme you like.</p></li> </ol> <p>The first option is pretty straightforward, and described in <a href="http://developer.apple.com/library/ios/DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html#//apple_ref/doc/uid/TP40007072-CH7-SW50" rel="noreferrer">Implementing Custom URL Schemes</a>. To let the system know that your app can handle a given scheme: </p> <ul> <li><p>update your app's Info.plist with a CFBundleURLTypes entry</p></li> <li><p>implement <code>-application:didFinishLaunchingWithOptions:</code> in your app delegate.</p></li> </ul> <p>The second possibility is to write your own protocol handler. This works only within your app, but you can use it in conjunction with the technique described above. Use the method above to get the system to launch your app for a given URL, and then use a custom URL protocol handler within your app to leverage the power of iOS's URL loading system:</p> <ul> <li><p>Create a your own subclass of <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLProtocol_Class/Reference/Reference.html#//apple_ref/doc/uid/20001700-387826" rel="noreferrer"><code>NSURLProtocol</code></a>.</p></li> <li><p>Override <code>+canInitWithRequest:</code> -- usually you'll just look at the URL scheme and accept it if it matches the scheme you want to handle, but you can look at other aspects of the request as well.</p></li> <li><p>Register your subclass: <code>[MyURLProtocol registerClass];</code></p></li> <li><p>Override <code>-startLoading</code> and <code>-stopLoading</code> to start and stop loading the request, respectively.</p></li> </ul> <p>Read the NSURLProtocol docs linked above for more information. The level of difficulty here depends largely on what you're trying to implement. It's common for iOS apps to implement a custom URL handler so that other apps can make simple requests. Implementing your own HTTP or FTP handler is a bit more involved.</p> <p>For what it's worth, this is exactly how PhoneGap works on iOS. PhoneGap includes an NSURLProtocol subclass called PGURLProtocol that looks at the scheme of any URL the app tries to load and takes over if it's one of the schemes that it recognizes. PhoneGap's open-source cousin is <a href="http://incubator.apache.org/cordova/" rel="noreferrer">Cordova</a> -- you may find it helpful to take a look.</p>
11,259,152
Chrome IOS - Is it just a UIWebView?
<p>I'm not sure this is a suitable question for here but is the new Chrome app for IOS just a UIWebView?</p> <p>If so then would it be safe to assume that there shouldn't be any rendering differences between it and mobile Safari?</p>
46,010,531
3
3
null
2012-06-29 09:19:03.547 UTC
13
2018-12-14 16:12:58.93 UTC
2012-06-29 20:39:50.853 UTC
null
936,643
null
936,643
null
1
61
ios|chrome-ios
40,460
<p>As of version 48, Chrome for iOS uses WKWebView, which is the same view used in Safari.</p> <p>Sources:</p> <ul> <li><a href="https://blog.chromium.org/2016/01/a-faster-more-stable-chrome-on-ios.html" rel="noreferrer">Chromium Blog</a></li> <li><a href="https://arstechnica.com/gadgets/2016/01/new-chrome-for-ios-is-finally-as-fast-and-stable-as-safari/" rel="noreferrer">Ars Technica</a></li> <li><a href="https://venturebeat.com/2016/01/27/google-speeds-up-chrome-for-ios-with-apples-wkwebview-officially-launches-data-saver-extension-on-the-desktop/" rel="noreferrer">VentureBeat</a></li> </ul>
11,063,900
Determine if uploaded file is image (any format) on MVC
<p>So I'm using this code for view:</p> <pre><code>&lt;form action="" method="post" enctype="multipart/form-data"&gt; &lt;label for="file"&gt;Filename:&lt;/label&gt; &lt;input type="file" name="file" id="file" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>This for model:</p> <pre><code>[HttpPost] public ActionResult Index(HttpPostedFileBase file) { if (file.ContentLength &gt; 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(path); } return RedirectToAction("Index"); } </code></pre> <p>Works great unless the user add a file which isn't an image. How can I assure the file uploaded is an image. Thanks</p>
14,587,821
11
4
null
2012-06-16 13:37:08.267 UTC
36
2021-07-19 08:02:55.45 UTC
2021-07-19 08:01:26.13 UTC
null
11,455,105
null
744,484
null
1
67
c#|.net|asp.net-mvc|razor|file-upload
85,469
<p>In case it can helps anyone, Here is a static method for <code>HttpPostedFileBase</code> that checks if a given uploaded file is an image:</p> <pre><code>public static class HttpPostedFileBaseExtensions { public const int ImageMinimumBytes = 512; public static bool IsImage(this HttpPostedFileBase postedFile) { //------------------------------------------- // Check the image mime types //------------------------------------------- if (!string.Equals(postedFile.ContentType, &quot;image/jpg&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFile.ContentType, &quot;image/jpeg&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFile.ContentType, &quot;image/pjpeg&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFile.ContentType, &quot;image/gif&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFile.ContentType, &quot;image/x-png&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFile.ContentType, &quot;image/png&quot;, StringComparison.OrdinalIgnoreCase)) { return false; } //------------------------------------------- // Check the image extension //------------------------------------------- var postedFileExtension = Path.GetExtension(postedFile.FileName); if (!string.Equals(postedFileExtension , &quot;.jpg&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFileExtension , &quot;.png&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFileExtension , &quot;.gif&quot;, StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(postedFileExtension , &quot;.jpeg&quot;, StringComparison.OrdinalIgnoreCase)) { return false; } //------------------------------------------- // Attempt to read the file and check the first bytes //------------------------------------------- try { if (!postedFile.InputStream.CanRead) { return false; } //------------------------------------------ // Check whether the image size exceeding the limit or not //------------------------------------------ if (postedFile.ContentLength &lt; ImageMinimumBytes) { return false; } byte[] buffer = new byte[ImageMinimumBytes]; postedFile.InputStream.Read(buffer, 0, ImageMinimumBytes); string content = System.Text.Encoding.UTF8.GetString(buffer); if (Regex.IsMatch(content, @&quot;&lt;script|&lt;html|&lt;head|&lt;title|&lt;body|&lt;pre|&lt;table|&lt;a\s+href|&lt;img|&lt;plaintext|&lt;cross\-domain\-policy&quot;, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline)) { return false; } } catch (Exception) { return false; } //------------------------------------------- // Try to instantiate new Bitmap, if .NET will throw exception // we can assume that it's not a valid image //------------------------------------------- try { using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream)) { } } catch (Exception) { return false; } finally { postedFile.InputStream.Position = 0; } return true; } } </code></pre> <p>Edit 2/10/2017: According to a suggested edit, added a finally statement to reset the stream, so we can use it later.</p>
11,212,569
Retrieve path of tmpfile()
<p>Quickie...</p> <p>Is there a way to retrieve the path of a file created by <code>tmpfile()</code>?</p> <p>Or do I need to do it myself with <code>tempnam()</code>?</p>
14,976,027
2
0
null
2012-06-26 17:13:49.507 UTC
9
2013-03-14 06:05:36.75 UTC
null
null
null
null
1,159,140
null
1
68
php
33,922
<p>It seems <a href="http://www.php.net/manual/en/function.stream-get-meta-data.php">stream_get_meta_data()</a> also works :</p> <pre><code>$tmpHandle = tmpfile(); $metaDatas = stream_get_meta_data($tmpHandle); $tmpFilename = $metaDatas['uri']; fclose($tmpHandle); </code></pre>
12,948,539
Cocoa - go to foreground/background programmatically
<p>I have an application with LSUIElement set to 1. It has a built-in editor, so I want the application to appear in Cmd+Tab cycle when the editor is open.</p> <pre><code> -(void)stepIntoForeground { if (NSAppKitVersionNumber &lt; NSAppKitVersionNumber10_7) return; if (counter == 0) { ProcessSerialNumber psn = {0, kCurrentProcess}; OSStatus osstatus = TransformProcessType(&amp;psn, kProcessTransformToForegroundApplication); if (osstatus == 0) { ++counter; } else { //... } } } -(void)stepIntoBackground { if (NSAppKitVersionNumber &lt; NSAppKitVersionNumber10_7) return; if (counter == 0) return; if (counter == 1) { ProcessSerialNumber psn = {0, kCurrentProcess}; OSStatus osstatus = TransformProcessType(&amp;psn, kProcessTransformToUIElementApplication); if (osstatus == 0) { --counter; } else { //.. } } } </code></pre> <p>The problems are:</p> <ul> <li>there's also a Dock icon (not a big deal);</li> <li>there's also Menu, that is not a big deal too, but they appear not always.</li> </ul> <p>Is there any way to disable menu at all or to make it appear always in foreground? Thanks in advance.</p>
12,981,068
3
4
null
2012-10-18 06:37:16.027 UTC
9
2019-11-19 13:14:23.337 UTC
2012-10-18 08:10:37.437 UTC
null
1,278,389
null
1,278,389
null
1
8
xcode|macos|cocoa
3,803
<p>This is how we do it. (Works 10.7+)</p> <ol> <li>DO NOT USE LSBackgroundOnly NOR LSUIElement in the app plist</li> <li>Add and init your menu and NSStatusBar menu</li> <li><p>After app initialized but not yet shown any window take a place where you might want to show the first window if any. We use applicationDidFinishLaunching.</p> <ul> <li><p>If you do not want to show any window yet after app initialized use</p> <p><code>[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];</code></p> <p>on 10.9 you can use at last the otherwise much correct</p> <p><code>[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];</code></p></li> <li><p>If you should open any window after app init finished than simply show the main window</p></li> </ul></li> <li><p>Maintain your list of windows</p></li> <li><p>If last window closed, call</p> <p><code>[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];</code></p> <p>on 10.9 you can use at last the otherwise much correct</p> <p><code>[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];</code></p></li> <li><p>When your first window shown next time, call</p> <p><code>[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];</code><br> <code>[NSApp activateIgnoringOtherApps:YES];</code><br> <code>[[self window] makeKeyAndOrderFront:nil];</code></p></li> </ol> <p>This should do the trick, if at least one app window is visible you will have menu, dock icon with state signaled, and cmd+tab element with your app, if last app window closed only your NSStatusBar element stays.</p> <h2>Known issues:</h2> <ul> <li><p>The first step is important because without that if a system modal dialog suspends your startup (f.e. your app is downloaded from the net and become quarantined a confirmation dialog might appear at first startup depending on your security settings) your menubar might not be owned by your app after your first app window shown. </p> <p><strong>Workaround</strong>: Starting as normal app (step 1.) would solve this problem, but will cause another small one, your app icon might appear for a moment in the dock at startup even if you would like to startup without any window shown. (but we can deal with this, not owning the menubar was a bigger problem for us, so we chose this instead)</p></li> <li><p>Changing between NSApplicationActivationPolicyRegular and NSApplicationActivationPolicyAccessory (or NSApplicationActivationPolicyProhibited on OSes bellow 10.9) will kill your tooltip of status bar menu element, the tooltip will be shown initially but will not ever after the second call of NSApplicationActivationPolicyAccessory -> NSApplicationActivationPolicyProhibited </p> <p><strong>Workaround</strong>: We could not find a working workaround for this and reported to Apple as a bug.</p></li> <li><p>Changing from NSApplicationActivationPolicyRegular to NSApplicationActivationPolicyAccessory has other problems on some OS versions like there might be no more mouse events in visible app windows sometimes</p> <p><strong>Workaround</strong>: switch first to NSApplicationActivationPolicyProhibited (take care this leads to unwanted app messages, like NSApplicationWillResignActiveNotification, NSWindowDidResignMainNotification, etc. !)</p></li> <li><p>Changing from NSApplicationActivationPolicyAccessory to NSApplicationActivationPolicyRegular is bogus as on some OS versions </p> <ul> <li>the app main menu is frozen till the first app front status change</li> <li>the app activated after this policy not always get placed front in the application order <hr></li> </ul> <p><strong>Workaround</strong>: switch first to NSApplicationActivationPolicyProhibited, take care the final switch to the desired NSApplicationActivationPolicyRegular should be made delayed, use f.e. dispatch_async or similar</p></li> </ul>
13,193,248
How to make a Gaussian filter in Matlab
<p>I have tried to make a Gaussian filter in Matlab without using <code>imfilter()</code> and <code>fspecial()</code>. I have tried this but result is not like the one I have with imfilter and fspecial.</p> <p>Here is my codes.</p> <pre><code>function Gaussian_filtered = Gauss(image_x, sigma) % for single axis % http://en.wikipedia.org/wiki/Gaussian_filter Gaussian_filtered = exp(-image_x^2/(2*sigma^2)) / (sigma*sqrt(2*pi)); end </code></pre> <p>for 2D Gaussian, </p> <pre><code>function h = Gaussian2D(hsize, sigma) n1 = hsize; n2 = hsize; for i = 1 : n2 for j = 1 : n1 % size is 10; % -5&lt;center&lt;5 area is covered. c = [j-(n1+1)/2 i-(n2+1)/2]'; % A product of both axes is 2D Gaussian filtering h(i,j) = Gauss(c(1), sigma)*Gauss(c(2), sigma); end end end </code></pre> <p>and the final one is</p> <pre><code>function Filtered = GaussianFilter(ImageData, hsize, sigma) %Get the result of Gaussian filter_ = Gaussian2D(hsize, sigma); %check image [r, c] = size(ImageData); Filtered = zeros(r, c); for i=1:r for j=1:c for k=1:hsize for m=1:hsize Filtered = Filtered + ImageData(i,j).*filter_(k,m); end end end end end </code></pre> <p>But the processed image is almost same as the input image. I wonder the last function <code>GaussianFiltered()</code> is problematic...</p> <p>Thanks.</p>
13,205,520
2
2
null
2012-11-02 10:14:59.757 UTC
3
2017-04-11 14:26:37.96 UTC
2016-04-06 07:33:41.723 UTC
null
4,423,636
null
1,098,761
null
1
8
image|matlab|gaussian
58,851
<p>here's an alternative:</p> <p>Create the 2D-Gaussian:</p> <pre><code> function f=gaussian2d(N,sigma) % N is grid size, sigma speaks for itself [x y]=meshgrid(round(-N/2):round(N/2), round(-N/2):round(N/2)); f=exp(-x.^2/(2*sigma^2)-y.^2/(2*sigma^2)); f=f./sum(f(:)); </code></pre> <p>Filtered image, given your image is called <code>Im</code>:</p> <pre><code> filtered_signal=conv2(Im,gaussian2d(N,sig),'same'); </code></pre> <p>Here's some plots:</p> <pre><code>imagesc(gaussian2d(7,2.5)) </code></pre> <p><img src="https://i.stack.imgur.com/gsj7t.png" alt="enter image description here"></p> <pre><code> Im=rand(100);subplot(1,2,1);imagesc(Im) subplot(1,2,2);imagesc(conv2(Im,gaussian2d(7,2.5),'same')); </code></pre> <p><img src="https://i.stack.imgur.com/pxqrF.png" alt="enter image description here"></p>
12,817,151
How to get column names with query data in sqlite3?
<p>I use sqlite3 console to debug my app while it is executing in Android. Is there a way to show also column names (not only data) with data in result of sql query?</p>
12,817,182
1
0
null
2012-10-10 10:24:47.13 UTC
5
2012-10-10 10:33:30.513 UTC
2012-10-10 10:33:30.513 UTC
null
1,048,087
null
1,048,087
null
1
37
android|sqlite|console-application
14,178
<p>Yes, after logged into <strong>sql</strong> <em>prompt mode</em>, execute the following each at a time:</p> <pre><code>.header on .mode column </code></pre>
12,801,815
Regions in TypeScript
<p>In my JavaScript (.js) files, I use a Visual Studio 2012 plugin for regions <a href="http://visualstudiogallery.msdn.microsoft.com/4be701d8-af03-40a4-8cdc-d2add5cde46c" rel="noreferrer">(here)</a> like this:</p> <pre><code>//#region "My Region" //Code here //#endregion "My Region" </code></pre> <p>I would also like to have regions in TypeScript (.ts) files as well. Is this a possibility right now? </p>
14,443,261
4
11
null
2012-10-09 14:02:14.637 UTC
8
2017-10-28 16:17:00.11 UTC
2017-07-19 13:41:56.403 UTC
null
271,200
null
695,874
null
1
80
javascript|visual-studio-2012|typescript|regions
78,944
<p>You can download <a href="https://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6" rel="noreferrer">Web Essentials 2012</a>, it lets you use regions in TypeScript.</p> <p>If you use, Visual Studio 2015, here is the freshest link. <a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebEssentials20153" rel="noreferrer">Web Essentials 2015.3</a></p>
30,624,709
CSS / HTML Navigation and Logo on same line
<p>I can't figure out how to put them on the same line. </p> <p><a href="http://codepen.io/anon/pen/dovZdQ" rel="noreferrer">http://codepen.io/anon/pen/dovZdQ</a></p> <pre><code>&lt;body&gt; &lt;div class="navigation-bar"&gt; &lt;div id="navigation-container"&gt; &lt;img src="logo.png"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Projects&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Services&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Get in Touch&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
30,624,865
6
5
null
2015-06-03 15:39:32.6 UTC
8
2021-07-08 14:19:24.23 UTC
2015-06-03 15:43:33.523 UTC
null
2,530,089
null
4,970,343
null
1
7
html|css|navigation
257,338
<p>The <code>&lt;ul&gt;</code> is by default a block element, make it <code>inline-block</code> instead:</p> <pre><code>.navigation-bar ul { padding: 0px; margin: 0px; text-align: center; display:inline-block; vertical-align:top; } </code></pre> <h2><a href="http://codepen.io/anon/pen/GJWOBV" rel="noreferrer">CodePen Demo</a></h2>
16,985,891
Can iOS do central and peripheral work on same app at same time?
<p>Can iOS (iPhone or iPad) app have Core Bluetooth (BTLE) central manger and peripheral manager objects at same time?</p> <p>Can they operate asynchronously, or does main app thread need to make them share (switch back and forth).</p> <p>Sharing conceptual algorithm would be: disable peripheral manager, enable central manager and do central functions, and then, disable central mgr, enable peripheral mgr, and do peripheral functions (that is, send automatic nofications, and wait for and respond to remote characteristic commands), repeat...</p> <p>BACKGROUND GORY DETAILS: We have a local system with multiple iOS devices and multiple non-iOS devices that need to inter-communicate by BTLE. The non-iOS devices all use Broadcom BCM20732 Bluetooth LE chip. But hardware is not ready yet, so I'm using iOS devices to emulate the non-iOS, which requires simultaneous central AND peripheral functionality, ie. 1. act as central to periodically interrogate multiple other non-iOS devices in system. 2. act as peripheral to respond to requests for data from iOS user interface devices.</p>
17,030,770
2
1
null
2013-06-07 13:57:04.273 UTC
12
2013-06-10 18:51:23.18 UTC
2013-06-07 20:27:05.36 UTC
null
1,226,963
null
746,100
null
1
15
ios|bluetooth|core-bluetooth
6,474
<p>I got it working. I just started with the Apple "BTLE central peripheral transfer", then first delted the -35 db bug that it has (search for "-35" then delete the if(){ return }), then I combined both the central.m and the peripheral.m into a single UIViewController .m file, added a UISwitch to select one of two service UUID's, and modified the peripheral sender to automatically increment the text field (after init'ing it to ASCII '0').</p> <p>I had two iPad mini's continuously each sending the incrementing number to the other side. It got up to over 900 transfers and then hung. But I've seen the Apple "BTLE c p transfer" always hang after a few minutes, requiring iPad restart to continue. I ended app at both iPad's and cycled power, re-started app, and they got up to 1600 increments, and then hung.</p> <p>To solve the hang, I'll add resource control to prevent central and peripheral managers from connecting at same time, as per Abo's recommendation.</p>
16,885,690
CSS Background Gradient with offset
<p>I applied a gradient as background image to my body. Then I added 255px offset at the top using <code>background-position:0 255px;</code>.</p> <p>It looks quite good except one little issue: of course the gradient does not end at the bottom of the page but 255px underneath.</p> <p>Is there any easy way to let the gradient end at the bottom but start with offset from to?</p> <p><a href="http://jsfiddle.net/julian_weinert/ar6jC/" rel="noreferrer">http://jsfiddle.net/julian_weinert/ar6jC/</a></p>
16,886,425
1
1
null
2013-06-02 18:04:59.78 UTC
2
2018-11-22 03:38:49.953 UTC
null
null
null
null
1,041,122
null
1
15
css|background-image|gradient|background-position
38,067
<p>You can achieve what you want like this: Place your background at <code>0px 0px</code> and define a gradient with more color-stops, having one solid color area at the top and then the actual gradient, like this: </p> <pre class="lang-css prettyprint-override"><code>background-position: 0px 0px; background-image: linear-gradient(to bottom, #FFFFFF 0px, /* Have one solid white area */ #FFFFFF 255px, /* at the top (255px high). */ #C4C7C9 255px, /* Then begin the gradient at 255px */ #FFFFFF 100% /* and end it at 100% (= body's height). */ ); </code></pre> <p>(The sample code works on latest versions of Chrome and FireFox, but adapting it to support all major browsers and versions is straight-forward, applying the same principle.)</p> <p>See, also, this <strong><a href="http://jsfiddle.net/ExpertSystem/yyvT3/" rel="noreferrer">short demo</a></strong>.</p>
16,996,549
How to convert String to date time in Scala?
<p>I am new to Scala and I've learned it for the last few days. I have a doubt about Scala's date converting from string.</p> <p>How to convert String to Date and time using Scala ?</p> <p>Does it work the same way as Java?</p> <p>When I do it that way, I get a compiler error and I can't convert that into Scala because I am new to Scala. And I know that it's not good to convert Java to Scala... </p> <p>Please share your answer.</p>
16,996,898
3
1
null
2013-06-08 05:51:54.617 UTC
14
2020-01-19 05:00:46.87 UTC
2020-01-19 05:00:46.87 UTC
null
2,089,675
null
2,442,466
null
1
49
scala|datetime
116,798
<p>If you are using Java's util.Date then like in java:</p> <pre><code>val format = new java.text.SimpleDateFormat("yyyy-MM-dd") format.parse("2013-07-06") </code></pre> <p>docs for formating - <a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a></p> <p>or if you are using joda's DateTime, then call parse method:</p> <pre><code>DateTime.parse("07-06-2013") </code></pre> <p>docs - <a href="http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html">DateTime</a></p>
20,610,080
Can we read the OS environment variables in Java?
<p>My OS is windows7. I want to read the environment variables in my Java application. I have searched google and many people's answer is to use the method <code>System.getProperty(String name)</code> or <code>System.getenv(String name)</code>. But it doesn't seem to work. Through the method, I can read some variable's value that defined in the JVM. </p> <p>If I set an environment variable named "Config", with value "some config information", how can I get the value in Java?</p>
20,610,185
2
8
null
2013-12-16 11:42:05.887 UTC
4
2019-06-19 14:51:37.443 UTC
2019-06-19 14:51:37.443 UTC
null
5,759,072
null
3,101,697
null
1
52
java|environment-variables
71,645
<p>You should use <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getenv%28%29">System.getenv()</a>, for example:<br></p> <pre><code>import java.util.Map; public class EnvMap { public static void main (String[] args) { Map&lt;String, String&gt; env = System.getenv(); for (String envName : env.keySet()) { System.out.format("%s=%s%n", envName, env.get(envName)); } } } </code></pre> <p>When running from an IDE you can define additional environment variable which will be passed to your Java application. For example in IntelliJ IDEA you can add environment variables in the "Environment variables" field of the <a href="http://www.jetbrains.com/idea/webhelp/run-debug-configuration-application.html">run configuration</a>.<br></p> <p>Notice (as mentioned in the comment by @vikingsteve) that the JVM, like any other Windows executable, system-level changes to the environment variables are only propagated to the process when it is restarted.<br><br> For more information take a look at the "<a href="http://docs.oracle.com/javase/tutorial/essential/environment/env.html">Environment Variables</a>" section of the Java tutorial.<br><br> <code>System.getProperty(String name)</code> is intended for getting Java <a href="http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html">system properties</a> which are not environment variables.</p>
4,255,848
javascript - pass object via post
<p>I have an object that looks like this</p> <p>var obj = { p1 : true, p2 : true, p3 : false }</p> <p>I am looking to try and pass this object as part of a post request.</p> <p>however on the other end (in php) all I get is</p> <blockquote> <p>[object Object] </p> </blockquote> <p>How can I send an object via post?</p> <p>basically what I am trying to do is</p> <p>I have an input that is hidden and is created like so</p> <p><code>&lt;input id="obj" type="hidden" name="obj[]"&gt;</code></p> <p>which is part of a hidden form.</p> <p>when a button is pressed I have</p> <pre><code>$(#obj).val(obj); $('form').submit(); </code></pre> <p><hr /> Please no suggestions to use ajax as I must do it this way as it is to download a dynamically created file.</p>
4,255,879
2
0
null
2010-11-23 12:08:08.537 UTC
4
2015-07-21 19:15:37.467 UTC
null
null
null
null
383,759
null
1
14
javascript|jquery|post|object
49,707
<p>You need to serialize/convert the object to a string before submitting it. You can use <a href="http://api.jquery.com/jQuery.param" rel="noreferrer"><code>jQuery.param()</code></a> for this.</p> <pre><code>$('#obj').val(jQuery.param(obj)); </code></pre>
4,387,288
convert std::wstring to const *char in c++
<p>How can I convert <code>std::wstring</code> to <code>const *char</code> in C++?</p>
4,387,335
2
3
null
2010-12-08 12:14:32.49 UTC
5
2022-04-22 21:27:01.42 UTC
2018-03-27 08:10:09.817 UTC
null
7,670,262
null
396,506
null
1
19
c++
46,394
<p>You can convert a <code>std::wstring</code> to a <code>const wchar_t *</code> using the <code>c_str</code> member function :</p> <pre><code>std::wstring wStr; const wchar_t *str = wStr.c_str(); </code></pre> <p>However, a conversion to a <code>const char *</code> isn't natural : it requires an additional call to <a href="http://en.cppreference.com/w/cpp/string/multibyte/wcstombs" rel="noreferrer"><code>std::wcstombs</code></a>, like for example:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cstdlib&gt; // ... std::wstring wStr; const wchar_t *input = wStr.c_str(); // Count required buffer size (plus one for null-terminator). size_t size = (wcslen(input) + 1) * sizeof(wchar_t); char *buffer = new char[size]; #ifdef __STDC_LIB_EXT1__ // wcstombs_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined size_t convertedSize; std::wcstombs_s(&amp;convertedSize, buffer, size, input, size); #else std::wcstombs(buffer, input, size); #endif /* Use the string stored in "buffer" variable */ // Free allocated memory: delete buffer; </code></pre>
4,210,855
How do you create user stories and tasks in Jira / GreenHopper?
<p>We are using Jira / GreenHopper to run our sprints on a Scrum team. The fact that Jira is a bug tracking tool and GreenHopper is a Scrum-ish add-on is becoming painfully apparent.</p> <p>We want our Product Owner to enter user stories in Jira/GreenHopper and have the team hang technical tasks onto the user stories. How does one do this? Jira/GreenHopper does not seem to have any notion of user stories with tasks. Is this correct or am I missing something?</p> <p>Also, we want the task board in Jira/GreenHopper to track the user stories and tasks as they move from To Do to Done. Again, there seems to be no way to do this. A User Story is Done when all of its tasks are done. Tasks should be able to move from To Do to Done while the User Story is In Progress. Are we correct in thinking that the Jira/GreenHopper task board cannot do this?</p> <p>I am generally interested in any thoughts, books, tutorials, etc. on how to use Jira/GreenHopper to solve the above issues.</p>
4,210,941
2
0
null
2010-11-18 01:33:21.24 UTC
10
2014-07-23 09:54:26.45 UTC
2014-07-23 09:54:26.45 UTC
null
736,079
null
128,807
null
1
21
jira|scrum|jira-agile
39,962
<p>A lot has to do with how you set the tool up. Jira only allows one level of sub-task, so you'll have to make the Task type a sub-task type. That will allow you to associate the sub-task to the Story. When I had Jira/GreenHopper on a project in the past, there were a lot of manual steps that I had to take to get it set up--but it was exactly the way I wanted. The installation is a lot easier now, but you lose some of that insight from doing the configuration yourself. Check out the following guides to get things customized the way you want:</p> <ul> <li><a href="http://confluence.atlassian.com/display/GH/GreenHopper+101" rel="nofollow noreferrer">http://confluence.atlassian.com/display/GH/GreenHopper+101</a></li> <li><a href="http://confluence.atlassian.com/display/GH/Specifying+your+Project+Templates" rel="nofollow noreferrer"><a href="http://confluence.atlassian.com/display/GH/Specifying+your+Project+Templates" rel="nofollow noreferrer">http://confluence.atlassian.com/display/GH/Specifying+your+Project+Templates</a></a></li> <li><a href="http://confluence.atlassian.com/display/GH/Setting+Up+Epics+for+your+Project" rel="nofollow noreferrer">http://confluence.atlassian.com/display/GH/Setting+Up+Epics+for+your+Project</a></li> </ul> <p>I wish I could do better than this. Jira is very configurable, and their online help is usually pretty responsive in my experience.</p>
4,377,541
Servlet mapping: url-pattern for URLs with trailing slash
<p>I have a problem related to the servlet mapping. I have the following in web.xml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;servlet&gt; &lt;servlet-name&gt;HelloWorldServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;test.HelloWorldServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;HelloWorldServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/HelloWorld&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>If I access to <code>http://localhost:&lt;port&gt;/MyApp/HelloWorld</code> the servlet <code>HelloWorldServlet</code> is called.</p> <p>I also want my servelet to respond to <code>http://localhost:&lt;port&gt;/MyApp/HelloWorld/</code>. How can I achieve this effect? I'm developing with NetBeans but it does not allow me to put a pattern ended with <code>/</code>.</p>
4,377,606
2
4
null
2010-12-07 14:15:09.78 UTC
7
2014-05-19 14:48:27.217 UTC
2014-05-19 14:48:27.217 UTC
null
638,471
null
458,093
null
1
27
java|tomcat|servlets|netbeans|web.xml
55,922
<p>After you've added your wildcard on your <code>&lt;url-pattern&gt;</code></p> <pre class="lang-xml prettyprint-override"><code>&lt;url-pattern&gt;/HelloWorld/*&lt;/url-pattern&gt; </code></pre> <p>You can get the extra path associated with the URL by using <a href="http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getPathInfo%28%29"><code>HttpServletRequest.getPathInfo()</code></a>.</p> <p>E.g. </p> <p><code>http://localhost:&lt;port&gt;/MyApp/HelloWorld/one/</code></p> <p>The result will be </p> <pre><code>/one/ </code></pre> <p>From the JavaDoc:</p> <blockquote> <p>Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character.</p> </blockquote>
26,578,313
How do I create a sequence in MySQL?
<p>I'm trying to create a sequence in MySQL (I'm very new to SQL as a whole). I'm using the following code, but it causes an error:</p> <pre><code>CREATE SEQUENCE ORDID INCREMENT BY 1 START WITH 622; </code></pre> <p>ORDID refers to a field in a table I'm using. How do I create the sequence properly?</p> <p>Edit:</p> <p>Allegedly, MySQL doesn't use sequences. I'm now using the following code, but this is causing errors too. How do I fix them?</p> <pre><code>CREATE TABLE ORD ( ORDID NUMERIC(4) NOT NULL AUTO_INCREMENT START WITH 622, //Rest of table code </code></pre> <p>Edit:</p> <p>I think I found a fix. For phpMyAdmin (which I was using) you can use the following code.</p> <pre><code>ALTER TABLE ORD AUTO_INCREMENT = 622; </code></pre> <p>I have no idea why it prefers this, but if anyone else needs help with this then here you go. :)</p>
26,578,578
6
7
null
2014-10-26 21:43:44.963 UTC
13
2022-08-12 00:30:27.447 UTC
2014-10-26 23:29:51.203 UTC
null
4,067,575
null
4,067,575
null
1
38
mysql|sql|sequence
198,720
<p>Check out <a href="http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html">this article</a>. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.</p> <p>In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want. </p> <p>Without additional details on the specific error, it is difficult to provide more specific help.</p> <p><strong>UPDATE</strong></p> <pre><code>CREATE TABLE ORD ( ORDID INT NOT NULL AUTO_INCREMENT, //Rest of table code PRIMARY KEY (ordid) ) AUTO_INCREMENT = 622; </code></pre> <p><a href="http://www.tutorialspoint.com/mysql/mysql-using-sequences.htm">This link</a> is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a <a href="http://dev.mysql.com/doc/refman/5.0/en/create-table.html">table option</a>, and not something that is specified as a column attribute specifically.</p> <p>Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.</p> <pre><code>ALTER TABLE ORD AUTO_INCREMENT = 622; </code></pre> <p><strong>UPDATE 2</strong> Here is a link to a <a href="http://sqlfiddle.com/#!2/f90716/1">working sqlfiddle example</a>, using auto increment.<br> I hope this info helps.</p>
10,228,690
Ray - Octree intersection algorithms
<p>I'm looking for a good ray-octree intersection algorithm, which gives me the leafs the ray passes through in an iterative way. I'm planning on implementing it on the CPU, since I do not want to dive into CUDA just yet :)</p> <p>At the moment, my Voxel raycaster just does 3D DDA (Amanatides/Woo version) on a non-hierarchic array of XxYxZ voxels. You can imagine that this is pretty costly when there's a lot of empty space, as demonstrated in the following picture (brighter red = more work :) ):</p> <p><img src="https://i.stack.imgur.com/icGL9.png" alt="Workload for dumb 3D DDA - red = more work"></p> <p>I've already figured out that there are two kinds of algorithms for this task: <strong>bottom-up</strong>, which works from the leafs back upwards, and <strong>top-down</strong>, which is basicly depth-first search.</p> <p>I've already found Revelles' algorithm from 2000, called <em><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.29.987" rel="noreferrer">An efficient parametric algorithm for octree traversal</a></em>, which looks interesting, but is quite old. This is a top-down algorithm.</p> <p>The most popular bottom-up approach seems to be <em>K. Sung, A DDA Octree Traversal Algorithm for Ray Tracing, Eurographics'91, North Holland-Elsevier, ISBN 0444 89096 3, p. 73-85.</em> Problem is that most DDA Octree traversal algorithms expect the octree to be of equal depth, which I do not want - empty subtrees should just be a null pointer or something similar.</p> <p>In the more recent literature about Sparse Voxel Octrees I've managed to read through, (most notably <a href="http://code.google.com/p/efficient-sparse-voxel-octrees/" rel="noreferrer">Laine's work on SVO's</a>, they all seem to be based on some kind of GPU-implemented version of DDA (Amanatides/Woo style).</p> <p>Now, here's my question: does anybody have any experience implementing a basic, no-frills ray-octree intersection algorithm? What would you recommend?</p>
10,515,457
2
4
null
2012-04-19 13:02:42.08 UTC
18
2021-01-05 11:20:02.737 UTC
2012-05-27 20:21:47.597 UTC
null
556,997
null
556,997
null
1
23
algorithm|graphics|traversal|voxel|octree
16,588
<p>For the record, this is my implementation of the Revelles paper I ended up using:</p> <pre><code>#include &quot;octree_traversal.h&quot; using namespace std; unsigned char a; // because an unsigned char is 8 bits int first_node(double tx0, double ty0, double tz0, double txm, double tym, double tzm){ unsigned char answer = 0; // initialize to 00000000 // select the entry plane and set bits if(tx0 &gt; ty0){ if(tx0 &gt; tz0){ // PLANE YZ if(tym &lt; tx0) answer|=2; // set bit at position 1 if(tzm &lt; tx0) answer|=1; // set bit at position 0 return (int) answer; } } else { if(ty0 &gt; tz0){ // PLANE XZ if(txm &lt; ty0) answer|=4; // set bit at position 2 if(tzm &lt; ty0) answer|=1; // set bit at position 0 return (int) answer; } } // PLANE XY if(txm &lt; tz0) answer|=4; // set bit at position 2 if(tym &lt; tz0) answer|=2; // set bit at position 1 return (int) answer; } int new_node(double txm, int x, double tym, int y, double tzm, int z){ if(txm &lt; tym){ if(txm &lt; tzm){return x;} // YZ plane } else{ if(tym &lt; tzm){return y;} // XZ plane } return z; // XY plane; } void proc_subtree (double tx0, double ty0, double tz0, double tx1, double ty1, double tz1, Node* node){ float txm, tym, tzm; int currNode; if(tx1 &lt; 0 || ty1 &lt; 0 || tz1 &lt; 0) return; if(node-&gt;terminal){ cout &lt;&lt; &quot;Reached leaf node &quot; &lt;&lt; node-&gt;debug_ID &lt;&lt; endl; return; } else{ cout &lt;&lt; &quot;Reached node &quot; &lt;&lt; node-&gt;debug_ID &lt;&lt; endl;} txm = 0.5*(tx0 + tx1); tym = 0.5*(ty0 + ty1); tzm = 0.5*(tz0 + tz1); currNode = first_node(tx0,ty0,tz0,txm,tym,tzm); do{ switch (currNode) { case 0: { proc_subtree(tx0,ty0,tz0,txm,tym,tzm,node-&gt;children[a]); currNode = new_node(txm,4,tym,2,tzm,1); break;} case 1: { proc_subtree(tx0,ty0,tzm,txm,tym,tz1,node-&gt;children[1^a]); currNode = new_node(txm,5,tym,3,tz1,8); break;} case 2: { proc_subtree(tx0,tym,tz0,txm,ty1,tzm,node-&gt;children[2^a]); currNode = new_node(txm,6,ty1,8,tzm,3); break;} case 3: { proc_subtree(tx0,tym,tzm,txm,ty1,tz1,node-&gt;children[3^a]); currNode = new_node(txm,7,ty1,8,tz1,8); break;} case 4: { proc_subtree(txm,ty0,tz0,tx1,tym,tzm,node-&gt;children[4^a]); currNode = new_node(tx1,8,tym,6,tzm,5); break;} case 5: { proc_subtree(txm,ty0,tzm,tx1,tym,tz1,node-&gt;children[5^a]); currNode = new_node(tx1,8,tym,7,tz1,8); break;} case 6: { proc_subtree(txm,tym,tz0,tx1,ty1,tzm,node-&gt;children[6^a]); currNode = new_node(tx1,8,ty1,8,tzm,7); break;} case 7: { proc_subtree(txm,tym,tzm,tx1,ty1,tz1,node-&gt;children[7^a]); currNode = 8; break;} } } while (currNode&lt;8); } void ray_octree_traversal(Octree* octree, Ray ray){ a = 0; // fixes for rays with negative direction if(ray.direction[0] &lt; 0){ ray.origin[0] = octree-&gt;center[0] * 2 - ray.origin[0];//camera origin fix ray.direction[0] = - ray.direction[0]; a |= 4 ; //bitwise OR (latest bits are XYZ) } if(ray.direction[1] &lt; 0){ ray.origin[1] = octree-&gt;center[1] * 2 - ray.origin[1]; ray.direction[1] = - ray.direction[1]; a |= 2 ; } if(ray.direction[2] &lt; 0){ ray.origin[2] = octree-&gt;center[2] * 2 - ray.origin[2]; ray.direction[2] = - ray.direction[2]; a |= 1 ; } double divx = 1 / ray.direction[0]; // IEEE stability fix double divy = 1 / ray.direction[1]; double divz = 1 / ray.direction[2]; double tx0 = (octree-&gt;min[0] - ray.origin[0]) * divx; double tx1 = (octree-&gt;max[0] - ray.origin[0]) * divx; double ty0 = (octree-&gt;min[1] - ray.origin[1]) * divy; double ty1 = (octree-&gt;max[1] - ray.origin[1]) * divy; double tz0 = (octree-&gt;min[2] - ray.origin[2]) * divz; double tz1 = (octree-&gt;max[2] - ray.origin[2]) * divz; if( max(max(tx0,ty0),tz0) &lt; min(min(tx1,ty1),tz1) ){ proc_subtree(tx0,ty0,tz0,tx1,ty1,tz1,octree-&gt;root); } } </code></pre>
9,811,828
Common HTTPclient and proxy
<p>I am using apache's common httpclient library. Is it possible to make HTTP request over proxy? More specific, I need to use proxy list for multithreaded POST requests (right now I am testing with single threaded GET requests).</p> <p>I tried to use:</p> <pre><code> httpclient.getHostConfiguration().setProxy("67.177.104.230", 58720); </code></pre> <p>I get errors with that code:</p> <pre><code>21.03.2012. 20:49:17 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect 21.03.2012. 20:49:17 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry INFO: Retrying request 21.03.2012. 20:49:19 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect 21.03.2012. 20:49:19 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry INFO: Retrying request 21.03.2012. 20:49:21 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect 21.03.2012. 20:49:21 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry INFO: Retrying request org.apache.commons.httpclient.ProtocolException: The server xxxxx failed to respond with a valid HTTP response at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1846) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1590) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:995) at org.apache.commons.httpclient.ConnectMethod.execute(ConnectMethod.java:144) at org.apache.commons.httpclient.HttpMethodDirector.executeConnect(HttpMethodDirector.java:495) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:390) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324) at test.main(test.java:42) </code></pre> <p>When I remove that line, everything runs fine as expected.</p>
9,811,969
7
7
null
2012-03-21 19:51:34.373 UTC
4
2018-09-17 08:46:02.15 UTC
null
null
null
null
1,248,294
null
1
24
java|post|proxy|get|httpclient
118,451
<p>For httpclient 4.1.x you can set the proxy like this (taken from <a href="http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientExecuteProxy.java" rel="noreferrer">this example</a>):</p> <pre><code> HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpHost target = new HttpHost("issues.apache.org", 443, "https"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via " + proxy); HttpResponse rsp = httpclient.execute(target, req); ... } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } </code></pre>
10,167,604
How can I add a two column unique id to the mongodb in a meteor app?
<p>I am trying to create a two column unique index on the underlying mongodb in a meteor app and having trouble. I can't find anything in the meteor docs. I have tried from the chrome console. I have tried from term and even tried to point mongod at the /db/ dir inside .meteor . I have tried </p> <p><code>Collection.ensureIndex({first_id: 1, another_id: 1}, {unique: true});</code> variations.</p> <p>I want to be able to prevent duplicate entries on a meteor app mongo collection.</p> <p>Wondering if anyone has figured this out?</p> <p>I answered my own question, what a noob.</p> <p>I figured it out. </p> <ol> <li><p>Start meteor server</p></li> <li><p>Open 2nd terminal and type <code>meteor mongo</code></p></li> </ol> <p>Then create your index...for example I did these for records of thumbsup and thumbsdown type system.</p> <pre><code>db.thumbsup.ensureIndex({item_id: 1, user_id: 1}, {unique: true}) db.thumbsdown.ensureIndex({item_id: 1, user_id: 1}, {unique: true}) </code></pre> <p>Now, just gotta figure out a bootstrap install setup that creates these when pushed to prod instead of manually.</p>
10,168,299
4
2
null
2012-04-16 01:03:39.53 UTC
12
2015-08-17 10:47:53.05 UTC
2012-04-16 02:50:28.817 UTC
null
2,044,362
null
2,044,362
null
1
27
javascript|mongodb|meteor
8,748
<p>According to the <a href="http://docs.meteor.com/#collections" rel="noreferrer">docs</a> "Minimongo currently doesn't have indexes. This will come soon." And looking at the methods available on a Collection, there's no <code>ensureIndex</code>.</p> <p>You can run <code>meteor mongo</code> for a mongo shell and enable the indexes server-side, but the Collection object still won't know about them. So the app will let you add multiple instances to the Collection cache, while on the server-side the additional inserts will fail silently (errors get written to the output). When you do a hard page refresh, the app will re-sync with server</p> <p>So your best bet for now is probably to do something like:</p> <pre><code>var count = MyCollection.find({first_id: 'foo', another_id: 'bar'}).count() if (count === 0) MyCollection.insert({first_id: 'foo', another_id: 'bar'}); </code></pre> <p>Which is obviously not ideal, but works ok. You could also enable indexing in mongodb on the server, so even in the case of a race condition you won't actually get duplicate records.</p>
10,191,048
socket.io.js not found
<p>For some reason my node server cannot serve the route <code>/socket.io/socket.io.js</code>, I always get a 404 error.<br> I tried compiling different node versions (<em>current is 0.6.13 which also runs on server, where it actually works</em>).<br> From the app.js I get <code>info: socket.io started</code> and no error when trying to call the socket.io.js.</p> <p>I try it from localhost and port 8000 and I use the express framework</p> <p>This is the code from app.js:</p> <pre><code>var express = require('express') , app = require('express').createServer() , io = require('socket.io').listen(app, { log: true }); app.listen(8000); app.configure(function() { app.use(express.static(__dirname + '/public')); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); io.sockets.on('connection', function (socket) { // all other stuff here </code></pre>
10,192,084
6
1
null
2012-04-17 12:15:03.753 UTC
18
2022-03-06 01:19:46.15 UTC
2012-04-17 12:24:47.243 UTC
null
612,202
null
612,202
null
1
45
javascript|node.js|express|socket.io
39,196
<p>Please check your Express version. Express recently is updated to 3.0alpha which API was changed. If 3.0 you can change your code to something likes this:</p> <pre><code>var express = require('express') , http = require('http'); var app = express(); var server = http.createServer(app); var io = require('socket.io').listen(server); ... server.listen(8000); </code></pre> <p>Same issue with connect: <a href="https://github.com/senchalabs/connect/issues/500#issuecomment-4620773" rel="noreferrer">https://github.com/senchalabs/connect/issues/500#issuecomment-4620773</a></p>
10,086,427
What is the exact difference between currentTarget property and target property in JavaScript
<p>Can anyone please tell me the exact difference between <code>currentTarget</code> and <code>target</code> property in JavaScript events with example and which property is used in which scenario?</p>
10,086,501
10
1
null
2012-04-10 09:45:52.04 UTC
121
2022-08-24 08:27:23.153 UTC
2021-05-02 23:53:16.703 UTC
null
8,888,320
null
1,302,468
null
1
572
javascript
156,148
<p>Events <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture" rel="noreferrer">bubble</a> by default. So the difference between the two is:</p> <ul> <li><code>target</code> is the element that triggered the event (e.g., the user clicked on)</li> <li><code>currentTarget</code> is the element that the event listener is attached to.</li> </ul>
9,973,056
cURL: How to display progress information while uploading?
<p>I use the following syntax to upload files:</p> <pre><code>curl --form upload=@localfilename --form press=OK [URL] </code></pre> <p>How to display the progress? Thx.</p>
12,046,822
5
1
null
2012-04-02 08:25:07.203 UTC
16
2022-05-07 14:37:44.887 UTC
null
null
null
null
544,806
null
1
70
curl
102,210
<p>This is what I use in one of my build scripts:</p> <pre><code>curl "${UPLOAD_URL}" \ --progress-bar \ --verbose \ -F build="${BUILD}" \ -F version="${VERSION}" \ -F ipa="@${IPA};type=application/octet-stream" \ -F assets="@-;type=text/xml" \ -F replace="${REPLACE}" \ -A "${CURL_FAKE_USER_AGENT}" \ &lt;&lt;&lt; "${ASSETS}" \ | tee -a "${LOG_FILE}" ; test ${PIPESTATUS[0]} -eq 0 </code></pre> <p>The <code>-F</code> and <code>-A</code> options will probably not be of interest to you, but the helpful parts are:</p> <pre><code>curl "${UPLOAD_URL}" --progress-bar </code></pre> <p>which tells <code>curl</code> to show a progress bar (instead of the default 'progress meter') during the upload, and:</p> <pre><code> | tee -a "${LOG_FILE}" ; test ${PIPESTATUS[0]} -eq 0 </code></pre> <p>which appends the output of the command to a log file and also echo's it to <code>stdout</code>. The <code>test ${PIPESTATUS[0]} -eq 0</code> part makes it so that the exit status of this line (which is in a bash script) is the same exit code that the <code>curl</code> command returned and not the exit status of the <code>tee</code> command (necessary because <code>tee</code> is actually the last command being executed in this line, not <code>curl</code>).</p> <hr> <p>From <code>man curl</code>:</p> <pre><code>PROGRESS METER curl normally displays a progress meter during operations, indicating the amount of transferred data, transfer speeds and estimated time left, etc. curl displays this data to the terminal by default, so if you invoke curl to do an operation and it is about to write data to the terminal, it disables the progress meter as otherwise it would mess up the output mixing progress meter and response data. If you want a progress meter for HTTP POST or PUT requests, you need to redirect the response output to a file, using shell redirect (&gt;), -o [file] or similar. It is not the same case for FTP upload as that operation does not spit out any response data to the terminal. If you prefer a progress "bar" instead of the regular meter, -# is your friend. OPTIONS -#, --progress-bar Make curl display progress as a simple progress bar instead of the standard, more informational, meter. </code></pre>
9,950,144
Access lapply index names inside FUN
<p>Is there a way to get the list index name in my lapply() function?</p> <pre><code>n = names(mylist) lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" }) </code></pre> <p>I asked <a href="https://stackoverflow.com/questions/9469504/access-and-preserve-list-names-in-lapply-function">before</a> if it's possible to preserve the index names in the lapply() <em>returned</em> list, but I still don't know if there is an easy way to fetch each element name inside the custom function. I would like to avoid to call lapply on the names themselves, I'd rather get the name in the function parameters.</p>
9,950,217
12
1
null
2012-03-30 20:40:07.11 UTC
69
2019-11-15 10:43:20.15 UTC
2017-05-23 12:02:46.81 UTC
null
-1
null
382,271
null
1
204
r|lapply|names|indices
80,852
<p>Unfortunately, <code>lapply</code> only gives you the elements of the vector you pass it. The usual work-around is to pass it the names or indices of the vector instead of the vector itself.</p> <p>But note that you can always pass in extra arguments to the function, so the following works:</p> <pre><code>x &lt;- list(a=11,b=12,c=13) # Changed to list to address concerns in commments lapply(seq_along(x), function(y, n, i) { paste(n[[i]], y[[i]]) }, y=x, n=names(x)) </code></pre> <p>Here I use <code>lapply</code> over the indices of <code>x</code>, but also pass in <code>x</code> and the names of <code>x</code>. As you can see, the order of the function arguments can be anything - <code>lapply</code> will pass in the "element" (here the index) to the first argument <em>not</em> specified among the extra ones. In this case, I specify <code>y</code> and <code>n</code>, so there's only <code>i</code> left...</p> <p>Which produces the following:</p> <pre><code>[[1]] [1] "a 11" [[2]] [1] "b 12" [[3]] [1] "c 13" </code></pre> <p><strong>UPDATE</strong> Simpler example, same result:</p> <pre><code>lapply(seq_along(x), function(i) paste(names(x)[[i]], x[[i]])) </code></pre> <p>Here the function uses "global" variable <code>x</code> and extracts the names in each call.</p>
63,196,352
How can std::vector access elements with huge gaps between them?
<p>Having this code:</p> <pre><code>template &lt;class IIt, class OIt&gt; OIt copy2(IIt begin, IIt end, OIt dest) { while (begin != end) { //make gap between element addresses for (int i = 0; i &lt; 99999999; i++) { dest++; } *dest++ = *begin++; } return dest; } int main(int argc, char** argv) { vector&lt;int&gt; vec({ 1, 2, 3 }); vector&lt;int&gt; vec2; copy2(vec.begin(), vec.end(), back_inserter(vec2)); for (int i : vec2) { cout &lt;&lt; i &lt;&lt; endl; } } </code></pre> <p>Which takes quite a long to compile, but will finally do with the proper output</p> <pre><code>1 2 3 </code></pre> <p>The problem is (<em>without knowing the inner implementation of <code>std::vector</code>, is it <code>c-style</code> array? or more complex structure?</em>), how can it properly <em>find</em> those elements in the <code>for(int i:vec2)</code>, when the address (pointers) of those elements are <em>not</em> sequential? (i.e. <em>because of the shifting of the iterator/pointer by <code>99999999</code></em>).</p> <p>I thought there was a requirement for <code>OutputIterator</code> to have that property, that only one-access, one-shift could be performed on it. But when you shift(add) it more than once between accessing them, then there is a gap, which is quite huge in my case. So how does it compile?</p>
63,196,401
3
10
null
2020-07-31 17:19:25.16 UTC
3
2020-07-31 22:00:52.867 UTC
2020-07-31 22:00:52.867 UTC
null
9,609,840
null
13,770,014
null
1
40
c++|algorithm|templates|iterator|stdvector
2,175
<p>You've been fooled.</p> <p>The iterator returned by <code>std::back_inserter</code> has <a href="https://en.cppreference.com/w/cpp/iterator/back_insert_iterator/operator%2B%2B" rel="noreferrer"><code>it++</code> as a no-op</a>. So those 'gaps' you are creating? Yeah that's all doing nothing.</p>
7,924,173
Create Android app release mode
<p>I want to create my Android app in release mode. I did the suggested Export from Eclipse. Android tools -> Export Unassigned ( then signed it aligned it etc ) I though the export would give me release mode app. I checked on disk and the .apk is just the same size as the one I get when I normally compile in Eclipse.<br> Further I installed it in the emulator by >adb install myapp.apk then I tried to attach to the application in the Eclipse debugger and sure enough it hit my breakpoint. So I'm convinced I have indeed a debug version. The question is how can I create release mode version of my application from Eclipse before signing and submitting to the market place ?</p> <h2>Edit</h2> <p>If I log it the debuggable flag is off when exported, as well when running from Eclipse. Unless I explicitly set it to true in the Manifest application section. It seems the debug / release mode is just a flag on / off. Doesn't do anything more than that, I can set breakpoints and debug both versions. The resulting .apk is the same size. </p> <pre><code>cxLog.e( "TOKEN", " Debuggable=" + (( context.getPackageManager().getApplicationInfo( comp.getPackageName(), 0 ).flags &amp;= ApplicationInfo.FLAG_DEBUGGABLE ) != 0 ) ); </code></pre> <blockquote> <p>10-28 14:46:12.479: ERROR/TOKEN(1856): Debuggable=false</p> </blockquote>
7,924,535
3
1
null
2011-10-28 01:13:44.083 UTC
3
2017-11-30 15:39:01.163 UTC
2011-10-28 21:19:59.43 UTC
null
245,189
null
245,189
null
1
18
android|release
40,631
<blockquote> <p>The question is how can I create release mode version of my application from Eclipse</p> </blockquote> <p>Check this out : <a href="http://developer.android.com/guide/publishing/app-signing.html#releasecompile" rel="noreferrer">Compile the application in the release mode</a></p> <blockquote> <p>Android Tools &gt; Export Unsigned Application Package</p> </blockquote> <hr /> <blockquote> <p><a href="http://developer.android.com/sdk/tools-notes.html" rel="noreferrer">Support for a true debug build</a>. Developers no longer need to add the android:debuggable attribute to the tag in the manifest — the build tools add the attribute automatically. In Eclipse/ADT, all incremental builds are assumed to be debug builds, so the tools insert android:debuggable=&quot;true&quot;. When exporting a signed release build, the tools do not add the attribute. In Ant, a ant debug command automatically inserts the android:debuggable=&quot;true&quot; attribute, while ant release does not. If android:debuggable=&quot;true&quot; is manually set, then ant release will actually do a debug build, rather than a release build.</p> </blockquote>
8,355,024
AutoMapper mapping properties with private setters
<p>Is it possible to assign properties with private setters using AutoMapper?</p>
8,359,993
3
4
null
2011-12-02 10:37:31.637 UTC
5
2019-08-16 18:45:36.73 UTC
null
null
null
null
680,038
null
1
28
automapper|private|setter
23,030
<p>If you set the value for this properties in the constructor like this</p> <pre><code>public class RestrictedName { public RestrictedName(string name) { Name = name; } public string Name { get; private set; } } public class OpenName { public string Name { get; set; } } </code></pre> <p>then you can use ConstructUsing like this</p> <pre><code>Mapper.CreateMap&lt;OpenName, RestrictedName&gt;() .ConstructUsing(s =&gt; new RestrictedName(s.Name)); </code></pre> <p>which works with this code</p> <pre><code>var openName = new OpenName {Name = "a"}; var restrictedName = Mapper.Map&lt;OpenName, RestrictedName&gt;(openName); Assert.AreEqual(openName.Name, restrictedName.Name); </code></pre>
11,610,781
SlickGrid: Simple example of using DataView rather than raw data?
<p>I'm working with SlickGrid, binding data directly to the grid from an Ajax call. It's working well at the moment, the grid updates dynamically and is sortable, and I'm using a custom formatter for one column: </p> <pre><code>var grid; var columns = [{ id: "time", name: "Date", field: "time" }, { id: "rating", name: "Rating", formatter: starFormatter // custom formatter } ]; var options = { enableColumnReorder: false, multiColumnSort: true }; // When user clicks button, fetch data via Ajax, and bind it to the grid. $('#mybutton').click(function() { $.getJSON(my_url, function(data) { grid = new Slick.Grid("#myGrid", data, columns, options); }); }); </code></pre> <p>However, I want to apply a class to rows in the grid based on the value of the data, so it appears I <a href="https://stackoverflow.com/questions/8930167/how-do-i-add-a-css-class-to-particular-rows-in-slickgrid">need to use a DataView instead</a>. The <a href="http://mleibman.github.com/SlickGrid/examples/example4-model.html" rel="nofollow noreferrer">DataView example on the SlickGrid wiki</a> is rather complicated, and has all kinds of extra methods. </p> <p>Please could someone explain how I simply convert <code>data</code> to a <code>DataView</code> - both initially and on Ajax reload - while leaving the grid sortable, and continuing to use my custom formatter? (I don't need to know how to apply the class, literally just how to use a DataView.)</p> <p>I'm hoping it's one or two extra lines inside the <code>.getJSON</code> call, but I fear it may be more complicated than that. </p>
11,611,477
3
0
null
2012-07-23 10:30:36.03 UTC
10
2014-09-11 07:31:47.907 UTC
2017-05-23 11:53:25.143 UTC
null
-1
null
1,073,252
null
1
12
javascript|jquery|datagrid|slickgrid
28,260
<p>The key pieces are to initialise the grid with a dataview as data source, wire up events so that the grid responds to changes in the dataview and finally feed the data to the dataview. It should look something like this:</p> <pre><code>dataView = new Slick.Data.DataView(); grid = new Slick.Grid("#myGrid", dataView, columns, options); // wire up model events to drive the grid dataView.onRowCountChanged.subscribe(function (e, args) { grid.updateRowCount(); grid.render(); }); dataView.onRowsChanged.subscribe(function (e, args) { grid.invalidateRows(args.rows); grid.render(); }); // When user clicks button, fetch data via Ajax, and bind it to the dataview. $('#mybutton').click(function() { $.getJSON(my_url, function(data) { dataView.beginUpdate(); dataView.setItems(data); dataView.endUpdate(); }); }); </code></pre> <p>Note that you don't need to create a new grid every time, just bind the data to the dataview.</p> <p>If you want to implement sorting you'll also need to tell the dataview to sort when the grid receives a sort event:</p> <pre><code>grid.onSort.subscribe(function (e, args) { sortcol = args.sortCol.field; // Maybe args.sortcol.field ??? dataView.sort(comparer, args.sortAsc); }); function comparer(a, b) { var x = a[sortcol], y = b[sortcol]; return (x == y ? 0 : (x &gt; y ? 1 : -1)); } </code></pre> <p>(This basic sorting is taken from the SlickGrid examples but you may want to implement something home-grown; without using the global variable for example)</p>
11,989,465
sql how to cast a select query
<p>Is it possible to apply the cast function to a select statement? If yes, how? I have a query that returns a number which I have to use a string to get other info's from another table.</p>
11,989,524
5
3
null
2012-08-16 14:32:24.38 UTC
6
2014-10-31 13:23:04.52 UTC
2012-08-16 15:16:45.157 UTC
null
1,018,437
null
1,018,437
null
1
23
sql|sql-server-2008
124,072
<p>You just <code>CAST()</code> this way</p> <pre><code>SELECT cast(yourNumber as varchar(10)) FROM yourTable </code></pre> <p>Then if you want to <code>JOIN</code> based on it, you can use:</p> <pre><code>SELECT * FROM yourTable t1 INNER JOIN yourOtherTable t2 on cast(t1.yourNumber as varchar(10)) = t2.yourString </code></pre>
11,674,824
How to use RequireJS build profile + r.js in a multi-page project
<p>I am currently learning RequireJS fundamentals and have some questions regarding a build profile, main files, and use of RequireJS with multi-page projects.</p> <p>My project's directory structure is as follows:</p> <pre> httpdocs_siteroot/ app/ php files... media/ css/ css files... js/ libs/ jquery.js require.js mustache.js mains/ main.page1.js main.page2.js main.page3.js plugins/ jquery.plugin1.js jquery.plugin2.js jquery.plugin3.js utils/ util1.js util2.js images/ </pre> <p>Since this project is not a single-page app, I have a separate main file for each page (although some pages use the same main file). </p> <p>My questions are: </p> <ol> <li><p>Is RequireJS even practical for projects that are not single-page?</p></li> <li><p>Without using the optimizer, each of my main files start with essentially the same config options:</p> <pre><code>requirejs.config({ paths: { 'jquery': 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min' }, baseUrl: '/media/js/', // etc... }); require(['deps'], function() { /* main code */ }); </code></pre> <p>Is there a way to avoid this? Like having each main file include the same build profile without having to actually build it?</p></li> <li><p>Should r.js go in <code>httpdocs_siteroot</code>'s parent directory?</p></li> <li><p>Is there something glaringly wrong with my app dir structure or my use of RequireJS?</p></li> </ol>
11,730,147
2
3
null
2012-07-26 17:34:06.69 UTC
36
2013-08-22 06:15:17.127 UTC
2013-08-22 06:15:17.127 UTC
null
211,563
null
332,622
null
1
34
javascript|requirejs
14,095
<p>First of all, this is not a question with a unique solution. I'll explain the way I use RequireJS that works for me, and may work for you :)</p> <p>Second, English is not my mother language. Corrections and tips about the language will be very appreciated. Feel free, guys :)</p> <blockquote> <p>1) Is require js even practical for projects that are not single-page?</p> </blockquote> <p>It depends. If your project does not have shared code between pages for example, RequireJS help will be modest. The main idea of RequireJS is modularize the application into chunks of reusable code. If your application uses only page-specific code, then using RequireJS may not be a good idea.</p> <blockquote> <p>2) Without using the optimizer, each of my main files start with essentially the same config options. Is there a way to avoid this? Like having each main file include the same build profile without having to actually build it?</p> </blockquote> <p>The only way I see is making the configuration on the main file, or create a module that will configure RequireJS and then use that module as the first dependency on main.js. But this can be tricky. I do not use many main.js files in my applications; I use only one that acts as a loader (see below).</p> <blockquote> <p>3) Should r.js go in httpdocs_siteroot's parent directory?</p> </blockquote> <p>Not necessarily. You can put it inside the /media directory, since all your client stuff is there.</p> <blockquote> <p>4) Is there something glaringly wrong with my app dir structure or my use of requirejs?</p> </blockquote> <p>I would not say that. On the other hand, the structure is perhaps a bit too fragmented. For example, you can put all '3rd party stuff' inside a /vendor directory. But this is just sugar; your structure will work well and seems right. I think the major problem is the requirejs.config() call in multiple main files.</p> <p>I had the same problems you are having now and I ended up with the following solution:</p> <p>1) Do not wrap the non-AMD-compliant files with a define. Although it works, you can achieve the same results using the "shim" property in requirejs.config (see below).</p> <p>2) In a multi-page application, the solution for me is not to require the page-specific modules from the optimized main.js file. Instead, I require all the shared code (3rd party and my own) from the main file, leaving the page-specific code to load on each page. The main file ends up only being a loader that starts the page-specific code after loading all shared/lib files.</p> <p><strong>This is the boilerplate I use to build a multi-page application with requirejs</strong></p> <p>Directory structure:</p> <p>/src - I put all the client stuff inside a src directory, so I can run the optimizer inside this directory (this is your media directory).</p> <p>/src/vendor - Here I place all 3rd party files and plugins, including require.js.</p> <p>/src/lib - Here I place all my own code that is shared by the entire application or by some pages. In other words, modules that are not page-specific.</p> <p>/src/page-module-xx - And then, I create one directory for each page that I have. This is not a strict rule.</p> <p><strong>/src/main.js</strong>: This is the only main file for the entire application. It will:</p> <ul> <li>configure RequireJS, including shims</li> <li>load shared libraries/modules</li> <li>load the page-specific main module</li> </ul> <p>This is an example of a requirejs.config call:</p> <pre><code>requirejs.config({ baseUrl: ".", paths: { // libraries path "json": "vendor/json2", "jquery": "vendor/jquery", "somejqueryplugion": "vendor/jquery.somejqueryplufin", "hogan": "vendor/hogan", // require plugins "templ": "vendor/require.hogan", "text": "vendor/require.text" }, // The shim section allows you to specify // dependencies between non AMD compliant files. // For example, "somejqueryplugin" must be loaded after "jquery". // The 'exports' attribute tells RequireJS what global variable // it must assign as the module value for each shim. // For example: By using the configutation below for jquery, // when you request the "jquery" module, RequireJS will // give the value of global "$" (this value will be cached, so it is // ok to modify/delete the global '$' after all plugins are loaded. shim: { "jquery": { exports: "$" }, "util": { exports: "_" }, "json": { exports: "JSON" }, "somejqueryplugin": { exports: "$", deps: ["jquery"] } } }); </code></pre> <p>And then, after configuration we can make the first require() request for all those libraries and after that do the request for our "page main" module.</p> <pre><code>//libs require([ "templ", //require plugins "text", "json", //3rd libraries "jquery", "hogan", "lib/util" // app lib modules ], function () { var $ = require("jquery"), // the start module is defined on the same script tag of data-main. // example: &lt;script data-main="main.js" data-start="pagemodule/main" src="vendor/require.js"/&gt; startModuleName = $("script[data-main][data-start]").attr("data-start"); if (startModuleName) { require([startModuleName], function (startModule) { $(function(){ var fn = $.isFunction(startModule) ? startModule : startModule.init; if (fn) { fn(); } }); }); } }); </code></pre> <p>As you can see in the body of the require() above, we're expecting another attribute on the require.js script tag. The <strong>data-start</strong> attribute will hold the name of the module for the current page.</p> <p>Thus, on the HTML page we must add this extra attribute:</p> <pre><code>&lt;script data-main="main" data-start="pagemodule/main" src="vendor/require.js"&gt;&lt;/script&gt; </code></pre> <p>By doing this, we will end up with an optimized main.js that contains all the files in "/vendor" and "/lib" directories (the shared resources), but not the page-specific scripts/modules, as they are not hard-coded in the main.js as dependencies. The page-specific modules will be loaded separately on each page of the application.</p> <p>The "page main" module should return a <code>function()</code> that will be executed by the "app main" above. </p> <pre><code>define(function(require, exports, module) { var util = require("lib/util"); return function() { console.log("initializing page xyz module"); }; }); </code></pre> <p><strong>EDIT</strong> </p> <p>Here is example of how you can use build profile to optimize the page-specific modules that have more than one file.</p> <p>For example, let's say we have the following page module:</p> <p>/page1/main.js</p> <p>/page1/dep1.js</p> <p>/page1/dep2.js</p> <p>If we do not optimize this module, then the browser will make 3 requests, one for each script. We can avoid this by instructing r.js to create a package and include these 3 files.</p> <p>On the "modules" attribute of the build profile:</p> <pre><code>... "modules": [ { name: "main" // this is our main file }, { // create a module for page1/main and include in it // all its dependencies (dep1, dep2...) name: "page1/main", // excluding any dependency that is already included on main module // i.e. all our shared stuff, like jquery and plugins should not // be included in this module again. exclude: ["main"] } ] </code></pre> <p>By doing this, we create another per-page main file with all its dependencies. But, since we already have a main file that will load all our shared stuff, we don't need to include them again in page1/main module. The config is a little verbose since you have to do this for each page module where you have more than one script file.</p> <p>I uploaded the code of the boilerplate in GitHub: <a href="https://github.com/mdezem/MultiPageAppBoilerplate">https://github.com/mdezem/MultiPageAppBoilerplate</a>. It is a working boilerplate, just install node and r.js module for node and execute build.cmd (inside the /build directory, otherwise it will fail because it uses relative paths)</p> <p>I hope I have been clear. Let me know if something sounds strange ;)</p> <p>Regards!</p>
11,740,256
Refactor a PL/pgSQL function to return the output of various SELECT queries
<p>I wrote a function that outputs a PostgreSQL <code>SELECT</code> query well formed in text form. Now I don't want to output a text anymore, but actually run the generated <code>SELECT</code> statement against the database and return the result - just like the query itself would.</p> <h3>What I have so far:</h3> <pre><code>CREATE OR REPLACE FUNCTION data_of(integer) RETURNS text AS $BODY$ DECLARE sensors varchar(100); -- holds list of column names type varchar(100); -- holds name of table result text; -- holds SQL query -- declare more variables BEGIN -- do some crazy stuff result := 'SELECT\r\nDatahora,' || sensors || '\r\n\r\nFROM\r\n' || type || '\r\n\r\nWHERE\r\id=' || $1 ||'\r\n\r\nORDER BY Datahora;'; RETURN result; END; $BODY$ LANGUAGE 'plpgsql' VOLATILE; ALTER FUNCTION data_of(integer) OWNER TO postgres; </code></pre> <p><code>sensors</code> holds the list of column names for the table <code>type</code>. Those are declared and filled in the course of the function. Eventually, they hold values like:</p> <ul> <li><p><code>sensors</code>: <code>'column1, column2, column3'</code><br /> Except for <code>Datahora</code> (<code>timestamp</code>) all columns are of type <code>double precision</code>.</p> </li> <li><p><code>type</code> :<code>'myTable'</code><br /> Can be the name of one of four tables. Each has different columns, except for the common column <code>Datahora</code>.</p> </li> </ul> <p><a href="http://pastebin.com/A2tZ9K3Q" rel="noreferrer"><strong>Definition of the underlying tables</strong>.</a></p> <p>The variable <code>sensors</code> will hold <em>all</em> columns displayed here for the corresponding table in <code>type</code>. For example: If <code>type</code> is <code>pcdmet</code> then <code>sensors</code> will be <code>'datahora,dirvento,precipitacao,pressaoatm,radsolacum,tempar,umidrel,velvento'</code></p> <p>The variables are used to build a <code>SELECT</code> statement that is stored in <code>result</code>. Like:</p> <pre><code>SELECT Datahora, column1, column2, column3 FROM myTable WHERE id=20 ORDER BY Datahora; </code></pre> <p>Right now, my function returns this statement as <code>text</code>. I copy-paste and execute it in pgAdmin or via psql. I want to automate this, run the query automatically and return the result. How can I do that?</p>
11,751,557
4
2
null
2012-07-31 12:38:51.403 UTC
28
2021-09-09 00:03:53.723 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,530,410
null
1
38
sql|database|postgresql|plpgsql|dynamic-sql
34,616
<h2>Dynamic SQL and <code>RETURN</code> type</h2> <p><sup>(I saved the best for last, keep reading!)</sup><br /> You want to execute <strong>dynamic SQL</strong>. In principal, that's simple in plpgsql with the help of <a href="https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN" rel="noreferrer"><strong><code>EXECUTE</code></strong></a>. You don't <em>need</em> a cursor. In fact, most of the time you are better off without explicit cursors.</p> <p>The problem you run into: you want to <strong>return records of yet undefined type</strong>. A function needs to declare its return type in the <a href="https://www.postgresql.org/docs/current/sql-createfunction.html" rel="noreferrer"><strong><code>RETURNS</code></strong></a> clause (or with <code>OUT</code> or <code>INOUT</code> parameters). In your case you would have to fall back to anonymous records, because <em>number</em>, <em>names</em> and <em>types</em> of returned columns vary. Like:</p> <pre><code>CREATE FUNCTION data_of(integer) RETURNS SETOF record AS ... </code></pre> <p>However, this is not particularly useful. You have to provide a column definition list with every call. Like:</p> <pre><code>SELECT * FROM data_of(17) AS foo (colum_name1 integer , colum_name2 text , colum_name3 real); </code></pre> <p>But how would you even do this, when you don't know the columns beforehand?<br /> You could use less structured document data types like <code>json</code>, <code>jsonb</code>, <code>hstore</code> or <code>xml</code>. See:</p> <ul> <li><a href="https://stackoverflow.com/questions/27065244/how-to-store-a-data-table-or-listkeyvaluepairint-object-or-dictionary-in/27066058#27066058">How to store a data table in database?</a></li> </ul> <p>But, for the purpose of this question, let's assume you want to return individual, correctly typed and named columns as much as possible.</p> <h2>Simple solution with fixed return type</h2> <p>The column <code>datahora</code> seems to be a given, I'll assume data type <code>timestamp</code> and that there are always two more columns with varying name and data type.</p> <p><em>Names</em> we'll abandon in favor of generic names in the return type.<br /> <em>Types</em> we'll abandon, too, and cast all to <code>text</code> since <em>every</em> data type can be cast to <code>text</code>.</p> <pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION data_of(_id integer) RETURNS TABLE (datahora timestamp, col2 text, col3 text) LANGUAGE plpgsql AS $func$ DECLARE _sensors text := 'col1::text, col2::text'; -- cast each col to text _type text := 'foo'; BEGIN RETURN QUERY EXECUTE ' SELECT datahora, ' || _sensors || ' FROM ' || quote_ident(_type) || ' WHERE id = $1 ORDER BY datahora' USING _id; END $func$; </code></pre> <p>The variables <code>_sensors</code> and <code>_type</code> could be input parameters instead.</p> <p>Note the <a href="https://www.postgresql.org/docs/current/sql-createfunction.html" rel="noreferrer"><code>RETURNS TABLE</code></a> clause.</p> <p>Note the use of <a href="https://www.postgresql.org/docs/current/plpgsql-control-structures.html#AEN54103" rel="noreferrer"><code>RETURN QUERY EXECUTE</code></a>. That is one of the more elegant ways to return rows from a dynamic query.</p> <p>I use a name for the function parameter, just to make the <code>USING</code> clause of <code>RETURN QUERY EXECUTE</code> less confusing. <code>$1</code> in the SQL-string does not refer to the function parameter but to the value passed with the <code>USING</code> clause. (Both happen to be <code>$1</code> in their respective scope in this simple example.)</p> <p>Note the example value for <code>_sensors</code>: each column is cast to type <code>text</code>.</p> <p>This kind of code is very vulnerable to <a href="https://en.wikipedia.org/wiki/Sql_injection" rel="noreferrer"><strong>SQL injection</strong></a>. I use <a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER" rel="noreferrer"><code>quote_ident()</code></a> to protect against it. Lumping together a couple of column names in the variable <code>_sensors</code> prevents the use of <code>quote_ident()</code> (and is typically a bad idea!). Ensure that no bad stuff can be in there some other way, for instance by individually running the column names through <code>quote_ident()</code> instead. A <code>VARIADIC</code> parameter comes to mind ...</p> <h3>Simpler since PostgreSQL 9.1</h3> <p>With version 9.1 or later you can use <a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER" rel="noreferrer"><code>format()</code></a> to further simplify:</p> <pre class="lang-sql prettyprint-override"><code>RETURN QUERY EXECUTE format(' SELECT datahora, %s -- identifier passed as unescaped string FROM %I -- assuming the name is provided by user WHERE id = $1 ORDER BY datahora' ,_sensors, _type) USING _id; </code></pre> <p>Again, individual column names could be escaped properly and would be the clean way.</p> <h2>Variable number of columns sharing the same type</h2> <p>After your question updates it looks like your return type has</p> <ul> <li>a variable <em>number</em> of columns</li> <li>but all columns of the same <em>type</em> <code>double precision</code> (alias <code>float8</code>)</li> </ul> <p>Use an <code>ARRAY</code> type in this case to nest a variable number of values. Additionally, I return an array with column names:</p> <pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION data_of(_id integer) RETURNS TABLE (datahora timestamp, names text[], values float8[]) LANGUAGE plpgsql AS $func$ DECLARE _sensors text := 'col1, col2, col3'; -- plain list of column names _type text := 'foo'; BEGIN RETURN QUERY EXECUTE format(' SELECT datahora , string_to_array($1) -- AS names , ARRAY[%s] -- AS values FROM %s WHERE id = $2 ORDER BY datahora' , _sensors, _type) USING _sensors, _id; END $func$; </code></pre> <br/> <h1>Various complete table types</h1> <p>To actually return <strong>all columns of a table</strong>, there is a simple, powerful solution using a <a href="https://www.postgresql.org/docs/current/extend-type-system.html#EXTEND-TYPES-POLYMORPHIC" rel="noreferrer"><strong>polymorphic type</strong></a>:</p> <pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION data_of(_tbl_type anyelement, _id int) RETURNS SETOF anyelement LANGUAGE plpgsql AS $func$ BEGIN RETURN QUERY EXECUTE format(' SELECT * FROM %s -- pg_typeof returns regtype, quoted automatically WHERE id = $1 ORDER BY datahora' , pg_typeof(_tbl_type)) USING _id; END $func$; </code></pre> <p>Call (important!):</p> <pre><code>SELECT * FROM data_of(NULL::pcdmet, 17); </code></pre> <p>Replace <code>pcdmet</code> in the call with any other table name.</p> <h3>How does this work?</h3> <p><code>anyelement</code> is a pseudo data type, a polymorphic type, a placeholder for any non-array data type. All occurrences of <code>anyelement</code> in the function evaluate to the same type provided at run time. By supplying a value of a defined type as argument to the function, we implicitly define the return type.</p> <p>PostgreSQL automatically defines a row type (a composite data type) for every table created, so there is a well defined type for every table. This includes temporary tables, which is convenient for ad-hoc use.</p> <p>Any type can be <code>NULL</code>. Hand in a <code>NULL</code> value, cast to the table type: <strong><code>NULL::pcdmet</code></strong>.</p> <p>Now the function returns a well-defined row type and we can use <code>SELECT * FROM data_of()</code> to decompose the row and get individual columns.</p> <p><a href="https://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE" rel="noreferrer"><strong><code>pg_typeof(_tbl_type)</code></strong></a> returns the name of the table as <a href="https://www.postgresql.org/docs/current/datatype-oid.html" rel="noreferrer">object identifier type <code>regtype</code></a>. When automatically converted to <code>text</code>, identifiers are <strong>automatically double-quoted and schema-qualified</strong> if needed, defending against SQL injection automatically. This can even deal with schema-qualified table-names where <code>quote_ident()</code> would fail. See:</p> <ul> <li><a href="https://stackoverflow.com/questions/10705616/table-name-as-a-postgresql-function-parameter/10711349#10711349">Table name as a PostgreSQL function parameter</a></li> </ul>
11,490,988
C++ compile time error: expected identifier before numeric constant
<p>I have read other similar posts but I just don't understand what I've done wrong. I think my declaration of the vectors is correct. I even tried to declare without size but even that isn't working.What is wrong?? My code is:</p> <pre><code>#include &lt;vector&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;fstream&gt; #include &lt;cmath&gt; using namespace std; vector&lt;string&gt; v2(5, "null"); vector&lt; vector&lt;string&gt; &gt; v2d2(20,v2); class Attribute //attribute and entropy calculation { vector&lt;string&gt; name(5); //error in these 2 lines vector&lt;int&gt; val(5,0); public: Attribute(){} int total,T,F; }; int main() { Attribute attributes; return 0; } </code></pre>
11,491,003
3
4
null
2012-07-15 09:53:02.84 UTC
21
2022-03-06 03:13:55.157 UTC
null
null
null
null
1,484,717
null
1
50
c++|vector|g++
147,044
<p>You cannot do this:</p> <pre><code>vector&lt;string&gt; name(5); //error in these 2 lines vector&lt;int&gt; val(5,0); </code></pre> <p>in a class outside of a method.</p> <p>You can initialize the data members at the point of declaration, but not with <code>()</code> brackets:</p> <pre><code>class Foo { vector&lt;string&gt; name = vector&lt;string&gt;(5); vector&lt;int&gt; val{vector&lt;int&gt;(5,0)}; }; </code></pre> <p>Before C++11, you need to declare them first, then initialize them e.g in a contructor</p> <pre><code>class Foo { vector&lt;string&gt; name; vector&lt;int&gt; val; public: Foo() : name(5), val(5,0) {} }; </code></pre>
11,944,932
How to download a file with Node.js (without using third-party libraries)?
<p>How do I download a file with Node.js <strong>without using third-party libraries</strong>?</p> <p>I don't need anything special. I only want to download a file from a given URL, and then save it to a given directory.</p>
11,944,984
31
4
null
2012-08-14 02:21:44.943 UTC
187
2022-09-22 16:06:13.573 UTC
2021-01-29 14:27:41.617 UTC
null
6,871,901
null
1,478,546
null
1
607
javascript|node.js|download|fs
748,243
<p>You can create an HTTP <code>GET</code> request and pipe its <code>response</code> into a writable file stream:</p> <pre><code>const http = require('http'); // or 'https' for https:// URLs const fs = require('fs'); const file = fs.createWriteStream(&quot;file.jpg&quot;); const request = http.get(&quot;http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg&quot;, function(response) { response.pipe(file); // after download completed close filestream file.on(&quot;finish&quot;, () =&gt; { file.close(); console.log(&quot;Download Completed&quot;); }); }); </code></pre> <p>If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like <a href="https://github.com/visionmedia/commander.js/" rel="noreferrer">Commander</a>.</p> <p>More detailed explanation in <a href="https://sebhastian.com/nodejs-download-file/" rel="noreferrer">https://sebhastian.com/nodejs-download-file/</a></p>
11,784,656
AngularJS $location not changing the path
<p>I'm having an issue with changing the URL of the page after a form has been submitted.</p> <p>Here's the flow of my app:</p> <ol> <li>Routes are set, URL is recognized to some form page.</li> <li>Page loads, controller sets variables, directives are fired.</li> <li>A special form directive is fired which performs a special form submission using AJAX.</li> <li>After the AJAX is performed (Angular doesn't take care of the AJAX) then a callback is fired and the directive calls the <code>$scope.onAfterSubmit</code> function which sets the location.</li> </ol> <p>The problem is that after setting the location the nothing happens. I've tried setting the location param to <code>/</code> as well... Nope. I've also tried not submitting the form. Nothing works.</p> <p>I've tested to see if the code reaches the <code>onAfterSubmit</code> function (which it does).</p> <p>My only thought is that somehow the scope of the function is changed (since its called from a directive), but then again how can it call <code>onAfterSubmit</code> if the scope changed? </p> <p>Here's my code</p> <pre><code>var Ctrl = function($scope, $location, $http) { $http.get('/resources/' + $params.id + '/edit.json').success(function(data) { $scope.resource = data; }); $scope.onAfterSubmit = function() { $location.path('/').replace(); }; } Ctrl.$inject = ['$scope','$location','$http']; </code></pre> <p>Can someone help me out please?</p>
11,932,283
9
4
null
2012-08-02 19:42:55.643 UTC
33
2020-06-12 14:27:35.667 UTC
2015-12-19 09:56:48.243 UTC
null
2,333,214
null
340,939
null
1
129
angularjs
131,845
<p>I had a similar problem some days ago. In my case the problem was that I changed things with a 3rd party library (jQuery to be precise) and in this case even though calling functions and setting variable works Angular doesn't always recognize that there are changes thus it never digests.</p> <blockquote> <p>$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).</p> </blockquote> <p>Try to use <code>$scope.$apply()</code> right after you have changed the location and called <code>replace()</code> to let Angular know that things have changed.</p>
4,019,595
Best way to kill application instance
<p>What is the best way to kill an application instance? I am aware of these three methods:</p> <ol> <li><p><code>Application.Exit()</code></p></li> <li><p><code>Environment.Exit(0)</code></p></li> <li><p><code>Process.GetCurrentProcess().Kill()</code></p></li> </ol> <p>Can anyone tell me which is better or when using each of the above would be appropriate?</p>
4,019,622
4
0
null
2010-10-25 23:08:53.03 UTC
2
2019-07-21 04:55:22.117 UTC
2019-07-21 04:55:22.117 UTC
null
11,585,798
null
385,853
null
1
16
c#|winforms|process
38,161
<p>guidelines from c# faq:</p> <p>System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread. This is the call to use if you are running a WinForms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run.</p> <p>System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.</p> <p>Killing the process is likely not recommended.</p>
3,361,478
What are views for collections and when would you want to use them?
<p>In Scala, for many (all?) types of collections you can create views.</p> <p>What exactly is a view and for which purposes are views useful?</p>
3,361,746
4
0
null
2010-07-29 10:23:15.49 UTC
14
2018-05-10 22:56:53.62 UTC
2013-04-17 16:29:57.5 UTC
null
298,389
null
135,589
null
1
55
scala|views|scala-collections
7,150
<p>Views are non-strict versions of collections. This means that the elements are calculated at access and not eagerly as in normal collections.</p> <p>As an example take the following code:</p> <pre><code>val xs = List.tabulate(5)(_ + 1) val ys = xs.view map { x =&gt; println(x); x * x } </code></pre> <p>Just this will not print anything but every access to the list will perform the calculation and print the value, i.e. every call to <code>ys.head</code> will result in <code>1</code> being printed. If you want to get a strict version of the collection again you can call <code>force</code> on it. In this case you will see all numbers printed out.</p> <p>One use for views is when you need to traverse a collection of values which are expensive to compute and you only need one value at a time. Also views let you build lazy sequences by calling <code>toStream</code> on them that will also cache the evaluated elements.</p>
3,710,617
list recursively all files and folders under the given path?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c">How to recursively list all the files in a directory in C#?</a> </p> </blockquote> <p>I want to list the "sub-path" of files and folders for the giving folder (path)</p> <p>let's say I have the folder C:\files\folder1\subfolder1\file.txt</p> <p>if I give the function c:\files\folder1\</p> <p>I will get subfolder1 subfolder1\file.txt</p>
3,710,704
5
1
null
2010-09-14 15:57:49.027 UTC
7
2016-11-29 12:52:58.843 UTC
2017-05-23 11:54:33.733 UTC
null
-1
null
321,172
null
1
13
c#|.net|file|path|filesystems
50,045
<p>Try something like this:</p> <pre><code>static void Main(string[] args) { DirSearch(@"c:\temp"); Console.ReadKey(); } static void DirSearch(string dir) { try { foreach (string f in Directory.GetFiles(dir)) Console.WriteLine(f); foreach (string d in Directory.GetDirectories(dir)) { Console.WriteLine(d); DirSearch(d); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } } </code></pre>
3,348,753
Search for a file using a wildcard
<p>I want get a list of filenames with a search pattern with a wildcard. Like:</p> <pre><code>getFilenames.py c:\PathToFolder\* getFilenames.py c:\PathToFolder\FileType*.txt getFilenames.py c:\PathToFolder\FileTypeA.txt </code></pre> <p>How can I do this?</p>
3,348,761
5
0
null
2010-07-27 23:20:17.893 UTC
9
2020-07-01 14:42:14.04 UTC
2014-01-17 23:57:55.913 UTC
null
488,657
null
248,430
null
1
54
python|file|wildcard
87,985
<p>You can do it like this:</p> <pre><code>&gt;&gt;&gt; import glob &gt;&gt;&gt; glob.glob('./[0-9].*') ['./1.gif', './2.txt'] &gt;&gt;&gt; glob.glob('*.gif') ['1.gif', 'card.gif'] &gt;&gt;&gt; glob.glob('?.gif') ['1.gif'] </code></pre> <p><em>Note</em>: If the directory contains files starting with <code>.</code> they won’t be matched by default. For example, consider a directory containing <code>card.gif</code> and <code>.card.gif</code>:</p> <pre><code>&gt;&gt;&gt; import glob &gt;&gt;&gt; glob.glob('*.gif') ['card.gif'] &gt;&gt;&gt; glob.glob('.c*') ['.card.gif'] </code></pre> <p>This comes straight from here: <a href="http://docs.python.org/library/glob.html" rel="noreferrer">http://docs.python.org/library/glob.html</a></p>
3,859,340
Calling Haskell from C++ code
<p>I'm currently writing an app in C++ and found that some of its functionality would be better written in Haskell. I've seen instructions on <a href="http://www.haskell.org/haskellwiki/Calling_Haskell_from_C" rel="noreferrer">calling Haskell from C code</a>, but is it possible to do the same with C++?</p> <p><strong>EDIT:</strong> To clarify, what I'm looking for is a way to compile Haskell code into an external library that g++ can link with the object code from C++.</p> <p><strong>UPDATE:</strong> I've put up a working example below for anyone else interested (also so I won't forget).</p>
3,860,170
5
3
null
2010-10-04 21:37:12.82 UTC
44
2019-04-06 03:38:14.383 UTC
2011-04-23 21:20:11.217 UTC
null
83,805
null
351,105
null
1
57
c++|haskell|linker|ffi
16,054
<p><strong>Edit:</strong> You should also see Tomer's answer below. My answer here describes the theory of what's going on, but I may have some of the details of execution incomplete, whereas his answer is a complete working example.</p> <p>As sclv indicates, compiling should be no problem. The difficulty there is likely to be linking the C++ code, and here you will have a little bit of difficulty with getting all the needed runtime libraries linked in. The problem is that Haskell programs need to be linked with the Haskell runtime libraries, and C++ programs need to be linked with the C++ runtime libraries. In the Wiki page you reference, when they do</p> <pre><code>$ ghc -optc -O test.c A.o A_stub.o -o test </code></pre> <p>to compile the C program, that actually does two steps: It compiles the C program into an object file, and then links it together. Written out, that would be something like (probably not quite right, as I don't speak GHC):</p> <pre><code>$ ghc -c -optc-O test.c -o test.o $ ghc test.o A.o A_stub.o -o test </code></pre> <p>GHC just acts like GCC (and, IIUC, functionally <em>is</em> GCC) when compiling the C program. When linking it, however, it is different from what happens if you call GCC directly, because it also magically includes the Haskell runtime libraries. G++ works the same way for C++ programs -- when it's used as a linker, it includes the C++ runtime libraries.</p> <p>So, as I mentioned, you need to compile in a way that links with both runtime libraries. If you run G++ in verbose mode to compile and link a program, like so:</p> <pre><code>$ g++ test.cpp -o test -v </code></pre> <p>it will create a long list of output about what it's doing; at the end will be a line of output where it does the linking (with the <code>collect2</code> subprogram) indicating what libraries it links to. You can compare that to the output for compiling a simple C program to see what's different for C++; on my system, it adds <code>-lstdc++</code>.</p> <p>Thus, you should be able to compile and link your mixed Haskell/C++ program like so:</p> <pre><code>$ ghc -c -XForeignFunctionInterface -O A.hs # compile Haskell object file. $ g++ -c -O test.cpp # compile C++ object file. $ ghc A.o A_stub.o test.o -lstdc++ -o test # link </code></pre> <p>There, because you've specified <code>-lstdc++</code>, it will include the C++ runtime library (assuming <code>-l</code> is the right GHC syntax; you'll need to check), and because you've linked with <code>ghc</code>, it will include the Haskell runtime library. This should result in a working program.</p> <p>Alternately, you should be able to do something similar to the <code>-v</code> output investigation with GHC, and figure out what Haskell runtime library (or libraries) it links to for Haskell support, and then add that library when linking your program with C++, just as you already do for pure C++ programs. (See Tomer's answer for details of that, since that's what he did.)</p>
3,361,918
Dark Theme for Visual Studio 2010 With Productivity Power Tools
<p>There's a lot of new things going on in the Productivity Power Tools extensions, and I find that many of the new features come with very weird color combinations, that many times make the text completely illegible. I assume this is because I've previously set a dark theme for Visual Studio, and some, but not all, of the settings that affect the extension have been changed.</p> <p>Are there any good dark themes out there that have been put together <em>after the Productivity Tools Extension was published</em>, that create a unified color theme for both VS and the extension features?</p> <p><strong>Clarification:</strong> This question is <strong>not</strong> about color schemes for code, such as those found at <a href="http://studiostyles.info" rel="noreferrer">studiostyles</a>. I'm talking about color schemes that apply to the development environment itself; toolboxes, menus, tooltips, windows, buttons...</p>
4,160,221
5
0
null
2010-07-29 11:20:21.773 UTC
43
2020-05-26 10:34:43.043 UTC
2013-08-21 07:49:36.777 UTC
null
895,245
null
38,055
null
1
92
visual-studio-2010|visual-studio|themes|pro-power-tools
215,167
<ol> <li>Install the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/20cd93a2-c435-4d00-a797-499f16402378" rel="nofollow noreferrer">Visual Studio Color Theme Editor extension</a>:</li> <li>Make your own color scheme or try: <a href="https://raw.githubusercontent.com/peteristhegreat/DarkVS2010Theme/master/Expression.vstheme" rel="nofollow noreferrer">The Dark Expression Blend Color Theme</a> (preview below)</li> <li>Once you have that, you'll want schemes for the text editor as well. <a href="http://studiostyles.info/" rel="nofollow noreferrer">This site</a> has several, including the VS2012 "dark" theme implemented for VS2010.</li> </ol> <p><img src="https://i.stack.imgur.com/HLt6A.jpg" alt="Visual Studio 2010 with Dark Theme"></p>
3,634,204
About UIAlertView with Textfield...
<p>I have this code to prompt the <code>UIAlertView</code>, with <code>UITextfield</code>:</p> <pre><code>UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"New List Item", @"new_list_dialog") message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)]; [myTextField setBackgroundColor:[UIColor whiteColor]]; [myAlertView addSubview:myTextField]; [myAlertView show]; [myAlertView release]; </code></pre> <p>But I would like to add a get the textfield value, after the user click "OK", and after the user click , I want to call a method, how can I assign that to the myAlertView? Thank you. </p>
3,634,231
6
4
null
2010-09-03 08:44:53.927 UTC
14
2018-03-29 18:07:54.613 UTC
2018-03-29 18:07:54.613 UTC
null
2,284,065
null
148,978
null
1
37
iphone|objective-c
52,513
<p>Declare the text field as global.And in the method of alertView clicked <code>- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex</code> just take the value of the textfield and do the operations you want with it.....</p> <p>Heres the revised code</p> <pre><code>UITextField *myTextField; ... { UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"New List Item", @"new_list_dialog") message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)]; [myTextField setBackgroundColor:[UIColor whiteColor]]; [myAlertView addSubview:myTextField]; [myAlertView show]; [myAlertView release]; } .... - (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog(@"string entered=%@",myTextField.text); } </code></pre> <p>For iOS 5 and later You can use <code>alertViewStyle</code> property of <code>UIAlertView</code>.</p> <p>Please refer Hamed's Answer for the same</p>
3,698,158
What is the difference between microprocessor and microcontroller?
<p>One difference is microcontrollers are usually designed to perform a small set of specific functions whereas microprocessors are for huge, general functions. </p> <p>Anything else??</p>
3,698,231
7
2
null
2010-09-13 06:12:50.81 UTC
6
2014-01-22 09:28:02.623 UTC
2010-09-13 06:40:42.28 UTC
null
50,846
null
441,075
null
1
11
microcontroller
40,176
<p>A microcontroller is a microprocessor (a.k.a. CPU core or cores) with additional peripherals on-chip. The terms come from the 1970s, where a microprocessor (e.g. Motorola 6800 or Intel 8086) would have an address bus, a data bus, and control lines, and a microcontroller (e.g. Motorola 6801 or Intel 8051) would have peripheral I/O pins (serial ports, parallel I/O, timer I/O, etc.) but no external memory bus (you were stuck with what was on the chip). </p> <p>Additionally, microprocessors executed their programs from external ROM and microcontrollers would use internal masked (as in "programmed at the factory by changing the IC photo mask") ROM. The only practical erasable ROMs were UV-erased EPROMS, electrically erasable PROMS (EEPROMS) were expensive, slow, and not very dense, and "flash" meant the bits of plastic sticking out of the mold seam lines on the chip.</p> <p>Honestly, the line between them is fading away. Modern microcontrollers such as the Motorola 6812 series have an external memory bus <em>and</em> peripheral I/O pins at the same time, and can be used as either a microprocessor or microcontroller.</p>
3,533,408
Regex: I want this AND that AND that... in any order
<p>I'm not even sure if this is possible or not, but here's what I'd like.</p> <pre><code>String: "NS306 FEBRUARY 20078/9/201013B1-9-1Low31 AUGUST 19870" </code></pre> <p>I have a text box where I type in the search parameters and they are space delimited. Because of this, I want to return a match is string1 is in the string and then string2 is in the string, OR string2 is in the string and then string1 is in the string. I don't care what order the strings are in, but they ALL (will somethings me more than 2) have to be in the string.</p> <p>So for instance, in the provided string I would want:</p> <pre><code>"FEB Low" </code></pre> <p>or</p> <pre><code>"Low FEB" </code></pre> <p>...to return as a match.</p> <p>I'm REALLY new to regex, only read some tutorials on <a href="http://perldoc.perl.org/perlretut.html" rel="noreferrer">here</a> but that was a while ago and I need to get this done today. Monday I start a new project which is much more important and can't be distracted with this issue. Is there anyway to do this with regular expressions, or do I have to iterate through each part of the search filter and permutate the order? Any and all help is extremely appreciated. Thanks.</p> <p>UPDATE: The reason I don't want to iterate through a loop and am looking for the best performance wise is because unfortunately, the dataTable I'm using calls this function on every key press, and I don't want it to bog down.</p> <p>UPDATE: Thank you everyone for your help, it was much appreciated.</p> <p>CODE UPDATE:</p> <p>Ultimately, this is what I went with.</p> <pre><code>string sSearch = nvc["sSearch"].ToString().Replace(" ", ")(?=.*"); if (sSearch != null &amp;&amp; sSearch != "") { Regex r = new Regex("^(?=.*" + sSearch + ").*$", RegexOptions.IgnoreCase); _AdminList = _AdminList.Where&lt;IPB&gt;( delegate(IPB ipb) { //Concatenated all elements of IPB into a string bool returnValue = r.IsMatch(strTest); //strTest is the concatenated string return returnValue; }).ToList&lt;IPB&gt;(); } } </code></pre> <p>The IPB class has X number of elements and in no one table throughout the site I'm working on are the columns in the same order. Therefore, I needed to any order search and I didn't want to have to write a lot of code to do it. There were other good ideas in here, but I know my boss really likes Regex (preaches them) and therefore I thought it'd be best if I went with that for now. If for whatever reason the site's performance slips (intranet site) then I'll try another way. Thanks everyone.</p>
3,533,526
7
0
null
2010-08-20 17:38:26.24 UTC
27
2020-04-06 06:04:59.323 UTC
2010-08-25 15:21:08.867 UTC
null
419,603
null
419,603
null
1
61
c#|regex
37,255
<p>You can use <code>(?=…)</code> <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer"><em>positive lookahead</em></a>; it asserts that a given pattern can be matched. You'd anchor at the beginning of the string, and one by one, in any order, look for a match of each of your patterns.</p> <p>It'll look something like this:</p> <pre><code>^(?=.*one)(?=.*two)(?=.*three).*$ </code></pre> <p>This will match a string that contains <code>"one"</code>, <code>"two"</code>, <code>"three"</code>, in any order (<a href="http://www.rubular.com/r/QFEfj9lMn3" rel="noreferrer">as seen on rubular.com</a>).</p> <p>Depending on the context, you may want to <a href="http://www.regular-expressions.info/anchors.html" rel="noreferrer">anchor</a> on <code>\A</code> and <code>\Z</code>, and use single-line mode so <a href="http://www.regular-expressions.info/dot.html" rel="noreferrer">the dot</a> matches everything.</p> <p>This is not the most efficient solution to the problem. The best solution would be to parse out the words in your input and putting it into an efficient set representation, etc.</p> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/3092797/how-does-the-regular-expression-work/">How does the regular expression <code>(?&lt;=#)[^#]+(?=#)</code> work?</a></li> </ul> <hr> <h3>More practical example: password validation</h3> <p>Let's say that we want our password to:</p> <ul> <li>Contain between 8 and 15 characters</li> <li>Must contain an uppercase letter</li> <li>Must contain a lowercase letter</li> <li>Must contain a digit</li> <li>Must contain one of special symbols</li> </ul> <p>Then we can write a regex like this:</p> <pre><code>^(?=.{8,15}$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&amp;*]).*$ \__________/\_________/\_________/\_________/\______________/ length upper lower digit symbol </code></pre>
3,919,845
Presenting a modal view controller immediately after dismissing another
<p>I'm dismissing a modal view controller and then immediately presenting another one, but the latter never happens. Here's the code:</p> <pre> [self dismissModalViewControllerAnimated:YES]; UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; [self presentModalViewController:picker animated:YES]; </pre> <p>The first modal VC slides down, but the new <code>picker</code> never comes up. Any idea as to what's going on?</p>
3,919,894
8
2
null
2010-10-12 23:37:31.667 UTC
15
2017-05-05 21:33:20.997 UTC
null
null
null
null
95,267
null
1
38
iphone|objective-c|uiimagepickercontroller
33,644
<p>Like other animated things, <code>dismissModalViewControllerAnimated</code> doesn't block until the view controller disappears. Instead it "kicks off" dismissal of the view controller. You might need to use a callback in <code>viewDidDisappear</code> of modal controller 1 that calls something like <code>modalViewControllerDisappeared</code> in the parent view controller. In that method you present modal controller 2. Otherwise what Robot K said.</p>
3,772,093
How to do database unit testing?
<p>I have heard that when developing application which uses a database you should do database unit testing.</p> <p>What are the best practices in database unit testing? What are the primary concerns when doing DB unit testing and how to do it &quot;right&quot;?</p>
3,772,382
8
3
null
2010-09-22 17:43:25.903 UTC
26
2021-09-20 06:50:15.857 UTC
2021-09-20 06:50:15.857 UTC
null
2,088,053
null
368,537
null
1
51
database|unit-testing|database-testing
46,897
<blockquote> <p>What are the best practices in database unit testing? </p> </blockquote> <p>The <a href="http://dbunit.sourceforge.net/" rel="noreferrer">DbUnit</a> framework (a testing framework allowing to put a database in a know state and to perform assertion against its content) has a page listing database testing <a href="http://dbunit.sourceforge.net/bestpractices.html" rel="noreferrer">best practices</a> that, to my experience, are true.</p> <blockquote> <p>What are the primary concerns when doing db unit testing</p> </blockquote> <ul> <li>Creating an up to date schema, managing schema changes</li> <li>Setting up data (reference data, test data) and <strong>maintaining</strong> test data</li> <li>Keeping tests independent</li> <li>Allowing developers to work concurrently</li> <li>Speed (tests involving database are typically slower and will make your whole build take more time)</li> </ul> <blockquote> <p>and how to do it "right"?</p> </blockquote> <p>As hinted, follow known good practices and use dedicated tools/frameworks:</p> <ul> <li>Prefer in memory database if possible (for speed)</li> <li>Use one schema per developer is a must (to allow concurrent work)</li> <li>Use a "database migration" tool (à la RoR) to manage schema changes and update a schema to the ultimate version</li> <li>Build or use a test harness allowing to put the database in a known state before each test and to perform asserts against the data after the execution (or to run tests inside a transaction that you rollback at the end of the test).</li> </ul>
3,395,798
MySQL, Check if a column exists in a table with SQL
<p>I am trying to write a query that will check if a specific table in MySQL has a specific column, and if not — create it. Otherwise do nothing. This is really an easy procedure in any enterprise-class database, yet MySQL seems to be an exception.</p> <p>I thought something like</p> <pre><code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='prefix_topic' AND column_name='topic_last_update') BEGIN ALTER TABLE `prefix_topic` ADD `topic_last_update` DATETIME NOT NULL; UPDATE `prefix_topic` SET `topic_last_update` = `topic_date_add`; END; </code></pre> <p>would work, but it fails badly. Is there a way?</p>
7,264,865
10
5
null
2010-08-03 10:52:29.907 UTC
32
2021-07-20 01:36:45.64 UTC
2013-11-03 20:11:34.297 UTC
null
31,480
null
184,484
null
1
154
mysql
259,546
<p>This works well for me.</p> <pre class="lang-sql prettyprint-override"><code>SHOW COLUMNS FROM `table` LIKE 'fieldname'; </code></pre> <p>With PHP it would be something like...</p> <pre class="lang-php prettyprint-override"><code>$result = mysql_query(&quot;SHOW COLUMNS FROM `table` LIKE 'fieldname'&quot;); $exists = (mysql_num_rows($result))?TRUE:FALSE; </code></pre>
3,228,871
SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?
<p>What is the difference between CROSS JOIN and FULL OUTER JOIN in SQL Server?</p> <p>Are they the same, or not? Please explain. When would one use either of these?</p>
3,228,910
10
0
null
2010-07-12 13:17:11.37 UTC
61
2022-06-08 05:36:13.213 UTC
2010-07-12 13:58:03.127 UTC
null
13,302
null
127,488
null
1
240
sql-server|cross-join|full-outer-join
279,020
<p>A cross join produces a cartesian product between the two tables, returning all possible combinations of all rows. It has no <code>on</code> clause because you're just joining everything to everything.</p> <p>A <code>full outer join</code> is a combination of a <code>left outer</code> and <code>right outer</code> join. It returns all rows in both tables that match the query's <code>where</code> clause, and in cases where the <code>on</code> condition can't be satisfied for those rows it puts <code>null</code> values in for the unpopulated fields.</p> <p>This <a href="http://en.wikipedia.org/wiki/Join_(SQL)" rel="noreferrer">wikipedia</a> article explains the various types of joins with examples of output given a sample set of tables.</p>
7,774,015
How to yank the text on a line and paste it inline in Vim?
<p>Say, I have the following lines:</p> <pre><code>thing(); getStuff(); </code></pre> <p>I want to take <code>getStuff()</code> using the <code>yy</code> command, go forward to <code>thing()</code>, placing the cursor on <code>(</code>, and paste via the <code>p</code> command, but since I yanked the whole line, <code>p</code> will paste <code>getStuff()</code> right back where it was.</p> <p>I know you can first move the cursor to the beginning of that <code>getStuff()</code> line and cut the characters from there until its end via the <code>^D</code> commands—then <kbd>p</kbd> will do what I want. However, I find typing <code>^D</code> to be much more tedious than <code>yy</code>.</p> <p>Is there a way to <code>yy</code>, but paste the line <em>inline</em> instead?</p>
7,774,200
4
2
null
2011-10-14 21:58:41.38 UTC
19
2021-01-05 02:50:16.01 UTC
2020-09-30 02:51:14.647 UTC
null
254,635
null
61,410
null
1
69
vim
36,707
<p>Use <kbd>y</kbd><kbd>i</kbd><kbd>w</kbd> (&quot;yank inner word&quot;) instead of <kbd>y</kbd><kbd>y</kbd> to yank just what you want:</p> <p><kbd>y</kbd><kbd>y</kbd> is line-wise yank and will grab the whole line including the carriage return, which you can see if you look at the unnamed register (<code>&quot;&quot;</code>) in <code>:registers</code> which is used as the source for pastes. See <code>:help &quot;&quot;</code>:</p> <blockquote> <p>Vim uses the contents of the unnamed register for any put command (<code>p</code> or <code>P</code>) which does not specify a register. Additionally you can access it with the name <code>&quot;</code>. This means you have to type two double quotes. Writing to the &quot;&quot; register writes to register <code>&quot;0</code>.</p> </blockquote> <p>An additional benefit to <kbd>y</kbd><kbd>i</kbd><kbd>w</kbd> is that you don't have to be at the front of the &quot;word&quot; you are yanking!</p>
8,355,123
How to display string that contains HTML in twig template?
<p>How can I display a string that contains HTML tags in twig template?</p> <p>My PHP variable contains this html and text:</p> <pre><code>$word = '&lt;b&gt; a word &lt;/b&gt;'; </code></pre> <p>When I do this in my twig template:</p> <pre><code>{{ word }} </code></pre> <p>I get this:</p> <pre><code>&amp;lt;b&amp;gt; a word &amp;lt;b&amp;gt; </code></pre> <p>I want this instead:</p> <pre><code>&lt;b&gt; a word &lt;/b&gt; </code></pre> <p>Is it possible to get this easily?</p>
8,355,239
4
1
null
2011-12-02 10:44:59.557 UTC
27
2020-07-01 12:18:22.983 UTC
2020-02-20 09:17:25.713 UTC
null
1,589,444
null
1,027,355
null
1
194
php|html|symfony|twig
199,382
<p>Use raw keyword, <a href="http://twig.sensiolabs.org/doc/api.html#escaper-extension" rel="noreferrer">http://twig.sensiolabs.org/doc/api.html#escaper-extension</a></p> <pre><code>{{ word | raw }} </code></pre>