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
50,757,647
E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation
<p>I have installed docker on windows 10 pro. I am facing an issue while running the following command in git-bash. </p> <p>docker-compose up -d --build</p> <p>and got following error. </p> <pre><code>E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation (23) Failed writing body Error executing command, exiting ERROR: Service 'web' failed to build: The command '/bin/sh -c curl -sL https://deb.nodesource.com/setup_8.x | bash' returned a non-zero code: 1 </code></pre>
51,752,997
5
1
null
2018-06-08 09:35:26.977 UTC
18
2021-09-24 22:41:29.53 UTC
2020-02-12 17:05:14.337 UTC
null
4,551,041
null
4,354,064
null
1
201
docker|docker-compose
188,468
<p>In your Dockerfile, run this first:</p> <pre><code>apt-get update &amp;&amp; apt-get install -y gnupg2 </code></pre> <p>or</p> <pre><code>apt-get update &amp;&amp; apt-get install -y gnupg </code></pre>
10,764,007
Python While Loop, the and (&) operator is not working
<p>I am trying to find the greatest common factor.</p> <p>I wrote a bad (operation intensive) algorithm that decrements the lower value by one, checks using % to see if it evenly divides both the numerator and denominator, if it does then it exits the program. However, my while loop is not using the and operator, and thus once the numerator is divisible it stops, even though its not the correct answer. </p> <p>The numbers I am using are 54 and 42, the correct GCD (greatest common denominator) is 6. </p> <pre><code>#heres a simple algorithm to find the greatest common denominator: iterations = 0; #used to calculate number of times while loop is executed u = 54; v= 42; d = v-1; #u is the numerator, v is the denominator, d is the number decremented by one while ((v % d !=0) &amp; (u % d != 0)): #while both numerator AND denominator cannot be evenly divided by the decremented number d -= 1 #decrement the number by one print d #print the number decremented iterations +=1 #add 1 to the count of iterations in while loop print "the gcd is " +str(d) #should be 6 when the number can evenly divide both print "the number of iterations was " +str(iterations) #display times it took algorithm to complete </code></pre> <p>The answer I am getting is 27, which tells me once it reaches 27 and can divide 54/27 evenly, it stops. Any thoughts on how to use an and operator in a while loop in python? </p> <p>Thanks!</p>
10,764,020
2
0
null
2012-05-26 05:59:49.143 UTC
0
2019-03-30 08:56:33.137 UTC
2012-05-26 06:45:30.17 UTC
null
164,234
null
1,404,663
null
1
7
python|while-loop|operator-keyword
64,696
<p>You should be using the keyword <code>and</code> instead of the bitwise and operator <code>&amp;</code>:</p> <pre><code>while (v % d != 0) and (u % d != 0): </code></pre> <p>This is also the same:</p> <pre><code>while (v % d) and (u % d): </code></pre> <p>Note that <code>&amp;</code> and <code>and</code> will give the same result in the first case, but not in the second.</p> <p>Your problem though is that you want to use <code>or</code> instead of <code>and</code>. Also your algorithm is highly inefficient. There are <a href="http://en.wikipedia.org/wiki/Greatest_common_divisor#Calculation" rel="noreferrer">better ways to calculate the GCD</a>.</p>
5,846,939
Difference between fzero and fsolve for one variable
<p>Is there a difference between using fzero and fsolve for a single variable equation?</p>
5,847,286
2
0
null
2011-05-01 06:43:30.54 UTC
6
2011-05-01 11:02:41.667 UTC
null
null
null
null
232,495
null
1
10
matlab
39,983
<p>Yes, there is. I'll just mention the most straightforward difference between the two: </p> <blockquote> <p><a href="http://www.mathworks.com/help/toolbox/optim/ug/fsolve.html" rel="noreferrer"><code>fsolve</code></a> can be used to solve for the zero of a single variable equation. However, <a href="http://www.mathworks.com/help/toolbox/optim/ug/fzero.html" rel="noreferrer"><code>fzero</code></a> will find the zero <em>if and only if</em> the function crosses the x-axis.</p> </blockquote> <p>Here's a simple example: Consider the function <code>f=x^2</code>. The function is non-negative for all real values of <code>x</code>. This has a root at <code>x=0</code>. We'll define an anonymous function as <code>f=@(x)x.^2;</code> and try to find the root using both the methods.</p> <p><strong>Using fsolve</strong></p> <pre><code>options=optimset('MaxIter',1e3,'TolFun',1e-10); fsolve(f,0.1,options) Equation solved. fsolve completed because the vector of function values is near zero as measured by the selected value of the function tolerance, and the problem appears regular as measured by the gradient. &lt;stopping criteria details&gt; ans = 1.9532e-04 </code></pre> <p>Not zero, but close.</p> <p><strong>Using fzero</strong></p> <pre><code>fzero(f,0.1) Exiting fzero: aborting search for an interval containing a sign change because NaN or Inf function value encountered during search. (Function value at -1.37296e+154 is Inf.) Check function or try again with a different starting value. ans = NaN </code></pre> <p>It <em>cannot</em> find a zero. </p> <p>Consider another example with the function <code>f=@(x)x.^3;</code> that crosses the x-axis and has a root at <code>x=0</code>.</p> <pre><code>fsolve(f,0.1) ans = 0.0444 fzero(f,0.1) ans = -1.2612e-16 </code></pre> <p><code>fsolve</code> doesn't return exactly <code>0</code> in this case either. Even using the <code>options</code> I defined above only gets me to <code>0.0017</code> with <code>fsolve</code>. However, <code>fzero</code>'s answer is correct to within machine precision!. The difference in answers is not because of inefficient algorithms. It's because their <strong>objectives are different</strong>.</p> <p><code>fzero</code> has a clear goal: find the zero! Simple. No ambiguities there. If it crosses the x-axis, there <em>is</em> a zero and it will find it (real only). If it doesn't cross, it whines.</p> <p>However, <code>fsolve</code>'s scope is broader. It is designed to solve a system of nonlinear equations. Often you can't find an exact solution to those equations and will have to set a tolerance level, within which you're willing to accept the solution as the answer. As a result, there are a host of options and tolerances that need to be set manually to massage out the exact root. Sure, you have finer control but for finding a zero of a single var equation, I consider it a pain. I'd probably use <code>fzero</code> in that case (assuming it crosses the x-axis).</p> <p>Apart from this major difference, there are differences in implementations and the algorithms used. For that, I'll refer you to the online documentation on the functions (see the links above).</p>
6,004,891
undefined method for ActiveRecord::Relation
<p>User model</p> <pre><code>class User &lt; ActiveRecord::Base has_many :medicalhistory end </code></pre> <p>Mdedicalhistory model</p> <pre><code>class Medicalhistory &lt; ActiveRecord::Base belongs_to :user #foreign key -&gt; user_id accepts_nested_attributes_for :user end </code></pre> <p><strong>Error</strong></p> <pre><code>undefined method `lastname' for #&lt;ActiveRecord::Relation:0xb6ad89d0&gt; #this works @medicalhistory = Medicalhistory.find(current_user.id) print "\n" + @medicalhistory.lastname #this doesn't! @medicalhistory = Medicalhistory.where("user_id = ?", current_user.id) print "\n" + @medicalhistory.lastname #error on this line </code></pre>
6,004,962
2
2
null
2011-05-14 21:26:48.867 UTC
7
2016-05-17 07:06:20.203 UTC
2011-05-14 21:36:08.647 UTC
null
44,286
null
44,286
null
1
24
ruby-on-rails-3|activerecord
39,771
<p>Well, you are getting back an object of <code>ActiveRecord::Relation</code>, not your model instance, thus the error since there is no method called <code>lastname</code> in <code>ActiveRecord::Relation</code>.</p> <p>Doing <code>@medicalhistory.first.lastname</code> works because <code>@medicalhistory.first</code> is returning the first instance of the model that was found by the <code>where</code>.</p> <p>Also, you can print out <code>@medicalhistory.class</code> for both the working and "erroring" code and see how they are different.</p>
5,612,571
What's the difference between SpecialFolder.Desktop and SpecialFolder.DesktopDirectory?
<p>I'm confused about the differences between these two special folders.</p> <p>Here's a code snippet that writes the output of each, but they output the same thing. </p> <pre><code>string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string pathTwo = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); Console.WriteLine(path); Console.WriteLine(pathTwo); Console.ReadKey(); </code></pre> <p>According to the <a href="http://msdn.microsoft.com/en-us/library/system.environment.specialfolder%28v=vs.71%29.aspx" rel="noreferrer">MSDN</a> documentation (<em>for .NET 1.1</em>):</p> <p><strong>Desktop</strong><br> The logical Desktop rather than the physical file system location.</p> <p><strong>DesktopDirectory</strong><br> The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder.</p> <p>What does it mean when it says <code>the logical Desktop rather than the physical file system location</code>? Also, what is a <code>virtual folder</code> in simple terms?</p> <p>In the newer .NET 4 version of the <a href="http://msdn.microsoft.com/en-us/library/system.environment.specialfolder%28v=VS.100%29.aspx" rel="noreferrer">documentation</a>, I noticed that they removed the <code>Desktop</code> entirely and only left <code>DesktopDirectory</code>. Why is this?</p>
5,612,650
2
0
null
2011-04-10 14:56:12.517 UTC
7
2022-03-14 17:40:35.26 UTC
null
null
null
null
699,978
null
1
49
c#|.net|desktop|special-folders
12,362
<h2>Answer to original question</h2> <p>A directory is a location in the file system. A folder is a location in the shell namespace. A directory is a kind of folder. A virtual folder is not necessarily backed by a directory. For example consider libraries or search folders.</p> <p>The user's desktop directory is a location in the file system. The desktop folder merges that with virtual items like all users items, recycle bin, shortcut to documents folder etc.</p> <h2>Additional question and answer pulled from comments</h2> <p><strong>Question</strong> (by <a href="https://stackoverflow.com/users/1518100/lei-yang">Lei Yang</a>) Why is the following always true:</p> <p><code>Environment.GetFolderPath(Environment.SpecialFolder.Desktop) == Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)</code></p> <p><strong>Answer</strong> (by <a href="https://stackoverflow.com/users/505088/david-heffernan">David Heffernan</a>):</p> <p>The answer addresses the two specific questions asked. It doesn't attempt to address the issue you raise. If you look at the two CSIDL enum values that correspond to the two .net special folder values you will see that they map to the same known folder guid. This suggests to me that in older versions of Windows there was a difference but that has changed.</p> <p>See <a href="https://docs.microsoft.com/en-us/windows/win32/shell/csidl" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/windows/win32/shell/csidl</a></p> <p><code>Ctrl+F</code> for &quot;FOLDERID_Desktop&quot;</p>
33,273,180
Create a PEM from a PPK file
<p>So there are plenty of tutorials on how to convert a <code>PEM</code> to a <code>PPK</code> using <code>puttyGen</code>. However my issue is that my windows machine had the only <code>PEM</code> copy and I converted it into a <code>PPK</code> and deleted it. Now I need to figure out how to convert a <code>PPK</code> into a <code>PEM</code> so that my mac can <code>ssh</code> into the server. I still have access to the server so I could also just make a new key if I had to, anyone know how to convert <code>PPK</code> to <code>PEM</code>?</p>
38,854,929
4
0
null
2015-10-22 03:58:05.023 UTC
17
2021-03-25 11:55:59.213 UTC
2021-03-25 11:55:59.213 UTC
null
10,625,611
null
805,779
null
1
56
ssh|putty|openssh|pem
100,504
<ol> <li><p>Install <em>PuttyTools</em></p> <pre><code>apt-get install putty-tools </code></pre></li> <li><p>Generate a <code>pem</code> file form the <code>ppk</code></p> <pre><code>puttygen server.ppk -O private-openssh -o server.pem </code></pre></li> </ol> <p>The file <em>server.pem</em> file will be saved on same location</p>
19,349,011
How to change authentication cookies after changing UserName of current user with asp.net identity
<p>Using asp.net identity version 1.0.0-rc1 with Entity Framework 6.0.0-rc1 (the ones that come with Visual Studio 2013 RC).</p> <p>Trying to give users an opportunity to change their <code>UserName</code>. There seems to be no function for that under <code>AuthenticationIdentityManager</code>, so I change the data using EF (get User object for current user, change UserName and save changes).</p> <p>The problem is that authentication cookies remain unchanged, and the next request fails as there is no such user.</p> <p>With forms authentication in the past I used the following code to solve this.</p> <pre><code>var formsAuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; var isPersistent = FormsAuthentication.Decrypt(formsAuthCookie.Value).IsPersistent; FormsAuthentication.SetAuthCookie(newUserName, isPersistent); </code></pre> <p>What should I do with asp.net identity to update the cookies?</p> <p><strong>UPDATE</strong></p> <p>The following code seems to update the authentication cookie.</p> <pre><code>var identity = new ClaimsIdentity(User.Identity); identity.RemoveClaim(identity.FindFirst(identity.NameClaimType)); identity.AddClaim(new Claim(identity.NameClaimType, newUserName)); AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = false}); </code></pre> <p>The remaining problem is: how to extract <code>IsPersistent</code> value from current authentication cookie?</p>
19,354,940
1
0
null
2013-10-13 18:57:27.467 UTC
12
2014-10-08 15:38:54.673 UTC
2014-10-08 15:38:54.673 UTC
null
244,353
null
1,234,444
null
1
18
asp.net-mvc-5|owin|asp.net-identity
16,264
<p><a href="https://stackoverflow.com/questions/19091157/how-do-you-login-authenticate-a-user-with-asp-net-mvc5-rtm-bits-using-aspnet-ide?rq=1">How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity?</a></p> <pre><code>private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } </code></pre> <p>For the RC1, You can use the similar code.</p> <pre><code>AuthenticationManager.SignOut(); IdentityManager.Authentication.SignIn(AuthenticationManager, user.UserId, isPersistent:false); </code></pre> <p>For persistent value, you need to access the authentication cookie and retrieve the status. </p> <p>Updated:</p> <p>Use appropriate AuthenticationType used in place of "Bearer". Also make sure while issuing the signin ticket, you are setting the AuthenticationProperties.IsPersistent.</p> <pre><code>bool isPersistent=false; var authContext = await Authentication.AuthenticateAsync("Bearer"); if (authContext != null) { var aProperties = authContext.Properties; isPersistent = aProperties.IsPersistent; } </code></pre>
19,590,197
How to define global parameters in OpenAPI?
<p>I'm preparing my API documentation by doing it per hand and not auto generated. There I have headers that should be sent to all APIs and don't know if it is possible to define parameters globally for the whole API or not?</p> <p>Some of these headers are static and some has to be set when call to API is made, but they are all the same in all APIs, I don't want to copy and paste parameters for each API and each method as this will not be maintainable in the future.</p> <p>I saw the static headers by API definition but there is no single document for how somebody can set them or use them.</p> <p>Is this possible at all or not?</p>
37,254,318
4
0
null
2013-10-25 12:42:41.73 UTC
7
2022-01-31 14:35:38.203 UTC
2020-07-28 13:07:04.113 UTC
null
113,116
null
438,727
null
1
29
swagger|openapi
23,974
<p><strong>If you're talking about header parameters sent by consumer when calling the API...</strong></p> <p>You can at least define them once and for all in parameters sections then only reference them when needed. In the example below:</p> <ul> <li><code>CommonPathParameterHeader</code>, <code>ReusableParameterHeader</code> and <code>AnotherReusableParameterHeader</code> are defined once and for all in <code>parameters</code>on the root of the document and can be used in any parameters list</li> <li><code>CommonPathParameterHeader</code>is referenced in <code>parameters</code> section of <code>/resources</code> and <code>/other-resources</code> paths, meaning that ALL operation of these paths need this header</li> <li><code>ReusableParameterHeader</code> is referenced in <code>get /resources</code> meaning that it's needed on this operation</li> <li>Same thing for <code>AnotherReusableParameterHeader</code> in <code>get /other-resources</code></li> </ul> <p>Example:</p> <pre><code>swagger: '2.0' info: version: 1.0.0 title: Header API description: A simple API to learn how you can define headers parameters: CommonPathParameterHeader: name: COMMON-PARAMETER-HEADER type: string in: header required: true ReusableParameterHeader: name: REUSABLE-PARAMETER-HEADER type: string in: header required: true AnotherReusableParameterHeader: name: ANOTHER-REUSABLE-PARAMETER-HEADER type: string in: header required: true paths: /resources: parameters: - $ref: '#/parameters/CommonPathParameterHeader' get: parameters: - $ref: '#/parameters/ReusableParameterHeader' responses: '200': description: gets some resources /other-resources: parameters: - $ref: '#/parameters/CommonPathParameterHeader' get: parameters: - $ref: '#/parameters/AnotherReusableParameterHeader' responses: '200': description: gets some other resources post: responses: '204': description: Succesfully created. </code></pre> <p><strong>If you're talking about header sent with each API response...</strong></p> <p>Unfortunately you cannot define reusable response headers. But at least you can define a reusable response containing these headers for common HTTP responses such as a 500 error.</p> <p>Example:</p> <pre><code>swagger: '2.0' info: version: 1.0.0 title: Header API description: A simple API to learn how you can define headers parameters: CommonPathParameterHeader: name: COMMON-PARAMETER-HEADER type: string in: header required: true ReusableParameterHeader: name: REUSABLE-PARAMETER-HEADER type: string in: header required: true AnotherReusableParameterHeader: name: ANOTHER-REUSABLE-PARAMETER-HEADER type: string in: header required: true paths: /resources: parameters: - $ref: '#/parameters/CommonPathParameterHeader' get: parameters: - $ref: '#/parameters/ReusableParameterHeader' responses: '200': description: gets some resources headers: X-Rate-Limit-Remaining: type: integer X-Rate-Limit-Reset: type: string format: date-time /other-resources: parameters: - $ref: '#/parameters/CommonPathParameterHeader' get: parameters: - $ref: '#/parameters/AnotherReusableParameterHeader' responses: '200': description: gets some other resources headers: X-Rate-Limit-Remaining: type: integer X-Rate-Limit-Reset: type: string format: date-time post: responses: '204': description: Succesfully created. headers: X-Rate-Limit-Remaining: type: integer X-Rate-Limit-Reset: type: string format: date-time '500': $ref: '#/responses/Standard500ErrorResponse' responses: Standard500ErrorResponse: description: An unexpected error occured. headers: X-Rate-Limit-Remaining: type: integer X-Rate-Limit-Reset: type: string format: date-time </code></pre> <p><strong>About OpenAPI (fka. Swagger) Next version</strong></p> <p>The OpenAPI spec (fka. Swagger) will evolve and include the definition of reusable response headers among other things (cf. <a href="https://github.com/OAI/OpenAPI-Specification/issues/563" rel="nofollow noreferrer">https://github.com/OAI/OpenAPI-Specification/issues/563</a>).</p>
32,922,914
Difference between Spring MVC and Spring Boot
<p>I have just started learning Spring. In my next step, I would like to develop bigger web applications. </p> <p>Now I am wondering if I should start with Spring Boot or Spring MVC. I have already read some stuff, but it is confusing because both look similar. </p> <p>So what are the differences between the two? </p>
32,923,000
11
0
null
2015-10-03 13:03:30.827 UTC
99
2020-08-11 07:33:35.793 UTC
2019-07-12 15:11:12.747 UTC
null
3,841,734
null
963,546
null
1
272
spring|spring-mvc|spring-boot
224,417
<ul> <li><strong>Spring MVC</strong> is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with <code>@Controller</code>, where you implement methods you can access using different HTTP requests. It has an equivalent <code>@RestController</code> to implement REST-based APIs.</li> <li><strong>Spring boot</strong> is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under <a href="https://spring.io/projects" rel="noreferrer">its umbrella</a>, as <em>spring-core</em>, <em>spring-data</em>, <em>spring-web</em> (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on).</li> </ul> <p>So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based <em>production-ready</em> project initializer. You might find useful visiting the <a href="https://stackoverflow.com/tags/spring-mvc/info">Spring MVC tag wiki</a> as well as the <a href="https://stackoverflow.com/tags/spring-boot/info">Spring Boot tag wiki</a> in SO.</p>
21,199,057
Force single line of text in element to fill width with CSS
<p>I have a <code>div</code> element that holds one line of text. How can I get this text to fill the width 100%?</p> <p><code>text-align:justify</code> is only working on elements with several lines of text, and has no effect on the <code>div</code> with single line. Manually adjusting the letter-spacing and word-spacing is ugly and ineffective. </p> <p>Are there any other alternatives?</p>
21,199,162
1
1
null
2014-01-18 01:49:12.913 UTC
7
2017-06-09 11:43:16.067 UTC
2017-06-09 11:43:16.067 UTC
null
4,084,003
null
2,200,440
null
1
31
html|css|text
72,408
<p>Try this:</p> <pre><code>div { text-align: justify; } div:after { content: ""; display: inline-block; width: 100%; } </code></pre> <p><a href="http://jsfiddle.net/B4Y2u/">jsFiddle</a></p> <p>Take a look <a href="http://blog.vjeux.com/2012/css/css-displaying-a-justified-line-of-text.html">here</a> for more info.</p>
46,961,097
Is the Dart VM still used?
<p>I've been using dart/flutter for a few projects, and I'm really enjoying it.</p> <p>I've read that when building a mobile app, dart builds a native app with native code. But I've also read that dart has its own VM for performance.</p> <p>What I'm trying to understand is if that VM is what is used when you build a mobile app, or is it building other code that it compiles for the native app. And if its doing something else, what is the dart VM still used for?</p>
46,988,481
3
0
null
2017-10-26 18:10:52.86 UTC
10
2019-02-10 16:01:12.83 UTC
null
null
null
null
92,694
null
1
32
dart|flutter
8,149
<p>Short answer: yes, Dart VM is still being used when you build your mobile app.</p> <p>Now longer answer: Dart VM has two different operation modes a JIT one and an AOT one. </p> <p>In the JIT mode Dart VM is capable of dynamically loading Dart source, parsing it and compiling it to native machine code on the fly to execute it. This mode is used when you develop your app and provides features such as debugging, hot reload, etc.</p> <p>In the AOT mode Dart VM does not support dynamic loading/parsing/compilation of Dart source code. It only supports loading and executing <em>precompiled</em> machine code. However even precompiled machine code still needs VM to execute, because VM provides <em>runtime system</em> which contains garbage collector, various native methods needed for <code>dart:*</code> libraries to function, runtime type information, dynamic method lookup, etc. This mode is used in your deployed app. </p> <p>Where does precompiled machine code for the AOT mode comes from? This code is generated by (a special mode of the) VM from your Flutter application when you build your app in the release mode.</p> <p>You can read more about how Dart VM executes Dart code <a href="https://mrale.ph/dartvm" rel="noreferrer">here</a>.</p>
46,989,568
Firestore - Get document collections
<p>I would automate the backup process of a firestore database.</p> <p>The idea is to loop over the root document to build a JSON tree, but I didn't find a way to get all collections available for a document. I guess it's possible as in firestore console we can see the tree.</p> <p>Any ideas?</p> <ul> <li>ref doc: <a href="https://firebase.google.com/docs/reference/js/firebase.firestore" rel="nofollow noreferrer">https://firebase.google.com/docs/reference/js/firebase.firestore</a></li> </ul>
47,019,860
5
1
null
2017-10-28 12:09:48.043 UTC
8
2021-11-02 01:27:36.19 UTC
2021-11-02 01:27:36.19 UTC
null
2,097,529
null
1,669,518
null
1
12
firebase|google-cloud-firestore
59,256
<p>If you are using the Node.js server SDK you can use the <code>getCollections()</code> method on <code>DocumentReference</code>: <a href="https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/DocumentReference#getCollections" rel="noreferrer">https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/DocumentReference#getCollections</a></p> <p>This method will return a promise for an array of <code>CollectionReference</code> objects which you can use to access the documents within the collections.</p>
8,481,048
How does allauth work when user logs in via social registration
<p>I have been trying to use <a href="https://github.com/pennersr/django-allauth" rel="nofollow">django-allauth</a> to provide Social registration, but I am having trouble configuring the profiles for the user. There is no documentation of django-allauth which tells </p> <ol> <li>how a django user account is created when a user logs in via a third party such as facebook</li> <li>What username is assigned to that user and what password is used.</li> <li>Certain third party providers such as Facebook provide a lot of information about the user such as their name, email etc. so how can we get them and save in the user account/profile </li> </ol> <p>If anybody has used allauth in their projects and can provide some details then it would be really helpful.</p>
9,180,767
1
0
null
2011-12-12 21:22:22.723 UTC
11
2022-05-30 21:33:35.327 UTC
2022-05-30 21:33:35.327 UTC
null
1,161,484
null
538,191
null
1
6
django|registration|django-allauth|user-profile
1,943
<p>I am using django_allauth in my project. </p> <p><strong>(1) How a django user account is created when a user logs in via a third party such as facebook ?</strong></p> <p>You should take a look at :<br/></p> <ol> <li><strong>your admin panel</strong> and see what happens when somebody logs in.<br/></li> <li><strong>allauth.facebook.views.login</strong> and try to track the login process</li> </ol> <p>It is something like this (in a few words):<br/></p> <ol> <li>When a user logs in your site via his Facebook credentials he is given an access token<br/></li> <li>This token is saved in the FACEBOOK_ACCESS_TOKENS table (you can see it in the admin panel)<br/></li> <li>With this access token and with the help of Facebook GraphApi we know his social_id<br/></li> <li>When we know his social_id - we can have his Facebook account from our database<br/></li> <li>If we haven't saved it in the db already - we save the Facebook account in the FACEBOOK_ACCOUNTS table (Facebook Accounts in the admin panel)<br/></li> <li>Then we create a user in the USERS table with the data present in the Facebook account. (you can see the new user in the Users section in the admin panel)<br/></li> </ol> <p><br/> <strong>(2) What username is assigned to that user and what password is used ?</strong></p> <p>As I mentioned before with the help of Facebook GraphApi we get the username of the Facebook user and it is assigned to the User profile as User.username <br/> <br/> <br/> <strong>(3) Certain third party providers such as Facebook provide a lot of information about the user such as their name, email etc. so how can we get them and save in the user account/profile?</strong></p> <p>Again - the Facebook GraphApi - it gets you the info you need.</p> <p>I have integrated django_allauth in my site and it is working properly. I will be happy to answer(if I can) if you have more questions. <br/> <br/> <br/> <strong>EDIT</strong> - For the avatar support...</p> <p>I think you have to take a look at the <a href="https://github.com/pennersr/django-allauth/" rel="noreferrer">django_allauth settings</a> and particularly in: </p> <pre>SOCIALACCOUNT_AVATAR_SUPPORT (= 'avatar' in settings.INSTALLED_APPS)</pre> <blockquote> <p>Enable support for django-avatar. When enabled, the profile image of the user is copied locally into django-avatar at signup.</p> </blockquote>
8,425,861
How do I upgrade a database without removing the data that the user input in the previous database?
<p>I am creating an app that needs a database. I created it using sqlite database browser, which means the app I created, imports the database I created into the phone.</p> <p>The app that I create requires that the user enter data into the database. When upgrading the database, I hope to retain the data that the user had input.</p> <p><br>My database helper code is below:</p> <pre><code>public class DatabaseHelper extends SQLiteOpenHelper { //The Android's default system path of your application database. private static String DB_PATH = "/data/data/test.test/databases/"; private static String DB_NAME = "TestDatabase"; private static final int DB_VERSION = 1; private SQLiteDatabase myDatabase; private final Context myContext; /** * # Constructor # * Takes and keeps a reference of the passed context in order to access to the application assets and resources. * @param context */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); this.myContext = context; }//constructor /** * # Create Database # * Creates a empty database on the system and rewrites it with your own database. */ public void createDatabase() throws IOException { boolean dbExist = checkDatabase(); if(dbExist) { //do nothing - database already exist }//if else { //By calling this method and empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. this.getReadableDatabase(); try { copyDatabase(); } catch (IOException e) { throw new Error("Error copying database"); }//catch }//else }//createDatabase private boolean checkDatabase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch(SQLiteException e) { //database does't exist yet. }//catch if(checkDB != null) { checkDB.close(); }//if return checkDB != null ? true : false; }//checkDatabase private void copyDatabase() throws IOException { //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))&gt;0) { myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); }//copyDatabase // # open database # public void openDatabase() throws SQLException { //Open the database String myPath = DB_PATH + DB_NAME; myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); }//openDatabase @Override public synchronized void close() { if(myDatabase != null) myDatabase.close(); super.close(); }//close @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public List&lt;String&gt; selectData (String tableName, String [] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) { List&lt;String&gt; list = new ArrayList&lt;String&gt;(); Cursor cursor = this.myDatabase.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy); if (cursor.moveToFirst()) { do { list.add(cursor.getString(0)); } while (cursor.moveToNext()); } if (cursor != null &amp;&amp; !cursor.isClosed()) { cursor.close(); } return list; }//selectData public void insertData (String tableName, String nullColumnHack, ContentValues values) { try { myDatabase.insert(tableName, nullColumnHack, values); } catch (Exception e) { Log.e("Error :","unable to insert data"); }//catch }//insertData //edit row public void updateData (String tableName, ContentValues values, String whereClause, String[] whereArgs) { try { myDatabase.update(tableName, values, whereClause, whereArgs); } catch (Exception e) { Log.e("Error :","unable to update data"); }//catch }//updateData public void deleteRow (String tableName, String whereClause, String[] whereArgs) { try { myDatabase.delete(tableName, whereClause, whereArgs); } catch (Exception e) { Log.e("Error :","unable to delete row"); }//catch }//deleteRow } </code></pre> <p>*note: My database consist of more than one table. Two tables require user input. The others don't.</p> <p>I hope that real answer could be given, instead of giving website that is not in the exact situation that I have, as I get confused easily.</p>
8,426,128
1
0
null
2011-12-08 03:40:19.62 UTC
12
2011-12-08 04:51:09.627 UTC
2011-12-08 04:51:09.627 UTC
null
1,007,364
null
1,036,781
null
1
12
android|database|sqlite|upgrade
11,270
<p>You should add some code into the <code>onUpgrade</code> method. With that, you can check the oldVersion and the newVersion and do the proper ALTER TABLE statements. As you can see, the current version is 23 and the check code checks what is the old version. If version 22 it does just the v22 statements, but if version 21 it does both v21 AND v22 statements. This is part of the Google I/O app:</p> <pre><code>private static final int VER_LAUNCH = 21; private static final int VER_SESSION_FEEDBACK_URL = 22; private static final int VER_SESSION_NOTES_URL_SLUG = 23; private static final int DATABASE_VERSION = VER_SESSION_NOTES_URL_SLUG; ... @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { case VER_LAUNCH: // Version 22 added column for session feedback URL. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT"); version = VER_SESSION_FEEDBACK_URL; case VER_SESSION_FEEDBACK_URL: // Version 23 added columns for session official notes URL and slug. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_NOTES_URL + " TEXT"); db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_SLUG + " TEXT"); version = VER_SESSION_NOTES_URL_SLUG; } Log.d(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { Log.w(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); // ... delete all your tables ... onCreate(db); } } </code></pre>
8,550,832
Accessing logged in user in Symfony2 action and template
<p>I am using Doctrine as Auth provider in my symfony2 app. How can I access authenticated user in action or template?</p>
8,551,051
2
0
null
2011-12-18 09:26:42.077 UTC
12
2017-11-13 00:42:39.58 UTC
null
null
null
null
720,943
null
1
29
symfony
20,119
<p>In your templates, you can do:</p> <pre><code>{{ app.user }} </code></pre> <p>And in your controller, if you extend the base controller provided by the framework bundle, you can do:</p> <pre><code>$this-&gt;getUser(); </code></pre> <p>Anyway, you can access it from the service container:</p> <pre><code>$securityContext = $container-&gt;get('security.context'); $token = $securityContext-&gt;getToken(); $user = $token-&gt;getUser(); </code></pre>
8,554,568
Add a big buffer to a pipe between two commands
<p>Given a bash command line of the form</p> <pre><code>commandA | commandB </code></pre> <p>I want to add a buffer of size ~1MB that sits between <code>commandA</code> and <code>commandB</code>. I would expect to be able to do this with something of the form</p> <pre><code>commandA | BUFFER | commandB </code></pre> <p>but what is the command to use for <code>BUFFER</code>?</p> <p>Remark: I want to do this in order to decouple the two commands to make them parallelize better. The problem is that <code>commandB</code> processes data in large chunks, which currently means that <code>commandA</code> blocks until <code>commandB</code> is done with a chunk. So everything runs sequentially :-(</p>
8,554,595
5
0
null
2011-12-18 20:28:57.59 UTC
7
2021-03-29 16:11:41.76 UTC
2017-05-21 16:36:04.903 UTC
null
1,104,870
null
1,104,870
null
1
30
bash|unix
16,701
<p>BUFFER is called buffer. (man 1 buffer, maybe after apt-get install buffer)</p>
30,734,509
How to pass optional parameters while omitting some other optional parameters?
<p>Given the following signature:</p> <pre><code>export interface INotificationService { error(message: string, title?: string, autoHideAfter?: number); } </code></pre> <p>How can I call the function <code>error()</code> <em>not</em> specifying the <code>title</code> parameter, but setting <code>autoHideAfter</code> to say <code>1000</code>?</p>
30,734,778
12
0
null
2015-06-09 14:09:09.877 UTC
43
2022-07-31 15:53:25.473 UTC
2019-09-03 21:06:32.91 UTC
null
3,345,644
null
1,157,814
null
1
431
typescript
445,938
<p>As specified in the <a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters" rel="noreferrer">documentation</a>, use <code>undefined</code>:</p> <pre><code>export interface INotificationService { error(message: string, title?: string, autoHideAfter? : number); } class X { error(message: string, title?: string, autoHideAfter?: number) { console.log(message, title, autoHideAfter); } } new X().error(&quot;hi there&quot;, undefined, 1000); </code></pre> <p><a href="http://www.typescriptlang.org/Playground#src=export%20interface%20INotificationService%20%7B%0A%20%20%20%20error(message%3A%20string%2C%20title%3F%3A%20string%2C%20autoHideAfter%3F%20%3A%20number)%3B%0A%7D%0A%0Aclass%20X%20%7B%0A%09error(message%3A%20string%2C%20title%3F%3A%20string%2C%20autoHideAfter%3F%3A%20number)%20%7B%0A%09%09console.log(message%2C%20title%2C%20autoHideAfter)%3B%0A%09%7D%0A%7D%0A%0Anew%20X().error(%22hi%20there%22%2C%20undefined%2C%201000)%3B" rel="noreferrer">Playground link</a>.</p>
362,360
Image resize in Grails
<p>I am developing a Web Album using Grails and for image processing, I am using grails-image-tools plugin. I need a functionality to resize the images if the uploaded images size is too big (for eg: more than 600 * 840 ) . In this case I need to resize this image to 600 * 840). What is the most efficient way to do this? Thanks a lot.</p>
362,411
3
0
null
2008-12-12 10:07:58.15 UTC
15
2019-05-29 18:58:46.357 UTC
2012-10-18 15:58:41.457 UTC
null
517,236
Omnipotent
11,193
null
1
13
java|grails|image-processing|frameworks
10,062
<pre><code>import java.awt.Image as AWTImage import java.awt.image.BufferedImage import javax.swing.ImageIcon import javax.imageio.ImageIO as IIO import java.awt.Graphics2D static resize = { bytes, out, maxW, maxH -&gt; AWTImage ai = new ImageIcon(bytes).image int width = ai.getWidth( null ) int height = ai.getHeight( null ) def limits = 300..2000 assert limits.contains( width ) &amp;&amp; limits.contains( height ) : 'Picture is either too small or too big!' float aspectRatio = width / height float requiredAspectRatio = maxW / maxH int dstW = 0 int dstH = 0 if (requiredAspectRatio &lt; aspectRatio) { dstW = maxW dstH = Math.round( maxW / aspectRatio) } else { dstH = maxH dstW = Math.round(maxH * aspectRatio) } BufferedImage bi = new BufferedImage(dstW, dstH, BufferedImage.TYPE_INT_RGB) Graphics2D g2d = bi.createGraphics() g2d.drawImage(ai, 0, 0, dstW, dstH, null, null) IIO.write( bi, 'JPEG', out ) } </code></pre>
896,473
POCO's, DTO's, DLL's and Anaemic Domain Models
<p>I was looking at the <a href="https://stackoverflow.com/questions/725348/poco-vs-dto">differences between POCO and DTO</a> (It appears that POCO's are dto's with behaviour (methods?))and came across <a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html" rel="nofollow noreferrer">this article</a> by Martin Fowler on the anaemic domain model. </p> <p>Through lack of understanding, I think I have created one of these anaemic domain models.</p> <p>In one of my applications I have my business domain entities defined in a 'dto' dll. They have a lot of properties with getter's and setter's and not much else. My business logic code (populate, calculate) is in another 'bll' dll, and my data access code is in a 'dal' dll. 'Best practice' I thought.</p> <p>So typically I create a dto like so:</p> <pre><code>dto.BusinessObject bo = new dto.BusinessObject(...) </code></pre> <p>and pass it to the bll layer like so:</p> <pre><code>bll.BusinessObject.Populate(bo); </code></pre> <p>which in turn, performs some logic and passes it to the dal layer like so:</p> <pre><code>dal.BusinessObject.Populate(bo); </code></pre> <p>From my understanding, to make my dto's into POCO's I need to make the business logic and behaviour (methods) part of the object. So instead of the code above it is more like:</p> <pre><code>poco.BusinessObject bo = new poco.BusinessObject(...) bo.Populate(); </code></pre> <p>ie. I am calling the method on the object rather than passing the object to the method.</p> <p>My question is - how can I do this and still retain the 'best practice' layering of concerns (separate dll's etc...). Doesn't calling the method on the object mean that the method must be defined in the object?</p> <p>Please help my confusion.</p>
911,874
3
0
null
2009-05-22 05:22:18.66 UTC
15
2010-11-19 07:10:40.38 UTC
2017-05-23 12:25:03.437 UTC
null
-1
null
30,639
null
1
22
dll|poco|data-access-layer|dto|bll
5,400
<p>Typically, you don't want to introduce persistence into your domain objects, since it is not part of that business model (an airplane does not construct itself, it flies passengers/cargo from one location to another). You should use the <a href="http://www.martinfowler.com/eaaCatalog/repository.html" rel="noreferrer">repository pattern</a>, an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="noreferrer">ORM framework</a>, or some other data access pattern to manage the persistent storage and retreival of an object's <em>state</em>.</p> <p>Where the anemic domain model comes in to play is when you're doing things like this:</p> <pre><code>IAirplaneService service = ...; Airplane plane = ...; service.FlyAirplaneToAirport(plane, "IAD"); </code></pre> <p>In this case, the management of the airplane's state (whether it's flying, where it's at, what's the departure time/airport, what's the arrival time/airport, what's the flight plan, etc) is delegated to something external to the plane... the AirplaneService instance.</p> <p>A POCO way of implementing this would be to design your interface this way:</p> <pre><code>Airplane plane = ...; plane.FlyToAirport("IAD"); </code></pre> <p>This is more discoverable, since developers know where to look to make an airplane fly (just tell the airplane to do it). It also allows you to ensure that state is <em>only</em> managed internally. You can then make things like current location read-only, and ensure that it's only changed in one place. With an anemic domain object, since state is set externally, discovering where state is changed becomes increasingly difficult as the scale of your domain increases.</p>
1,165,648
Getting Original Path from FileStream
<p>Given a <code>System.IO.FileStream</code> object, how can I get the original path to the file it's providing access to?</p> <p>For example, in the <code>MyStreamHandler()</code> function below, I want to get back the path of the file that created the <code>FileStream</code>:</p> <pre><code>public static void Main() { string path = @"c:\temp\MyTest.txt"; FileStream fs = File.Create(path)); MyStreamHandler(fs); MyOtherStreamHandler(fs); fs.Close(); fs.Dispose(); } private static void MyStreamHandler(FileStream fs) { // Get the originating path of 'fs' } private static void MyOtherStreamHandler(FileStream fs) { } </code></pre>
1,165,676
3
0
null
2009-07-22 14:24:41.683 UTC
1
2020-07-07 10:42:18.557 UTC
null
null
null
user116592
null
null
1
48
c#|path|filestream|.net
47,582
<p>The FileStream's Name property.</p> <p>See documentation in <a href="https://msdn.microsoft.com/en-us/library/system.io.filestream.name(v=vs.110).aspx" rel="noreferrer">MSDN</a></p>
741,390
Unit testing Scala
<p>I just recently started learning the Scala language and would like to do it in <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer">TDD</a>-way. Could you share your experiences on the unit testing frameworks there are for Scala and the pros/cons of them.</p> <p>I'm using IntelliJ IDEA for Scala development, so it would be nice to be able to run the tests with IDE-support.</p>
741,532
3
0
null
2009-04-12 07:18:22.463 UTC
9
2016-06-03 17:00:08.687 UTC
null
null
null
null
51,445
null
1
55
unit-testing|scala|tdd
22,000
<p>Have you looked at <a href="http://www.artima.com/scalatest/" rel="noreferrer">ScalaTest</a> ?</p> <p>I've not used it, but it comes from Bill Venners and co at Artima, and consequently I suspect it'll do the job. It doesn't appear to have IDE integration, however.</p> <p><a href="http://www.theserverside.com/blogs/thread.tss?thread_id=48085" rel="noreferrer">This blog entry</a> is a little old, but suggests that TestNG is the best option for testing Scala. TestNG will certainly have IDE integrations.</p> <p>EDIT: I've just realised that I wrote this answer in 2009, and the world has moved on (!). I am currently using ScalaTest, the IDE integration works fine, and I can strongly recommend it. In particular the <a href="http://www.scalatest.org/user_guide/using_matchers" rel="noreferrer">matcher DSL</a> works very nicely</p>
22,408,150
Get thumbprint of a certificate
<p>I want to store the thumbprint of a certificate in a variable like this:</p> <pre><code>$thumbprint = 0F273F77B77E8F60A8B5B7AACD032FFECEF4776D </code></pre> <p>But my command output is:</p> <pre><code>Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -match &quot;XXXXX&quot;} Thumbprint Subject ---------- ------- 0F273F77B77E8F60A8B5B7AACD032FFECEF4776D CN=XXXXXXX, OU=YYYYYYY </code></pre> <p>I need to remove everything but the thumbprint of that output</p> <p>Any idea?</p>
22,408,208
4
0
null
2014-03-14 14:41:57.25 UTC
null
2020-09-29 10:27:15.763 UTC
2020-09-29 10:27:15.763 UTC
null
336,648
null
1,783,187
null
1
18
powershell|certificate
54,937
<p>All you have to do is wrap the command in parentheses, and then use dot-notation to access the <code>Thumbprint</code> property.</p> <p>Try this out:</p> <pre><code>$Thumbprint = (Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -match "XXXXXXX"}).Thumbprint; Write-Host -Object "My thumbprint is: $Thumbprint"; </code></pre> <p>If you get multiple certificates back from your command, then you'll have to concatenate the thumbprints into a single string, perhaps by using the <code>-join</code> PowerShell operator.</p> <pre><code>$Thumbprint = (Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -match "XXXXXXX"}).Thumbprint -join ';'; Write-Host -Object "My thumbprints are: $Thumbprint"; </code></pre>
36,247,382
Remove HTML tags from Strings on laravel blade
<p>I want remove HTML tags (all) from a string on laravel blade ...</p> <p>code</p> <pre><code>{!! \Illuminate\Support\Str::words($subject-&gt;body, 5,'...') !!} </code></pre> <p>output (example)</p> <pre><code>&lt;p&gt;hassen zouari&lt;/p&gt; </code></pre> <p>I want that it be like this</p> <pre><code>hassen zouari </code></pre>
36,247,435
10
1
null
2016-03-27 12:34:36.643 UTC
4
2022-09-24 19:15:55.8 UTC
null
null
null
null
6,100,646
null
1
47
laravel|laravel-4|laravel-5
95,219
<p>Try to use <code>strip_tags()</code> function:</p> <p><a href="http://php.net/manual/en/function.strip-tags.php" rel="noreferrer">http://php.net/manual/en/function.strip-tags.php</a></p> <p><strong>Update:</strong> Try to do something like this in a controller:</p> <pre><code>$taglessBody = strip_tags($subject-&gt;body); </code></pre> <p>Then pass this variable into a blade template and use it instead of <code>$subject-&gt;body</code>.</p>
20,367,402
Android 4.4 Step Detector and Counter
<p>Is there any documentation around Android 4.4 KitKat's (well specifically Nexus 5 for now) step detector and counter APIs? I tried to search a lot but did not find anything.</p> <p>I am planning to try my hands on these new concepts and want to use the API but there's nothing around it on the Internet.</p>
20,367,627
2
0
null
2013-12-04 05:13:46.253 UTC
4
2016-08-23 07:21:59.453 UTC
2013-12-04 16:45:29.303 UTC
null
136,445
null
906,577
null
1
14
android|android-4.4-kitkat
43,677
<p>I found an example for you, hope it helps in someway, the sensor explanation on the API page is pretty straight forward too..</p> <p>API Page: <a href="http://developer.android.com/about/versions/android-4.4.html#UserInput" rel="noreferrer">http://developer.android.com/about/versions/android-4.4.html#UserInput</a></p> <p>Blog Post: <a href="http://theelfismike.wordpress.com/2013/11/10/android-4-4-kitkat-step-detector-code/" rel="noreferrer">http://theelfismike.wordpress.com/2013/11/10/android-4-4-kitkat-step-detector-code/</a> Github Project referenced in the blog: <a href="https://github.com/theelfismike/android-step-counter" rel="noreferrer">https://github.com/theelfismike/android-step-counter</a></p>
35,810,172
webpack is not recognized as a internal or external command,operable program or batch file
<p>I am Learning React.js and i am using windows 8 OS.i have navigate to my root folder</p> <pre><code>1.Created the package.json file by npm init 2. install webpack by npm install -S webpack.now webpack has been downloaded to my modules folder 3. install webpack globally by typing npm install webpack -g 4. i am also having a webpack.config.js in my root folder which contains the source and ouput directory 5. when i type the webpack command i am getting the below error. </code></pre> <p><strong>webpack is not recognized as a internal or external command,operable program or batch file</strong></p>
35,817,969
25
1
null
2016-03-05 04:52:40.24 UTC
29
2022-05-06 10:25:40.75 UTC
null
null
null
null
5,984,184
null
1
166
npm|webpack
267,250
<p>I had this issue for a long time too. (webpack installed globally etc. but still not recognized) It turned out that I haven't specified enviroment variable for npm (where is file webpack.cmd sitting) So I add to my Path variable</p> <pre><code>%USERPROFILE%\AppData\Roaming\npm\ </code></pre> <p>If you are using Powershell, you can type the following command to effectively add to your path :</p> <pre><code>[Environment]::SetEnvironmentVariable(&quot;Path&quot;, &quot;$env:Path;%USERPROFILE%\AppData\Roaming\npm\&quot;, &quot;User&quot;) </code></pre> <p><strong>IMPORTANT :</strong> Don't forget to close and re-open your powershell window in order to apply this.</p>
41,258,391
TensorBoard Embedding Example?
<p>I'm looking for a tensorboard embedding example, with iris data for example like the embedding projector <a href="http://projector.tensorflow.org/" rel="noreferrer">http://projector.tensorflow.org/</a></p> <p>But unfortunately i couldn't find one. Just a little bit information about how to do it in <a href="https://www.tensorflow.org/how_tos/embedding_viz/" rel="noreferrer">https://www.tensorflow.org/how_tos/embedding_viz/</a></p> <p>Does someone knows a basic tutorial for this functionality?</p> <p>Basics:</p> <p>1) Setup a 2D tensor variable(s) that holds your embedding(s).</p> <pre><code>embedding_var = tf.Variable(....) </code></pre> <p>2) Periodically save your embeddings in a LOG_DIR.</p> <p>3) Associate metadata with your embedding.</p>
41,262,360
7
0
null
2016-12-21 08:35:29.703 UTC
11
2019-11-04 09:43:55.65 UTC
2016-12-21 11:47:58.003 UTC
null
1,909,965
null
1,909,965
null
1
22
tensorflow|embedding|tensorboard
25,593
<p>It sounds like you want to get the Visualization section with t-SNE running on TensorBoard. As you've described, the API of Tensorflow has only provided the bare essential commands in the <a href="https://www.tensorflow.org/how_tos/embedding_viz/" rel="nofollow noreferrer">how-to document</a>.</p> <p><strong>I’ve uploaded my working solution with the MNIST dataset to <a href="https://github.com/normanheckscher/mnist-tensorboard-embeddings/blob/master/mnist_t-sne.py" rel="nofollow noreferrer">my GitHub repo</a>.</strong></p> <p>Yes, it is broken down into three general steps:</p> <ol> <li>Create metadata for each dimension.</li> <li>Associate images with each dimension.</li> <li>Load the data into TensorFlow and save the embeddings in a LOG_DIR. </li> </ol> <p>Only generic details are inculded with the TensorFlow r0.12 release. There is no full code example that I’m aware of within the official source code. </p> <p>I found that there were two tasks involved that were not documented in the how to.</p> <ol> <li>Preparing the data from the source</li> <li>Loading the data into a <code>tf.Variable</code></li> </ol> <p>While TensorFlow is designed for the use of GPUs, in this situation I opted to generate the t-SNE visualization with the CPU as the process took up more memory than my MacBookPro GPU has access to. API access to the MNIST dataset is included with TensorFlow, so I used that. The MNIST data comes as a structured a numpy array. Using the <code>tf.stack</code> function enables this dataset to be stacked into a list of tensors which can be embedded into a visualization. The following code contains is how I extracted the data and setup the TensorFlow embedding variable. </p> <pre><code>with tf.device("/cpu:0"): embedding = tf.Variable(tf.stack(mnist.test.images[:FLAGS.max_steps], axis=0), trainable=False, name='embedding') </code></pre> <p>Creating the metadata file was perfomed with the slicing of a numpy array.</p> <pre><code>def save_metadata(file): with open(file, 'w') as f: for i in range(FLAGS.max_steps): c = np.nonzero(mnist.test.labels[::1])[1:][0][i] f.write('{}\n'.format(c)) </code></pre> <p>Having an image file to associate with is as described in the how-to. I've uploaded a png file of the first 10,000 MNIST images to <a href="https://github.com/normanheckscher/mnist-tensorboard-embeddings/blob/master/mnist_t-sne.py" rel="nofollow noreferrer">my GitHub</a>.</p> <p>So far TensorFlow works beautifully for me, it’s computationaly quick, well documented and the API appears to be functionally complete for anything I am about to do for the moment. I look forward to generating some more visualizations with custom datasets over the coming year. This post was edited from <a href="http://www.normansoft.com/blog/embedding-tensorboard-visua.html" rel="nofollow noreferrer">my blog</a>. Best of luck to you, please let me know how it goes. :)</p>
5,960,455
How to add check box inside combobox in c#
<p>I want to add check box inside comboBox in C#. My purpose is that the user can select multiple values from one ComboBox ( Check all and Uncheck all ).</p> <p>Please Help</p>
5,960,488
3
5
null
2011-05-11 07:01:48.577 UTC
null
2019-09-16 07:56:26.673 UTC
null
null
null
null
434,910
null
1
10
c#|combobox|checkbox
66,780
<p>You have to extend the ComboBox control by providing your own rendering strategy, and "manually" adding a CheckBox.</p> <p>Theses open source project are ready to use :</p> <p><a href="http://www.codeproject.com/KB/combobox/CheckComboBox.aspx" rel="noreferrer">http://www.codeproject.com/KB/combobox/CheckComboBox.aspx</a> <a href="http://www.codeproject.com/KB/combobox/extending_combobox.aspx" rel="noreferrer">http://www.codeproject.com/KB/combobox/extending_combobox.aspx</a></p>
5,736,987
How to switch to a different remote branch in git
<p>I have 3 local and 3 remote branches and want to be on the same branch on both.</p> <p><strong>on local:</strong></p> <pre><code>git branch A * B master git branch -r origin/A origin/B origin/master </code></pre> <p><strong>on remote:</strong></p> <pre><code>git branch A B * master </code></pre> <p>I am able to commit, push and pull B but my update hook deploys master instead of B, I suppose because the remote branch is still set to master. I created branch B using:</p> <pre><code>git branch B git checkout B git push origin B </code></pre>
5,737,084
3
0
null
2011-04-20 21:41:46.263 UTC
10
2021-04-13 08:36:17.757 UTC
null
null
null
null
234,104
null
1
26
git
61,715
<p>As far as I know, there's no way to change a remote's current branch with <code>git push</code>. Pushing will just copy your local changes up into that repository. Typically remotes you push to should be <code>--bare</code>, without a working directory (and thus no "current branch").</p>
5,911,320
How can I count unique pairs of values in SQL?
<p>With the following sql statement I can get all unique values with their counts for a given column:</p> <pre><code>select column, count(column) as count from table group by column order by count desc; </code></pre> <p>How would I get all unique pairs of values with counts. For instance if I had a table of with columns first_name and last_name, I might find results something like this:</p> <blockquote> <p>first_name | last_name | count</p> <p>John | Smith | 42</p> <p>John | Johnson | 39</p> <p>David | Smith | 37</p> </blockquote> <p>etc...</p> <p>Can I do this in basic SQL? I generally use MySQL, but I assume whatever solution you come up with should be translatable to any db.</p>
5,911,347
4
0
null
2011-05-06 12:20:41.053 UTC
3
2013-08-02 06:01:15.2 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
240,566
null
1
25
sql|count
52,340
<p>You've almost got it correct... You just add an additional <code>GROUP BY</code> column like so:</p> <pre><code>SELECT [first_name], [last_name], COUNT(*) AS [Count] FROM [Table] GROUP BY [first_name], [last_name] ORDER BY [Count] DESC; </code></pre>
6,081,170
Update a DataTable in C# without using a loop?
<p>Let suppose there are three columns in my DataTable</p> <ol> <li><p>code</p></li> <li><p>name</p></li> <li><p>color</p></li> </ol> <p>If I know the code and name, how can I update the color of that specific row whose code and name match my criteria? I want to do this <strong>without using Loops!</strong></p>
6,081,238
5
3
null
2011-05-21 10:36:55.667 UTC
9
2020-09-10 14:45:30.63 UTC
2017-04-04 12:47:25.687 UTC
null
271,200
null
538,789
null
1
10
c#|.net|datatable
82,502
<p>You can use LINQ:</p> <pre><code>DataRow dr = datatable.AsEnumerable().Where(r =&gt; ((string)r["code"]).Equals(someCode) &amp;&amp; ((string)r["name"]).Equals(someName)).First(); dr["color"] = someColor; </code></pre> <p>Of course I'm assuming all those criteria are strings. You should change the casts to the correct types.</p>
52,502,189
Java 11 package javax.xml.bind does not exist
<p>I'm trying to deserialize XML data into a Java content tree using <a href="https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/package-summary.html" rel="noreferrer">JAXB</a>, validating the XML data as it is unmarshalled:</p> <pre class="lang-java prettyprint-override"><code>try { JAXBContext context = JAXBContext.newInstance("com.acme.foo"); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); FooObject fooObj = (FooObject) unmarshaller.unmarshal(new File("foo.xml")); } catch (UnmarshalException ex) { ex.printStackTrace(); } catch (JAXBException ex) { ex.printStackTrace(); } </code></pre> <p>When I build the project with <strong>Java 8</strong> it's fine, but building it with <strong>Java 11</strong> fails with a compilation error:</p> <pre><code>package javax.xml.bind does not exist </code></pre> <p>How do I fix the issue?</p>
52,502,208
1
2
null
2018-09-25 15:49:36.153 UTC
60
2022-06-07 08:31:19.32 UTC
2020-03-25 15:55:00.017 UTC
null
3,301,492
null
3,301,492
null
1
314
java|jakarta-ee|jaxb|java-11
410,088
<p>According to the <a href="https://www.oracle.com/java/technologies/javase/11-relnote-issues.html#JDK-8190378" rel="noreferrer">release-notes</a>, Java 11 removed the Java EE modules:</p> <pre><code>java.xml.bind (JAXB) - REMOVED </code></pre> <ul> <li>Java 8 - OK</li> <li>Java 9 - DEPRECATED</li> <li>Java 10 - DEPRECATED</li> <li>Java 11 - REMOVED</li> </ul> <p>See <a href="http://openjdk.java.net/jeps/320#Java-EE-modules" rel="noreferrer">JEP 320</a> for more info.</p> <p>You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-core&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; </code></pre> <h2>Jakarta EE 8 update (Mar 2020)</h2> <p>Instead of using old JAXB modules you can fix the issue by using <a href="https://search.maven.org/artifact/jakarta.xml.bind/jakarta.xml.bind-api" rel="noreferrer">Jakarta XML Binding</a> from <a href="https://jakarta.ee/specifications/xml-binding/2.3/" rel="noreferrer">Jakarta EE 8</a>:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jakarta.xml.bind-api&lt;/artifactId&gt; &lt;version&gt;2.3.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt; &lt;version&gt;2.3.3&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <h2>Jakarta EE 9 update (Nov 2020)</h2> <p>Use latest release of Jakarta XML Binding <a href="https://jakarta.ee/specifications/xml-binding/3.0/" rel="noreferrer">3.0</a>:</p> <ul> <li>Jakarta EE 9 API <a href="https://search.maven.org/artifact/jakarta.xml.bind/jakarta.xml.bind-api" rel="noreferrer">jakarta.xml.bind-api</a></li> <li>compatible implementation <a href="https://search.maven.org/artifact/com.sun.xml.bind/jaxb-impl" rel="noreferrer">jaxb-impl</a></li> </ul> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jakarta.xml.bind-api&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p><strong>Note:</strong> Jakarta EE 9 adopts new API package namespace <code>jakarta.xml.bind.*</code>, so update import statements:</p> <pre><code>javax.xml.bind -&gt; jakarta.xml.bind </code></pre> <h2>Jakarta EE 10 update (Jun 2022)</h2> <p>Use latest release of Jakarta XML Binding <a href="https://jakarta.ee/specifications/xml-binding/4.0/" rel="noreferrer">4.0</a> (requires Java SE 11 or newer):</p> <ul> <li>Jakarta EE 10 API <a href="https://search.maven.org/artifact/jakarta.xml.bind/jakarta.xml.bind-api" rel="noreferrer">jakarta.xml.bind-api</a></li> <li>compatible implementation <a href="https://search.maven.org/artifact/com.sun.xml.bind/jaxb-impl" rel="noreferrer">jaxb-impl</a></li> </ul> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jakarta.xml.bind-api&lt;/artifactId&gt; &lt;version&gt;4.0.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt; &lt;version&gt;4.0.0&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; </code></pre>
5,671,519
arranging div one below the other
<p>I have two inner divs which are nested inside a wrapper div. I want the two inner div's to get arranged one below the other. But as of now they are getting arranged on the same line. </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-css lang-css prettyprint-override"><code>#wrapper{ margin-left:auto; margin-right:auto; height:auto; width:auto; } #inner1{ float:left; } #inner2{ float:left; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div id="wrapper"&gt; &lt;div id="inner1"&gt;This is inner div 1&lt;/div&gt; &lt;div id="inner2"&gt;This is inner div 2&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
5,671,535
5
1
null
2011-04-15 01:28:29.587 UTC
10
2021-02-16 10:44:54.147 UTC
2019-07-01 23:07:45.47 UTC
null
3,994,240
null
544,079
null
1
58
html|css
215,915
<p>Try a clear: left on #inner2. Because they are both being set to float it should cause a line return.</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-css lang-css prettyprint-override"><code>#inner1 { float:left; } #inner2{ float:left; clear: left; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper"&gt; &lt;div id="inner1"&gt;This is inner div 1&lt;/div&gt; &lt;div id="inner2"&gt;This is inner div 2&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
6,107,465
Remove Datepicker Function dynamically
<p>I want to remove datepicker function depending on the dropdownlist selected value. I try the following codes, but it still shows the calendar when I put the cursor in the text box. Please give me a suggestion.</p> <pre><code>$("#ddlSearchType").change(function () { if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") { $("#txtSearch").datepicker(); } else { $("#txtSearch").datepicker("option", "disabled", true); } }); </code></pre> <p><img src="https://i.stack.imgur.com/s3VMd.jpg" alt="enter image description here"></p>
6,107,981
6
4
null
2011-05-24 08:09:29.197 UTC
7
2018-03-15 11:18:37.377 UTC
2014-01-21 09:23:49.94 UTC
null
87,015
null
296,074
null
1
45
javascript|jquery|jquery-ui|jquery-ui-datepicker
120,591
<p>You can try the enable/disable methods instead of using the option method:</p> <pre><code>$("#txtSearch").datepicker("enable"); $("#txtSearch").datepicker("disable"); </code></pre> <p>This disables the entire textbox. So may be you can use <a href="http://jqueryui.com/demos/datepicker/#method-destroy" rel="noreferrer"><code>datepicker.destroy()</code></a> instead: </p> <pre><code>$(document).ready(function() { $("#ddlSearchType").change(function() { if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") { $("#txtSearch").datepicker(); } else { $("#txtSearch").datepicker("destroy"); } }).change(); }); </code></pre> <p><a href="http://jsfiddle.net/salman/faZ9u/" rel="noreferrer">Demo here</a>.</p>
5,834,613
Failed to connect to MySQL at 127.0.0.1 in MySQL Workbench. System error 61
<p>I'm running into a little trouble with MySQL Workbench. This is the situation, I'm developing a database to query it remotely from Android devices. This is the first time I use MySQL Workbench, so I've followed this tutorial:</p> <p><a href="http://net.tutsplus.com/tutorials/databases/visual-database-creation-with-mysql-workbench/" rel="nofollow">http://net.tutsplus.com/tutorials/databases/visual-database-creation-with-mysql-workbench/</a></p> <p>I have no problem creating the EER diagram and generating the SQL script. The problem comes when I try to connect to a MySQL server. I get this error: </p> <p>"<strong><em>Failed to Connect to MySQL at 127.0.0.1:3306 with user root. Lost connection to MySQL server at 'reading initial communication packet', system error: 61</em></strong>"</p> <p><a href="http://img101.imageshack.us/i/capturadepantalla201104i.png/" rel="nofollow">http://img101.imageshack.us/i/capturadepantalla201104i.png/</a> (if the link stops working tell me)</p> <p>I've also tried using the Local Socket/Pipe connection method with the MAMP Socket in '/Applications/MAMP/tmp/mysql/mysql.sock', but it gives the same error. And I've also tried using MAMP port 8889 but still nothing.</p> <p>So anyone knows how to fix it? And another question, can I connect from my Android device to my laptop(where the database is placed) without using MAMP? MySQL needs MAMP to serve queries? And the last thing, am I going into the right way? Or should I do it other way?</p> <p>Thanks for reading.</p>
5,834,738
9
2
null
2011-04-29 16:21:06.647 UTC
2
2015-08-16 17:13:30.163 UTC
null
null
null
null
715,678
null
1
1
mysql|database|connection|mamp|mysql-workbench
54,967
<p>You need to sure that Mysql process is running in your system. not sure in MAC but in windows it'called mysqld.exe</p> <p>well take a look</p> <p><a href="http://lists.mysql.com/mysql/124371" rel="nofollow">http://lists.mysql.com/mysql/124371</a></p>
5,836,515
What is the PHP shorthand for: print var if var exist
<p>We've all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.</p> <pre><code>&lt;input value='&lt;?php if(isset($var)){print($var);}; ?&gt;'&gt; </code></pre> <p>How can I write this shorter? I'm okay introducing a new function like this:</p> <pre><code>&lt;input value='&lt;?php printvar('myvar'); ?&gt;'&gt; </code></pre> <p>But I don't succeed in writing the printvar() function.</p>
5,836,648
11
2
null
2011-04-29 19:28:34.547 UTC
8
2022-08-28 10:21:52.19 UTC
null
null
null
null
78,297
null
1
36
php|var|isset
33,612
<h1>For PHP &gt;= 7.0:</h1> <p>As of PHP 7 you can use the <a href="http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op" rel="nofollow noreferrer">null-coalesce operator</a>:</p> <pre><code>$user = $_GET['user'] ?? 'guest'; </code></pre> <p>Or in your usage:</p> <pre><code>&lt;?= $myVar ?? '' ?&gt; </code></pre> <h1>For PHP &gt;= 5.x:</h1> <p>My recommendation would be to create a <code>issetor</code> function:</p> <pre><code>function issetor(&amp;$var, $default = null) { return isset($var) ? $var : $default; } </code></pre> <p>This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:</p> <pre><code>echo issetor($myVar); </code></pre> <p>But also use it in other cases:</p> <pre><code>$user = issetor($_GET['user'], 'guest'); </code></pre>
5,239,131
Nginx location matches
<p>What is the difference between:</p> <pre><code> location = /abc {} </code></pre> <p>and</p> <pre><code> locaton ~ /abc {} </code></pre>
5,241,381
1
1
null
2011-03-08 22:25:55.913 UTC
10
2016-12-30 07:33:17.773 UTC
2016-12-30 07:33:17.773 UTC
null
1,610,034
null
650,505
null
1
55
nginx|nginx-location
66,232
<p><code>location = /abc {}</code> matches the exact uri <code>/abc</code></p> <p><code>location ~ /abc</code> is a regex match on the uri, meaning any uri containing <code>/abc</code>, you probably want: <code>location ~ ^/abc</code> for the uri begining with <code>/abc</code> instead</p>
25,146,557
How do I get the color of a pixel in a UIImage with Swift?
<p>I'm trying to get the color of a pixel in a UIImage with Swift, but it seems to always return 0. Here is the code, translated from @Minas' answer on <a href="https://stackoverflow.com/questions/3284185/get-pixel-color-of-uiimage">this</a> thread:</p> <pre><code>func getPixelColor(pos: CGPoint) -&gt; UIColor { var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage)) var data: UnsafePointer&lt;UInt8&gt; = CFDataGetBytePtr(pixelData) var pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4 var r = CGFloat(data[pixelInfo]) var g = CGFloat(data[pixelInfo+1]) var b = CGFloat(data[pixelInfo+2]) var a = CGFloat(data[pixelInfo+3]) return UIColor(red: r, green: g, blue: b, alpha: a) } </code></pre> <p>Thanks in advance!</p>
25,956,283
15
1
null
2014-08-05 19:13:04.767 UTC
37
2022-05-19 10:50:48.557 UTC
2017-05-23 10:31:38.977 UTC
null
-1
null
2,016,800
null
1
65
ios|uiimage|swift
59,401
<p>A bit of searching leads me here since I was facing the similar problem. You code works fine. The problem might be raised from your image. <br></p> <p>Code: <br></p> <pre><code> //On the top of your swift extension UIImage { func getPixelColor(pos: CGPoint) -&gt; UIColor { let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage)) let data: UnsafePointer&lt;UInt8&gt; = CFDataGetBytePtr(pixelData) let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4 let r = CGFloat(data[pixelInfo]) / CGFloat(255.0) let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0) let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0) let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0) return UIColor(red: r, green: g, blue: b, alpha: a) } } </code></pre> <p>What happens is this method will pick the pixel colour from the image's CGImage. So make sure you are picking from the right image. e.g. If you UIImage is 200x200, but the original image file from Imgaes.xcassets or wherever it came from, is 400x400, and you are picking point (100,100), you are actually picking the point on the upper left section of the image, instead of middle.</p> <p>Two Solutions: <br> 1, Use image from Imgaes.xcassets, and only put one @1x image in 1x field. Leave the @2x, @3x blank. Make sure you know the image size, and pick a point that is within the range. </p> <pre><code>//Make sure only 1x image is set let image : UIImage = UIImage(named:"imageName") //Make sure point is within the image let color : UIColor = image.getPixelColor(CGPointMake(xValue, yValue)) </code></pre> <p>2, Scale you CGPoint up/down the proportion to match the UIImage. e.g. <code>let point = CGPoint(100,100)</code> in the example above, </p> <pre><code>let xCoordinate : Float = Float(point.x) * (400.0/200.0) let yCoordinate : Float = Float(point.y) * (400.0/200.0) let newCoordinate : CGPoint = CGPointMake(CGFloat(xCoordinate), CGFloat(yCoordinate)) let image : UIImage = largeImage let color : UIColor = image.getPixelColor(CGPointMake(xValue, yValue)) </code></pre> <p>I've only tested the first method, and I am using it to get a colour off a colour palette. Both should work. Happy coding :)</p>
25,106,554
Why doesn't println! work in Rust unit tests?
<p>I've implemented the following method and unit test:</p> <pre><code>use std::fs::File; use std::path::Path; use std::io::prelude::*; fn read_file(path: &amp;Path) { let mut file = File::open(path).unwrap(); let mut contents = String::new(); file.read_to_string(&amp;mut contents).unwrap(); println!("{}", contents); } #[test] fn test_read_file() { let path = &amp;Path::new("/etc/hosts"); println!("{:?}", path); read_file(path); } </code></pre> <p>I run the unit test this way:</p> <pre class="lang-none prettyprint-override"><code>rustc --test app.rs; ./app </code></pre> <p>I could also run this with</p> <pre class="lang-none prettyprint-override"><code>cargo test </code></pre> <p>I get a message back saying the test passed but the <code>println!</code> is never displayed on screen. Why not?</p>
25,107,081
7
1
null
2014-08-03 16:10:50.973 UTC
66
2022-03-08 22:27:53.583 UTC
2017-07-28 18:29:16 UTC
null
155,423
null
70,600
null
1
498
rust|println
115,253
<p>This happens because Rust test programs hide the stdout of successful tests in order for the test output to be tidy. You can disable this behavior by passing the <code>--nocapture</code> option to the test binary or to <code>cargo test</code> (but, in this case <em>after</em> <code>--</code> – see below):</p> <pre><code>#[test] fn test() { println!(&quot;Hidden output&quot;) } </code></pre> <p>Invoking tests:</p> <pre class="lang-none prettyprint-override"><code>% rustc --test main.rs; ./main running 1 test test test ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured % ./main --nocapture running 1 test Hidden output test test ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured % cargo test -- --nocapture running 1 test Hidden output test test ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured </code></pre> <p>If tests fail, however, their stdout will be printed regardless if this option is present or not.</p>
21,887,504
Facebook PHP SDK - How to get access token?
<p>I'm trying to post on user's Facebook wall from my app. The user granted the permissions to the app to post on his wall, and I have userid in db. I need to send the post automatically, without the user logging in again.</p> <p>My code is:</p> <pre><code>try{ require_once(dirname(__FILE__) . '\lib\facebook-php\src\facebook.php' ); } catch(Exception $o){ print_r($o); } $config = array( 'appId' =&gt; '123456', 'secret' =&gt; '454544', 'allowSignedRequest' =&gt; false // optional but should be set to false for non-canvas apps ); $facebook = new Facebook($config); $user_id = $facebook-&gt;getUser(); $user_id = '123456'; if($user_id) { // We have a user ID, so probably a logged in user. // If not, we'll get an exception, which we handle below. try { $ret_obj = $facebook-&gt;api('/me/feed', 'POST', array( 'access_token' =&gt; $facebook-&gt;getAccessToken(), 'link' =&gt; 'www.example.com', 'message' =&gt; 'Posting with the PHP SDK!' )); echo '&lt;pre&gt;Post ID: ' . $ret_obj['id'] . '&lt;/pre&gt;'; // Give the user a logout link echo '&lt;br /&gt;&lt;a href="' . $facebook-&gt;getLogoutUrl() . '"&gt;logout&lt;/a&gt;'; } catch(FacebookApiException $e) { // If the user is logged out, you can have a // user ID even though the access token is invalid. // In this case, we'll get an exception, so we'll // just ask the user to login again here. var_dump($e); $login_url = $facebook-&gt;getLoginUrl( array( 'scope' =&gt; 'publish_stream' )); echo 'Please &lt;a href="' . $login_url . '"&gt;login.&lt;/a&gt;'; error_log($e-&gt;getType()); error_log($e-&gt;getMessage()); } } else { // No user, so print a link for the user to login // To post to a user's wall, we need publish_stream permission // We'll use the current URL as the redirect_uri, so we don't // need to specify it here. $login_url = $facebook-&gt;getLoginUrl( array( 'scope' =&gt; 'publish_stream' ) ); echo 'Please &lt;a href="' . $login_url . '"&gt;login.&lt;/a&gt;'; } </code></pre> <p>This throws <code>An active access token must be used to query information about the current user.</code> error and asks for login. After I click login, the post is sucesfully posted. </p> <p>How can I get the access token with userid without the user logging in?</p>
21,900,732
2
1
null
2014-02-19 17:11:11.11 UTC
3
2017-06-27 09:45:13.047 UTC
null
null
null
null
1,049,961
null
1
6
php|facebook|facebook-graph-api
50,341
<p>This happens when the active access token is not available while calling the API end point <code>/me</code></p> <p>There are two solutions to get rig of this</p> <ul> <li><p>use the userid instead of /me</p></li> <li><p>set the access-token prior sending the api call</p></li> </ul> <p>For the first you can make the call as</p> <pre><code>ret_obj = $facebook-&gt;api('/'.$user_id.'/feed', 'POST', array( 'link' =&gt; 'www.example.com', 'message' =&gt; 'Posting with the PHP SDK!' )); </code></pre> <p>You dont need to send <code>'access_token' =&gt; $facebook-&gt;getAccessToken(),</code></p> <p>The Second option is to do as</p> <pre><code>$access_token = $facebook-&gt;getAccessToken(); $facebook-&gt;setAccessToken($access_token); ret_obj = $facebook-&gt;api('/me/feed', 'POST', array( 'link' =&gt; 'www.example.com', 'message' =&gt; 'Posting with the PHP SDK!' )); </code></pre> <p>NOTE: <code>publish_stream</code> scope must be send while doing the login</p> <p>Deprecation Notice :<code>publish_stream</code> was replaced by <code>publish_actions</code>, check the facebook doc for <a href="https://developers.facebook.com/docs/facebook-login/permissions/v2.1" rel="noreferrer">permission</a></p>
42,483,311
Cross-platform background service in .NET Core (think windows service/unix daemon)?
<p>So I have an app that is composed from an API and a Windows service (wrapped by Topshelf) that is continuously listening for events using RabbitMQ and processes data on demand.</p> <p>For education and fun, I'm trying to rewrite this into an equivalent setup that would run on .NET Core and unix (e.g. in a docker container on AWS)</p> <p><strong>What would be the best way to implement something equivalent to a windows service like that (forever-running background process) using .NET Core if I want to keep it cross-platform?</strong> </p>
59,182,310
2
2
null
2017-02-27 10:27:03.19 UTC
16
2019-12-04 18:08:43.407 UTC
null
null
null
null
6,028,537
null
1
40
unix|cross-platform|.net-core|daemon
14,237
<p>See Worker Services (.NET Core 3.x):</p> <p>You can create one from the new Visual Studio 2019 Worker Service project template, or by using the .NET CLI:</p> <p><code>dotnet new worker</code></p> <p>See also: <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&amp;tabs=visual-studio" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&amp;tabs=visual-studio</a></p>
42,453,375
How to call a function on every route change in angular2
<p>My module.ts,</p> <pre><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule,Router } from '@angular/router'; import { AppComponent } from './crud/app.component'; import { Profile } from './profile/profile'; import { Mainapp } from './demo.app'; import { Navbar } from './header/header'; // import {ToasterModule, ToasterService} from 'angular2-toaster'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule,FormsModule, ReactiveFormsModule , RouterModule.forRoot([ { path: '', component:AppComponent}, { path: 'login', component:AppComponent}, { path: 'profile', component:Profile} ]) ], declarations: [ AppComponent,Mainapp,Navbar,Profile ], bootstrap: [ Mainapp ] }) export class AppModule { } </code></pre> <p>Here i want to call a function from main.ts on every route change and how can i do that.Can anyone please help me.Thanks. My mainapp.ts,</p> <pre><code> export class Mainapp { showBeforeLogin:any = true; showAfterLogin:any; constructor( public router: Router) { this.changeOfRoutes(); } changeOfRoutes(){ if(this.router.url === '/'){ this.showAfterLogin = true; } } } </code></pre> <p>I want to call this changeofRoutes() for every route change and how can i do that?Can anyone please help me.</p>
42,453,471
4
2
null
2017-02-25 07:44:41.687 UTC
10
2019-03-15 19:44:01.917 UTC
2018-12-06 13:25:57.357 UTC
null
9,338,572
null
7,597,629
null
1
38
angular|typescript|angular2-routing
49,079
<p>you can call <code>activate</code> method from main <code>router-outlet</code> like this</p> <pre><code>&lt;router-outlet (activate)=&quot;changeOfRoutes()&quot;&gt;&lt;/router-outlet&gt; </code></pre> <p>which will call every time when route will change.</p> <h1>Update -</h1> <p>Another way to achieve the same is to subscribe to the router events even you can filter them out on the basis of navigation state may be start and end or so, for example -</p> <pre><code>import { Router, NavigationEnd } from '@angular/router'; @Component({...}) constructor(private router: Router) { this.router.events.subscribe((ev) =&gt; { if (ev instanceof NavigationEnd) { /* Your code goes here on every router change */} }); } </code></pre>
30,772,145
Storyboard reference in Xcode, where should we use it?
<p>There is one new control in <code>Xcode7 beta</code> named as <code>Storyboard Reference</code>. Below is its image.</p> <p><img src="https://i.stack.imgur.com/iGrnU.png" alt="enter image description here"></p> <p>It has its description as </p> <blockquote> <p>Provides a placeholder for a view controller in an external storyboard. Segues connected to this placeholder will instantiate the referenced view controller at runtime.</p> </blockquote> <p>So the questions are </p> <ol> <li>In which situations should we use this?</li> <li>Is this used to connect two storyboard's view controllers via segue?</li> <li>Is this approach used to replace VC of another storyboard programatically?</li> <li>Will it work on older iOS version(before iOS 9)?</li> </ol>
30,772,291
7
2
null
2015-06-11 05:19:15.253 UTC
19
2016-10-20 03:23:31.893 UTC
2015-11-04 08:03:16.763 UTC
null
348,796
null
1,679,187
null
1
66
ios|xcode|xcode7
29,016
<p><strong>UPDATE (January 6, 2016)</strong>: I just want to quickly mention that using Storyboard references is <em>very</em> simple and is going to help you use Storyboards in a much more clean and maintainable way. <strong>A good use case for it is e.g. a <code>UITabBarController</code> with multiple tabs. Just create one Storyboard for each tab and in your <code>Main.Storyboard</code> link to those individual Storyboards using Storyboard references.</strong> Usage is very straightforward: after creating a Storyboard reference you only need to give it the <em>filename</em> of the individual Storyboard that you want to link to and set the <em>initial view controller</em> within that individual Storyboard. That's it! :)</p> <p>What follows now is the <strong>original answer</strong> I gave to @YogeshSuthar's question.</p> <ol> <li><p>this can be used in cases where you are using multiple storyboards in your app. until now you'd have to instantiate view controllers from other storyboards programmatically, seems like now you can just use this reference and create your segue in the storyboards just like with view controllers from the same storyboard</p></li> <li><p>yes, you connect one view controller from your current storyboard with another view controller from a different storyboard and you can create a segue between these two</p></li> <li><p>yes, this can be used to replace the code that was formerly used to instantiate view controllers from other storyboards programmatically</p></li> <li><p>[UPDATE thx to @AlexBasson] Storyboard references can deployed to <strong>iOS 8</strong>, <strong>OS X 10.10</strong> and <strong>watchOS 1</strong>.</p></li> </ol>
34,362,898
PropTypes check of object with dynamic keys
<p>React has lots of ways of using PropTypes to check the value of a prop. One that I commonly use is <code>React.PropTypes.shape({...})</code>. However, I recently came across a situation where I have an object that will have dynamic key/values inside. I know that each key should be a string (in a known format), and each value should be an int. Even using a custom prop validation function, it still assumes you know the key of the prop. How do I use PropTypes to check that both the keys and values of an object/shape are correct?</p> <pre><code>... someArray: React.PropTypes.arrayOf(React.PropTypes.shape({ // How to specify a dynamic string key? Keys are a date/datetime string &lt;dynamicStringKey&gt;: React.PropTypes.number })) ... </code></pre> <p>So again: I want to at the very least check that the value of each key is a number. Ideally, I would also like to be able to check the the key itself is a string in the correct format.</p>
34,365,401
4
1
null
2015-12-18 19:48:28.827 UTC
18
2021-04-09 08:59:52.203 UTC
2016-04-01 01:23:10.273 UTC
null
2,518,231
null
2,518,231
null
1
85
reactjs
46,522
<blockquote> <p><strong>Note</strong>: This answer was written in 2015 when the current version of React was 0.14.3. It may or may not apply to the version of React you're using today.</p> </blockquote> <p>That's an interesting question. From your question it sounds like you've read about custom type checkers in the docs for <a href="https://reactjs.org/docs/typechecking-with-proptypes.html" rel="noreferrer">Prop Validation</a>. For posterity I'll reproduce it here:</p> <blockquote> <pre class="lang-javascript prettyprint-override"><code>// You can also specify a custom validator. It should return an Error // object if the validation fails. Don't `console.warn` or throw, as this // won't work inside `oneOfType`. customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error('Validation failed!'); } } </code></pre> </blockquote> <p>When implementing type checkers I prefer to use React's built-in type checkers as much as possible. You want to check if the values are numbers, so we should use <code>PropTypes.number</code> for that, right? It would be nice if we could just do <code>PropTypes.number('not a number!')</code> and get the appropriate error, but unfortunately it's a little more involved than that. The first stop is to understand...</p> <h2>How type checkers work</h2> <p>Here's the function signature of a type checker:</p> <pre class="lang-javascript prettyprint-override"><code>function(props, propName, componentName, location, propFullName) =&gt; null | Error </code></pre> <p>As you can see, all of the props are passed as the first argument and the name of the prop being tested is passed as the second. The last three arguments are used for printing out useful error messages and are optional: <code>componentName</code> is self-explanatory. <code>location</code> will be one of <code>'prop'</code>, <code>'context'</code>, or <code>'childContext'</code> (we're only interested in <code>'prop'</code>), and <code>propFullName</code> is for when we're dealing with nested props, e.g. <code>someObj.someKey</code>.</p> <p>Armed with this knowledge, we can now invoke a type checker directly:</p> <pre class="lang-javascript prettyprint-override"><code>PropTypes.number({ myProp: 'bad' }, 'myProp'); // =&gt; [Error: Invalid undefined `myProp` of type `string` supplied // to `&lt;&lt;anonymous&gt;&gt;`, expected `number`.] </code></pre> <p>See? Not quite as useful without all of the arguments. This is better:</p> <pre class="lang-javascript prettyprint-override"><code>PropTypes.number({ myProp: 'bad' }, 'myProp', 'MyComponent', 'prop') // =&gt; [Error: Invalid prop `myProp` of type `string` supplied // to `MyComponent`, expected `number`.] </code></pre> <h2>An array type checker</h2> <p>One thing the docs don't mention is that when you supply a custom type checker to <code>PropTypes.arrayOf</code>, it will be called for each array element, and the first two arguments will be the array itself and the current element's index, respectively. Now we can start sketching out our type checker:</p> <pre class="lang-javascript prettyprint-override"><code>function validArrayItem(arr, idx, componentName, location, propFullName) { var obj = arr[idx]; console.log(propFullName, obj); // 1. Check if `obj` is an Object using `PropTypes.object` // 2. Check if all of its keys conform to some specified format // 3. Check if all of its values are numbers return null; } </code></pre> <p>So far it'll always return <code>null</code> (which indicates valid props), but we threw in a <code>console.log</code> to get a peek at what's going on. Now we can test it like this:</p> <pre class="lang-javascript prettyprint-override"><code>var typeChecker = PropTypes.arrayOf(validArrayItem); var myArray = [ { foo: 1 }, { bar: 'qux' } ]; var props = { myProp: myArray }; typeChecker(props, 'myProp', 'MyComponent', 'prop'); // -&gt; myProp[0] { foo: 1 } // myProp[1] { bar: 'qux' } // =&gt; null </code></pre> <p>As you can see, <code>propFullName</code> is <code>myProp[0]</code> for the first item and <code>myProp[1]</code> for the second.</p> <p>Now let's flesh out the three parts of the function.</p> <h3>1. Check if <code>obj</code> is an Object using <code>PropTypes.object</code></h3> <p>This is the easiest part:</p> <pre class="lang-javascript prettyprint-override"><code>function validArrayItem(arr, idx, componentName, location, propFullName) { var obj = arr[idx]; var props = {}; props[propFullName] = obj; // Check if `obj` is an Object using `PropTypes.object` var isObjectError = PropTypes.object(props, propFullName, componentName, location); if (isObjectError) { return isObjectError; } return null; } var typeChecker = PropTypes.arrayOf(validArrayItem); var props = { myProp: [ { foo: 1 }, 'bar' ] }; typeChecker(props, 'myProp', 'MyComponent', 'prop'); // =&gt; [Error: Invalid prop `myProp[1]` of type `string` supplied to // `MyComponent`, expected `object`.] </code></pre> <p>Perfect! Next...</p> <h3>2. Check if all of its keys conform to some specified format</h3> <p>In your question you say "each key should be a string," but all object keys in JavaScript are strings, so let's say, arbitrarily, that we want to test if the keys all start with a capital letter. Let's make a custom type checker for that:</p> <pre class="lang-javascript prettyprint-override"><code>var STARTS_WITH_UPPERCASE_LETTER_EXPR = /^[A-Z]/; function validObjectKeys(props, propName, componentName, location, propFullName) { var obj = props[propName]; var keys = Object.keys(obj); // If the object is empty, consider it valid if (keys.length === 0) { return null; } var key; var propFullNameWithKey; for (var i = 0; i &lt; keys.length; i++) { key = keys[i]; propFullNameWithKey = (propFullName || propName) + '.' + key; if (STARTS_WITH_UPPERCASE_LETTER_EXPR.test(key)) { continue; } return new Error( 'Invalid key `' + propFullNameWithKey + '` supplied to ' + '`' + componentName + '`; expected to match ' + STARTS_WITH_UPPERCASE_LETTER_EXPR + '.' ); } return null; } </code></pre> <p>We can test it on its own:</p> <pre class="lang-javascript prettyprint-override"><code>var props = { myProp: { Foo: 1, bar: 2 } }; validObjectKeys(props, 'myProp', 'MyComponent', 'prop'); // -&gt; myProp.Foo Foo // myProp.bar bar // =&gt; [Error: Invalid key `myProp.bar` supplied to `MyComponent`; // expected to match /^[A-Z]/.] </code></pre> <p>Great! Let's integrate it into our <code>validArrayItem</code> type checker:</p> <pre class="lang-javascript prettyprint-override"><code>function validArrayItem(arr, idx, componentName, location, propFullName) { var obj = arr[idx]; var props = {}; props[propFullName] = obj; // Check if `obj` is an Object using `PropTypes.object` var isObjectError = PropTypes.object(props, propFullName, componentName, location); if (isObjectError) { return isObjectError; } // Check if all of its keys conform to some specified format var validObjectKeysError = validObjectKeys(props, propFullName, componentName); if (validObjectKeysError) { return validObjectKeysError; } return null; } </code></pre> <p>And test it out:</p> <pre class="lang-javascript prettyprint-override"><code>var props = { myProp: [ { Foo: 1 }, { bar: 2 } ] }; var typeChecker = PropTypes.arrayOf(validArrayItem); typeChecker(props, 'myProp', 'MyComponent', 'prop'); // -&gt; myProp[0].Foo Foo // myProp[1].bar bar // =&gt; [Error: Invalid key `myProp[1].bar` supplied to `MyComponent`; // expected to match /^[A-Z]/.] </code></pre> <p>And finally...</p> <h3>3. Check if all of its values are numbers</h3> <p>Happily, we don't need to do much work here, since we can use the built-in <code>PropTypes.objectOf</code>:</p> <pre class="lang-javascript prettyprint-override"><code>// Check if all of its values are numbers var validObjectValues = PropTypes.objectOf(PropTypes.number); var validObjectValuesError = validObjectValues(props, propFullName, componentName, location); if (validObjectValuesError) { return validObjectValuesError; } </code></pre> <p>We'll test it below.</p> <h2>All together now</h2> <p>Here's our final code:</p> <pre class="lang-javascript prettyprint-override"><code>function validArrayItem(arr, idx, componentName, location, propFullName) { var obj = arr[idx]; var props = {}; props[propFullName] = obj; // Check if `obj` is an Object using `PropTypes.object` var isObjectError = PropTypes.object(props, propFullName, componentName, location); if (isObjectError) { return isObjectError; } // Check if all of its keys conform to some specified format var validObjectKeysError = validObjectKeys(props, propFullName, componentName); if (validObjectKeysError) { return validObjectKeysError; } // Check if all of its values are numbers var validObjectValues = PropTypes.objectOf(PropTypes.number); var validObjectValuesError = validObjectValues(props, propFullName, componentName, location); if (validObjectValuesError) { return validObjectValuesError; } return null; } </code></pre> <p>We'll write a quick convenience function for testing and throw some data at it:</p> <pre class="lang-javascript prettyprint-override"><code>function test(arrayToTest) { var typeChecker = PropTypes.arrayOf(validArrayItem); var props = { testProp: arrayToTest }; return typeChecker(props, 'testProp', 'MyComponent', 'prop'); } test([ { Foo: 1 }, { Bar: 2 } ]); // =&gt; null test([ { Foo: 1 }, { bar: 2 } ]); // =&gt; [Error: Invalid key `testProp[1].bar` supplied to `MyComponent`; // expected to match /^[A-Z]/.] test([ { Foo: 1 }, { Bar: false } ]); // =&gt; [Error: Invalid prop `testProp[1].Bar` of type `boolean` supplied to // `MyComponent`, expected `number`.] </code></pre> <p>It works! Now you can use it in your React component just like the built-in type checkers:</p> <pre class="lang-javascript prettyprint-override"><code>MyComponent.propTypes = { someArray: PropTypes.arrayOf(validArrayItem); }; </code></pre> <p>Of course, I would recommend giving it a more meaningful name and moving it into its own module.</p>
47,536,005
Can't toast on a thread that has not called Looper.prepare()
<p>I try to run a test for my android app but I get this trace. What does it mean?</p> <pre><code>java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare() at android.widget.Toast$TN.&lt;init&gt;(Toast.java:390) at android.widget.Toast.&lt;init&gt;(Toast.java:114) at android.widget.Toast.makeText(Toast.java:277) at android.widget.Toast.makeText(Toast.java:267) at dev.android.gamex.CatchGame.onDraw(MainActivity.java:317) at dev.android.gamex.JamieTest.useAppContext(JamieTest.java:45) at java.lang.reflect.Method.invoke(Native Method) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:58) at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:375) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074) Tests ran to completion. </code></pre> <p>My test class</p> <pre><code>package dev.android.gamex; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.support.test.InstrumentationRegistry; import android.widget.TextView; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class JamieTest { private static final String FAKE_STRING = "HELLO WORLD"; private OnScoreListener onScoreListener = new OnScoreListener() { @Override public void onScore(int score) { } }; @Mock Canvas can; @Test public void useAppContext() throws Exception { Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("dev.android.gamex", appContext.getPackageName()); CatchGame cg = new CatchGame(appContext, 5, "Jamie", onScoreListener); cg.initialize(); assertTrue(! cg.gameOver); cg.onDraw(new Canvas()); assertTrue(! cg.paused); } } </code></pre> <p>The code I want to test is below. </p> <pre><code>package dev.android.gamex; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.MotionEventCompat; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.Random; public class MainActivity extends AppCompatActivity { CatchGame cg; public TextView textView; public LinearLayout mainLayout; String[] spinnerValue = {"Rookie", "Advanced", "Expert", "Master"}; // start app @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainLayout = new LinearLayout(this); mainLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout menuLayout = new LinearLayout(this); menuLayout.setBackgroundColor(Color.parseColor("#FFFFFF")); textView = new TextView(this); textView.setVisibility(View.VISIBLE); String str = "Score: 0"; textView.setText(str); menuLayout.addView(textView); Button button = new Button(this); button.setText("Pause"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { togglePausePlay(); } }); menuLayout.addView(button); Spinner spinner2 =new Spinner(this); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;&gt;(MainActivity.this, android.R.layout.simple_list_item_1, spinnerValue); spinner2.setAdapter(adapter); menuLayout.addView(spinner2); mainLayout.addView(menuLayout); cg = new CatchGame(this, 5, "Jamie", onScoreListener); cg.setBackground(getResources().getDrawable(R.drawable.bg_land_mdpi)); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); } private void togglePausePlay() { if (cg.paused) { // play // getSupportActionBar().hide(); Toast.makeText(MainActivity.this, "Play", Toast.LENGTH_SHORT).show(); } else { // pause // getSupportActionBar().show(); Toast.makeText(MainActivity.this, "Pause", Toast.LENGTH_SHORT).show(); } cg.paused = !cg.paused; } private OnScoreListener onScoreListener = new OnScoreListener() { @Override public void onScore(int score) { textView.setText("Score: " + score); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_menu, menu); return true; } // method called when top right menu is tapped @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int difficulty = cg.NBRSTEPS; String name = cg.heroName; switch (item.getItemId()) { case R.id.item11: cg = new CatchGame(this, 3, name, onScoreListener); setContentView(cg); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); return true; case R.id.item12: cg = new CatchGame(this, 5, name, onScoreListener); setContentView(cg); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); return true; case R.id.item13: cg = new CatchGame(this, 7, name, onScoreListener); setContentView(cg); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); return true; case R.id.item14: cg = new CatchGame(this, 9, name, onScoreListener); setContentView(cg); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); return true; case R.id.item15: cg = new CatchGame(this, 11, name, onScoreListener); setContentView(cg); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); return true; case R.id.item21: cg = new CatchGame(this, difficulty, "Jamie", onScoreListener); setContentView(cg); mainLayout.addView(cg); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); setContentView(mainLayout); return true; case R.id.item22: cg = new CatchGame(this, difficulty, "Spaceship", onScoreListener); setContentView(cg); //mainLayout.addView(cg); //getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getSupportActionBar().hide(); //setContentView(mainLayout); return true; default: cg.paused = true; return super.onOptionsItemSelected(item); } } } interface OnScoreListener { void onScore(int score); } class CatchGame extends View { int NBRSTEPS; // number of discrete positions in the x-dimension; must be uneven String heroName; int screenW; int screenH; int[] x; // x-coordinates for falling objects int[] y; // y-coordinates for falling objects int[] hero_positions; // x-coordinates for hero Random random = new Random(); int ballW; // width of each falling object int ballH; // height of ditto float dY; //vertical speed Bitmap falling, hero, jamie2, jamieleft, jamieright; int heroXCoord; int heroYCoord; int xsteps; int score; int offset; boolean gameOver; // default value is false boolean toastDisplayed; boolean paused = false; OnScoreListener onScoreListener; // constructor, load images and get sizes public CatchGame(Context context, int difficulty, String name, OnScoreListener onScoreListener) { super(context); NBRSTEPS = difficulty; heroName = name; this.onScoreListener = onScoreListener; x = new int[NBRSTEPS]; y = new int[NBRSTEPS]; hero_positions = new int[NBRSTEPS]; int resourceIdFalling = 0; int resourceIdHero = 0; if (heroName.equals("Jamie")) { resourceIdFalling = R.mipmap.falling_object2; resourceIdHero = R.drawable.left_side_hdpi; setBackground(getResources().getDrawable(R.mipmap.background)); } if (heroName.equals("Spaceship")) { resourceIdFalling = R.mipmap.falling_object; resourceIdHero = R.mipmap.ufo; setBackground(getResources().getDrawable(R.mipmap.space)); } falling = BitmapFactory.decodeResource(getResources(), resourceIdFalling); //load a falling image hero = BitmapFactory.decodeResource(getResources(), resourceIdHero); //load a hero image jamieleft = BitmapFactory.decodeResource(getResources(), R.drawable.left_side_hdpi); //load a hero image jamieright = BitmapFactory.decodeResource(getResources(), R.drawable.right_side_hdpi); //load a hero image ballW = falling.getWidth(); ballH = falling.getHeight(); } public CatchGame(Context context, int difficulty, String name, OnScoreListener onScoreListener, Drawable background) { this(context, difficulty, name, onScoreListener); this.setBackground(background); } // set coordinates, etc. void initialize() { if (!gameOver) { // run only once, when the game is first started int maxOffset = (NBRSTEPS - 1) / 2; for (int i = 0; i &lt; x.length; i++) { int origin = (screenW / 2) + xsteps * (i - maxOffset); x[i] = origin - (ballW / 2); hero_positions[i] = origin - hero.getWidth(); } int heroWidth = hero.getWidth(); int heroHeight = hero.getHeight(); hero = Bitmap.createScaledBitmap(hero, heroWidth * 2, heroHeight * 2, true); hero = Bitmap.createScaledBitmap(hero, heroWidth * 2, heroHeight * 2, true); jamieleft = Bitmap.createScaledBitmap(jamieleft, jamieleft.getWidth()* 2, jamieright.getWidth() * 2, true); jamieright = Bitmap.createScaledBitmap(jamieright, jamieright.getWidth()* 2, jamieright.getWidth() * 2, true); heroYCoord = screenH - 2 * heroHeight; // bottom of screen } for (int i = 0; i &lt; y.length; i++) { y[i] = -random.nextInt(1000); // place items randomly in vertical direction } offset = (NBRSTEPS - 1) / 2; // place hero at centre of the screen heroXCoord = hero_positions[offset]; // initialize or reset global attributes dY = 2.0f; score = 0; gameOver = false; toastDisplayed = false; } // method called when the screen opens @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); screenW = w; screenH = h; xsteps = w / NBRSTEPS; initialize(); } // method called when the "game over" toast has finished displaying void restart(Canvas canvas) { toastDisplayed = true; initialize(); draw(canvas); } // update the canvas in order to display the game action @Override public void onDraw(Canvas canvas) { if (toastDisplayed) { restart(canvas); return; } super.onDraw(canvas); int heroHeight = hero.getHeight(); int heroWidth = hero.getWidth(); int heroCentre = heroXCoord + heroWidth / 2; Context context = this.getContext(); // compute locations of falling objects for (int i = 0; i &lt; y.length; i++) { if (!paused) { y[i] += (int) dY; } // if falling object hits bottom of screen if (y[i] &gt; (screenH - ballH) &amp;&amp; !gameOver) { dY = 0; gameOver = true; paused = true; int duration = Toast.LENGTH_SHORT; final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration); toast.show(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { toast.cancel(); toastDisplayed = true; } }, 3000); //Vibrator v = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE); // Vibrate for 3000 milliseconds //v.vibrate(3000); } // if the hero catches a falling object if (x[i] &lt; heroCentre &amp;&amp; x[i] + ballW &gt; heroCentre &amp;&amp; y[i] &gt; screenH - ballH - heroHeight) { y[i] = -random.nextInt(1000); // reset to new vertical position score += 1; onScoreListener.onScore(score); } } canvas.save(); //Save the position of the canvas. for (int i = 0; i &lt; y.length; i++) { canvas.drawBitmap(falling, x[i], y[i], null); //Draw the falling on the canvas. } canvas.drawBitmap(hero, heroXCoord, heroYCoord, null); //Draw the hero on the canvas. canvas.restore(); //Call the next frame. invalidate(); } // event listener for when the user touches the screen @Override public boolean onTouchEvent(MotionEvent event) { if (paused) { paused = false; } int action = MotionEventCompat.getActionMasked(event); if (action != MotionEvent.ACTION_DOWN || gameOver) { // non-touchdown event or gameover return true; // do nothing } int coordX = (int) event.getX(); int xCentre = (screenW / 2) - (hero.getWidth() / 2); int maxOffset = hero_positions.length - 1; // can't move outside right edge of screen int minOffset = 0; // ditto left edge of screen if (coordX &lt; xCentre &amp;&amp; offset &gt; minOffset) { // touch event left of the centre of screen offset--; // move hero to the left if(coordX &lt; heroXCoord)// + heroWidth / 2) hero = Bitmap.createScaledBitmap(jamieleft, jamieleft.getWidth() , jamieleft.getHeight() , true); } if (coordX &gt; xCentre &amp;&amp; offset &lt; maxOffset) { // touch event right of the centre of screen offset++; // move hero to the right if(coordX &gt; heroXCoord) hero = Bitmap.createScaledBitmap(jamieright, jamieright.getWidth() , jamieright.getHeight() , true); } heroXCoord = hero_positions[offset]; return true; } } </code></pre> <p>The repository is <a href="http://github.com/montao/gamex" rel="noreferrer">available online.</a> </p>
47,536,058
4
2
null
2017-11-28 16:07:53.937 UTC
6
2021-09-23 03:16:31.913 UTC
null
null
null
null
108,207
null
1
45
android
46,076
<p>You CANNOT show a <code>Toast</code> on non-UI thread. You need to call <code>Toast.makeText()</code> (and most other functions dealing with the UI) from <strong>within the main thread</strong>. </p> <hr> <p>You could use <a href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)" rel="noreferrer">Activity#runOnUiThread()</a>:</p> <pre><code>runOnUiThread(new Runnable() { public void run() { final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration); toast.show(); } }); </code></pre> <p>If you want execute a instrumentation test on main thread, add <code>@UiThreadTest</code> annotation:</p> <pre><code>@Test @UiThreadTest public void useAppContext() { // ... } </code></pre> <hr> <p>P.s: There are also many other ways with explain (using Handler, Looper, Observable..) in these posts: <a href="https://stackoverflow.com/questions/3134683/android-toast-in-a-thread">Android: Toast in a thread</a> and <a href="https://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare">Can&#39;t create handler inside thread that has not called Looper.prepare()</a> </p>
7,292,568
Add an object to the beginning of an NSMutableArray?
<p>Is there an efficient way to add an object to start of an <code>NSMutableArray</code>? I am looking for a good double ended queue in <code>objective C</code> would work as well.</p>
7,292,586
2
0
null
2011-09-03 10:29:02.88 UTC
6
2016-12-07 09:52:45.157 UTC
2016-12-07 09:52:45.157 UTC
null
875,943
null
728,358
null
1
50
iphone|objective-c|ios|nsmutablearray|deque
28,126
<p>Simply</p> <pre><code>[array insertObject:obj atIndex:0]; </code></pre> <p>Check the <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/insertObject:atIndex:" rel="noreferrer">documentation</a></p>
23,384,230
how to post multiple value with same key in python requests?
<pre><code>requests.post(url, data={'interests':'football','interests':'basketball'}) </code></pre> <p>I tried this, but it is not working. How would I post <code>football</code> and <code>basketball</code> in the <code>interests</code> field?</p>
23,384,253
3
1
null
2014-04-30 09:20:07.137 UTC
12
2020-05-27 11:36:43.623 UTC
2019-01-04 01:13:46.03 UTC
null
8,020,385
null
1,653,498
null
1
40
python|python-requests
37,890
<p>Dictionary keys <em>must</em> be unique, you can't repeat them. You'd use a sequence of key-value tuples instead, and pass this to <code>data</code>:</p> <pre><code>requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')]) </code></pre> <p>Alternatively, make the values of the <code>data</code> dictionary <em>lists</em>; each value in the list is used as a separate parameter entry:</p> <pre><code>requests.post(url, data={'interests': ['football', 'basketball']}) </code></pre> <p>Demo POST to <a href="http://httpbin.org" rel="noreferrer">http://httpbin.org</a>:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; url = 'http://httpbin.org/post' &gt;&gt;&gt; r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')]) &gt;&gt;&gt; r.request.body 'interests=football&amp;interests=basketball' &gt;&gt;&gt; r.json()['form'] {u'interests': [u'football', u'basketball']} &gt;&gt;&gt; r = requests.post(url, data={'interests': ['football', 'basketball']}) &gt;&gt;&gt; r.request.body 'interests=football&amp;interests=basketball' &gt;&gt;&gt; r.json()['form'] {u'interests': [u'football', u'basketball']} </code></pre>
32,108,969
Why do I get "Failed to bounce to type" when I turn JSON from Firebase into Java objects?
<p><em>[Disclosure: I am an engineer at Firebase. This question is meant to be a reference question to answer many questions in one go.]</em></p> <p>I have the following JSON structure in my Firebase database:</p> <pre><code>{ "users": { "-Jx5vuRqItEF-7kAgVWy": { "handle": "puf", "name": "Frank van Puffelen", "soId": 209103 }, "-Jx5w3IOHD2kRFFgkMbh": { "handle": "kato", "name": "Kato Wulf", "soId": 394010 }, "-Jx5x1VWs08Zc5S-0U4p": { "handle": "mimming", "name": "Jenny Tong", "soId": 839465 } } } </code></pre> <p>I am reading this with the following code:</p> <pre><code>private static class User { String handle; String name; public String getHandle() { return handle; } public String getName() { return name; } } Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/32108969/users"); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot usersSnapshot) { for (DataSnapshot userSnapshot : usersSnapshot.getChildren()) { User user = userSnapshot.getValue(User.class); System.out.println(user.toString()); } } @Override public void onCancelled(FirebaseError firebaseError) { } }); </code></pre> <p>But I get this error:</p> <blockquote> <p>Exception in thread "FirebaseEventTarget" com.firebase.client.FirebaseException: Failed to bounce to type</p> </blockquote> <p>How can I read my users into Java objects?</p>
32,109,104
3
1
null
2015-08-20 03:15:00.307 UTC
19
2021-08-07 22:41:31.497 UTC
2015-12-17 05:33:58.62 UTC
null
209,103
null
209,103
null
1
44
java|android|firebase|firebase-realtime-database
13,876
<p>Firebase uses Jackson to allow serialization of Java objects to JSON and deserialization of JSON back into Java objects. You can find more about Jackson on <a href="https://github.com/FasterXML/jackson" rel="nofollow noreferrer">the Jackson website</a> and this <a href="http://www.baeldung.com/jackson-annotations" rel="nofollow noreferrer">page about Jackson annotations</a>.</p> <p>In the rest of this answer, we’ll show a few common ways of using Jackson with Firebase.</p> <h1>Loading complete users</h1> <p>The simplest way of loading the users from Firebase into Android is if we create a Java class that completely mimics the properties in the JSON:</p> <pre><code>private static class User { String handle; String name; long stackId; public String getHandle() { return handle; } public String getName() { return name; } public long getStackId() { return stackId; } @Override public String toString() { return &quot;User{handle='&quot;+handle+“', name='&quot;+name+&quot;', stackId=&quot;+stackId+&quot;\’}”; } } </code></pre> <p>We can use this class in a listener:</p> <pre><code>Firebase ref = new Firebase(&quot;https://stackoverflow.firebaseio.com/32108969/users&quot;); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot usersSnapshot) { for (DataSnapshot userSnapshot : usersSnapshot.getChildren()) { User user = userSnapshot.getValue(User.class); System.out.println(user.toString()); } } @Override public void onCancelled(FirebaseError firebaseError) { } }); </code></pre> <p>You may note that the User class follow the <a href="https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html" rel="nofollow noreferrer">JavaBean property pattern</a>. Every JSON property maps by a field in the User class and we have a public getter method for each field. By ensuring that all properties are mapped with the exact same name, we ensure that Jackson can automatically map them.</p> <p>You can also manually control the mapping by putting Jackson annotations on your Java class, and its fields and methods. We’ll cover the two most common annotations (<code>@JsonIgnore</code> and <code>@JsonIgnoreProperties</code>) below.</p> <h1>Partially loading users</h1> <p>Say that you only care about the user’s name and handle in your Java code. Let’s remove the <code>stackId</code> and see what happens:</p> <pre><code>private static class User { String handle; String name; public String getHandle() { return handle; } public String getName() { return name; } @Override public String toString() { return &quot;User{handle='&quot; + handle + “\', name='&quot; + name + &quot;\’}”; } } </code></pre> <p>If we now attach the same listener as before and run the program, it will throw an exception:</p> <pre><code>Exception in thread &quot;FirebaseEventTarget&quot; com.firebase.client.FirebaseException: Failed to bounce to type at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:187) at com.firebase.LoadPartialUsers$1.onDataChange(LoadPartialUsers.java:16) </code></pre> <p>The “failed to debounce type” indicates that Jackson was unable to deserialize the JSON into a User object. In the nested exception it tells us why:</p> <pre><code>Caused by: com.shaded.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field &quot;stackId&quot; (class com.firebase.LoadPartialUsers$User), not marked as ignorable (2 known properties: , &quot;handle&quot;, &quot;name&quot;]) at [Source: java.io.StringReader@43079089; line: 1, column: 15] (through reference chain: com.firebase.User[&quot;stackId&quot;]) at com.shaded.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79) </code></pre> <p>Jackson found a property <code>stackId</code> in the JSON and doesn’t know what to do with it, so it throws an exception. Luckily there is an annotation that we can use to tell it to ignore specific properties from the JSON when mapping it to our <code>User</code> class:</p> <pre><code>@JsonIgnoreProperties({ &quot;stackId&quot; }) private static class User { ... } </code></pre> <p>If we not run the code with our listener again, Jackson will know that it can ignore <code>stackId</code> in the JSON and it will be able to deserialize the JSON into a User object again.</p> <p>Since adding properties to the JSON is such a common practice in Firebase applications, you may find it more convenient to simply tell Jackson to ignore all properties that don’t have a mapping in the Java class:</p> <pre><code>@JsonIgnoreProperties(ignoreUnknown=true) private static class User { ... } </code></pre> <p>Now if we add properties to the JSON later, the Java code will still be able to load the <code>User</code>s. Just keep in mind that the User objects won’t contain all information that was present in the JSON, so be careful when writing them back to Firebase again.</p> <h1>Partially saving users</h1> <p>One reason why it is nice to have a custom Java class, is that we can add convenience methods to it. Say that we add a convenience method that gets the name to display for a user:</p> <pre><code>private static class User { String handle; String name; public String getHandle() { return handle; } public String getName() { return name; } @JsonIgnore public String getDisplayName() { return getName() + &quot; (&quot; + getHandle() + &quot;)&quot;; } @Override public String toString() { return &quot;User{handle='&quot; + handle + &quot;\', name='&quot; + name + &quot;\', displayName='&quot; + getDisplayName() + &quot;'}&quot;; } } </code></pre> <p>Now let's read the users from Firebase and write them back into a new location:</p> <pre><code>Firebase srcRef = new Firebase(&quot;https://stackoverflow.firebaseio.com/32108969/users&quot;); final Firebase copyRef = new Firebase(&quot;https://stackoverflow.firebaseio.com/32108969/copiedusers&quot;); srcRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot usersSnapshot) { for (DataSnapshot userSnapshot : usersSnapshot.getChildren()) { User user = userSnapshot.getValue(User.class); copyRef.child(userSnapshot.getKey()).setValue(user); } } @Override public void onCancelled(FirebaseError firebaseError) { } }); </code></pre> <p>The JSON in the <code>copiedusers</code> node looks like this:</p> <pre><code>&quot;copiedusers&quot;: { &quot;-Jx5vuRqItEF-7kAgVWy&quot;: { &quot;displayName&quot;: &quot;Frank van Puffelen (puf)&quot;, &quot;handle&quot;: &quot;puf&quot;, &quot;name&quot;: &quot;Frank van Puffelen&quot; }, &quot;-Jx5w3IOHD2kRFFgkMbh&quot;: { &quot;displayName&quot;: &quot;Kato Wulf (kato)&quot;, &quot;handle&quot;: &quot;kato&quot;, &quot;name&quot;: &quot;Kato Wulf&quot; }, &quot;-Jx5x1VWs08Zc5S-0U4p&quot;: { &quot;displayName&quot;: &quot;Jenny Tong (mimming)&quot;, &quot;handle&quot;: &quot;mimming&quot;, &quot;name&quot;: &quot;Jenny Tong&quot; } } </code></pre> <p>That’s not the same as the source JSON, because Jackson recognizes the new <code>getDisplayName()</code> method as a JavaBean getter and thus added a <code>displayName</code> property to the JSON it outputs. We solve this problem by adding a <code>JsonIgnore</code> annotation to <code>getDisplayName()</code>.</p> <pre><code> @JsonIgnore public String getDisplayName() { return getName() + &quot;(&quot; + getHandle() + &quot;)&quot;; } </code></pre> <p>When serializing a User object, Jackson will now ignore the <code>getDisplayName()</code> method and the JSON we write out will be the same as what we got it.</p>
31,742,601
How to check internet connection on iOS device?
<p>I'm wondering how I can check if the user is connect to internet through WIFI or cellular data 3G or 4G.</p> <p>Also I don't want to check if a website is reachable or not, the thing that I want to check if there is internet on the device or not. I tried to look over the internet all that I see is that they check if the website is reachable or not using the <code>Rechability</code> class.</p> <p><strong>I want to check if the user has internet or not when he opens my application.</strong></p> <p><em>I'm using Xcode6 with Objective-C.</em></p>
31,742,631
10
2
null
2015-07-31 09:22:52.567 UTC
6
2017-10-31 22:35:53.57 UTC
2015-07-31 09:52:28.513 UTC
null
2,227,743
null
4,934,615
null
1
15
ios|objective-c|cocoa-touch|reachability
44,801
<p>Use this code and import <code>Reachability.h</code> file</p> <pre><code>if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable) { //connection unavailable } else { //connection available } </code></pre>
31,382,531
Why I can't create an array with large size?
<p>Why it is impossible to create an array with max int size?</p> <pre><code>int i = 2147483647; int[] array = new int[i]; </code></pre> <p>I found this explanation:</p> <blockquote> <p>Java arrays are accessed via 32-bit ints, resulting in a maximum theoretical array size of 2147483647 elements.</p> </blockquote> <p>But as you can see my code doesn't work. It is also impossible to create an array with size</p> <pre><code>new int[Integer.MAX_VALUE - 5]; </code></pre> <h2>Technical details</h2> <ul> <li>64-Bit HotSpot JVM</li> <li>OSX 10.10.4 </li> </ul> <p><em>PS</em></p> <p>And why <code>-5</code> actually?</p>
31,388,054
5
5
null
2015-07-13 11:46:40.997 UTC
11
2019-01-07 08:34:25.283 UTC
2019-01-07 08:34:25.283 UTC
null
1,352,098
null
4,528,545
null
1
13
java|jvm|jvm-hotspot
29,841
<h2>Theory</h2> <p>There are two possible exceptions:</p> <ul> <li><code>OutOfMemoryError: Java heap space</code> means your array does not fit into java heap space. In order to solve you can increase the maximum heap size by using JVM option <code>-Xmx</code>. Also take into account that <a href="https://stackoverflow.com/questions/24202523/java-process-memory-check-test">the maximum size of object cannot be larger than the largest heap generation</a>.</li> <li><code>OutOfMemoryError: Requested array size exceeds VM limit</code> means platform-specific size was exceeded: <ul> <li>the upper bound limit is set by the restrictions of the size type used to describe an index in the array, so theoretical array size is limited by <code>2^31-1=2147483647</code> elements.</li> <li>the other limit is JVM/platform specific. According to <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html" rel="noreferrer">chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition</a> there is no strict limit on array length, thus array size may be reduced without violating JLS.</li> </ul></li> </ul> <h2>Practice</h2> <p>In HotSpot JVM array size is limited by internal representation. In the GC code JVM passes around the size of an array in heap words as an <code>int</code> then converts back from heap words to <code>jint</code> this may cause an overflow. So in order to avoid crashes and unexpected behavior the maximum array length is limited by <a href="https://github.com/openjdk-mirror/jdk7u-hotspot/blob/master/src/share/vm/oops/arrayOop.hpp#L109" rel="noreferrer">(max size - header size)</a>. Where <a href="http://hg.openjdk.java.net/jdk7u/jdk7u/hotspot/file/f49c3e79b676/src/share/vm/oops/arrayOop.hpp#l47" rel="noreferrer">header size</a> depends on C/C++ compiler which was used to build the JVM you are running(gcc for linux, clang for macos), and runtime settings(like <code>UseCompressedClassPointers</code>). For example on my linux:</p> <ul> <li>Java HotSpot(TM) 64-Bit Server VM 1.6.0_45 limit <code>Integer.MAX_VALUE</code></li> <li>Java HotSpot(TM) 64-Bit Server VM 1.7.0_72 limit <code>Integer.MAX_VALUE-1</code></li> <li>Java HotSpot(TM) 64-Bit Server VM 1.8.0_40 limit <code>Integer.MAX_VALUE-2</code></li> </ul> <h2>Useful Links</h2> <ul> <li><a href="https://bugs.openjdk.java.net/browse/JDK-8059914" rel="noreferrer">https://bugs.openjdk.java.net/browse/JDK-8059914</a></li> <li><a href="https://bugs.openjdk.java.net/browse/JDK-8029587" rel="noreferrer">https://bugs.openjdk.java.net/browse/JDK-8029587</a></li> </ul>
18,828,486
Using apply function on a matrix with NA entries
<p>I read Data from a csv file. If I see this file in R, I have:</p> <pre><code> V1 V2 V3 V4 V5 V6 V7 1 14 25 83 64 987 45 78 2 15 65 789 32 14 NA NA 3 14 67 89 14 NA NA NA </code></pre> <p>If I want the maximum value in each column, I use this:</p> <pre><code>apply(df,2,max) </code></pre> <p>and this is the result:</p> <pre><code> V1 V2 V3 V4 V5 V6 V7 15 67 789 64 NA NA NA </code></pre> <p>but it works on the column that has no <code>NA</code>. How can I change my code, to compare columns with <code>NA</code> too?</p>
18,828,521
5
0
null
2013-09-16 12:48:01.583 UTC
5
2018-10-07 22:04:30.513 UTC
2013-09-16 13:18:09.717 UTC
null
2,138,016
null
2,357,558
null
1
19
r
65,788
<p>You just need to add <code>na.rm=TRUE</code> to your apply call.</p> <pre><code>apply(df,2,max,na.rm=TRUE) </code></pre> <p>Note: This does assume every column has at least one data point. If one does not <code>sum</code> will return <code>0</code>. </p> <p><strong>EDIT BASED ON COMMENT</strong></p> <p><code>fft</code> does not have an <code>na.rm</code> argument. Therefore, you will need to write your own function.</p> <pre><code>apply(df,2,function(x){fft(x[!is.na(x)])}) </code></pre> <p>For example:</p> <pre><code>df &lt;- data.frame(matrix(5,5,5)) df[,3] &lt;- NA &gt; df X1 X2 X3 X4 X5 1 5 5 NA 5 5 2 5 5 NA 5 5 3 5 5 NA 5 5 4 5 5 NA 5 5 5 5 5 NA 5 5 &gt; apply(df,2,function(x){fft(x[!is.na(x)])}) $X1 [1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i [5] 1.776357e-15+0i $X2 [1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i [5] 1.776357e-15+0i $X3 complex(0) $X4 [1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i [5] 1.776357e-15+0i $X5 [1] 2.500000e+01+0i 1.776357e-15+0i 1.776357e-15+0i 1.776357e-15+0i [5] 1.776357e-15+0i </code></pre>
38,038,521
ReactJS onClick setState to different element
<p>I am new to react, and I am having a little issue. Maybe somebody can help me out. </p> <p>So the issue is that I am unable to triger the element I want with onCLick function. Now I am trying to remove the navigation when </p> <pre><code>import React from "react"; import ReactDOM from "react-dom"; export default class Nav extends React.Component { constructor() { super(); this.state = {navStatus: "navHide"}; } navClose() { var navOpened = document.getElementById("myNav"); navOpened.setState({navStatus: "navHide"}); } navOpen() { this.setState({navStatus: "navShow"}); } render() { return( &lt;nav onClick={this.navOpen.bind(this)}&gt; &lt;div id="myNav" className={this.state.navStatus}&gt; &lt;div className="navClose" onClick={this.navClose.bind(this)}&gt; &lt;object className="navCloseBtn" type="image/svg+xml" data="svg/close.svg"&gt;&lt;/object&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; ); } } </code></pre> <p>The error I am having is </p> <pre><code>nav.js:12 Uncaught TypeError: navOpened.setState is not a function </code></pre> <p>Also if you notice some patterns that I could improve in my code, I would really appreciate the feedback.</p> <p>Thank You!</p>
38,038,603
3
2
null
2016-06-26 12:27:12.627 UTC
1
2019-10-16 20:11:09.04 UTC
2016-06-26 13:09:02.587 UTC
null
4,484,822
null
5,353,525
null
1
9
javascript|reactjs
54,283
<p>Only react components have <code>setState</code> method. Working example:</p> <pre><code>import React from "react"; import ReactDOM from "react-dom"; export default class Nav extends React.Component { constructor() { super(); this.state = { navStatus: "navHide" }; this.navClose = this.navClose.bind(this); this.navOpen = this.navOpen.bind(this); } navClose(e) { e.stopPropagation(); this.setState({ navStatus: "navHide" }); } navOpen() { this.setState({ navStatus: "navShow" }); } render() { return( &lt;nav onClick={this.navOpen}&gt; &lt;div id="myNav" className={this.state.navStatus}&gt; &lt;div className="navClose" onClick={this.navClose}&gt; &lt;object className="navCloseBtn" type="image/svg+xml" data="svg/close.svg" &gt;&lt;/object&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; ); } </code></pre> <p>Also you should bind event handlers in constructor instead of <code>render</code> method.</p>
36,950,078
Cannot connect to (LocalDB)\MSSQLLocalDB -> Login failed for user 'User-PC\User'
<p>I am getting an error, While I am trying to connect (LocalDB)\MSSQLLocalDB through SQL Server management studio. I also tried to login with default database as master the error is same.</p> <p><a href="https://i.stack.imgur.com/Q3Gyb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Q3Gyb.png" alt="enter image description here"></a> Here is the Server details. <a href="https://i.stack.imgur.com/dE9Aw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dE9Aw.png" alt="enter image description here"></a></p>
36,950,372
2
1
null
2016-04-30 02:35:55.9 UTC
22
2021-07-27 19:08:22.107 UTC
2019-03-07 06:23:43.917 UTC
null
2,024,157
null
3,894,854
null
1
54
sql|sql-server|ssms|localdb
64,400
<p>The following command through sqllocaldb utility works for me.</p> <pre><code>sqllocaldb stop mssqllocaldb sqllocaldb delete mssqllocaldb sqllocaldb start "MSSQLLocalDB" </code></pre> <p><a href="https://i.stack.imgur.com/Vqiv6.png"><img src="https://i.stack.imgur.com/Vqiv6.png" alt="enter image description here"></a></p> <p>After that I restarted the sql server management studio, and it is successfully established connection through <code>(LocalDB)\MSSQLLocalDB</code> </p>
36,948,557
How to use Redux to refresh JWT token?
<p>Our React Native Redux app uses JWT tokens for authentication. There are many actions that require such tokens and a lot of them are dispatched simultaneously e.g. when app loads.</p> <p>E.g.</p> <pre><code>componentDidMount() { dispath(loadProfile()); dispatch(loadAssets()); ... } </code></pre> <p>Both <code>loadProfile</code> and <code>loadAssets</code> require JWT. We save the token in the state and <code>AsyncStorage</code>. My question is how to handle token expiration.</p> <p>Originally I was going to use middleware for handling token expiration</p> <pre><code>// jwt-middleware.js export function refreshJWTToken({ dispatch, getState }) { return (next) =&gt; (action) =&gt; { if (isExpired(getState().auth.token)) { return dispatch(refreshToken()) .then(() =&gt; next(action)) .catch(e =&gt; console.log('error refreshing token', e)); } return next(action); }; </code></pre> <p>}</p> <p>The problem that I ran into was that refreshing of the token will happen for both <code>loadProfile</code> and <code>loadAssets</code> actions because at the time when they are dispatch the token will be expired. Ideally I would like to "pause" actions that require authentication until the token is refreshed. Is there a way to do that with middleware?</p>
36,986,329
4
2
null
2016-04-29 22:40:54.33 UTC
41
2021-06-27 20:21:24.27 UTC
2016-05-02 18:01:38.92 UTC
null
616,776
null
616,776
null
1
60
javascript|reactjs|react-native|redux|jwt
38,659
<p>I found a way to solve this. I am not sure if this is best practice approach and there are probably some improvements that could be made to it.</p> <p>My original idea stays: JWT refresh is in the middleware. That middleware has to come before <code>thunk</code> if <code>thunk</code> is used.</p> <pre><code>... const createStoreWithMiddleware = applyMiddleware(jwt, thunk)(createStore); </code></pre> <p>Then in the middleware code we check to see if token is expired before any async action. If it is expired we also check if we are already are refreshing the token -- to be able to have such check we add promise for fresh token to the state.</p> <pre><code>import { refreshToken } from '../actions/auth'; export function jwt({ dispatch, getState }) { return (next) =&gt; (action) =&gt; { // only worry about expiring token for async actions if (typeof action === 'function') { if (getState().auth &amp;&amp; getState().auth.token) { // decode jwt so that we know if and when it expires var tokenExpiration = jwtDecode(getState().auth.token).&lt;your field for expiration&gt;; if (tokenExpiration &amp;&amp; (moment(tokenExpiration) - moment(Date.now()) &lt; 5000)) { // make sure we are not already refreshing the token if (!getState().auth.freshTokenPromise) { return refreshToken(dispatch).then(() =&gt; next(action)); } else { return getState().auth.freshTokenPromise.then(() =&gt; next(action)); } } } } return next(action); }; } </code></pre> <p>The most important part is <code>refreshToken</code> function. That function needs to dispatch action when token is being refreshed so that the state will contain the promise for the fresh token. That way if we dispatch multiple async actions that use token auth simultaneously the token gets refreshed only once.</p> <pre><code>export function refreshToken(dispatch) { var freshTokenPromise = fetchJWTToken() .then(t =&gt; { dispatch({ type: DONE_REFRESHING_TOKEN }); dispatch(saveAppToken(t.token)); return t.token ? Promise.resolve(t.token) : Promise.reject({ message: 'could not refresh token' }); }) .catch(e =&gt; { console.log('error refreshing token', e); dispatch({ type: DONE_REFRESHING_TOKEN }); return Promise.reject(e); }); dispatch({ type: REFRESHING_TOKEN, // we want to keep track of token promise in the state so that we don't try to refresh // the token again while refreshing is in process freshTokenPromise }); return freshTokenPromise; } </code></pre> <p>I realize that this is pretty complicated. I am also a bit worried about dispatching actions in <code>refreshToken</code> which is not an action itself. Please let me know of any other approach you know that handles expiring JWT token with redux.</p>
3,698,532
Online k-means clustering
<p>Is there a online version of the <a href="http://en.wikipedia.org/wiki/K-means_clustering" rel="noreferrer">k-Means clustering</a> algorithm?</p> <p>By online I mean that every data point is processed in serial, one at a time as they enter the system, hence saving computing time when used in real time.</p> <p>I have wrote one my self with good results, but I would really prefer to have something "standardized" to refer to, since it is to be used in my master thesis.</p> <p>Also, does anyone have advice for other online clustering algorithms? (lmgtfy failed ;))</p>
3,706,827
1
0
null
2010-09-13 07:33:43.573 UTC
9
2013-05-26 08:53:02.283 UTC
2010-09-13 08:26:36.893 UTC
null
441,337
null
441,337
null
1
30
cluster-analysis|k-means
18,288
<p>Yes there is. Google failed to find it because it's more commonly known as "sequential k-means".</p> <p>You can find two pseudo-code implementations of sequential K-means in <a href="http://www.cs.princeton.edu/courses/archive/fall08/cos436/Duda/C/sk_means.htm" rel="noreferrer">this section of some Princeton CS class notes</a> by <a href="http://en.wikipedia.org/wiki/Richard_O._Duda" rel="noreferrer">Richard Duda</a>. I've reproduced one of the two implementations below:</p> <pre><code>Make initial guesses for the means m1, m2, ..., mk Set the counts n1, n2, ..., nk to zero Until interrupted Acquire the next example, x If mi is closest to x Increment ni Replace mi by mi + (1/ni)*( x - mi) end_if end_until </code></pre> <p>The beautiful thing about it is that you only need to remember the mean of each cluster and the count of the number of data points assigned to the cluster. Once you update those two variables, you can throw away the data point.</p> <p>I'm not sure where you would be able to find a citation for it. I would start looking in Duda's classic text <a href="http://openlibrary.org/books/OL5287711M/Pattern_classification_and_scene_analysis" rel="noreferrer">Pattern Classification and Scene Analysis</a> or the newer edition <a href="http://books.google.ca/books?id=YoxQAAAAMAAJ" rel="noreferrer">Pattern Classification</a>. If it's not there, you could try Chris Bishop's newest book or Daphne Koller and Nir Friedman's recent text.</p>
21,250,339
How to pass ArrayList<CustomeObject> from one activity to another?
<p>I want to send Following ArrayList from one activity to another please help.</p> <pre><code>ContactBean m_objUserDetails = new ContactBean(); ArrayList&lt;ContactBean&gt; ContactLis = new ArrayList&lt;ContactBean&gt;(); </code></pre> <p>I am sending the above arraylist after adding data in it as follows</p> <pre><code> Intent i = new Intent(this,DisplayContact.class); i.putExtra("Contact_list", ContactLis); startActivity(i); </code></pre> <p>But I am getting problem while recovering it.</p> <pre><code>ArrayList&lt;ContactBean&gt; l1 = new ArrayList&lt;ContactBean&gt;(); Bundle wrapedReceivedList = getIntent().getExtras(); l1= wrapedReceivedList.getCharSequenceArrayList("Contact_list"); </code></pre> <p>At this point I am getting this error:</p> <pre><code>Type mismatch: cannot convert from ArrayList&lt;CharSequence&gt; to ArrayList&lt;ContactBean&gt; </code></pre> <p>My ContactBean class implements Serializable please also tell why we have to implement serializable interface.</p>
21,250,407
4
3
null
2014-01-21 06:02:34.327 UTC
12
2018-06-02 05:38:27.893 UTC
2014-01-21 07:17:27.033 UTC
null
101,361
null
2,843,856
null
1
54
android|android-intent|bundle|serializable
136,974
<p>You can pass an <code>ArrayList&lt;E&gt;</code> the same way, if the <code>E</code> type is <code>Serializable</code>.</p> <p>You would call the <code>putExtra (String name, Serializable value)</code> of <code>Intent</code> to store, and <code>getSerializableExtra (String name)</code> for retrieval.</p> <p><strong>Example:</strong></p> <pre><code>ArrayList&lt;String&gt; myList = new ArrayList&lt;String&gt;(); intent.putExtra("mylist", myList); </code></pre> <p><strong>In the other Activity:</strong></p> <pre><code>ArrayList&lt;String&gt; myList = (ArrayList&lt;String&gt;) getIntent().getSerializableExtra("mylist"); </code></pre>
18,733,383
show entire certificate chain for a local certificate file
<p>I have a certificate (for example <a href="https://www.incommon.org/cert/repository/InCommonServerCA.txt">this one</a>) saved in a local file. Using <code>openssl</code> from the command line, <strong>how can I display the entire chain from this certificate to a root CA?</strong> I tried:</p> <pre><code>openssl verify -verbose -purpose sslserver -CApath /etc/ssl/certs InCommonServerCA.txt </code></pre> <p>and got this confusing output that only seems to show the leaf certificate:</p> <pre><code>InCommonServerCA.txt: C = US, O = Internet2, OU = InCommon, CN = InCommon Server CA error 26 at 0 depth lookup:unsupported certificate purpose OK </code></pre> <p>Any ideas?</p>
18,757,313
2
0
null
2013-09-11 05:36:05.087 UTC
3
2018-01-18 21:52:00.763 UTC
2013-09-11 16:57:46.63 UTC
null
744,071
null
744,071
null
1
28
ssl|openssl|certificate
72,457
<p>If you want to verify the chain and purpose, your openssl command is correct. The "OK" indicates the chain verifies. The error indicates there is an issue with that certificate being used for an sslserver purpose. It looks like your certificate is a CA cert, not a leaf cert. </p> <p>What kind of chain info are you trying to display? You could look at the <code>subject</code> and <code>issuer</code> fields to show chaining. The verify command you used above proves that the one cert signed the other cert.</p>
360,851
How do you concatenate text when using Bind expression in asp.net
<p>What is the syntax to concatenate text into a binding expression for an asp.net webpage (aspx).</p> <p>For example if I had a hyperlink that was being bound like this:</p> <pre><code>&lt;asp:HyperLink id="lnkID" NavigateUrl='&lt;%# Bind("Link") %&gt;' Target="_blank" Text="View" runat="server"/&gt; </code></pre> <p>How do you change, say, the Text to concatenate a bound value with a string? Variations like this aren't quite right.</p> <pre><code>Text='&lt;%# Bind("ID") + " View" %&gt;' </code></pre> <p>neither does</p> <pre><code>Text='&lt;%# String.Concat(Bind("ID"), " View") %&gt;' </code></pre>
364,328
4
0
null
2008-12-11 20:55:35.253 UTC
4
2019-11-13 09:39:53.89 UTC
null
null
null
The Imir of GrooFunkistan
1,874
null
1
15
asp.net|data-binding|syntax|binding
58,566
<p>You can also place the "concatenation" in the text portion of a tag if using a template field:</p> <pre><code>&lt;asp:TemplateField HeaderText="Name" SortExpression="sortName"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="lbName" runat="server" OnClick="lbName_Click" CommandArgument='&lt;%# Eval("ID") %&gt;'&gt; &lt;%--Enter any text / eval bindind you want between the tags--%&gt; &lt;%# Eval("Name") %&gt; (&lt;%# Eval("ID") %&gt;) &lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; </code></pre> <p></p> <p>This results in output like:</p> <p>Name (ID)</p> <p>inside of the template column.</p>
1,257,519
Nested foreach()
<p>I have the following array:</p> <pre><code>Array ( [1] =&gt; Array ( [spubid] =&gt; A00319 [sentered_by] =&gt; pubs_batchadd.php [sarticle] =&gt; Lateral mixing of the waters of the Orinoco, Atabapo [spublication] =&gt; Acta Cientifica Venezolana [stags] =&gt; acta,confluence,orinoco,rivers,venezuela,waters [authors] =&gt; Array ( [1] =&gt; Array ( [stype] =&gt; Author [iorder] =&gt; 1 [sfirst] =&gt; A [slast] =&gt; Andersen ) [2] =&gt; Array ( [stype] =&gt; Author [iorder] =&gt; 2 [sfirst] =&gt; S. [slast] =&gt; Johnson ) [3] =&gt; Array ( [stype] =&gt; Author [iorder] =&gt; 3 [sfirst] =&gt; J. [slast] =&gt; Doe ) ) ) ) </code></pre> <p>I am using a nested foreach() to walk through the elements in the outer array but when it comes to spitting out the list of authors I am running into problems. Namely the problem of outputting each one multiple (multiple) times because of the crazy foreach() nesting. What would be a better approach than nesting foreach() loops in this example?</p> <p><strong>UPDATE (With solution)</strong></p> <p>Here is the loop I settled on, a bit messy (IMHO) but it works:</p> <pre><code>$sauthors = NULL; $stitle = NULL; foreach($apubs as $apub) { $stitle = $apub['sarticle']; foreach($apub as $svar=&gt;$sval) { if($svar === "authors") { foreach($sval as $apeople) { $sauthors .= $apeople['slast'].", ".$apeople['sfirst']."; "; } } } echo "$sauthors&lt;br /&gt;\n$stitle&lt;br /&gt;\n"; } </code></pre>
1,259,255
4
3
null
2009-08-10 22:12:37.517 UTC
1
2009-08-11 10:42:06.763 UTC
2009-08-10 22:56:21.453 UTC
null
59,975
null
59,975
null
1
16
php|arrays|loops|foreach
80,341
<p>Why don't you do</p> <pre><code>foreach($apubs as $apub) { $sauthors = ''; $stitle = $apub['sarticle']; foreach($apub['authors'] as $author) { $sauthors .= $author['slast'].", ".$author['sfirst']."; "; } echo "$sauthors&lt;br /&gt;\n$stitle&lt;br /&gt;\n"; } </code></pre>
431,533
C++: Dynamically loading classes from dlls
<p>For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.</p> <p>I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.</p> <pre><code>//in namespace base class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt { public: virtual base::Texture *GetTexture()=0; virtual unsigned GetWidth()=0; virtual unsigned GetHeight()=0; virtual float GetCentreX()=0; virtual float GetCentreY()=0; virtual void SetCentre(float x, float y)=0; virtual void Draw(float x, float y)=0; virtual void Draw(float x, float y, float angle)=0; virtual void Draw(float x, float y, float scaleX, flota scaleY)=0; virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0; }; </code></pre> <p>The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.</p> <p>I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)</p> <p>EDIT: When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.</p> <p>The resulting dll could be imported in python just with "import [dllname]".</p> <pre><code>//dll compiled as cpputill.pyd extern "C" void initcpputill()//only exported method { static CppUtill* cpputill = new CppUtill; } class CppUtill : public Py::ExtensionModule&lt;CppUtill&gt; { public: CppUtill() : Py::ExtensionModule&lt;CppUtill&gt;("cpputill") { ExampleClass::init_type(); add_varargs_method("ExampleClass",&amp;CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass"); add_varargs_method("HelloWorld", &amp;CppUtill::HelloWorld, "HelloWorld(), print Hello World to console"); initialize("C Plus Plus module"); } ... class ExampleClass ... static void init_type() { behaviors().name("ExampleClass"); behaviors().doc ("example class"); behaviors().supportGetattr(); add_varargs_method("Random", &amp;ExampleClass::Random, "Random(), get float in range 0&lt;=x&lt;1"); } </code></pre> <p>How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?</p>
431,578
4
0
null
2009-01-10 18:52:31.783 UTC
15
2009-01-10 21:18:48.697 UTC
2009-01-10 19:27:33.38 UTC
Fire Lancer
6,266
Fire Lancer
6,266
null
1
30
c++|windows|class|dll
29,952
<p>Easiest way to do this, IMHO, is to have a simple C function that returns a pointer to an interface described elsewhere. Then your app, can call all of the functions of that interface, without actually knowing what class it is using.</p> <p>Edit: Here's a simple example.</p> <p>In your main app code, you create a header for the interface:</p> <pre><code>class IModule { public: virtual ~IModule(); // &lt;= important! virtual void doStuff() = 0; }; </code></pre> <p>Main app is coded to use the interface above, without any details on the actual implementation of the interface.</p> <pre><code>class ActualModule: public IModule { /* implementation */ }; </code></pre> <p>Now, the modules - the DLL's have the actual implementations of that interface, and those classes don't even have to be exported - <code>__declspec (dllexport)</code> isn't needed. The only requirement for the modules is to export a single function, that would create and return an implementation of the interface:</p> <pre><code>__declspec (dllexport) IModule* CreateModule() { // call the constructor of the actual implementation IModule * module = new ActualModule(); // return the created function return module; } </code></pre> <p>note: error checking left out - you'd usually want to check, if new returned the correct pointer and you should protect yourself from the exceptions that might be thrown in the constructor of the <code>ActualModule</code> class.</p> <p>Then, in your main app, all you need is to simply load the module (<code>LoadLibrary</code> function) and find the function <code>CreateModule</code> (<code>GetProcAddr</code> function). Then, you use the class through the interface.</p> <p>Edit 2: your RefCount (base class of the interface), can be implemented in (and exported from) the main app. Then all your module would need to link to the lib file of the main app (yes! EXE files can have LIB files just like DLL files!) And that should be enough.</p>
787,755
How to add a node to an mnesia cluster?
<p>I'm an erlang and mnesia newbie..</p> <p>How do I add a new disc_only_copies node to an mnesia database that already has a schema?</p> <p>Thanks</p>
788,847
1
0
null
2009-04-24 22:09:11.973 UTC
20
2015-08-30 06:09:28.02 UTC
2009-04-24 22:16:26.293 UTC
null
2,250,286
null
2,250,286
null
1
24
erlang|mnesia
9,968
<p>Start your new node (<code>b@node</code>) <code>erl -sname b -mnesia dir '"/path/to/storage"' -s mnesia</code>. This starts a new ram_copies node called <code>b@node</code>.</p> <p>On your original node (<code>a@node</code>), at the erlang prompt execute <code>mnesia:change_config(extra_db_nodes, ['b@node']).</code> This will cause the original node to connect <code>b</code> to the mnesia cluster. At this point, <code>b@node</code> has joined the cluster but only has a copy of the schema.</p> <p>To make new the node <code>b@node</code> capable of storing disc copies, we need to change the schema table type on <code>b@node</code> from <code>ram_copies</code> to <code>disc_copies</code>. Run <code>mnesia:change_table_copy_type(schema, 'b@node', disc_copies).</code> on any node.</p> <p><code>b@node</code> only has a copy of the schema at this point. To copy all the tables from <code>a@node</code> to <code>b@node</code> and maintain table types, you can run:</p> <pre><code>[{Tb, mnesia:add_table_copy(Tb, node(), Type)} || {Tb, [{'a@node', Type}]} &lt;- [{T, mnesia:table_info(T, where_to_commit)} || T &lt;- mnesia:system_info(tables)]]. </code></pre> <p>This command may take a while to execute as it will copy the contents of each table over the network.</p> <p><code>b@node</code> is now an exact replica of <code>a@node</code>. You could modify that statement - replace the <code>Type</code> variable with <code>disc_only_copies</code> in the call to <code>mnesia:add_table_copy/3</code> in order to copy the tables but ensure they're on disc only.</p> <p>The <a href="http://www.erlang.org/doc/man/mnesia.html" rel="noreferrer">mnesia documentation</a> explains how to use the functions I've shown here.</p>
1,124,181
How can I reference a constructor from C# XML comment?
<p>Is it possible to reference a constructor from a C# XML comment without resorting to the explicit prefixes (like M: or T:)?</p> <p>For instance, the following yields compilation warnings, because the compiler does not like ".ctor". Trying "PublishDynamicComponentAttribute.#ctor" is no good,<br> "PublishDynamicComponentAttribute.PublishDynamicComponentAttribute" is no good too.</p> <pre><code>/// &lt;summary&gt; /// Constructs a new &lt;see cref="PublishEntityAttribute"/&gt; instance. /// &lt;/summary&gt; /// &lt;seealso cref="PublishDynamicComponentAttribute..ctor(Type)"/&gt; public PublishEntityAttribute(Type entityFactoryType) : base(entityFactoryType) { } </code></pre> <p>I am sure the type itself is visible.</p> <p>So, I am left to use the explicit prefix M:, which removes the compiler verification, so when a type is moved/renamed the cref will be invalid.</p> <p>Any suggestions?</p>
1,124,254
1
0
null
2009-07-14 08:36:37.77 UTC
4
2021-09-03 02:20:50.993 UTC
null
null
null
null
80,002
null
1
30
c#|xml|constructor|comments
3,065
<p>You specify a constructor as if you are calling it, but with the types of the arguments instead of values for them:</p> <pre class="lang-cs prettyprint-override"><code>/// &lt;seealso cref=&quot;PublishDynamicComponentAttribute(Type)&quot;/&gt; </code></pre>
3,156,674
Can not deserialize instance of java.lang.Class out of START_OBJECT token
<p>I can't understand propperly the error I get when I run this code:</p> <pre><code>InputStream is = this.getClass().getClassLoader().getResourceAsStream(filename); String jsonTxt = IOUtils.toString(is); JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonTxt); JSONObject metadatacontent = json.getJSONObject(0); ObjectMapper mapper = new ObjectMapper(); mapper.readValue(metadatacontent.toString(), MetadataContentBean.class.getClass()); </code></pre> <p>Error: </p> <blockquote> <p>org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.Class out of START_OBJECT token at [Source: java.io.StringReader@e3b895; line: 1, column: 1] at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:159) at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:192) at org.codehaus.jackson.map.deser.StdDeserializer$ClassDeserializer.deserialize(StdDeserializer.java:439) at org.codehaus.jackson.map.deser.StdDeserializer$ClassDeserializer.deserialize(StdDeserializer.java:421) at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588) at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1116) at com.path.parser.JSon.Parser(JSon.java:65) at com.path.parser.JSon.main(JSon.java:29)</p> </blockquote> <p>What does it mean??</p> <p>Maybe if I know this, I could find out my error.</p>
3,156,694
2
0
null
2010-07-01 09:51:40.237 UTC
null
2012-05-30 15:18:04.447 UTC
2011-04-18 12:45:34.67 UTC
null
457,208
null
457,208
null
1
6
java|jackson
39,617
<p>Your problem is the last line:</p> <pre><code>MetadataContentBean.class.getClass() </code></pre> <p>This means "get me the <code>Class</code> object for the MetadataContentBean class, and then get me the <code>Class</code> object for that <code>Class</code> object".... if you see what I mean. So you're asking Jackson to deserialize your JSON onto a <code>Class</code> object, which it doesn't know how to do.</p> <p>This should be just</p> <pre><code>MetadataContentBean.class </code></pre>
41,008,092
Class template argument deduction not working with alias template
<p>consider the code pasted below. I have defined a very simple class, for which the compiler generates an implicit deduction guide so it can be constructed without explicit template arguments. However, the template argument deduction <em>does not</em> work for constructing an object from a simple alias template which only forwards directly to the target class:</p> <pre><code>template&lt; typename A, typename B &gt; struct Foo { Foo( A const &amp;a, B const &amp;b ) : a_(a), b_(b) { } A a_; B b_; }; template&lt; typename A, typename B &gt; using Bar = Foo&lt;A, B&gt;; auto foobar() { Foo r{1, 2}; Bar s{3, 4}; // ../src/geo/vector_test_unit.cpp: In function 'auto foobar()': // ../src/geo/vector_test_unit.cpp:16:6: error: missing template arguments before 's' // Bar s{3, 4}; // ^ return 1; } </code></pre> <p>As you can see from a code comment above, g++ is giving me an error about using the aliased template without template arguments. I was hoping in such an instance that template argument deduction would be forwarded.</p> <p><strong>So, my question</strong>: Is this by express design of the current wording of the proposal for class template argument deduction? Or is this an unfinished feature or bug in the current g++ implementation of the feature? And this would be more of a question for the authors of the proposal, or for the C++ ISO Committee, but if any of them see this: Would it be desired that the final wording of the feature include enabling alias templates such as this to also have implicit guides generated for them?</p> <p>I can understand that since alias templates can have any kind of template parameters it may not always be possible for the compiler to successfully deduce the target class template arguments, but in a case like this I would expect that the compiler would be able to in the same way that it can directly for the target class.</p> <p>I am building with gcc built from head only a few days ago, using <code>--std=c++1z</code>. The complete version info is: <code>gcc version 7.0.0 20161201 (experimental) (Homebrew gcc HEAD- --with-jit)</code></p>
41,008,415
2
0
null
2016-12-07 01:49:37.697 UTC
11
2020-03-26 21:49:45.993 UTC
2016-12-07 01:52:59.773 UTC
null
596,781
null
1,286,986
null
1
39
c++|c++17
3,891
<p>This was a feature that we considered when formulating the proposal, but it was eventually cut from the C++17 feature set because we didn't yet have a good enough design for it. In particular, there are some subtleties regarding how you select and transform deduction guides from the aliased template into deduction guides for the alias template. There are also open questions as to how to behave if the alias template is not a simple alias for another template. Some examples:</p> <pre><code>template&lt;typename T&gt; struct Q { Q(T); }; // #1 template&lt;typename T&gt; struct Q&lt;T*&gt; { Q(T); }; // #2 template&lt;typename U&gt; using QP = Q&lt;U*&gt;; int *x; Q p = x; // deduces Q&lt;int*&gt; using #1, ill-formed QP q = x; // deduces Q&lt;int*&gt; using #1, or // deduces Q&lt;int**&gt; using #2? template&lt;typename T&gt; Q(T) -&gt; Q&lt;T&gt;; // #3 QP r = x; // can we use deduction guide #3 here? template&lt;typename T&gt; Q(T*) -&gt; Q&lt;T**&gt;; // #4 int **y; QP s = y; // can we use deduction guide #4 here? </code></pre> <hr> <pre><code>template&lt;typename T&gt; struct A { typedef T type; struct Y {}; }; template&lt;typename T&gt; using X = typename A&lt;T&gt;::type; template&lt;typename T&gt; using Y = typename A&lt;T&gt;::Y; X x = 4; // can this deduce T == int? Y y = A&lt;int&gt;::Y(); // can this deduce T == int? </code></pre> <p>There are decent answers to the above questions, but tackling them adds complexity, and it seemed preferable to disallow deduction for alias templates for C++17 rather than rush something flawed in.</p> <p><strong>Update [C++20]</strong>: This topic was revisited for C++20, and we approved <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1814r0.html" rel="noreferrer">P1814R0</a>, which permits class template argument deduction for alias templates.</p> <p>The original example is now valid. For the examples above:</p> <ul> <li><p>CTAD still only considers constructors from the primary template. So in <code>QP q = x;</code>, #2 is not considered, and instead #1's constructor is used. That constructor is implicitly converted into a guide for <code>Q</code>:</p> <pre><code>template&lt;typename T&gt; Q(T) -&gt; Q&lt;T&gt;; </code></pre> <p>which is then converted into a guide for the alias template <code>QP</code> by deducing the right-hand side of the guide for <code>Q</code> (<code>Q&lt;T&gt;</code>) from the right-hand side of the alias template (<code>Q&lt;U*&gt;</code>), which deduces <code>T</code> = <code>U*</code>, then substituting that back into the guide, thereby producing the equivalent of:</p> <pre><code>template&lt;typename U&gt; Q(U*) -&gt; Q&lt;U*&gt;; // ... which is effectively ... template&lt;typename U&gt; QP(U*) -&gt; QP&lt;U&gt;; // ... except that explicit deduction guides are not // permitted for alias templates </code></pre> <p>That guide is then used to deduce the type of <code>q</code>, which deduces <code>U</code> = <code>int</code>, so the type of <code>q</code> is <code>Q&lt;int*&gt;</code>, so the initialization of <code>q</code> is ill-formed.</p></li> <li><p>The initialization of <code>r</code> does consider deduction guide #3, which is transformed into a guide for <code>QP</code> as described above</p></li> <li><p>The initialization of <code>s</code> does consider deduction guide #4; deducing <code>Q&lt;T**&gt;</code> from <code>Q&lt;U*&gt;</code> deduces nothing, so we retain the deduction guide</p> <pre><code>template&lt;typename T&gt; Q(T*) -&gt; Q&lt;T**&gt;; </code></pre> <p>as-is, but add a constraint that the result of deduction must match the form of <code>QP</code>. We then deduce <code>T</code> = <code>int</code>, substitute that in to compute a result type of <code>Q&lt;int**&gt;</code>, and check that we can deduce <code>QP&lt;U&gt;</code> from <code>Q&lt;int**&gt;</code>, which we can. So the type of <code>s</code> is deduced as <code>Q&lt;int**&gt;</code>.</p></li> <li><p>CTAD for alias templates is only supported where the right-hand side of the alias template is a <em>simple-template-id</em> (of the form <code>maybe::stuff::templatename&lt;args&gt;</code>). So neither <code>X</code> nor <code>Y</code> is deducible.</p></li> </ul>
48,682,572
CentOS installed php72 but command line php isn not working
<p>I'm reading the following tutorial on installing PHP 7.2 on CentOS 7 <a href="https://www.cyberciti.biz/faq/how-to-install-php-7-2-on-centos-7-rhel-7/" rel="noreferrer">https://www.cyberciti.biz/faq/how-to-install-php-7-2-on-centos-7-rhel-7/</a></p> <p>It basically says;</p> <pre><code>sudo yum install epel-release sudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm sudo yum install yum-utils sudo yum-config-manager --enable remi-php72 sudo yum update sudo yum install php72 </code></pre> <p>Then it says to verify the installation using the standard</p> <pre><code>php --version </code></pre> <p>Which returns the following;</p> <pre><code>-bash: php: command not found </code></pre> <p>BUT, if i type the following;</p> <pre><code>php72 --version </code></pre> <p>It works just fine and returns the version.</p> <p>The problem is that everything relies on the command php and not php72</p> <p>Any idea on what i should be doing?</p>
48,683,067
6
1
null
2018-02-08 09:59:14.677 UTC
10
2021-02-26 22:57:27.913 UTC
null
null
null
user9048585
null
null
1
19
php|linux|centos
51,976
<p>Please read the <a href="https://rpms.remirepo.net/wizard/" rel="noreferrer">Wizard instructions</a></p> <p>If you need a single version, using remi-php72 repository, and the <strong>php-*</strong> packages, the command will be <strong>php</strong>.</p> <pre><code># yum-config-manager --enable remi-php72 # yum update # yum install php-cli # php -v </code></pre> <p>If you need multiples versions, the <strong>php72-php-*</strong> packages are available, and the command is <strong>php72</strong> or</p> <pre><code># yum install php72-php-cli # php72 -v # scl enable php72 bash # php -v </code></pre> <p>So, according to your question, you have enable the remi-php72 repository, but installed the php72* packages from the remi-safe repository...</p>
33,483,350
How do I enable ISAPI DLLs for IIS 10 on Windows 10?
<p>I've configured ISAPI DLLs for IIS 7.x for years, but this is the first time I've tried with Windows 10, and it is not working, and I cannot find any descriptions of how to do it successfully. I am working in Windows 10 Professional, and IIS and supporting technologies are installed. </p> <p>Here's is what I've done in the past. First, I open the Internet Information Services Manager console. I then select the default Web site and open Handler Mappings. I right-click ISAPI-dll in the Disabled section, select Edit Feature Permissions, and place a checkmark next to Execute.</p> <p>Since my ISAPI dll is a 32-bit DLL, and I am running Windows 10 64-bit Professional, I select Application Pools in the Connections pane, right-click DefaultAppPool, and select Advanced Settings, and then set Enable 32-Bit Applications to True.</p> <p>Finally, I open the ISAPI and CGI Restrictions applet. I then right-click in the ISAPI and CGI Restrictions pane and select Edit Feature Settings, after which I place a checkmark next to Allow unspecified ISAPI modules.</p> <p>The Handler Mappings applet no longer has a disabled ISAPI-dll entry. However, with the Handler Mappings applet open, I have been able to select Edit Feature Permissions, and place a checkmark next to Execute. I have been able to allow 32-bit applications in the default application pool, but the ISAPI and CGI Restrictions applet is no where to be found.</p> <p>The end result is that despite the configuration that I have successfully performed as described above I still cannot run my ISAPI DLL. I have placed the DLL in the same location as my Windows 7 setup (under c:\inetpub\wwwroot\appfolder), and use the same URL. It runs in Windows 7, but not in Windows 10. </p> <p>How do I configure IIS in Windows 10 to run this ISAPI DLL?</p>
33,492,516
3
0
null
2015-11-02 17:23:26.89 UTC
null
2020-02-28 13:17:07.417 UTC
null
null
null
null
84,904
null
1
6
windows-10|isapi|iis-10
45,336
<p>Perhaps a silly question, but are you sure the "CGI" and "ISAPI Extensions" features are installed as part of the "Internet Information Services", "World Wide Web Services", "Application Development Features"? I just tested, and without these two features, you will see the Handler Mappings, but no disabled ISAPI-dll entry (and also no "ISAPI and CGI restrictions" applet).</p> <p>With these features present, I can use IIS7 the same way in Windows 10 as I normally do with Windows Server 2012.</p>
26,930,338
MomentJS - How to get last day of previous month from date?
<p>I'm trying to get last day of the previous month using:</p> <pre><code> var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD'); </code></pre> <p>Where: </p> <pre><code>dateFrom = 2014-11-30 </code></pre> <p>But after using </p> <pre><code>subtract(1, 'months') </code></pre> <p>it returns date </p> <pre><code>DATE_FROM: "2014-10-30" </code></pre> <p>But last day of the 10'th month is 31. </p> <p>How can I solve i please?</p> <p>Many thanks for any help.</p>
26,930,458
5
0
null
2014-11-14 12:44:19.183 UTC
10
2022-03-11 18:39:38.75 UTC
null
null
null
null
535,556
null
1
85
javascript|date|momentjs
95,894
<p>Simply add a <code>endOf('month')</code> to your calls:</p> <p><code>var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');</code></p> <p><a href="http://jsfiddle.net/r42jg/327/">http://jsfiddle.net/r42jg/327/</a></p>
30,611,172
Launch Chrome browser from Internet Explorer
<p>We have a web application which has some features that works only in Chrome and I want to launch this web app using Google chrome browser with url of the web app as parameter from Internet explorer via a hyperlink. I tried </p> <blockquote> <p>file:///C:/Program%20Files%20(x86)/Google/Chrome/application/chrome.exe </p> </blockquote> <p>but it downloads the file + how do I add parameter to the exe. </p>
30,611,308
6
0
null
2015-06-03 04:59:33.313 UTC
2
2020-08-26 17:13:22.353 UTC
2015-06-03 05:03:33.22 UTC
null
401,672
null
374,902
null
1
5
javascript|google-chrome|internet-explorer|hyperlink
46,648
<p>By default, a browser cannot launch another program (plugins and extensions being possible exceptions). If they could, imagine the havoc some malicious user could get up to. </p> <p>I don't think there's going to be a great answer for this, but you could make a .bat file that opens chrome to a particular URL (assuming you're using Windows), download that and click on it after it downloads.</p> <p><a href="https://stackoverflow.com/questions/19352463/writing-a-batch-file-that-opens-a-chrome-url">Here</a> is a useful answer in that case.</p> <p>You could also (theoretically) make an extension or lower the security settings on IE to allow ActiveX controls. <a href="https://stackoverflow.com/questions/6265717/how-to-start-up-a-desktop-application-in-client-side">Here's</a> a partial solution. I tried to make something similar a while back and didn't have much luck, but if you're determined...</p> <p>Maybe there's a better way that doesn't involve such complicated solutions?</p>
27,841,662
Linqpad dump more than 1000 rows
<p><code>.Dump()</code> only shows 1k results. How do I get it to show more than that with html formatting? The Grid results options doesn't have the formatting I need.</p>
27,841,688
1
0
null
2015-01-08 13:48:50.87 UTC
1
2016-07-04 09:46:04.513 UTC
2016-07-04 09:46:04.513 UTC
null
5,919,473
null
1,123,241
null
1
30
linqpad
6,795
<p>Taken from <a href="http://forum.linqpad.net/discussion/198/result-size" rel="noreferrer">this post at linqpad</a></p> <blockquote> <p>In the GUI go to edit -> preferences -> results . At the bottom you will see "In Rich Text Mode" as well as "In DataGrid Mode". The rich text mode works on the <code>.Dump()</code> in the editor, or automating a .linq query using <code>.Dump()</code></p> </blockquote>
39,140,068
How to connect to database from Unity
<p>I am trying to connect to a MS SQL database through Unity. However, when I try to open a connection, I get an IOException: Connection lost.</p> <p>I have imported System.Data.dll from Unity\Editor\Data\Mono\lib\mono\2.0. I am using the following code:</p> <pre><code> using UnityEngine; using System.Collections; using System.Data.Sql; using System.Data.SqlClient; public class SQL_Controller : MonoBehaviour { string conString = "Server=myaddress.com,port;" + "Database=databasename;" + "User ID=username;" + "Password=password;"; public string GetStringFromSQL() { LoadConfig(); string result = ""; SqlConnection connection = new SqlConnection(conString); connection.Open(); Debug.Log(connection.State); SqlCommand Command = connection.CreateCommand(); Command.CommandText = "select * from Artykuly2"; SqlDataReader ThisReader = Command.ExecuteReader(); while (ThisReader.Read()) { result = ThisReader.GetString(0); } ThisReader.Close(); connection.Close(); return result; } } </code></pre> <p>This is the error I get:</p> <pre><code>IOException: Connection lost Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader () Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket () Mono.Data.Tds.Protocol.TdsComm.GetByte () Mono.Data.Tds.Protocol.Tds.ProcessSubPacket () Mono.Data.Tds.Protocol.Tds.NextResult () Mono.Data.Tds.Protocol.Tds.SkipToEnd () Rethrow as TdsInternalException: Server closed the connection. Mono.Data.Tds.Protocol.Tds.SkipToEnd () Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters) Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters) </code></pre> <p>Please disregard any security risks with this approach, I NEED to do this for testing, security will come later. Thank you for your time.</p>
39,140,295
3
0
null
2016-08-25 08:18:36.207 UTC
18
2020-04-21 08:52:46.86 UTC
2018-01-11 07:42:52.27 UTC
null
3,785,314
null
6,756,019
null
1
10
c#|sql-server|sql-server-2008|unity3d|mono
70,837
<blockquote> <p>Please disregard any security risks with this approach</p> </blockquote> <p><em>Do not do it like this</em>. It doesn't matter if security will come before or after. You will end of re-writing the whole code because the <strong>password</strong> is hard-coded in your application which can be decompiled and retrieved <strong>easily</strong>. Do the connection the correct way now so that you won't have to re-write the whole application. </p> <p>Run your database command on your server with php, perl or whatever language you are comfortable with but this should be done on the server.</p> <p>From Unity, use the <a href="https://docs.unity3d.com/ScriptReference/WWW.html" rel="noreferrer"><code>WWW</code></a> or <a href="https://docs.unity3d.com/Manual/UnityWebRequest.html" rel="noreferrer"><code>UnityWebRequest</code></a> class to communicate with that script and then, you will be able to send and receive information from Unity to the server. There are many <a href="http://wiki.unity3d.com/index.php?title=Server_Side_Highscores" rel="noreferrer">examples</a> out <a href="https://stackoverflow.com/a/25200894/3785314">there</a>. Even with this, you still need to implement your own security but this is much more better than what you have now.</p> <p>You can also receive data multiple with <a href="https://docs.unity3d.com/ScriptReference/JsonUtility.html" rel="noreferrer">json</a>. </p> <p>Below is a complete example from <a href="http://wiki.unity3d.com/index.php?title=Server_Side_Highscores" rel="noreferrer">this</a> Unity wiki. It shows how to interact with a database in Unity using php on the server side and Unity + C# on the client side.</p> <p><strong>Server Side</strong>:</p> <p><em>Add score with PDO</em>:</p> <pre><code>&lt;?php // Configuration $hostname = 'localhot'; $username = 'yourusername'; $password = 'yourpassword'; $database = 'yourdatabase'; $secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below try { $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password); } catch(PDOException $e) { echo '&lt;h1&gt;An error has ocurred.&lt;/h1&gt;&lt;pre&gt;', $e-&gt;getMessage() ,'&lt;/pre&gt;'; } $realHash = md5($_GET['name'] . $_GET['score'] . $secretKey); if($realHash == $hash) { $sth = $dbh-&gt;prepare('INSERT INTO scores VALUES (null, :name, :score)'); try { $sth-&gt;execute($_GET); } catch(Exception $e) { echo '&lt;h1&gt;An error has ocurred.&lt;/h1&gt;&lt;pre&gt;', $e-&gt;getMessage() ,'&lt;/pre&gt;'; } } ?&gt; </code></pre> <p><em>Retrieve score with PDO</em>:</p> <pre><code>&lt;?php // Configuration $hostname = 'localhost'; $username = 'yourusername'; $password = 'yourpassword'; $database = 'yourdatabase'; try { $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password); } catch(PDOException $e) { echo '&lt;h1&gt;An error has occurred.&lt;/h1&gt;&lt;pre&gt;', $e-&gt;getMessage() ,'&lt;/pre&gt;'; } $sth = $dbh-&gt;query('SELECT * FROM scores ORDER BY score DESC LIMIT 5'); $sth-&gt;setFetchMode(PDO::FETCH_ASSOC); $result = $sth-&gt;fetchAll(); if(count($result) &gt; 0) { foreach($result as $r) { echo $r['name'], "\t", $r['score'], "\n"; } } ?&gt; </code></pre> <p><em>Enable cross domain policy on the server</em>:</p> <p>This file should be named "crossdomain.xml" and placed in the root of your web server. Unity requires that websites you want to access via a WWW Request have a cross domain policy.</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;cross-domain-policy&gt; &lt;allow-access-from domain="*"/&gt; &lt;/cross-domain-policy&gt; </code></pre> <hr> <p><strong>Client/Unity Side</strong>:</p> <p>The client code from Unity connects to the server, interacts with PDO and adds or retrieves score depending on which function is called. This client code is slightly modified to compile with the latest Unity version.</p> <pre><code>private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url public string highscoreURL = "http://localhost/unity_test/display.php"; //Text to display the result on public Text statusText; void Start() { StartCoroutine(GetScores()); } // remember to use StartCoroutine when calling this function! IEnumerator PostScores(string name, int score) { //This connects to a server side php script that will add the name and score to a MySQL DB. // Supply it with a string representing the players name and the players score. string hash = Md5Sum(name + score + secretKey); string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&amp;score=" + score + "&amp;hash=" + hash; // Post the URL to the site and create a download object to get the result. WWW hs_post = new WWW(post_url); yield return hs_post; // Wait until the download is done if (hs_post.error != null) { print("There was an error posting the high score: " + hs_post.error); } } // Get the scores from the MySQL DB to display in a GUIText. // remember to use StartCoroutine when calling this function! IEnumerator GetScores() { statusText.text = "Loading Scores"; WWW hs_get = new WWW(highscoreURL); yield return hs_get; if (hs_get.error != null) { print("There was an error getting the high score: " + hs_get.error); } else { statusText.text = hs_get.text; // this is a GUIText that will display the scores in game. } } public string Md5Sum(string strToEncrypt) { System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); // encrypt bytes System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) string hashString = ""; for (int i = 0; i &lt; hashBytes.Length; i++) { hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } return hashString.PadLeft(32, '0'); } </code></pre> <p>This is just an example on how to properly do this. If you need to implement session feature and care about security, look into the <em>OAuth 2.0</em> protocol. There should be existing libraries that will help get started with the <em>OAuth</em> protocol. </p>
22,077,231
mysql ERROR! The server quit without updating PID file?
<p>My Vps mysql wont boot , when i attempt to command service mysql start i got this error</p> <pre><code>root@## [/var/lib/mysql]# service mysql start Starting MySQL... ERROR! The server quit without updating PID file (/var/lib/mysql/***.***.com.pid). </code></pre> <p>this is <code>my.cnf</code></p> <pre><code>[mysqld] local-infile=0 set-variable = 100 max_connections=100 safe-show-database #userstat_running=on query_cache_limit=4M query_cache_size=64M query_cache_type=1 max_user_connections=100 interactive_timeout=30 wait_timeout=100 connect_timeout = 20 thread_cache_size = 256 key_buffer_size=16M join_buffer_size=2M max_heap_table_size=16M low_priority_updates=1 max_allowed_packet=128M max_seeks_for_key=100 record_buffer=2M sort_buffer_size=16M read_buffer_size=16M max_connect_errors=10 # Try number of CPU's*2 for thread_concurrency thread_concurrency=4 myisam_sort_buffer_size=64M tmp_table_size= 64M set-variable=table_cache=100 read_rnd_buffer_size=1M skip-name-resolve open_files_limit=6050 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid </code></pre> <p>and this is the error log</p> <pre><code>140227 21:23:41 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql 140227 21:23:41 [Note] Plugin 'FEDERATED' is disabled. 140227 21:23:41 InnoDB: The InnoDB memory heap is disabled 140227 21:23:41 InnoDB: Mutexes and rw_locks use InnoDB's own implementation 140227 21:23:41 InnoDB: Compressed tables use zlib 1.2.3 140227 21:23:41 InnoDB: Using Linux native AIO 140227 21:23:41 InnoDB: Initializing buffer pool, size = 128.0M 140227 21:23:41 InnoDB: Completed initialization of buffer pool 140227 21:23:41 InnoDB: highest supported file format is Barracuda. 140227 21:23:41 InnoDB: Waiting for the background threads to start 140227 21:23:42 InnoDB: 5.5.35 started; log sequence number 2155325 140227 21:23:42 [ERROR] /usr/sbin/mysqld: unknown variable 'set-variable=100' 140227 21:23:42 [ERROR] Aborting 140227 21:23:42 InnoDB: Starting shutdown... 140227 21:23:43 InnoDB: Shutdown completed; log sequence number 2155325 140227 21:23:43 [Note] /usr/sbin/mysqld: Shutdown complete 140227 21:23:43 mysqld_safe mysqld from pid file /var/lib/mysql/***/***.com.pid ended </code></pre> <p>how to fix this ? any idea </p>
22,077,260
4
0
null
2014-02-27 18:28:42.263 UTC
2
2017-01-24 14:38:48.24 UTC
null
null
null
null
3,059,001
null
1
8
mysql
46,866
<pre><code>140227 21:23:42 [ERROR] /usr/sbin/mysqld: unknown variable 'set-variable=100' </code></pre> <p>remove the line from configuration file</p>
36,292,438
How to use Bootstrap in an Angular project?
<p>I am starting my first <strong>Angular</strong> application and my basic setup is done.</p> <p>How can I add <strong>Bootstrap</strong> to my application?</p> <p>If you can provide an example then it would be a great help.</p>
43,254,064
20
0
null
2016-03-29 18:36:25.89 UTC
33
2021-07-14 08:22:57.397 UTC
2019-02-28 18:56:49.383 UTC
null
8,718,377
null
3,739,018
null
1
173
angular|twitter-bootstrap|typescript|twitter-bootstrap-3
191,371
<p>Provided you use the <strong>Angular-CLI</strong> to generate new projects, there's another way to make bootstrap accessible in <strong>Angular 2/4</strong>.</p> <ol> <li>Via command line interface navigate to the project folder. Then use <strong>npm</strong> to install bootstrap:<br> <code>$ npm install --save bootstrap</code>. The <code>--save</code> option will make bootstrap appear in the dependencies.</li> <li>Edit the .angular-cli.json file, which configures your project. It's inside the project directory. Add a reference to the <code>"styles"</code> array. The reference has to be the relative path to the bootstrap file downloaded with npm. In my case it's: <code>"../node_modules/bootstrap/dist/css/bootstrap.min.css",</code></li> </ol> <p><strong>My example .angular-cli.json:</strong></p> <pre><code>{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": "bootstrap-test" }, "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html", "main": "main.ts", "polyfills": "polyfills.ts", "test": "test.ts", "tsconfig": "tsconfig.app.json", "testTsconfig": "tsconfig.spec.json", "prefix": "app", "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.css" ], "scripts": [], "environmentSource": "environments/environment.ts", "environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } } ], "e2e": { "protractor": { "config": "./protractor.conf.js" } }, "lint": [ { "project": "src/tsconfig.app.json" }, { "project": "src/tsconfig.spec.json" }, { "project": "e2e/tsconfig.e2e.json" } ], "test": { "karma": { "config": "./karma.conf.js" } }, "defaults": { "styleExt": "css", "component": {} } } </code></pre> <p>Now bootstrap should be part of your default settings. </p>
37,389,788
Vue.js: check if a component exists
<p>I need to do some stuff in the <code>ready:</code> of the root instance only when some components don't exist (they weren't declared in the HTML).</p> <p>How can I check if a component exists?</p>
37,412,003
6
1
null
2016-05-23 11:28:01.597 UTC
6
2018-12-20 10:31:45.84 UTC
2016-06-07 20:23:46.177 UTC
null
2,867,928
null
2,192,660
null
1
24
javascript|vue.js
38,802
<p>I really hope there is a better answer than this, but for the moment this solves the problem. </p> <p>In the ready, I access the children elements through <code>this</code> (could be also <code>Vue</code>) and check whether their name is or not what I was expecting:</p> <pre><code> ready: function() { for (var i = 0; i &lt; this.$children.length; i++) { if ( this.$children[i].$options.name == 'my_component_a' || this.$children[i].$options.name == 'my_component_b' || this.$children[i].$options.name == 'my_component_c' ) { //do stuff } } } </code></pre> <p>You can also access them directly if you previously assigned them a reference in their template: //template:</p> <pre><code>&lt;comp v-ref:my_component_ref&gt;&lt;/comp&gt; </code></pre> <p>Then from the Vue component ready:</p> <pre><code>if (this.$refs.my_component_ref){ //do stuff } </code></pre>
25,445,318
Docker: How do I pull a specific build-id?
<p>I would like to always pull a specific version, rather than just the latest.</p> <p>A random example: <a href="https://registry.hub.docker.com/u/aespinosa/jenkins/builds_history/9511/" rel="noreferrer">https://registry.hub.docker.com/u/aespinosa/jenkins/builds_history/9511/</a></p> <p>I am doing this because I only want to deploy versions that I have audited. Is this currently possible? Or am I forced to fork them and make my own?</p>
40,730,725
3
2
null
2014-08-22 10:52:01.51 UTC
4
2021-07-21 17:20:38.47 UTC
null
null
null
null
1,282,045
null
1
28
docker|dockerhub
21,534
<p>You can pull a specific <a href="https://docs.docker.com/engine/reference/commandline/pull/#/pull-an-image-by-digest-immutable-identifier" rel="noreferrer">image by digest</a> by using the following syntax:</p> <pre><code>docker pull ubuntu@sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2 </code></pre> <p>If you need to find the hash, it is output when pushing/pulling the image. Some automated builds output it at the end. I tried looking for the hash with <code>docker inspect</code> but it didn't appear to be there, so you'll have to delete the image and pull it again to view the hash.</p>
30,387,978
HTML SVG - Is it possible to import a <svg> into Adobe Illustrator to modify it?
<p>As the title says, how can I modify a svg in Adobe Illustrator?</p> <p>For example, I got this</p> <pre><code>&lt;svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="595.28px" height="841.89px" viewBox="0 0 595.28 841.89" enable-background="new 0 0 595.28 841.89" xml:space="preserve"&gt; &lt;text transform="matrix(1 0 0 1 225 321)" font-family="'MyriadPro-Regular'" font-size="12"&gt;This a TEST!&lt;/text&gt; &lt;path fill="none" d="M177,246c0,92.859,77.824,168,174,168"/&gt; &lt;path fill="none" d="M357,246c0,161.398-105.555,292-236,292"/&gt; &lt;path fill="none" d="M288,414c0,113.311-23.252,205-51.987,205"/&gt; &lt;rect x="93" y="383" fill="none" width="364" height="147"/&gt; &lt;g&gt; &lt;rect x="167" y="272" fill="none" width="216" height="244.5"/&gt; &lt;/g&gt; &lt;rect x="476" y="428" fill="none" width="216" height="244.5"/&gt; &lt;rect x="121" y="230" fill="none" width="403" height="231"/&gt; &lt;rect x="179" y="158" fill="none" width="362" height="454.25"/&gt; &lt;rect x="73" y="230" fill="none" width="294" height="184"/&gt; &lt;rect x="371" y="516.5" fill="none" width="12" height="13.5"/&gt; &lt;rect x="167" y="143" fill="none" width="221" height="387"/&gt; &lt;/svg&gt; </code></pre> <p>(It doesn't contain anything, its just a random svg).</p> <p>Do I have to download it as .svg first? And how can I download it as .svg?</p>
30,388,050
4
1
null
2015-05-22 03:39:36.82 UTC
5
2021-11-23 21:06:18.67 UTC
null
null
null
null
4,484,822
null
1
24
html|svg
38,036
<p>Paste it into a text file named whatever.svg and open that file in Illustrator.</p>
20,600,800
JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images
<p>Digital camera photos are often saved as JPEG with an EXIF "orientation" tag. To display correctly, images need to be rotated/mirrored depending on which orientation is set, but browsers ignore this information rendering the image. Even in large commercial web apps, support for EXIF orientation can be spotty <a href="http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/" rel="noreferrer">1</a>. The same source also provides a nice summary of the <strong>8 different orientations</strong> a JPEG can have:</p> <p><img src="https://i.stack.imgur.com/6cJTP.gif" alt="Summary of EXIF Orientations"></p> <p>Sample images are available at <a href="http://www.galloway.me.uk/2012/01/uiimageorientation-exif-orientation-sample-images/" rel="noreferrer">4</a>. </p> <p><strong>The question is how to rotate/mirror the image on the client side so that it displays correctly and can be further processed if necessary?</strong></p> <p>There are JS libraries available to parse EXIF data, including the orientation attribute <a href="https://github.com/jseidelin/exif-js" rel="noreferrer">2</a>. Flickr noted possible performance problem when parsing large images, requiring use of webworkers <a href="http://code.flickr.net/2012/06/01/parsing-exif-client-side-using-javascript-2/" rel="noreferrer">3</a>.</p> <p>Console tools can correctly re-orient the images <a href="https://superuser.com/questions/36645/how-to-rotate-images-automatically-based-on-exif-data">5</a>. A PHP script solving the problem is available at <a href="http://www.neilyoungcv.com/blog/code-share/image-resizing-with-php-exif-orientation-fix/" rel="noreferrer">6</a></p>
20,600,801
14
2
null
2013-12-15 22:41:21.88 UTC
77
2022-02-04 09:45:47.063 UTC
2019-12-27 05:29:00.55 UTC
null
9,473,764
null
3,096,626
null
1
177
javascript|rotation|html5-canvas|exif
191,496
<p>The github project <a href="https://github.com/blueimp/JavaScript-Load-Image">JavaScript-Load-Image</a> provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of <a href="http://blueimp.github.io/JavaScript-Load-Image/">javascript exif orientation</a></p> <p>The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in <a href="https://github.com/blueimp/JavaScript-Load-Image/blob/master/js/load-image-orientation.js">js/load-image-orientation.js</a> through canvas operations.</p> <p>Hope this saves somebody else some time, and teaches the search engines about this open source gem :)</p>
4,223,083
Custom authentication strategy for devise
<p>I need to write a custom authentication strategy for <a href="https://github.com/plataformatec/devise" rel="noreferrer">https://github.com/plataformatec/devise</a> but there doesn't seem to be any docs. How's it done? </p>
4,223,556
1
0
null
2010-11-19 07:55:07.23 UTC
10
2011-12-12 21:57:16.327 UTC
2010-11-19 09:08:59.783 UTC
null
162,337
null
162,337
null
1
26
ruby-on-rails|ruby|devise
15,613
<p>I found this very helpful snippet in <a href="http://groups.google.com/group/plataformatec-devise/browse_thread/thread/4ae0ce2b5f1003e8/9b9e9de48bc18673?lnk=gst&amp;q=strategy#9b9e9de48bc18673" rel="noreferrer">this thread</a> on the devise google group </p> <p>initializers/some_initializer.rb: </p> <pre><code>Warden::Strategies.add(:custom_strategy_name) do def valid? # code here to check whether to try and authenticate using this strategy; return true/false end def authenticate! # code here for doing authentication; # if successful, call success!(resource) # where resource is the whatever you've authenticated, e.g. user; # if fail, call fail!(message) # where message is the failure message end end </code></pre> <p>add following to initializers/devise.rb </p> <pre><code> config.warden do |manager| manager.default_strategies.unshift :custom_strategy_name end </code></pre>
13,888,663
Method in the type is not applicable to the arguments
<p>i've looked through many posts on here and couldn't quite see the solution I need...</p> <p>I'm getting the error: </p> <pre><code>the method initTimer(untitled.Object, String, int int) in the type untitled.TimerClass is not applicable for the arguments (untitled.Toon, String, int, int) </code></pre> <p>and it's driving me crazy.</p> <pre><code> timers.initTimer(character, "regenAdd", 0,3); </code></pre> <p>The above line is the one throwing the error and the following is the function:</p> <pre><code>public void initTimer(final Object obj, final String method, int delay, int period) { delay*=1000; period*=1000; final Class&lt;?&gt; unknown = obj.getClass(); new Timer().schedule(new TimerTask() { public void run() { try { //get the method from the class Method whatToDo = unknown.getMethod(method, null); try { //invoke() the object method whatToDo.invoke(obj); } catch(Exception e) { println("Exception encountered: " + e); } } catch(NoSuchMethodException e) { println("Exception encountered: " + e); } runState = getTimerState(); if (!runState) { println("timer dead"); this.cancel(); } } } , delay, period); } </code></pre> <p>Thanks in advance to anybody who can help with this :)</p> <p>Additional info:</p> <blockquote> <p>runState is a boolean just incase you couldn't guess and character is an instance of the Toon class; the above method is within the TimerClass class and 'timers' is an instance of that class.</p> </blockquote>
13,888,990
2
5
null
2012-12-15 02:09:39.66 UTC
null
2016-03-24 04:33:41.413 UTC
2012-12-15 02:19:13.15 UTC
null
256,196
null
1,446,063
null
1
4
java|object|arguments|processing
53,739
<p>The error message</p> <blockquote> <p>the method <code>initTimer(untitled.Object, String, int int)</code> in the type <code>untitled.TimerClass</code> is not applicable for the arguments <code>(untitled.Toon, String, int, int)</code></p> </blockquote> <p>is due to the fact that <code>untitled.Toon</code> does not extend <code>untitled.Object</code>. It extends <code>java.lang.Object</code> of course, which is why the reason is not immediately obvious from the source code.</p>
15,730,913
Concatenate multiple HTML text inputs with stored variable
<p>I am trying to create a simple html form which asks for some details from a user and once this has been submitted will add the text to some predetermined text in a text box.</p> <p>Example of this...</p> <p>Text box 1 - Enter Name Text box 2 - Enter Age Text box 3 - Enter Location</p> <p>When this is submitted I would like this to be added preferably into a text box or even just output has text on an html page with other text already stored so the output would maybe be something like "Hello John, you are 25 years old and from London".</p> <p>What I have is very basic:</p> <pre><code> &lt;html&gt; &lt;form&gt; Name: &lt;input type="text" name="name"&gt;&lt;br&gt; Age: &lt;input type="text" name="age"&gt;&lt;br&gt; Location: &lt;input type="text" name="location"&gt;&lt;br&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;html&gt; </code></pre> <p>Beyond this I'm unsure how to get all the values into another text box with the other predetermined text.</p> <p>Any help or direction in this would be appreciated.</p>
15,731,081
2
1
null
2013-03-31 15:19:00.8 UTC
1
2019-05-28 11:39:43.123 UTC
2013-03-31 15:35:10.5 UTC
null
1,870,861
null
1,870,861
null
1
2
html|forms|string-concatenation
50,420
<p>Here is a solution, so get the elements using <code>document.getElementById()</code>, attach an event handler to the <code>click</code> event using <code>element.onclick = function () {}</code> and <code>alert()</code> to show a message box.</p> <p><a href="http://jsfiddle.net/Tyriar/YEb6W/" rel="nofollow">jsFiddle</a></p> <p><strong>JavaScript</strong></p> <pre><code>var button = document.getElementById('test'); var name = document.getElementById('name'); var age = document.getElementById('age'); var location = document.getElementById('location'); button.onclick = function () { var str = 'Hello ' + name.value + ', you are ' + age.value + ' years old and from ' + location.value; alert(str); }; </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;label&gt; Enter name: &lt;input id="name" /&gt; &lt;/label&gt; &lt;br /&gt; &lt;label&gt; Enter age: &lt;input id="age" /&gt; &lt;/label&gt; &lt;br /&gt; &lt;label&gt; Enter location: &lt;input id="location" /&gt; &lt;/label&gt; &lt;br /&gt; &lt;button id="test"&gt;Test&lt;/button&gt; </code></pre> <h2>Edit</h2> <p>To output it to the page use <code>element.innerHTML</code> to set the contents of an element.</p> <p><a href="http://jsfiddle.net/Tyriar/5ERRG/" rel="nofollow">jsFiddle</a></p> <pre><code>output.innerHTML = str; </code></pre>
39,557,999
Cannot find module 'react'
<p>I'm attempting to integrate React into an existing web page. At this time, I'm unable to get my React app loaded. My React app has two files. At this time, they look like this:</p> <p><strong>myApp.js</strong></p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import MyComponent from './components/myComponent'; ReactDOM.render(&lt;MyComponent /&gt;, document.getElementById('root')); </code></pre> <p><strong>myComponent.js</strong></p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; class MyComponent extends React.Component { render() { console.log('here'); return ( &lt;div&gt; &lt;h2&gt;Hello (from React)&lt;/h2&gt; &lt;br /&gt; &lt;/div&gt; ); } } export default MyComponent; </code></pre> <p>As you can see, I'm using ES6. I'm determined to use ES6 on this project. For that reason, I'm using Babel in my Gulp file to bundle my React app. I'm using Gulp instead of Webpack because my site is already using Gulp. Still, the relevant details in my package.json file look like this:</p> <p><strong>package.json</strong></p> <pre><code>... "devDependencies": { "babel-preset-es2015": "^6.14.0", "babel-preset-react": "^6.11.1", "babelify": "^7.3.0", "browserify": "^13.1.0", "gulp": "^3.9.1", "gulp-babel": "^6.1.2", "gulp-clean-css": "^2.0.11", "gulp-uglify": "^1.5.4", "vinyl-source-stream": "^1.1.0" } </code></pre> <p>I then bundle my React app using the following task:</p> <p><strong>gulpfile.js</strong></p> <pre><code>gulp.task('buildApp', function() { return browserify({ entries: ['./app/myApp.js', './app/components/myComponent.js'] }) .transform("babelify", {presets: ['es2015', 'react']}) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./app')) ; }); </code></pre> <p>When the above task is ran, the bundle.js file gets generated. It looks like this:</p> <pre><code>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&amp;&amp;require;if(!u&amp;&amp;a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&amp;&amp;require;for(var o=0;o&lt;r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _myComponent = require('./components/myComponent'); var _myComponent2 = _interopRequireDefault(_myComponent); function _interopRequireDefault(obj) { return obj &amp;&amp; obj.__esModule ? obj : { default: obj }; } _reactDom2.default.render(_react2.default.createElement(NyComponent, null), document.getElementById('root')); },{"./components/myComponent":2,"react":"react","react-dom":"react-dom"}],2:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i &lt; props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj &amp;&amp; obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call &amp;&amp; (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" &amp;&amp; superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass &amp;&amp; superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MyComponent = function (_React$Component) { _inherits(MyComponent, _React$Component); function MyComponent() { _classCallCheck(this, MyComponent); return _possibleConstructorReturn(this, (MyComponent.__proto__ || Object.getPrototypeOf(MyComponent)).apply(this, arguments)); } _createClass(MyComponent, [{ key: 'render', value: function render() { console.log('here'); return _react2.default.createElement( 'div', null, _react2.default.createElement( 'h2', null, 'Hello (from React)' ), _react2.default.createElement('br', null) ); } }]); return MyComponent; }(_react2.default.Component); exports.default = MyComponent; },{"react":"react","react-dom":"react-dom"}]},{},[1]); </code></pre> <p>Then, in the web page that I'm trying to load this app into, I have the following:</p> <pre><code>... &lt;div id="root"&gt;&lt;/div&gt; &lt;script type="text/javascript" src="https://unpkg.com/[email protected]/dist/react.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="https://unpkg.com/[email protected]/dist/react-dom.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/app/bundle.js"&gt;&lt;/script&gt; ... </code></pre> <p>When I load attempt to load this in the browser, my React app does not load. I can see in the console window the following error message:</p> <pre><code>Uncaught Error: Cannot find module 'react' </code></pre> <p>I don't understand why react isn't getting loaded.</p>
39,560,233
7
1
null
2016-09-18 13:12:18.023 UTC
5
2022-09-15 06:18:16.293 UTC
2016-09-18 13:23:27.867 UTC
null
687,554
null
687,554
null
1
26
javascript|reactjs|gulp
141,297
<p>Your package.json doesn't have React in it. It's pretty hard for your project to use a package you haven't installed.</p> <p>Just add: <code>"react": "^15.3.1"</code> to your package.json and do a new npm install, and you should be fine.</p>
31,641,973
How to blur background images in Android
<p>What is the best way to blur background images like the image below? I saw some code and libraries but their are a couple of years old or like BlurBehind library, but it doesn't give the same effect. Thanks in advance!</p> <p><a href="https://i.stack.imgur.com/9hKc5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9hKc5.png" alt="enter image description here"></a></p>
31,642,143
14
5
null
2015-07-26 21:08:26.06 UTC
25
2022-04-12 13:39:53.003 UTC
null
null
null
null
2,646,261
null
1
75
java|android
169,901
<p>The easiest way to do that is use a library. Take a look at this one: <a href="https://github.com/wasabeef/Blurry" rel="noreferrer">https://github.com/wasabeef/Blurry</a></p> <p>With the library you only need to do this:</p> <pre><code>Blurry.with(context) .radius(10) .sampling(8) .color(Color.argb(66, 255, 255, 0)) .async() .onto(rootView); </code></pre>
39,174,669
What is the difference between @Configuration and @Component in Spring?
<p><code>@ComponentScan</code> creates beans using both <code>@Configuration</code> and <code>@Component</code>. Both these annotations work fine when swapped. What is the difference then?</p>
39,175,018
7
4
null
2016-08-26 21:10:59.243 UTC
24
2022-01-10 07:14:21.473 UTC
2020-02-13 09:34:13.843 UTC
null
6,139,527
null
6,664,191
null
1
83
spring
101,981
<blockquote> <p>@Configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime</p> <p>@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.</p> <p>@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning</p> </blockquote> <p>You can see more here:</p> <p><a href="http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html" rel="noreferrer">http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html</a></p> <p>A @Configuration is also a @Component, but a @Component cannot act like a @Configuration.</p>
6,817,751
How do I align text in "top right"?
<p>I have the following table. </p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td align="right"&gt; &lt;b&gt;Car Name:&lt;/b&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;&lt;%=Model.DataMayLoad1%&gt;&lt;/div&gt; &lt;div&gt;&lt;%=Model.DataMayLoad2%&gt;&lt;/div&gt; &lt;div&gt;&lt;%=Model.DataMayLoad3%&gt;&lt;/div&gt; &lt;div&gt;&lt;%=Model.DataMayLoad4%&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>The "Car Name:" column is right aligned, but in the center. Is there a way to align that column to the top right corner?</p>
6,817,778
2
3
null
2011-07-25 14:34:41.72 UTC
0
2017-06-28 19:39:59.473 UTC
2017-06-28 19:39:59.473 UTC
null
4,370,109
null
54,197
null
1
6
html|asp.net|asp.net-mvc|html-table
53,412
<pre><code>&lt;table&gt; &lt;tr&gt; &lt;td align="right" style="vertical-align: top;"&gt; &lt;b&gt;Car Name:&lt;/b&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;&lt;%=Model.DataMayLoad1%&gt;&lt;/div&gt; &lt;div&gt;&lt;%=Model.DataMayLoad2%&gt;&lt;/div&gt; &lt;div&gt;&lt;%=Model.DataMayLoad3%&gt;&lt;/div&gt; &lt;div&gt;&lt;%=Model.DataMayLoad4%&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
55,213,680
In a Nested Navigator Structure of Flutter, How do you get the a Specific Navigator?
<p>I have this problem when I have Nested <code>Navigator</code>s. So something like,</p> <pre><code>class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), initialRoute: "/", routes: { '/': (context) =&gt; SomeOneView(), '/two': (context) =&gt; SomeTwoView(), '/three': (context) =&gt; SomeThreeView(), }, ); } } class SomeOneView extends StatefulWidget { @override _SomeOneViewState createState() =&gt; _SomeOneViewState(); } class _SomeOneViewState extends State&lt;SomeOneView&gt; { @override Widget build(BuildContext context) { return Container( width: double.infinity, height: double.infinity, color: Colors.indigo, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ MaterialButton( color: Colors.white, child: Text('Next'), onPressed: () =&gt; Navigator.of(context).pushNamed('/two'), ), ], ), ); } } class SomeTwoView extends StatefulWidget { @override _SomeTwoViewState createState() =&gt; _SomeTwoViewState(); } class _SomeTwoViewState extends State&lt;SomeTwoView&gt; { @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // Some implementation }, child: Navigator( initialRoute: "two/home", onGenerateRoute: (RouteSettings settings) { WidgetBuilder builder; switch (settings.name) { case "two/home": builder = (BuildContext context) =&gt; HomeOfTwo(); break; case "two/nextpage": builder = (BuildContext context) =&gt; PageTwoOfTwo(); break; } return MaterialPageRoute(builder: builder, settings: settings); }, ), ); } } class HomeOfTwo extends StatelessWidget { @override Widget build(BuildContext context) { return Container( width: double.infinity, height: double.infinity, color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ MaterialButton( color: Colors.white, child: Text('Next'), onPressed: () =&gt; Navigator.of(context).pushNamed('two/nextpage'), ), ], ), ); } } class PageTwoOfTwo extends StatelessWidget { @override Widget build(BuildContext context) { return Container( width: double.infinity, height: double.infinity, color: Colors.teal, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ MaterialButton( child: Text('Next'), onPressed: () =&gt; Navigator.of(context).pushNamed('/three'), ), ], ), ); } } </code></pre> <p>So as you can see, I navigate from the Top Most <code>Navigator</code> provided by <code>MaterialApp</code> going down to the child <code>Navigator</code>'s <code>'two/nextpage'</code> which should then go to <code>MaterialApp</code> <code>'/three'</code>. The problem is that doing <code>onPressed: () =&gt; Navigator.of(context).pushNamed('/three'),</code> returns the <code>Navigator</code> of the current <code>context</code> which is the child <code>Navigator</code>. I need to access the <code>MaterialApp</code>'s <code>Navigator</code> to navigate correctly. What is the right way to do this? </p> <p>Also how to handle the case where the <code>Navigator</code> I want to access is somewhere in the middle of a stack of <code>Navigator</code>s?</p>
55,218,112
4
1
null
2019-03-18 01:32:54.727 UTC
12
2022-02-14 14:52:58.42 UTC
2019-03-18 07:10:12.68 UTC
null
9,291,997
null
9,291,997
null
1
50
flutter|flutter-navigation
20,943
<p>Most of the time, you'll have only 2 Navigator. </p> <p>Which means to obtain the nested one, do:</p> <pre><code>Navigator.of(context) </code></pre> <p>And to obtain the root one do:</p> <pre><code>Navigator.of(context, rootNavigator: true) </code></pre> <hr> <p>For more complex architecture, the easiest by far is to use GlobalKey (since you'll never read Navigators during <em>build</em>)</p> <pre><code>final GlobalKey&lt;NavigatorState&gt; key =GlobalKey(); final GlobalKey&lt;NavigatorState&gt; key2 =GlobalKey(); class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: key, home: Navigator( key: key2, ), ); } } </code></pre> <p>Which you can then use this way:</p> <pre><code>key.currentState.pushNamed('foo') </code></pre>
7,037,433
How to set a cancel button in Progress Dialog?
<p>I want to set a cancel button in my <code>ProgressDialog</code>. Below is my code:</p> <pre><code>myDialog = new ProgressDialog(BaseScreen.this); myDialog.setMessage("Loading..."); myDialog.setCancelable(false); myDialog.show(); </code></pre> <p>I want to set a button with an <code>onClickListener</code> on this <code>ProgressDialog</code>. I tried with this code:</p> <pre><code>myDialog.setButton("Cancel", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub myDialog.dismiss(); } }); </code></pre> <p>But it isn't working. I tried other similar listeners also, but still no success. How can I solve this problem?</p>
7,037,532
3
0
null
2011-08-12 08:25:59.377 UTC
12
2020-01-23 13:49:49.257 UTC
2017-08-18 08:00:14.517 UTC
null
4,165,377
null
623,176
null
1
65
android
60,624
<p>The <code>setButton</code> method you are using is deprecated (although it should still work). Also, you might want to add the button <strong>before</strong> showing the dialog. Try:</p> <pre><code>myDialog = new ProgressDialog(BaseScreen.this); myDialog.setMessage("Loading..."); myDialog.setCancelable(false); myDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { myDialog.dismiss();//dismiss dialog } }); myDialog.show(); </code></pre>
7,219,532
Why a sawtooth shaped graph?
<p>When I run the below mentioned code using NetBeans, the allocated heap size graph resembles a sawtooth shape. I am attaching the screen capture from JVisualVM which shows the heap allocation graph in with a sawtooth shape. The program is a simple infinite loop printing "Hello, World!" into the console.</p> <pre><code>public class HelloWorld { public static void main(String a[]){ while(true) { System.out.println("Hello, World!"); } } } </code></pre> <p><img src="https://i.stack.imgur.com/O2KFi.png" alt="enter image description here"> Can anyone explain the reason behind the shape of the graph of used heap?</p> <p><strong>PS</strong>: This happens even if I run it without using NetBeans, so it is most likely not related to NetBeans...</p>
7,224,667
4
3
null
2011-08-28 07:10:04.467 UTC
9
2018-09-03 13:18:13.517 UTC
2018-09-03 13:18:13.517 UTC
null
7,962,741
null
826,514
null
1
23
java|jvm|memory-management|heap-memory|jvisualvm
15,719
<p>The sawtooth pattern in the heap usage can be explained by the fact that several local variables are created during the invocation of the <code>System.out.println</code> invocation. Most notably in the Oracle/Sun JRE, several <code>HeapCharBuffer</code> instances are created in the young generation, as noted in the following snapshot obtained using the memory profiler of VisualVM:</p> <p><img src="https://i.stack.imgur.com/AdmuK.png" alt="Visual VM - Memory snapshot"></p> <p>The interesting bit is in the number of live objects that are present on the heap. The sawtooth pattern results from the young-gen garbage collection cycle that occurs when the eden space fills up; since there is no heavy computational activity performed in the program, the JVM is able to execute several iterations of the loop, resulting in the eden space (of 4MB is in size) filling up. The succeeding young-gen collection cycle then clears out most of the garbage; it is almost always the whole of the eden space, unless the objects are still in use, as indicated by the following gc trace obtained from VisualVM:</p> <p><img src="https://i.stack.imgur.com/w1UyY.png" alt="Visual VM GC probes"></p> <p>The behavior of the sawtooth pattern can thus be explained by a series of object allocations in rapid succession that fill up the eden space, triggering a young gen garbage collection cycle; this process repeats cyclically with no delays as the underlying JVM process is not preempted by another process, and the main thread within the JVM that is responsible for the object allocations is also not preempted by another thread.</p>
24,177,707
Error: [ngModel:nonassign] Expression is non-assignable
<p>Trying to display a columnvalue from a gridcollection based on another value in that same row. The user can select/change values in a modal which contains a grid with values. When the modal closes the values are passed back. At that moment I would like to set a value for 'Also known as':</p> <p>html:</p> <pre><code> Also known as: &lt;input type="text" `ng-model="displayValue(displayNameData[0].show,displayNameData[0].value)"&gt;` </code></pre> <p>I created a function on scope to select the value only when the 'show' value is true:</p> <pre><code>$scope.displayValue = function (show, val) { if (show) { return val; } else { return ''; } } </code></pre> <p>However when I close the modal I get an error:</p> <pre><code>Error: [ngModel:nonassign] Expression 'displayValue(displayNameData[0].show,displayNameData[0].value)' is non-assignable. </code></pre> <p>plnkr reference:<a href="http://plnkr.co/edit/UoQHYwAxwdvX0qx7JFVW?p=preview">http://plnkr.co/edit/UoQHYwAxwdvX0qx7JFVW?p=preview</a></p>
24,177,923
3
1
null
2014-06-12 06:22:39.507 UTC
2
2017-12-28 13:11:00.553 UTC
null
null
null
null
1,029,283
null
1
21
angularjs|ng-grid
46,999
<p>As HackedByChinese mentioned, you can't bind ng-model to a function, so try like this:</p> <pre><code>&lt;input type="text" ng-if="displayNameData[0].show" ng-model="displayNameData[0].value"&gt; </code></pre> <p>Or if you want this control to be visible you can create directive, add function to <code>$parsers</code> that will set empty value according to <code>show</code>:</p> <pre><code> angular.module('yourModule').directive('bindIf', function() { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ngModel) { function parser(value) { var show = scope.$eval(attrs.bindIf); return show ? value: ''; } ngModel.$parsers.push(parser); } }; }); </code></pre> <p>HTML:</p> <pre><code>&lt;input type="text" bind-if="displayNameData[0].show" ng-model="displayNameData[0].value"&gt; </code></pre>
24,001,501
Does VBA contain a comment block syntax?
<p>In VBA is there a short way to comment out a block of code the same way java uses <code>/*...*/</code>?</p>
24,003,420
3
2
null
2014-06-02 19:05:53.683 UTC
1
2020-06-20 23:21:30.763 UTC
2020-06-20 23:21:30.763 UTC
null
100,297
null
3,011,251
null
1
33
excel|vba|ms-access|outlook|word
156,733
<p>Although there isn't a syntax, you can still get close by using the built-in block comment buttons:</p> <p>If you're not viewing the Edit toolbar already, right-click on the toolbar and enable the Edit toolbar:</p> <p><img src="https://i.stack.imgur.com/IvT9p.png" alt="enter image description here"></p> <p>Then, select a block of code and hit the "Comment Block" button; or if it's already commented out, use the "Uncomment Block" button:</p> <p><img src="https://i.stack.imgur.com/bevKm.png" alt="enter image description here"></p> <p>Fast and easy!</p>
59,432,964
Relational Data Model for Double-Entry Accounting
<p>Assume there is a bank, a large shop, etc, that wants the accounting to be done correctly, for both internal accounts, and keeping track of customer accounts. Rather than implementing that which satisfies the current simple and narrow requirement, which would a 'home brew': those turn out to be a temporary crutch for the current simple requirement, and difficult or impossible to extend when new requirements come it.</p> <p>As I understand it, <strong><a href="https://en.wikipedia.org/wiki/Double-entry_bookkeeping_system" rel="noreferrer">Double-Entry Accounting</a></strong> is a method that is well-established, and serves all Accounting and Audit requirements, including those that are not contemplated at the current moment. If that is implemented, it would:</p> <ul> <li>eliminate the incremental enhancements that would occur over time, and the expense,</li> <li>there will not be a need for future enhancement.</li> </ul> <p>I have studied this Answer to another question: <a href="https://stackoverflow.com/questions/29688982/derived-account-balance-vs-stored-account-balance-for-a-simple-bank-account/29713230#29713230">Derived account balance vs stored account balance for a simple bank account?</a>, it provides good information, for internal Accounts. A data model is required, so that one can understand the entities; their interaction; their relations, and @PerformanceDBA has given that. This model is taken from that Answer:</p> <p><img src="https://www.softwaregems.com.au/Documents/Student%20Resolutions/Anmol%20Gupta%20TA%20Account.png" alt=""></p> <p>Whereas that is satisfactory for simple internal accounts, I need to see a data model that provides the full Double-Entry Accounting method. </p> <p>The articles are need to be added are <code>Journal</code>; internal vs external <code>Transactions</code>; etc..</p> <p>Ideally I would like to see what those double entry rows look like in database terms, what the whole process will look like in SQL, which entities are affected in each case, etc. Cases like:</p> <ol> <li>A Client deposits cash to his account</li> <li>The Bank charges fees once a month to all Clients accounts (sample batch job),</li> <li>A Client does some operation over the counter, and the Bank charges a fee (cash withdrawal + withdrawal fee),</li> <li>Mary sends some money from her account, to John's account, which is in the same bank</li> </ol> <p>Let's just call it <code>System</code> instead of <code>Bank</code>, <code>Bank</code> may be too complex to model, and let the question be about <em>imaginary</em> system which operates with accounts and assets. Customers perform a set of operations with system (deposits, withdrawals, fee for latter, batch fees), and with each other (transfer).</p>
59,465,148
1
4
null
2019-12-21 01:54:41.337 UTC
57
2021-10-07 01:54:50.5 UTC
2019-12-23 18:27:12.94 UTC
null
484,814
null
4,896,540
null
1
40
sql|database|database-design|relational-database|accounting
26,286
<h1>A. Preliminary</h1> <h3>Your Approach</h3> <p>First and foremost, I must commend your attitude. It is rare to find someone who not only thinks and works from a solid grounding, and who wishes to understand and implement a Double-Entry Accounting system, instead of:</p> <ul> <li><p>either <em>not</em> implementing DEA, thus suffering multiple re-writes, and pain at each increment, each new requirement,</p> </li> <li><p>or implementing DEA, but re-inventing the wheel from scratch, by figuring it out for oneself, and suffering the pain at each exposure of error, and the demanded bug fixes, a sequence that never ends.</p> </li> </ul> <p>To avoid all that, and to seek the standard Method, is highly commended.</p> <p>Further, you want that in the form of a Relational data model, you are not enslaved by the Date; Darwen; Fagin; et al views that prescribes a <code>Record ID</code> based Record Filing Systems, that cripples both the modelling exercise and the resulting &quot;database&quot;. These days, some people are obsessed with primitive RFS and suppress Dr E F Codd's <em>Relational Model</em>.</p> <h2>1. Approach for the Answer</h2> <p>If you do not mind, I will explain things from the top, in logical order, so that I can avoid repeats, rather than just answering your particular requests. I apologise if you have complete knowledge of any of these points.</p> <h3>Obstacle</h3> <blockquote> <p>Ideally I would like to see what those <strong>double entry rows</strong> look like in database terms</p> </blockquote> <p>That is an obstacle to the proper approach that is required for modelling or defining anything.</p> <ul> <li>In the same way that stamping an <code>ID</code> field on every file, and making it the &quot;key&quot;, cripples the modelling exercise, because it prevents analysis of the data (what the thing that the data represents actually is), expecting two rows for a Credit/Debit pair at the start will cripple the understanding of what the thing is; what the accounting actions are; what effect those actions have; and most important, how the data will be modelled. Particularly when one is learning.</li> </ul> <blockquote> <p><sup><strong>Aristotle</strong> teaches us that:</sup></p> <blockquote> <p><sup><em>the least initial deviation from the truth is multiplied later a thousandfold ... </sup> <sup>a principle is great, rather in power, than in extent; hence that which was small [mistake] at the start turns out a giant [mistake] at the end.</em></sup></p> </blockquote> </blockquote> <p>Paraphrased as, a small mistake at the beginning (eg. principles; definitions) turns out to be a large mistake at the end.</p> <p>Therefore the intellectual requirement, the first thing, is to clear your mind regarding what it will be at the end of the modelling exercise. Of course, that is also required when one is learning what it is, in accounting terms.</p> <h2>2. Scope for the Answer</h2> <blockquote> <p>Assume there is a bank, a large shop, etc, that wants the accounting to be done correctly, for both internal accounts, and keeping track of customer accounts.<br /> Let's just call it <code>System</code> instead of <code>Bank</code>, <code>Bank</code> may be too complex to model ...<br /> Customers perform a set of operations with system (deposits, withdrawals, fee for latter, batch fees), and with each other (transfer).</p> </blockquote> <p>To be clear, I have determined the scope to be as follows. Please correct me if it is not:</p> <ul> <li>Not a small business with a General Ledger only, with no Customer Accounts</li> <li>But a small community Bank, with no branches (the head office is <em>the</em> branch)</li> <li>You want both the <strong>internal</strong> Accounts, which consists of:</li> <li>a simple General <strong>Ledger</strong>,</li> <li>as well as <strong>external</strong> Accounts, one for each Customer</li> <li>The best concept that I have in mind is a small community Bank, or a business that operates like one. An agricultural cooperative, where each farmer has an <strong>Account</strong> that he purchases against, and is billed and paid monthly, and the cooperative operates like a small bank, with a full General <strong>Ledger</strong>, and offers some simple bank facilities.</li> <li>A single Casino (not a chain) has the same requirement.</li> <li>Not a large Bank with multiple branches; various financial products; etc.</li> <li>Instead of <code>System</code> or <code>Bank</code>, I will call it <code>House</code>. The relevance of that will be clear later.</li> </ul> <p>Anyone seeking the Double-Entry method for <em>just</em> the <strong>Ledger</strong>, <em>without</em> the external Customer <strong>Account</strong>, can glean that easily from this Answer.</p> <p>In the same vein, the data model given here is easy to expand, the <code>Ledger</code> can be larger than the simple one given.</p> <hr /> <h1>B. Solution</h1> <h2>1. Double-Entry Accounting</h2> <h3>1.1. Concept</h3> <p>To know what that it is by name; that it has great value; that it is better than a roll-your-own system, is one thing, knowing what it is deeply enough to implement it, is another.</p> <ol> <li><p>First, one needs to have a decent understanding of a General Ledger, and general Accounting principles.</p> </li> <li><p>Second, understand the concept that money represents value. Value cannot be created or destroyed, it can only be moved. <strong>From</strong> one bucket in the accounts <strong>to</strong> another bucket, otherwise known as Debit (the from-account) and Credit (the to-account).</p> </li> <li><p>While it is true that <em>the SUM( all Credits ) = SUM( all Debits )</em>, and one can obtain such a report from a DEA system, that is not the understanding required for implementation, that is just one end result. There is more to it.</p> </li> </ol> <ul> <li><p>While it is true that <em>every transaction consists of a pair: one Credit and one Debit for the same amount</em>, there is more to that as well.</p> </li> <li><p>Each leg of the pair; the Credit and Debit, is not in the same Account or Ledger, they are in different Accounts, or Ledgers, or Accounts-and-Ledgers.</p> </li> <li><p>The <em>SUM( all Credits )</em> is not simple, because they are in those different places (sets). They are not in two rows in the same table (they could be, more later). Likewise, <em>the SUM( all Debits )</em>.</p> </li> <li><p>Thus each of the two SUM()s cover quite different sets (Relational Sets), and have to be obtained first, before the two SUM()s can be compared.</p> </li> </ul> <h3>1.2. Understanding Double-Entry Accounting</h3> <p>Before attempting a DEA implementation, we need to understand the thing that we are implementing, properly. I advise the following:</p> <ol> <li>You are right, the first principle is to hold the <strong>perspective of the Credit/Debit Pair</strong>, when dealing with anything in the books, the General Ledger; the Customer Accounts; the bank Accounts; etc.</li> </ol> <ul> <li><p>This is the overarching mindset to hold, separate to whatever needs to be done in this or that Account or Ledger.</p> </li> <li><p>I have positioned it at the top; left, in the data model, such that the subordination of all articles to it is rendered visually.</p> </li> </ul> <ol start="2"> <li>The <strong>purpose</strong> or goal of a Double-Entry Accounting system is:</li> </ol> <ul> <li><p>Eliminate (not just reduce) what is known as:</p> <ul> <li><p>&quot;lost&quot; money</p> </li> <li><p>&quot;lost&quot; Transactions (one or the other side of the Credit/Debit pair)</p> </li> <li><p>and the time wasted in chasing it down.</p> </li> <li><p>Not only can money be found easily, but exactly what happened to it, and where it is now, can be determined quickly.</p> </li> </ul> </li> <li><p>Full Audit functionality<br /> It is not good enough to keep good Accounts, it is imperative for a business that accounts for other people's money, to be readily audit-able. That is, any accountant or auditor must be able to examine the books without let or hindrance.</p> <ul> <li>This is why the first thing an outsider, eg. an auditor, wants to know is, <em>does the SUM( all Credits ) = SUM( all Debits )</em>. This also explains why the DEA concept is above any Accounts or accounting system that the company may be keeping.</li> </ul> </li> <li><p>The great benefit, although tertiary, is that the everyday or month end tasks, such as a Trial Balance or closing the books, can be closed easily and quickly. All reports; Statements; Balance Sheets; etc, can be obtained simply (and with a single <code>SELECT</code> if the database is Relation).</p> </li> </ul> <ol start="3"> <li><em>Then</em> ready the Wikipedia entry for <strong><a href="https://en.wikipedia.org/wiki/Double-entry_bookkeeping_system" rel="noreferrer">Double-Entry Bookkeeping</a></strong>.</li> </ol> <ul> <li><p>The internet has plenty of misleading information, and Wikipedia is particularly awful that is forever changing (truth does not change, falsity changes with the weather), but sorry, that is all we have. Use it only to obtain an overview, it has no structural or logical descriptions, despite its length. Follow the links for better info.</p> </li> <li><p>I do not entirely agree with the terminology in the <a href="https://en.wikipedia.org/wiki/Double-entry_bookkeeping_system" rel="noreferrer">Wikipedia article</a>. Nevertheless, in order to avoid avoidable confusion, I will use those terms.</p> </li> <li><p>There are tutorials available on the web, some better than others. These are recommended for anyone who is implementing a proper Accounting system, with or without DEA. That takes time, it is not relevant to an answer such as this, and that is why I have linked the <a href="https://en.wikipedia.org/wiki/Double-entry_bookkeeping_system" rel="noreferrer">Wikipedia article</a>.</p> </li> </ul> <h2>2. Business Transaction</h2> <blockquote> <p>Ideally I would like to see what <strike>those</strike> double entry <strike>rows</strike> looks like in database terms, what the whole process will look like in SQL, which entities are affected in each case, etc.</p> </blockquote> <p>Ok. Let's go with the Transactions first, then build up to understanding the data model that supports them, then inspect the example rows. Any other order would be counter-productive, and cause unnecessary back-and-forth.</p> <p>Your numbering. Green is <code>House</code> in the General <code>Ledger</code>, blue is external Customer <code>Account</code>, black is neutral.</p> <ul> <li><p>This is the first increment of <strong>Treatment</strong>, how a thing is treated, in different scenarios (your concern, and your request for specific examples, is precisely correct).</p> </li> <li><p><strong>Credit/Debit Pairs</strong><br /> This is the first principle of DEA, understand the pair, as the pair, and nothing but the pair.</p> </li> </ul> <p>Do not worry about how the General <code>Ledger</code> or the <code>Account</code> is set up, or what the data model looks like. Think in terms of an accountant (what has to be done in the books), not in terms of a developer (what has to be done in the system).</p> <p>Notice that the each leg of the pair is in the one set (the <code>Ledger</code>), or in two sets (one leg in the <code>Ledger</code>, the other leg in <code>Account</code>). There are no pairs in which both legs are in <code>Account</code>.</p> <ul> <li>Because DEA is implemented, each <strong>Business Transaction</strong> (as distinct from a database Transaction), consists of two actions, one for each Credit/Debit leg. The two actions are two entries in a paper-based account book.</li> </ul> <blockquote> <ol> <li>A Client deposits cash to his account</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Op%201_1.png" alt="Op11" title="DEA Credit/Debit pairs for Operation 1.1" /> <img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Op%201_2.png" alt="Op12" title="DEA Credit/Debit pairs for Operation 1.2" /></p> <ul> <li>During the DayEnd procedure, among other tasks, all cash is accounted for and checked. The day is closed. All cash sitting in <code>HouseCash</code> that is beyond whatever the bank deems necessary for everyday cash Transactions, is moved to <code>HouseReserve</code>.</li> </ul> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Op%201_3.png" alt="Op13" title="DEA Credit/Debit pairs for Operation 1.3" /></p> <blockquote> <ol start="2"> <li>The Bank charges fees once a month to all Clients accounts (sample batch job)</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Op%202.png" alt="Op2" title="DEA Credit/Debit pairs for Operation 2" /></p> <ul> <li>This charges each <code>Account</code> with the <code>Fee</code></li> <li><code>Fee</code> is dependent on <code>AccountType_Ext</code></li> <li>This is the simple case. If the <code>Fee</code> is dependent on something else, such as the number of transactions in the <code>Account</code>; or the <code>CurrentBalance</code> being below or above some limit; etc, that is not shown. I am sure you can figure that out.</li> </ul> <blockquote> <ol start="3"> <li>A Client does some operation over the counter, and the Bank charges a fee (cash withdrawal + withdrawal fee),</li> </ol> </blockquote> <ul> <li>Simple Transactions do not incur fees, and Deposit/Withdrawal has already been given. Let's examine a business Transaction that actually attracts a fee.</li> </ul> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Op%203.png" alt="Op3" title="DEA Credit/Debit pairs for Operation 3" /></p> <ul> <li>Mary sends $500 USD to her son Fred, who is travelling overseas looking for whales to save, and has run out of money. The bank charges $30 for an Overseas Bank Transfer. Fred can collect the funds (in local currency equivalent of $500 USD) at any partner bank branch.</li> <li>To actually transfer the money to the foreign bank, the <code>House</code> has to interact with a local big bank that provides international settlement and currency exchange services. That is not relevant to us, and not shown. In any case, all those types of <code>Interbank</code> transactions are batched and dealt with once per day, not once per <code>AccountTransaction</code>.</li> <li>In this simple DEA system, the <code>House</code> does not have currency accounts in the <code>Ledger</code>. That is easy enough to implement.</li> </ul> <blockquote> <ol start="4"> <li>Mary sends some money from her account, to John's account, which is in the same bank</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Op%204.png" alt="Op4" title="DEA Credit/Debit pairs for Operation 4" /></p> <ul> <li>The money is currently in Mary's account (deposited on a day prior to today), that is why it is in <code>HouseReserve</code>, not <code>HouseCash</code></li> <li>The money is moved from <code>HouseReserve</code> into <code>HouseCash</code> because John may come into the bank today and withdraw it.</li> <li>As described in example [1.3] above, at the DayEnd procedure, any money sitting in <code>HouseCash</code> in all <code>Accounts</code> will be moved to <code>HouseReserve</code>. Not shown.</li> </ul> <hr /> <h2>3. Relational Data Model • Initial</h2> <p>Now let's see what the data modeller has done, to support the accountant's needs, the business Transactions.</p> <ul> <li><p>This is of course, the second increment of <strong>Treatment</strong>, what the modeller has understood the real world business Transactions to be, expressed in Relational terms (FOPC; <em>RM</em>; Logic; Normalisation)</p> </li> <li><p>This is not the simplest data model that is required to satisfy the restated scope.</p> </li> <li><p>There are simpler models (more later), but they have problems that this one does not have, problems that are desirable, if not imperative, to avoid.</p> </li> <li><p>The image is too large for in-line viewing. Open the image in a new tab, to appreciate it in full size.</p> </li> </ul> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20TA.png" alt="TA" title="Relational data model/Double-Entry Account for Alex" /></p> <h3>3.1. Notation</h3> <ul> <li><p>All my data models are rendered in <strong><a href="https://www.iso.org/standard/60614.html" rel="noreferrer">IDEF1X</a></strong>, the Standard for modelling Relational databases since 1993.</p> </li> <li><p>My <strong><a href="https://www.softwaregems.com.au/Documents/Documentary%20Examples/IDEF1X%20Introduction.pdf" rel="noreferrer">IDEF1X Introduction</a></strong> is essential reading for those who are new to the <em>Relational Model</em>, or its modelling method. Note that IDEF1X models are rich in detail and precision, showing <em>all</em> required details, whereas home-grown models, being unaware of the imperatives of the Standard, have far less definition. Which means, the notation needs to be fully understood.</p> </li> </ul> <h3>3.2. Content</h3> <ul> <li><p>The main difference between a genuine Relational data model produced by someone else, and mine, is:<br /> a <strong>business Transaction (always two actions; two legs, one per Credit/Debit) is affected by a single row with two sides, one per Credit/Debit</strong>,<br /> in <code>AccountTransaction</code> or <code>LedgerTransaction</code>.</p> </li> <li><p>Most modellers will model two rows for the Credit/Debit pair, one for each leg or side (<em>hey, one leg is a Credit, and the other leg is a Debit, if I Normalise that, I get two rows</em>).</p> </li> <li><p>Wrong. If I tell you that Fred is Sally's father, you know, from that single Fact, that Sally is Fred's daughter.</p> </li> <li><p>A <code>FOREIGN KEY</code> needs to be declared just once, not once for each side.</p> </li> <li><p>Likewise, the <strong>Credit/Debit pair is a single Business Transaction</strong>,<br /> a single Atomic article, that can be perceived from either Side, like two sides of one coin. Modelled as such.</p> </li> <li><p>All manner of preventable bugs are prevented, the search for the &quot;missing&quot; leg is eliminated.</p> </li> <li><p>Even for those with sub-standard OLTP code, which causes quite preventable concurrency problems, if this method is implemented, this is one article wherein those problems will not arise.</p> </li> <li><p>Further, the number of rows in the <code>%Transaction</code> tables is halved.</p> </li> <li><p>I have arranged the articles such that the<br /> <strong>External</strong> <code>Account</code><br /> <strong>Internal</strong> <code>Ledger</code> and <code>LedgerTransaction</code><br /> <strong>Internal-External</strong> <code>AccountTransaction</code><br /> are clear.</p> </li> <li><p>Along with a nugget of definition from the <a href="https://en.wikipedia.org/wiki/Double-entry_bookkeeping_system" rel="noreferrer">Wikipedia entry</a>.</p> </li> <li><p>Having familiarised yourself with the DEA Credit/Debit pairs, now study the <strong>Treatment</strong> of the pair. Notice that the Treatment is different, it is based on a number of criteria (three account types; six <code>Ledger</code> types; etc), which in turn is based on the complexity of the General Ledger.</p> </li> <li><p>This <code>Ledger</code> is simple, with <code>Asset/Liability</code> accounts only. Of course, you are free to expand that.</p> </li> <li><p>The eagle-eyed will notice that <code>AccountStatement.ClosingBalance</code> and <code>LedgerStatement.ClosingBalance</code> can actually be derived, and thus (on the face of it), should not be stored. However, these are published figures, eg. the Monthly Bank Statement for each Account, and thus subject to <strong>Audit</strong>, and therefore it must be stored.</p> </li> </ul> <p>For a full treatment of that issue, including considerations; definition; treatment, refer to this Q &amp; A:</p> <ul> <li><strong><a href="https://stackoverflow.com/a/29713230/484814">Derived account balance vs stored account balance for a simple bank account?</a></strong></li> </ul> <h3>3.3. Summary</h3> <p>In closing this section, we should have reached this understanding:</p> <ul> <li><p>The overarching principle of DEA, the Credit/Debit pairs, purely intellectual</p> </li> <li><p>The typical business Transactions, always a Credit/Debit pair, two legs, two entries in the accounting books</p> </li> <li><p>A deeper understanding of the Treatment of said Transactions</p> </li> <li><p>The environment that the <code>House</code> (small bank; cooperative; casino) manages (internal <code>Ledger</code> and external customer <code>Account</code>)</p> </li> <li><p>A first look at a data model that is proposed to handle all that.</p> </li> </ul> <hr /> <h2>4. Relational Data Model • Full</h2> <p>Here it is again, with a full set of sample data.</p> <ul> <li><p>Re the <strong>Primary Keys</strong>:</p> </li> <li><p>Note that <code>LedgerNo</code> and <code>AccountNo</code> are not surrogates, they have meaning for the organisation, in ordering and structuring the <code>Ledger</code>, etc. They are stable numbers, not an <code>AUTOINCREMENT</code> or <code>IDENTITY</code> or anything of the sort.</p> </li> <li><p>The Primary Keys for <code>LedgerTransaction</code> and <code>AccountTransaction</code> are pure, composite Relational Keys.</p> </li> <li><p>It is not a Transaction Number of some kind that is beloved of paper-based accountants.</p> </li> <li><p>It is not a crippling <code>Record ID</code> either.</p> </li> <li><p>The <strong>Alternate Keys</strong> are more meaningful to humans, hence I have used them in the examples (Business Transactions, above [2], and below [5]). This Answer is already layered, it would be a nightmare trying to relate hundreds of <code>1's, 2's</code> and <code>3’s</code> to each other.</p> </li> <li><p>If we wish to understand what something means, we need to hold onto the meaning that exists in the thing, rather than excising the meaning by giving it a number.</p> </li> <li><p>In the example data, the Primary Keys are bold.</p> </li> </ul> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20TA%20Data.png" alt="TAdata" title="Relational data model/Double-Entry Account, with Sample Data, for Alex" /></p> <hr /> <h2>5. Business Transaction with Row</h2> <blockquote> <p>Ideally I would like to see what <strike>those</strike> double entry <strike>rows</strike> looks like in database terms, what the whole process will look like in SQL, which entities are affected in each case, etc.</p> </blockquote> <p>Now that we understand the Business Transactions, and the data model that services the requirement, we can examine the Business Transactions <em>along with</em> affected rows.</p> <ul> <li><p>Each Business Transaction, in DEA terms, has two legs, two entries in the paper-based account books, for each of the Credit/Debit pair,<br /> is yet a single Business Transaction, and now:<br /> it is affected by <strong>a single row</strong> with two sides, for each of the Credit/Debit pair.</p> </li> <li><p>This is the third increment in understanding <strong>Treatment</strong>: the business Transactions; data model to implement them; and now, the affected rows</p> </li> <li><p>The example database rows are prefixed with the table name in short form.<br /> Plus means <code>INSERT</code><br /> Minus means <code>DELETE</code><br /> Equal means <code>UPDATE</code>.</p> </li> </ul> <blockquote> <ol> <li>A Client deposits cash to his account</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Row%201_1.png" alt="Row11" title="DEA Credit/Debit pairs &amp; Row for Operation 1.1" /> <img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Row%201_2.png" alt="Row12" title="DEA Credit/Debit pairs &amp; Row for Operation 1.2" /> <img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Row%201_3.png" alt="Row13" title="DEA Credit/Debit pairs &amp; Row for Operation 1.3" /></p> <blockquote> <ol start="2"> <li>The Bank charges fees once a month to all Clients accounts (sample batch job)</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Row%202.png" alt="Row2" title="DEA Credit/Debit pairs &amp; Row for Operation 2" /></p> <ul> <li>This, too, is a batch job, just one task in the MonthEnd procedure.</li> <li>Notice the date is the first day of the month.</li> </ul> <blockquote> <ol start="3"> <li>A Client does some operation over the counter, and the Bank charges a fee (cash withdrawal + withdrawal fee),</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Row%203.png" alt="Row3" title="DEA Credit/Debit pairs &amp; Row for Operation 3" /></p> <ul> <li>To be clear, that is three Business Transactions; two entries each, one for each side of the Credit/Debit pair; affected by one database row each.</li> </ul> <blockquote> <ol start="4"> <li>Mary sends some money from her account, to John's account, which is in the same bank</li> </ol> </blockquote> <p><img src="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Row%204.png" alt="Row4" title="DEA Credit/Debit pairs &amp; Row for Operation 4" /></p> <hr /> <h2>6. SQL Code</h2> <p>There are usually several ways to skin a cat (code), but very few if the cat is alive (code for a high concurrency system).</p> <ul> <li><p>The <em>Relational Model</em> is <strong>founded</strong> on First Order Predicate Calculus (aka First Order Logic), all definitions (DDL) and thus all queries (DML) are entirely Logical.</p> </li> <li><p>A data model that conforms to that understanding, is therefore entirely Logical.</p> </li> <li><p>The queries against such a data model are dead easy: Logical and straight-forward. They have none of the convoluted code that is required for <code>Record ID</code> based filing systems.</p> </li> </ul> <p>Therefore, out of the several methods that are possible for the SQL code requests, I give the most direct and logical.</p> <blockquote> <p><sup>The code examples are that which is appropriate for SO, it is imperative that you trap and recover from errors; that you do not attempt anything that will fail (check the validity of the action before using a verb), and follow OLTP Standards for ACID Transactions, etc. The example code given here are the relevant snippets only.</sup></p> </blockquote> <h3>6.1. SQL View • Account Current Balance</h3> <p>Since this code segment gets used in many places, let's do the right thing and create a View.</p> <ul> <li><p>Note that on genuine SQL platforms, source code is compiled and run when it is submitted, Stored Procs and Views are stored in their compiled form, thus eliminating the compilation on every execution. Unlike the mickey mouse NONsql suites.</p> </li> <li><p>High-end commercial SQL platforms do a lot more, such as caching the Query Plans for Views, and the queries in Stored Procs.</p> </li> </ul> <pre class="lang-sql prettyprint-override"><code>CREATE VIEW Account_Current_V AS SELECT AccountNo, Date = DATEADD( DD, -1, GETDATE() ), -- show /as of/ previous day ASS.ClosingBalance, -- 1st of this month TotalCredit = ( SELECT SUM( Amount ) FROM AccountTransaction ATT WHERE ATT.AccountNo = ASS.AccountNo AND XactTypeCode_Ext IN ( &quot;AC&quot;, &quot;Dp&quot; ) -- &gt;= 1st day of this month yy.mm.01 /AND &lt;= current date/ AND DateTime &gt;= CONVERT( CHAR(6), GETDATE(), 2 ) + &quot;01&quot; ), TotalDebit = ( SELECT SUM( Amount ) FROM AccountTransaction ATT WHERE ATT.AccountNo = ASS.AccountNo AND XactTypeCode_Ext NOT IN ( &quot;AC&quot;, &quot;Dp&quot; ) AND DateTime &gt;= CONVERT( CHAR(6), GETDATE(), 2 ) + &quot;01&quot; ), CurrentBalance = ClosingBalance + &lt;TotalCredit&gt; - -- subquery above &lt;TotalDebit&gt; -- subquery above FROM AccountStatement ASS -- 1st day of this month WHERE ASS.Date = CONVERT( CHAR(6), GETDATE(), 2 ) + &quot;01&quot; </code></pre> <h3>6.2. SQL Transaction • [1.2] Withdraw from [External] Account</h3> <p>A proc for another DEA business Transaction.</p> <pre><code>CREATE PROC Account_Withdraw_tr ( @AccountNo, @Amount ) AS IF EXISTS ( SELECT 1 -- validate before verb FROM AccountCurrent_V WHERE AccountNo = @AccountNo AND CurrentBalance &gt;= @Amount -- withdrawal is possible ) BEGIN SELECT @LedgerNo = LedgerNo FROM Ledger WHERE Name = &quot;HouseCash&quot; BEGIN TRAN INSERT AccountTransaction VALUES ( @LedgerNo, GETDATE(), &quot;Cr&quot;, &quot;Wd&quot;, @AccountNo, @Amount ) COMMIT TRAN END </code></pre> <h3>6.3. SQL Transaction • [1.1] Deposit to [External] Account</h3> <p>A proc, set up as an SQL Transaction, to execute a DEA business Transaction.</p> <pre class="lang-sql prettyprint-override"><code>CREATE PROC Account_Deposit_tr ( @AccountNo, @Amount ) AS ... IF EXISTS, etc ... -- validate before verb BEGIN SELECT @LedgerNo ... BEGIN TRAN INSERT AccountTransaction VALUES ( @LedgerNo, GETDATE(), &quot;Dr&quot;, &quot;Dp&quot;, @AccountNo, @Amount ) COMMIT TRAN END </code></pre> <h3>6.4. SQL Transaction • [Internal] Ledger Account Transfer</h3> <p>A proc to add any business Transaction to <code>LedgerAccount</code>. It is always:</p> <ul> <li>one <code>LedgerTransaction.LedgerNo</code>, which is the <code>Credit</code> leg</li> <li>one <code>LedgerTransaction.LedgerNo_Dr</code>, which is the <code>Debit</code> leg.</li> <li>given by the caller.</li> </ul> <pre class="lang-sql prettyprint-override"><code>CREATE PROC Ledger_Xact_tr ( @LedgerNo, -- Credit Ledger Account @LedgerNo_Dr, -- Debit Ledger Account @Amount ) AS ... IF EXISTS, etc ... BEGIN SELECT @LedgerNo ... BEGIN TRAN INSERT LedgerTransaction VALUES ( @LedgerNo, GETDATE(), @LedgerNo_Dr, @Amount ) COMMIT TRAN END </code></pre> <h3>6.5. SQL Batch Task • Account Month End</h3> <p>This uses a View that is similar to <strong>[6.1 Account Current Balance]</strong>, for any month (views are generic), with the values constrained to the month. The caller selects the previous month.</p> <ul> <li>This Answer now exceeds the SO limit, thus it is provided in a link <a href="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Account_Month_V.sql" rel="noreferrer">Account_Month_V</a>.</li> </ul> <p>Just one Task, in a stored proc, to process the Month End for <code>AccountStatement</code>, which is executed as a batch job. Again, just the essential code, the infrastructure needs to be added.</p> <pre class="lang-sql prettyprint-override"><code>CREATE PROC Account_MonthEnd_btr ( ... ) AS ... begin loop ... batch transaction control (eg. 500 rows per xact), etc ... INSERT AccountStatement SELECT ACT.AccountNo, CONVERT( CHAR(6), GETDATE(), 2 ) + &quot;01&quot;, -- 1st day THIS month AMV.ClosingBalance, -- for PREVIOUS month AMV.TotalCredit, AMV.TotalDebit FROM Account ACT JOIN Account_Month_V AMV -- follow link for code ON ACT.AccountNo = AMV.AccountNo -- 1st day PREVIOUS month WHERE AMV.OpeningDate = DATEADD( MM, -1, ACT.Date ) ... end loop ... batch transaction control, etc ... </code></pre> <h3>6.6. SQL Report • SUM( Credit ) vs SUM( Debit )</h3> <blockquote> <blockquote> <p>While it is true that <em>the SUM( all Credits ) = SUM( all Debits )</em>, and one can obtain such a report from a DEA system, that is not the <strong>understanding</strong>. There is <strong>more</strong> to it.</p> </blockquote> </blockquote> <p>Hopefully, I have given the Method and details, and covered the <em>understanding</em> and the <em>more</em>, such that you can now write the required <code>SELECT</code> to produce the required report with ease.</p> <p>Or perhaps the Monthly Statement for external <code>Accounts</code>, with a running total <code>AccountBalance</code> column. Think: a Bank Statement.</p> <ul> <li>One of the many, great efficiencies of a genuine Relational database is, any report can be serviced via a <strong>single <code>SELECT</code> command</strong>.</li> </ul> <hr /> <h2>One PDF</h2> <p>Last but not least, it is desirable to have the Data Model; the example Transactions; the code snippets, all organised in a single <strong><a href="https://www.softwaregems.com.au/Documents/Student_Resolutions/Alex/Alex%20Account%20TA.pdf" rel="noreferrer">PDF</a></strong>, in A3 (11x17 for my American friends). For studying and annotation, print in A2 (17x22).</p> <hr />
1,459,069
Populating Swing JComboBox from Enum
<p>I would like to populate a <code>java.swing JComboBox</code> with values from an <code>Enum</code>.</p> <p>e.g. </p> <pre><code>public enum Mood { HAPPY, SAD, AWESOME; } </code></pre> <p>and have these three values populate a readonly <code>JComboBox</code>.</p> <p>Thanks!</p>
1,459,076
4
0
null
2009-09-22 09:32:00.613 UTC
5
2020-05-07 09:59:32.393 UTC
2014-11-16 23:38:04.21 UTC
null
3,998,607
null
171,898
null
1
36
java|swing|enums|jcombobox
40,232
<p>try:</p> <pre><code>new JComboBox(Mood.values()); </code></pre>
42,953,858
Loading modules from different server at runtime
<p>Is it somehow possible to load different modules in my angular 2 app runtime, from different servers and if so, how can I achieve this?</p> <p>I would like to have my app load different components from the overall application from isolated servers (A, B, C), so they can be taken down and updated independently from the main app and any components which are included in A, B or C won't be loaded. The 3 modules shown on the bottom would have the Components, but the Main App would declare in it's HTML where it should load the component.</p> <p><a href="https://i.stack.imgur.com/8VHxo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8VHxo.png" alt="Overview"></a></p> <p><strong>UPDATE</strong></p> <p>Lazy loading through routes is not what I'm looking for, the 3 modules should be completely independent modules which have their own repository, project, hosting, enz.</p>
44,760,962
1
6
null
2017-03-22 14:01:22.083 UTC
9
2017-06-26 13:43:12.24 UTC
2017-06-26 13:43:12.24 UTC
null
2,495,283
null
772,229
null
1
12
angular|webpack|angular-module
5,753
<p>A little late, but you can use the lazy-loading mechanism in routes to do exactly what you want.</p> <p>This article states on how to load a webpack module from another source: <a href="https://stackoverflow.com/questions/43163909/solution-load-independently-compiled-webpack-2-bundles-dynamically">Solution: load independently compiled Webpack 2 bundles dynamically</a></p> <p>In the routes you define a callback in the loadchildren section:</p> <pre><code>const appRoutes: Routes = [ {path: '', component: MainComponent}, {path: 'modulea', loadchildren: loadModuleA} ] </code></pre> <p>the loadModuleA method would look like:</p> <pre><code>export function loadModuleA() { return new Promise((resolve, reject) =&gt; { // the method from the article loadPlugin('path/to/server/of/moduleA', (exports) =&gt; { // The Submodule must export ModuleA resolve(exports.ModuleA); }); }); } </code></pre>
7,537,925
How to delete folders in sdcard of file explorer?
<p>I created several folders in the sdcard (Eclipse) by running an Android application in the emulator. Now I want to delete the folders which I have created on the sdcard.</p> <p>I am able to delete files in the folders but I could not delete the folders in the sdcard.</p> <p>How can I do this? Is there a way to delete folders?</p>
7,538,102
6
0
null
2011-09-24 08:33:09.743 UTC
7
2019-11-07 11:08:20.397 UTC
2019-11-07 11:08:20.397 UTC
null
452,775
null
745,375
null
1
41
android
101,035
<p>Using adb command you can delete folders.</p> <blockquote> <p>click Run - > CMD-> type adb shell --> cd sdcard -> rmdir {dirname}</p> </blockquote> <p>Note : Make sure your dir should be empty.</p> <p>For non-empty directory use.</p> <blockquote> <p>click Run - > CMD-> type adb shell --> cd sdcard -> rm -r {dirname}</p> </blockquote>
7,123,138
How to make this Header/Content/Footer layout using CSS?
<pre><code> ______________________ | Header | |______________________| | | | | | Content | | | | | |______________________| | Footer | |______________________| </code></pre> <p>I would like to make this UI, and each is a div. The header height is 30px. And the footer is 30px. But I don't know the content height. I need to use the user frame to calculate. </p> <p>The total height should be 100%. </p> <p>Can I do it in pure CSS?</p>
7,123,273
7
3
null
2011-08-19 14:34:16.18 UTC
16
2021-11-05 12:43:54.113 UTC
2011-08-19 14:49:01.717 UTC
null
398,242
null
148,978
null
1
49
css
154,793
<p>Using flexbox, this is easy to achieve.</p> <p>Set the wrapper containing your 3 compartments to <code>display: flex;</code> and give it a height of <code>100%</code> or <code>100vh</code>. The height of the wrapper will fill the entire height, and the <code>display: flex;</code> will cause all children of this wrapper which has the appropriate flex-properties (for example <code>flex:1;</code>) to be controlled with the flexbox-magic.</p> <p>Example markup:</p> <pre><code>&lt;div class="wrapper"&gt; &lt;header&gt;I'm a 30px tall header&lt;/header&gt; &lt;main&gt;I'm the main-content filling the void!&lt;/main&gt; &lt;footer&gt;I'm a 30px tall footer&lt;/footer&gt; &lt;/div&gt; </code></pre> <p>And CSS to accompany it:</p> <pre><code>.wrapper { height: 100vh; display: flex; /* Direction of the items, can be row or column */ flex-direction: column; } header, footer { height: 30px; } main { flex: 1; } </code></pre> <p>Here's that code live on Codepen: <a href="http://codepen.io/enjikaka/pen/zxdYjX/left" rel="noreferrer">http://codepen.io/enjikaka/pen/zxdYjX/left</a></p> <p>You can see more flexbox-magic here: <a href="http://philipwalton.github.io/solved-by-flexbox/" rel="noreferrer">http://philipwalton.github.io/solved-by-flexbox/</a></p> <p>Or find a well made documentation here: <a href="http://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">http://css-tricks.com/snippets/css/a-guide-to-flexbox/</a></p> <p><strong>--[Old answer below]--</strong></p> <p>Here you go: <a href="http://jsfiddle.net/pKvxN/" rel="noreferrer">http://jsfiddle.net/pKvxN/</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=utf-8 /&gt; &lt;title&gt;Layout&lt;/title&gt; &lt;!--[if IE]&gt; &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;style&gt; header { height: 30px; background: green; } footer { height: 30px; background: red; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;h1&gt;I am a header&lt;/h1&gt; &lt;/header&gt; &lt;article&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula dolor. &lt;/p&gt; &lt;/article&gt; &lt;footer&gt; &lt;h4&gt;I am a footer&lt;/h4&gt; &lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>That works on all modern browsers (FF4+, Chrome, Safari, IE8 and IE9+)</p>
7,376,647
What is the difference between Java's BufferedReader and InputStreamReader classes?
<p>What is the difference between Java's <code>BufferedReader</code> and <code>InputStreamReader</code> classes?</p>
7,376,667
7
5
null
2011-09-11 06:15:47.697 UTC
23
2020-04-29 15:12:36.023 UTC
2020-04-29 15:12:36.023 UTC
null
745,828
null
722,233
null
1
55
java|inputstream|bufferedreader|inputstreamreader
68,178
<p>BufferedReader is a wrapper for both "InputStreamReader/FileReader", which buffers the information each time a native I/O is called.</p> <p>You can imagine the efficiency difference with reading a character(or bytes) vis-a-vis reading a large no. of characters in one go(or bytes). With BufferedReader, if you wish to read single character, it will store the contents to fill its buffer (if it is empty) and for further requests, characters will directly be read from buffer, and hence achieves greater efficiency.</p> <p>InputStreamReader converts byte streams to character streams. It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. </p> <p>Hope it helps.</p>
7,395,049
Get Last Part of URL PHP
<p>I'm just wondering how I can extract the last part of a URL using PHP.</p> <p>The example URL is:</p> <pre class="lang-none prettyprint-override"><code>http://domain.example/artist/song/music-videos/song-title/9393903 </code></pre> <p>Now how can I extract the final part using PHP?</p> <pre class="lang-none prettyprint-override"><code>9393903 </code></pre> <p>There is always the same number of variables in the URL, and the id is always at the end.</p>
7,395,079
14
0
null
2011-09-12 23:04:17.703 UTC
20
2022-06-21 19:07:44.143 UTC
2022-06-21 19:04:57.817 UTC
null
1,145,388
null
290,957
null
1
75
php|url
135,721
<p>You can use <a href="http://php.net/manual/en/function.preg-match.php" rel="nofollow noreferrer"><code>preg_match</code></a> to match the part of the URL that you want.</p> <p>In this case, since the pattern is easy, we're looking for a forward slash (<code>\/</code> and we have to escape it since the forward slash denotes the beginning and end of the regular expression pattern), along with one or more digits (<code>\d+</code>) at the very end of the string (<code>$</code>). The parentheses around the <code>\d+</code> are used for capturing the piece that we want: namely the end. We then assign the ending that we want (<code>$end</code>) to <code>$matches[1]</code> (not <code>$matches[0]</code>, since that is the same as <code>$url</code> (ie the entire string)).</p> <pre><code>$url='http://domain.example/artist/song/music-videos/song-title/9393903'; if(preg_match(&quot;/\/(\d+)$/&quot;,$url,$matches)) { $end=$matches[1]; } else { //Your URL didn't match. This may or may not be a bad thing. } </code></pre> <p><strong>Note:</strong> You may or may not want to add some more sophistication to this regular expression. For example, if you know that your URL strings will <strong>always</strong> start with <code>http://</code> then the regex can become <code>/^http:\/\/.*\/(\d+)$/</code> (where <code>.*</code> means zero or more characters (that aren't the newline character)).</p>
7,167,279
Regex select all text between tags
<p>What is the best way to select all the text between 2 tags - ex: the text between all the '<code>&lt;pre&gt;</code>' tags on the page.</p>
7,167,486
21
4
null
2011-08-23 20:42:40.947 UTC
51
2022-07-28 21:56:48.523 UTC
2021-06-22 18:09:30.637 UTC
null
11,455,105
null
595,936
null
1
186
html|regex|html-parsing
443,039
<p>You can use <code>"&lt;pre&gt;(.*?)&lt;/pre&gt;"</code>, (replacing pre with whatever text you want) and extract the first group (for more specific instructions specify a language) but this assumes the simplistic notion that you have very simple and valid HTML.</p> <p>As other commenters have suggested, if you're doing something complex, use a HTML parser.</p>
14,065,580
copy tables with data to another database in SQL Server 2008
<p>I have to copy the <strong>tables with data from one database to another</strong> using <strong>Query</strong>. I know how to copy tables with data within a database. But I was not sure about how to do the same for copying between two databases.</p> <p>I have to copy huge number of tables, so I need any fast method using query...</p> <p>Anybody please help out...Thanks in advance...</p>
14,065,616
4
1
null
2012-12-28 06:31:47.25 UTC
3
2017-09-27 18:35:23.34 UTC
2012-12-28 07:13:49.68 UTC
null
13,302
null
1,565,133
null
1
11
sql|sql-server|sql-server-2008
60,150
<p>You can use the same way to copy the tables within one database, the <a href="http://msdn.microsoft.com/en-us/library/ms188029%28v=sql.100%29.aspx" rel="noreferrer"><strong><code>SELECT INTO</code></strong></a> but use a fully qualified tables names <code>database.schema.object_name</code> instead like so:</p> <pre><code>USE TheOtherDB; SELECT * INTO NewTable FROM TheFirstDB.Schemaname.OldTable </code></pre> <p>This will create a new table <code>Newtable</code> in the database <code>TheOtherDB</code> from the table <code>OldTable</code> whih belongs to the database<code>TheFirstDB</code></p>
14,073,323
Is it possible to cancel/stop a download started using DownloadManager?
<p>I am using DownloadManager to download a bunch of files in my application. I am not able to figure out how to cancel the downloads which has been enqueued by downloadManager. </p> <p>There are two possibilities: a. User can manually cancel it say by clicking it in the notification bar. b. Cancel and remove the download through code.</p> <p>I have the following receiver defined.</p> <pre><code>&lt;receiver android:name=".DownloadStatusReceiver" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.DOWNLOAD_COMPLETE" /&gt; &lt;action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>And in the receiver</p> <pre><code>if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) { Constants.showLog(TAG, "Notification clicked"); long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); DownloadManager dm =(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE); dm.remove(downloadId); } </code></pre> <p>Any insights?</p>
14,088,174
2
5
null
2012-12-28 17:29:33.447 UTC
11
2020-12-29 16:50:32.577 UTC
null
null
null
null
746,360
null
1
22
android|android-download-manager
24,062
<p>You can cancel downloads via <code>DownloadManager</code> by calling its <code>remove(long...)</code> method. For this you need the ID of the download. From my experience there basically are two reliable ways how to get it:</p> <ol> <li>Remember the return value of <code>enqueue(DownloadManager.Request)</code> method.</li> <li>Query the <code>DownloadManager</code> for downloads via <code>query(DownloadManager.Query)</code> method. Then retrieve the IDs from the returned <code>Cursor</code>, they are stored in the column named <code>DownloadManager.COLUMN_ID</code>.</li> </ol> <p><strong>Broadcast Receiver</strong></p> <p>From my experience, it is not reliable to retrieve download ID via <code>BroadcastReceiver</code> for action <code>android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED</code> (though the broadcast is always sent).</p> <ol> <li>Getting download IDs from extra <code>DownloadManager. EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS</code> does not work properly. On some devices, it always return null. If it returns something on some devices, it is the ID of the download started first. And if the first download is finished/canceled, it returns null for notification of the remaining downloads. </li> <li>Getting a value from extra <code>DownloadManager.EXTRA_DOWNLOAD_ID</code> does not work for this action.</li> </ol> <p>Getting ID in broadcast for action <code>android.intent.action.DOWNLOAD_COMPLETE</code> seems reliable. You have to get it from extra <code>DownloadManager.EXTRA_DOWNLOAD_ID</code>. Note that the broadcast is sent not only for completed download, it is also sent when you cancel download calling <code>remove()</code>.</p> <p><strong>Note:</strong> Downloads are sometimes grouped in one notification, sometimes create multiple notifications. I wasn't able to figure out the conditions when notifications do and do not group. It seems to depend on many factors like OS version, device, download title, ... and in general seems rather unpredictable.</p> <p><strong>Note:</strong> I've tested whether you can cancel other app's download and it doesn't seem so. Even though that the IDs are database IDs that are unique across all apps. Calling <code>remove()</code> does not cancel another app's download.</p>
14,352,932
View a file's history in Magit?
<p><a href="https://stackoverflow.com/questions/278192/view-the-change-history-of-a-file-using-git-versioning">View the change history of a file using Git versioning</a> talks about other ways of viewing history of a file in Git.</p> <p>Can it be done in Emacs Magit? </p>
15,966,567
6
1
null
2013-01-16 07:01:35.37 UTC
25
2022-04-04 04:31:18.717 UTC
2017-05-23 12:26:23.92 UTC
null
-1
null
433,570
null
1
108
git|emacs|magit
27,564
<p>Since magit 2.1: <code>magit-log-buffer-file</code> (as per comment below)</p> <p>Before magit 2.1: <code>magit-file-log</code> is what you are looking for. It will show you all commits for the file in the current buffer in the standard magit log view.</p>
9,173,428
Which font is used in MS-DOS?
<p>Does anyone know which is the font that the Windows console/MS-DOS uses?</p>
9,173,445
8
1
null
2012-02-07 08:59:24.003 UTC
7
2021-01-22 13:55:52.45 UTC
2014-08-28 14:30:46.973 UTC
null
3,826,372
null
2,612,112
null
1
22
fonts|font-face|truetype|windows-console
102,617
<p><a href="https://en.wikipedia.org/wiki/Terminal_%28typeface%29" rel="noreferrer">Terminal</a></p>
9,218,900
jQuery.getJSON and jQuery.parseJSON return [object Object]?
<p><strong>EDIT</strong>: I've gotten the "famous question" badge with this question, so I figured I'd come back to it and stick what happened to me right at the very tippy top for people searching it to get an answer right away.</p> <p>Basically, I was new to JSON. JSON is an object (obviously), as it contains all kinds of stuff! So I was like "Hey, javascript, just pop up an alert with all of this JSON data", expecting it to give me the JSON data as a string. But javascript doesn't do that (which is good!), so it was like "Hey, this is how we display objects, [object Object]".</p> <p>What I could've done is something like <code>alert(obj.DATA[0][1])</code> and it would've shown me that bit of the object.</p> <p>What I really wanted was to verify that I was making good JSON data, which I could've checked with <code>JSON.stringify</code>.</p> <p>Anyway, back to our regularly scheduled questions!</p> <hr> <p>I'm trying to get some JSON data with an ajax call, but jQuery doesn't seem to like my JSON.</p> <p>if I do something like:</p> <pre><code>function init2() { alert("inside init2"); jQuery.ajax({ url: "/Mobile_ReportingChain.cfm", type: "POST", async: false, success: function (data) { alert(data); var obj = jQuery.parseJSON(data); alert(obj); } }); } </code></pre> <p>I get this as from alert(data):</p> <pre><code> {"COLUMNS":["MFIRST_NAME","MLAST_NAME","MMDDL_NAME","MEMPLY_ID","MAIM_NBR","EMPLY_ID"], "DATA":[ ["FNAME1 ","LNAME1 ","MI1 ","000-14-7189","026-0010","000-62-7276"] ,["FNAME2 ","LNAME2 ","MI2 ","000-01-2302","101-1850","000-14-7189"] ,["FNAME3 ","LNAME3 ","MI3 ","000-91-3619","102-1000","000-01-2302"] ,["FNAME4 ","LNAME4 ","MI4 ","000-25-9687","102-1000","000-91-3619"] ]} </code></pre> <p>which JSONLint says is valid json. alert(obj) gives me this, however:</p> <pre><code>[object Object] </code></pre> <p>adding <code>dataType: "json"</code> or <code>"text json"</code> just makes it report <code>[object Object]</code> at <code>alert(data)</code>.</p> <p>I'd really like to get this figured out, does anyone know why it's doing this? I'm pretty new at jQuery, my goal is to get an array for each of the columns. The same code I'm using has worked on a different page it looks like, which is what's bothering me the most.</p>
9,218,947
8
1
null
2012-02-09 21:16:35.757 UTC
10
2021-04-07 07:26:46.993 UTC
2013-09-18 13:53:35.883 UTC
null
807,032
null
807,032
null
1
33
json|jquery
72,815
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.alert" rel="noreferrer"><code>alert()</code></a> function can only display a string of text. As its only parameter it takes a string or an object. <em>The object will however be converted into a string that can be displayed.</em> </p> <p>When fetching JSON through jQuery, the <code>$.ajax()</code> method will automatically parse the JSON and turn it into a JavaScript object for you. Your <code>data</code> variable is therefor a JavaScript object, and not a JSON string as one might expect.</p> <p>Since <code>alert()</code> only can display strings, when trying to alert your <code>data</code> object, your object will be turned into its string representation. The string representation of a JavaScript object is <code>[object Object]</code>. </p> <p>For debug-purposes you can use <code>console.log(data)</code> instead. You can then inspect the object and its content through the console in your browsers developer tools.</p> <pre><code>function init2() { jQuery.ajax({ url: "/Mobile_ReportingChain.cfm", type: "POST", dataType: "json", async: false, success: function (data) { console.log(data); } }); } </code></pre> <p><em>If you for some reason still want to alert the JSON-data, then you would have to turn your <code>data</code> object back into a JSON-string. To do that you can make use of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify" rel="noreferrer"><code>JSON.stringify</code></a>:</em></p> <pre><code>alert(JSON.stringify(data)); </code></pre>