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
24,746,892
How to calculate Euclidian distance between two points defined by matrix containing x, y?
<p>I am very lost in <strong>Euclidean distance calculation</strong>. I have found functions dist2{SpatialTools} or rdist{fields} to do this, but they doesn´t work as expected.</p> <p>I suppose that one point has two coordinates in carthesian system, so [x,y]. To measure distance between 2 points (defined by row), I need 4 coordinates for 2 points, so point A: [x1,y1] point B: [x2,y2] </p> <p>Points coordinations:</p> <p><img src="https://i.stack.imgur.com/RtEPq.png" alt="Points position"></p> <pre><code>A[0,1] B[0,0] C[1,1] D[1,1] </code></pre> <p>I have two matrices: <strong>x1</strong>(A and C are there, defined by rows) and <strong>x2</strong> (contain B and D). Written in matrix: </p> <pre><code>library("SpatialTools") x1&lt;-matrix(c(0,1,1,1), nrow = 2, ncol=2, byrow=TRUE) x2&lt;-matrix(c(0,0,1,1), nrow = 2, ncol=2, byrow=TRUE) </code></pre> <p>so I obtain</p> <pre><code>&gt; x1 [,1] [,2] [1,] 0 1 #(as xy coordinates of A point) [2,] 1 1 #(same for C point) &gt; x2 [,1] [,2] [1,] 0 0 #(same for B point) [2,] 1 1 #(same for D point) </code></pre> <p>To calculate euclidean distance between </p> <pre><code>A &lt;-&gt; B # same as x1[1,] &lt;-&gt; x2[1,] C &lt;-&gt; D # same as x1[2,] &lt;-&gt; x2[2,] </code></pre> <p>I assume to obtain <strong>EuclidDist</strong>:</p> <pre><code>&gt; x1 x2 EuclidDist [,1] [,2] [,1] [,2] [1,] 0 1 #A [1,] 0 0 #B 1 [2,] 1 1 #B [2,] 1 1 #D 0 </code></pre> <p>I would like just to obtain <strong>vector of distances between two points identified by [x,y] coordinates</strong>, however, using <code>dist2</code> I obtain a matrix:</p> <pre><code>&gt; dist2(x1,x2) [,1] [,2] [1,] 1.000000 1 [2,] 1.414214 0 </code></pre> <p>My question is, which numbers describe the real Euclidean distance between A-B and C-D from this matrix? Am I misunderstanding something? Thank you very much for every advice or any explanation.</p>
24,747,155
4
0
null
2014-07-14 22:13:28.09 UTC
3
2018-07-05 20:10:45.32 UTC
null
null
null
null
2,742,140
null
1
10
r|matrix|euclidean-distance
52,746
<p>If you just want a vector, something like this will work for you.</p> <p>Try something like this:</p> <pre><code>euc.dist &lt;- function(x1, x2) sqrt(sum((x1 - x2) ^ 2)) library(foreach) foreach(i = 1:nrow(x1), .combine = c ) %do% euc.dist(x1[i,],x2[i,]) </code></pre> <p>This will work for any dimensions.</p> <p>If you don't want to use foreach, you can use a simple loop:</p> <pre><code>dist &lt;- NULL for(i in 1:nrow(x1)) dist[i] &lt;- euc.dist(x1[i,],x2[i,]) dist </code></pre> <p>Although, I would recommend foreach (because it's very easy to for various tasks like this). Read more about it in the documentation of the package.</p>
28,458,694
Django REST framework: save related models in ModelViewSet
<p>I'm trying to figure out how to save related models using Django REST framework. In my app I have a model <code>Recipe</code> with 2 related models: <code>RecipeIngredient</code> and <code>RecipeStep</code>. A <code>Recipe</code> object MUST have at least 3 related <code>RecipeIngredient</code> and 3 <code>RecipeStep</code>. Before the introduction of the REST framework I was using a Django <code>CreateView</code> with two formsets and the save process was the following (follow the code from <code>form_valid()</code>):</p> <pre><code>def save_formsets(self, recipe): for f in self.get_formsets(): f.instance = recipe f.save() def save(self, form): with transaction.atomic(): recipe = form.save() self.save_formsets(recipe) return recipe def formsets_are_valid(self): return all(f.is_valid() for f in self.get_formsets()) def form_valid(self, form): try: if self.formsets_are_valid(): try: return self.create_ajax_success_response(form) except IntegrityError as ie: return self.create_ajax_error_response(form, {'IntegrityError': ie.message}) except ValidationError as ve: return self.create_ajax_error_response(form, {'ValidationError': ve.message}) return self.create_ajax_error_response(form) </code></pre> <p>Now I have my <code>RecipeViewSet</code>:</p> <pre><code>class RecipeViewSet(ModelViewSet): serializer_class = RecipeSerializer queryset = Recipe.objects.all() permission_classes = (RecipeModelPermission, ) </code></pre> <p>which uses <code>RecipeSerializer</code>:</p> <pre><code>class RecipeSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ( 'name', 'dish_type', 'cooking_time', 'steps', 'ingredients' ) ingredients = RecipeIngredientSerializer(many=True) steps = RecipeStepSerializer(many=True) </code></pre> <p>and these are the related serializers:</p> <pre><code>class RecipeIngredientSerializer(serializers.ModelSerializer): class Meta: model = RecipeIngredient fields = ('name', 'quantity', 'unit_of_measure') class RecipeStepSerializer(serializers.ModelSerializer): class Meta: model = RecipeStep fields = ('description', 'photo') </code></pre> <p>Now... how I'm supposed to validate related models (<code>RecipeIngredient</code> and <code>RecipeStep</code>) and save them when <code>RecipeViewSet</code>'s <code>create()</code> method is called? (<code>is_valid()</code> in <code>RecipeSerializer</code> is actually ignoring nested relationships and reporting only errors related to the main model <code>Recipe</code>). At the moment I tried to override the <code>is_valid()</code> method in <code>RecipeSerializer</code>, but is not so simple... any idea?</p>
28,460,714
2
0
null
2015-02-11 15:55:16.4 UTC
11
2016-09-05 08:41:56.133 UTC
null
null
null
null
267,719
null
1
13
django|django-forms|django-rest-framework|formset
6,685
<p>I was dealing with similiar issue this week and I found out, that django rest framework 3 actually supports nested writable serialisation (<a href="http://www.django-rest-framework.org/topics/3.0-announcement/#serializers" rel="noreferrer">http://www.django-rest-framework.org/topics/3.0-announcement/#serializers</a> in subchapter Writable nested serialization.)</p> <p>Im not sure if nested serialisers are writable be default, so I declared them:</p> <pre><code>ingredients = RecipeIngredientSerializer(many=True, read_only=False) steps = RecipeStepSerializer(many=True, read_only=False) </code></pre> <p>and you should rewrite your create methon inside RecipeSerializer:</p> <pre><code>class RecipeSerializer(serializers.ModelSerializer): ingredients = RecipeIngredientSerializer(many=True, read_only=False) steps = RecipeStepSerializer(many=True, read_only=False) class Meta: model = Recipe fields = ( 'name', 'dish_type', 'cooking_time', 'steps', 'ingredients' ) def create(self, validated_data): ingredients_data = validated_data.pop('ingredients') steps_data = validated_data.pop('steps') recipe = Recipe.objects.create(**validated_data) for ingredient in ingredients_data: #any ingredient logic here Ingredient.objects.create(recipe=recipe, **ingredient) for step in steps_data: #any step logic here Step.objects.create(recipe=recipe, **step) return recipe </code></pre> <p>if this structure Step.objects.create(recipe=recipe, **step) wont work, maybe you have to select data representeng each field separatly from steps_data / ingredients_data.</p> <p>This is link to my earlier (realted) question/answer on stack: <a href="https://stackoverflow.com/questions/28420802/how-to-create-multiple-objects-related-with-one-request-in-drf">How to create multiple objects (related) with one request in DRF?</a></p>
25,225,927
Android studio doesn't list my phone under "Choose Device"
<p>Just starting out with Android development; have a Nexus 5 bought in Japan, but with English version of android (presumably shouldn't matter). I installed Android Studio on Windows 8.1 to try making an app, but now I don't see my phone under "Choose Device". I've enabled developer mode and selected 'USB debugging'. Is there something else I need to do to get Android Studio to see my connected device?</p> <p><img src="https://i.stack.imgur.com/vHYo1.png" alt="Choose Device dialog"></p>
25,225,936
13
0
null
2014-08-10 05:46:01.467 UTC
9
2021-09-30 06:49:19.927 UTC
null
null
null
null
1,392,189
null
1
34
android|android-studio
148,502
<p>Have you installed drivers for the phone? <a href="http://developer.android.com/sdk/win-usb.html" rel="noreferrer">http://developer.android.com/sdk/win-usb.html</a></p> <p>It appears that the the sdk does not "install" the USB drivers. You can select that usb drivers in the sdk to see the file location, open that up, and right click to install the driver yourself.</p> <ul> <li>File -> Settings -> Android SDK -> SDK Tools -> Google USB Driver -> Right click -> Install <ul> <li>Ensure that Google USB driver is checked.</li> </ul></li> </ul> <p>If above doesn't work, @Abir Hasan appears to have another method in answers below.</p>
42,630,894
Jenkins + Docker: How to control docker user when using Image.inside command
<p>Dear Stackoverflow Community,</p> <p>I am trying to setup a Jenkins CI pipeline using docker images as containers for my build processes. I am defining a Jenkinsfile to have a build pipeline as code. I am doing something like this:</p> <pre><code>node { docker.withRegistry('http://my.registry.com', 'docker-credentials') { def buildimage = docker.image('buildimage:latest'); buildimage.pull(); buildimage.inside("") { stage('Checkout sources') { git url: '...', credentialsId: '...' } stage('Run Build and Publish') { sh "..." } } } } </code></pre> <p>Unfortunately I am stumbling upon a weird behavior of the Docker pipeline plugin. In the build output I can see that the Image.inside(...) command triggers the container with a</p> <pre><code>docker run -t -d -u 1000:1000 ... </code></pre> <p>This makes my build fail, because the user defined in the Dockerfile does not have the UID 1000 ... another user is actually taken. I even tried specifying which user should be used within the Jenkinsfile</p> <pre><code>node { docker.withRegistry('http://my.registry.com', 'docker-credentials') { def buildimage = docker.image('buildimage:latest'); buildimage.pull(); buildimage.inside("-u otheruser:othergroup") { stage('Checkout sources') { git url: '...', credentialsId: '...' } stage('Run Build and Publish') { sh "..." } } } } </code></pre> <p>but this leads to a duplicate -u switch in the resulting docker run command </p> <pre><code>docker run -t -d -u 1000:1000 -u otheruser:othergroup ... </code></pre> <p>and obviously only the first -u is applied because my build still fails. I also did debugging using whoami to validate my assumptions.</p> <p>So my questions: how can I change this behavior? Is there a switch where I can turn the -u 1000:1000 off? Is this even a bug? I actually like to work with the Docker plugin because it simplifies the usage of an own docker registry with credentials maintained in Jenkins. However, is there another simple way to get to my goal if the Docker Plugin is not usable?</p> <p>Thank you in advance for your time </p>
42,822,143
2
0
null
2017-03-06 16:37:52.847 UTC
6
2018-08-23 14:54:03.673 UTC
2018-01-20 21:44:38.913 UTC
null
3,318,954
null
3,318,954
null
1
44
docker|jenkins|jenkins-pipeline
32,217
<p>As you can see <a href="https://github.com/jenkinsci/docker-workflow-plugin/blob/docker-workflow-1.9/src/main/java/org/jenkinsci/plugins/docker/workflow/WithContainerStep.java#L175" rel="noreferrer">here</a> or <a href="https://github.com/jenkinsci/docker-workflow-plugin/blob/docker-workflow-1.9/src/main/java/org/jenkinsci/plugins/docker/workflow/client/DockerClient.java#L278" rel="noreferrer">here</a> is hardcoded the fact of append the uid and gid of the user that is running Jenkins (in your case, the Jenkins user created inside the oficial docker image).</p> <p>You can change the user that runs the processes inside your Jenkins image passing the --user (or -u) argument to the <code>docker run</code> command. Maybe this can minimize your problems.</p> <p><strong>Edited</strong></p> <blockquote> <p>how can I change this behavior? Is there a switch where I can turn the -u 1000:1000 off? </p> </blockquote> <p>You can't change this behaviour in the actual version because the whoami is hardcoded.</p> <blockquote> <p>Is this even a bug? </p> </blockquote> <p>In <a href="https://github.com/jenkinsci/docker-workflow-plugin/pull/57" rel="noreferrer">this</a> pull request seems that they are working on it.</p> <blockquote> <p>However, is there another simple way to get to my goal if the Docker Plugin is not usable?</p> </blockquote> <p>The new pipeline plugin version that comes with Jenkins also use the docker-workflow-plugin to run the containers. I don't know another plugin to run that in a simple way. To workaround this, you can run your Jenkins as root but is a very ugly solution.</p>
34,445,636
Why is Cocoapods complaining about the embedded content contains swift setting in the build settings?
<p>I recently added swift files to my test target (combined with older cocoa touch classes).</p> <p>Why is cocoapods complaining about the embedded content contains swift setting in the build settings?</p> <blockquote> <p>[!] The YOURP-PROJECT-Tests [Debug] target overrides the EMBEDDED_CONTENT_CONTAINS_SWIFT build setting defined in Pods/Target Support Files/Pods-YOUR-PROJECT-Tests/Pods-YOUR-PROJECT-Tests.debug.xcconfig. This can lead to problems with the CocoaPods installation</p> </blockquote>
34,445,637
2
0
null
2015-12-24 00:16:12.517 UTC
10
2016-12-12 20:30:24.743 UTC
2015-12-24 02:15:11.43 UTC
null
1,610,029
null
1,610,029
null
1
35
xcode|swift|cocoapods
12,217
<p>I needed to add the $(inherited) flag to the build setting</p> <p><a href="https://i.stack.imgur.com/Uaz6x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Uaz6x.png" alt="enter image description here"></a></p>
45,155,104
Displaying notification badge on BottomNavigationBar's Icon
<p>I'd like to display notification badge (a colored <strong>marble</strong>) on the <strong>top right corner</strong> of BottomNavigationBar's <strong>Icon</strong> widget when a new message has arrived in the inbox tab. It is similar to <a href="https://developer.android.com/preview/features/notification-badges.html" rel="noreferrer">https://developer.android.com/preview/features/notification-badges.html</a> but for my case it is displayed in-app.</p> <p>Any tips to paint the overlay on existing icon to create a <strong>custom</strong> Icon class?</p>
45,434,404
10
0
null
2017-07-17 23:22:06.843 UTC
27
2022-05-05 17:31:35.803 UTC
null
null
null
user8320143
null
null
1
68
dart|flutter
62,431
<p>Yes. It can be done by stacking two icons using the <code>Stack</code> and <code>Positioned</code> widget. </p> <pre><code> new BottomNavigationBarItem( title: new Text('Home'), icon: new Stack( children: &lt;Widget&gt;[ new Icon(Icons.home), new Positioned( // draw a red marble top: 0.0, right: 0.0, child: new Icon(Icons.brightness_1, size: 8.0, color: Colors.redAccent), ) ] ), ) </code></pre>
7,429,185
Using MsBuild to generate customized MsDeploy manifest (Package target)
<p>I am using Web Deploy to package and deploy web sites for my product. In particular, I have two different projects in my solution I use this method to deploy.</p> <p>I have a third project in the solution (a windows service) that also needs to be installed on the web server.</p> <p>I know I can write a custom manifest (for the <code>dirPath</code>, <code>filePath</code> and <code>runCommand</code> providers) and directly call MsDeploy to deploy it. But I would like to leverage the existing MsBuild tasks to package my service if possible.</p> <p>I see it is possible to do some customization of the manifest file via msbuild targets:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en/msbuild/thread/1044058c-f762-456b-8a68-b0863027ce47" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en/msbuild/thread/1044058c-f762-456b-8a68-b0863027ce47</a></p> <p>Particularly by using the <code>MsDeploySourceManifest</code> item.</p> <p>After poking through the appropriate .targets files, it looks like either <code>contentPath</code> or <code>iisApp</code> will get appended to my manifest if I use the <code>Package</code> target. Ideally I'd just like to copy an assembly (or directory), possibly set ACLs, and execute installutil.exe on the service.</p> <p>Is it possible to completely customize the manifest generated by the <code>Package</code> target, by editing my csproj file?</p> <p>If not, is there a simple way to build a new target that will do the equivalent to <code>Package</code>, yet allow me to spit out a completely custom manifest?</p>
8,222,862
1
8
null
2011-09-15 10:10:59.34 UTC
13
2012-04-28 02:46:41.31 UTC
2012-04-28 02:46:41.31 UTC
null
105,999
null
232,593
null
1
18
msbuild|manifest|msdeploy|slowcheetah
8,540
<p>I don't have a complete write up yet for people trying to learn how this works, but I now have a write up for how to at least accomplish this goal.</p> <p><strike><a href="http://thehappypath.net/2011/11/21/using-msdeploy-for-windows-services/" rel="nofollow noreferrer">http://thehappypath.net/2011/11/21/using-msdeploy-for-windows-services/</a></strike></p> <p>(<em>edit: link is dead for now. Let me know if you're interested and I can post it elsewhere</em>).</p> <p>My guide goes through these overall steps:</p> <ul> <li>Ensure the service starts itself upon installation (not crucial, but easier to deal with)</li> <li>Add the Microsoft.WebApplication.targets file to your project, even though you don't have a web project. This enables the <code>Package</code> MsBuild target.</li> <li>Add a custom .targets file to your project that builds a custom MsBuild package manifest</li> <li>Add some batch scripts to your project to stop/uninstall and install the service</li> <li>Add a Parameters.xml file to support changing the target deployment directory a bit more easily</li> <li>Set up app.config transformations using <a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5" rel="nofollow noreferrer">the SlowCheetah Visual Studio addon</a></li> </ul> <p>Then you can package your project with this command line:</p> <pre><code>msbuild MyProject.csproj /t:Package /p:Configuration=Debug </code></pre> <p>You can deploy the resulting package with this command line:</p> <pre><code>MyService.Deploy.cmd /Y /M:mywebserver -allowUntrusted </code></pre> <p>The most undocumented part of this (except for my guide) is creating the custom manifest. Here's a dump of my current file (note, it is still a bit buggy, but can be fixed - See this question: <a href="https://stackoverflow.com/questions/5408585/msdeploy-remoting-executing-manifest-twice">MsDeploy remoting executing manifest twice</a> - and try to keep to using <em>only</em> direct batch files for <code>runCommand</code>).</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; &lt;!-- This file must be included before Microsoft.Web.Publishing.targets so we can hook into BeforeAddIisSettingAndFileContentsToSourceManifest --&gt; &lt;PropertyGroup&gt; &lt;!-- Include our targets --&gt; &lt;IncludeStopServiceCommand&gt;True&lt;/IncludeStopServiceCommand&gt; &lt;IncludeSetCustomAclsProvider&gt;True&lt;/IncludeSetCustomAclsProvider&gt; &lt;IncludeInstallServiceCommand&gt;True&lt;/IncludeInstallServiceCommand&gt; &lt;IncludeMoveAppConfigToCorrectPackagePath&gt;True&lt;/IncludeMoveAppConfigToCorrectPackagePath&gt; &lt;!-- Uncomment to enable more verbose MsBuild logging --&gt; &lt;!-- &lt;EnablePackageProcessLoggingAndAssert&gt;True&lt;/EnablePackageProcessLoggingAndAssert&gt; --&gt; &lt;!-- Enable web.config transform, but hack it to work for app.config --&gt; &lt;ProjectConfigFileName&gt;app.config&lt;/ProjectConfigFileName&gt; &lt;TransformWebConfigEnabled&gt;True&lt;/TransformWebConfigEnabled&gt; &lt;UseParameterizeToTransformWebConfig&gt;True&lt;/UseParameterizeToTransformWebConfig&gt; &lt;!-- Enable web project packaging, but hack it to work for non-web app --&gt; &lt;DeployAsIisApp&gt;False&lt;/DeployAsIisApp&gt; &lt;IncludeIisSettingsOnPublish&gt;False&lt;/IncludeIisSettingsOnPublish&gt; &lt;IncludeSetAclProviderOnDestination&gt;False&lt;/IncludeSetAclProviderOnDestination&gt; &lt;DisableAllVSGeneratedMSDeployParameter&gt;True&lt;/DisableAllVSGeneratedMSDeployParameter&gt; &lt;!-- Insert our custom targets into correct places in build process --&gt; &lt;BeforeAddIisSettingAndFileContentsToSourceManifest Condition="'$(BeforeAddIisSettingAndFileContentsToSourceManifest)'==''"&gt; $(BeforeAddIisSettingAndFileContentsToSourceManifest); AddStopServiceCommand; &lt;/BeforeAddIisSettingAndFileContentsToSourceManifest&gt; &lt;AfterAddIisSettingAndFileContentsToSourceManifest Condition="'$(AfterAddIisSettingAndFileContentsToSourceManifest)'==''"&gt; $(AfterAddIisSettingAndFileContentsToSourceManifest); AddSetCustomAclsProvider; AddInstallServiceCommand; &lt;/AfterAddIisSettingAndFileContentsToSourceManifest&gt; &lt;OnAfterCopyAllFilesToSingleFolderForPackage Condition="'$(OnAfterCopyAllFilesToSingleFolderForPackage)'==''"&gt; $(OnAfterCopyAllFilesToSingleFolderForPackage); MoveAppConfigToCorrectPackagePath; &lt;/OnAfterCopyAllFilesToSingleFolderForPackage&gt; &lt;/PropertyGroup&gt; &lt;!-- Custom targets --&gt; &lt;Target Name="AddStopServiceCommand" Condition="'$(IncludeStopServiceCommand)'=='true'"&gt; &lt;Message Text="Adding runCommand to stop the running Service" /&gt; &lt;ItemGroup&gt; &lt;MsDeploySourceManifest Include="runCommand"&gt; &lt;path&gt;$(_MSDeployDirPath_FullPath)\bin\servicestop.bat&lt;/path&gt; &lt;waitInterval&gt;20000&lt;/waitInterval&gt; &lt;AdditionalProviderSettings&gt;waitInterval&lt;/AdditionalProviderSettings&gt; &lt;/MsDeploySourceManifest&gt; &lt;/ItemGroup&gt; &lt;/Target&gt; &lt;Target Name="AddSetCustomAclsProvider" Condition="'$(IncludeSetCustomAclsProvider)'=='true'"&gt; &lt;ItemGroup&gt; &lt;MsDeploySourceManifest Include="setAcl"&gt; &lt;Path&gt;$(_MSDeployDirPath_FullPath)&lt;/Path&gt; &lt;setAclUser&gt;LocalService&lt;/setAclUser&gt; &lt;setAclAccess&gt;FullControl&lt;/setAclAccess&gt; &lt;!-- Todo: Reduce these permissions --&gt; &lt;setAclResourceType&gt;Directory&lt;/setAclResourceType&gt; &lt;AdditionalProviderSettings&gt;setAclUser;setAclAccess;setAclResourceType&lt;/AdditionalProviderSettings&gt; &lt;/MsDeploySourceManifest&gt; &lt;/ItemGroup&gt; &lt;/Target&gt; &lt;Target Name="AddInstallServiceCommand" Condition="'$(IncludeInstallServiceCommand)'=='true'"&gt; &lt;Message Text="Adding runCommand to install the Service" /&gt; &lt;ItemGroup&gt; &lt;MsDeploySourceManifest Include="runCommand"&gt; &lt;path&gt;cmd.exe /c $(_MSDeployDirPath_FullPath)\bin\serviceinstall.bat&lt;/path&gt; &lt;waitInterval&gt;20000&lt;/waitInterval&gt; &lt;dontUseCommandExe&gt;false&lt;/dontUseCommandExe&gt; &lt;AdditionalProviderSettings&gt;waitInterval;dontUseCommandExe&lt;/AdditionalProviderSettings&gt; &lt;/MsDeploySourceManifest&gt; &lt;/ItemGroup&gt; &lt;/Target&gt; &lt;Target Name="MoveAppConfigToCorrectPackagePath" Condition="'$(IncludeMoveAppConfigToCorrectPackagePath)'=='true'"&gt; &lt;PropertyGroup&gt; &lt;OriginalAppConfigFilename&gt;$(_PackageTempDir)\App.Config&lt;/OriginalAppConfigFilename&gt; &lt;TargetAppConfigFilename&gt;$(_PackageTempDir)\bin\$(TargetFileName).config&lt;/TargetAppConfigFilename&gt; &lt;/PropertyGroup&gt; &lt;Copy SourceFiles="$(OriginalAppConfigFilename)" DestinationFiles="$(TargetAppConfigFilename)" Condition="Exists($(OriginalAppConfigFilename))" /&gt; &lt;Delete Files="$(OriginalAppConfigFilename)" Condition="Exists($(OriginalAppConfigFilename))" /&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre>
22,650,699
javascript Uncaught TypeError: Cannot read property 'firstChild' of null
<p>I am getting the following error in Google Chrome on a very old Form I inherited (seems to work OK in IE, no errors)</p> <blockquote> <p>Uncaught TypeError: Cannot read property 'firstChild' of null</p> </blockquote> <p>The error applies to the following js <strong>elem.firstChild.nodeValue = dispmessage;</strong>:</p> <pre><code>function msg(fld, msgtype, message) { if (emptyString.test(message)) dispmessage = String.fromCharCode(nbsp); else dispmessage = message; var elem = document.getElementById(fld); elem.firstChild.nodeValue = dispmessage; elem.className = msgtype; // set the CSS class to adjust appearance of message }; </code></pre> <p>Wondering if someone has come across similar issue before? Any ideas on how I can resolve?</p> <p>Cheers</p>
22,650,720
1
0
null
2014-03-26 03:03:42.093 UTC
null
2014-03-26 03:06:32.733 UTC
null
null
null
null
3,445,112
null
1
13
javascript|html|forms
38,526
<p>This error means the <code>elem</code> object is <code>null</code>. Check the fld value passed and see whether an object with that id actually exists in your code or not.</p>
64,306,943
DefaultValues of react-hook-form is not setting the values to the Input fields in React JS
<p>I want to provide default values in the input field using <code>react-hook-form</code>. First I retrieve the user data from the API endpoint and then setting the state <code>users</code> to that user data. Then I pass the state <code>users</code> to the <code>defaultValues</code> of <code>useForm()</code>.</p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import { useForm } from &quot;react-hook-form&quot;; import axios from &quot;axios&quot;; function LoginFile() { const [users, setUsers] = useState(null); useEffect(() =&gt; { axios .get(&quot;http://localhost:4000/users/1&quot;) .then((res) =&gt; setUsers(res.data)); }, []); useEffect(() =&gt; { console.log(users); }, [users]); const { register, handleSubmit, errors } = useForm({ defaultValues: users, }); return ( &lt;div&gt; &lt;form onSubmit={handleSubmit(onSubmit)}&gt; Email &lt;input type=&quot;email&quot; name=&quot;email&quot; ref={register} /&gt;&lt;br /&gt; firstname &lt;input name=&quot;firstname&quot; ref={register} /&gt;&lt;br/&gt; &lt;input type=&quot;submit&quot; /&gt; &lt;/form&gt; &lt;/div&gt; ); } export default LoginFile; </code></pre> <p>I did by the above code but didn't work as expected. All the input fields are still empty. I want to have some default values in the input field of my form.</p>
64,307,087
2
0
null
2020-10-11 17:17:59.757 UTC
8
2021-08-18 22:42:54.713 UTC
null
null
null
null
13,847,690
null
1
28
reactjs|react-hook-form
44,156
<p>The problem is that during the first render, <code>users</code> is the <code>useState</code> hook's initial value, which is <code>null</code>. The value only changes after the <code>axios.get()</code> request finishes, which is <em>after</em> the initial render. This means that the the default values passed to <code>useForm</code> is <code>null</code>.</p> <p>The <a href="https://react-hook-form.com/api/useform" rel="noreferrer">documentation for defaultValues</a> says the following:</p> <blockquote> <p><code>defaultValues</code> are cached <strong>on the first render</strong> within the custom hook. If you want to reset the <code>defaultValues</code>, you should use the <a href="https://react-hook-form.com/api/useform/reset" rel="noreferrer"><code>reset</code></a> api.</p> </blockquote> <p>So, you'll just need to use <code>reset</code> to reset the form manually to the values which you fetch. The documentation for <code>reset</code> says the following:</p> <blockquote> <p>You will need to pass <code>defaultValues</code> to <code>useForm</code> in order to <code>reset</code> the <code>Controller</code> components' value.</p> </blockquote> <p>However, it's unclear from the documentation whether <code>null</code> is enough as the defaultValues, or if you need to pass it a proper object with fields for each input. To play it safe, let's assume it's the latter.</p> <p>The code for doing this would look something like this:</p> <pre><code>function LoginFile() { const [users, setUsers] = useState({ email: &quot;&quot;, firstname: &quot;&quot; }); const { register, handleSubmit, errors, reset } = useForm({ defaultValues: users, }); useEffect(() =&gt; { axios.get(&quot;http://localhost:4000/users/1&quot;).then((res) =&gt; { setUsers(res.data); reset(res.data); }); }, [reset]); useEffect(() =&gt; { console.log(users); }, [users]); return ( &lt;div&gt; &lt;form onSubmit={handleSubmit(onSubmit)}&gt; Email &lt;input type=&quot;email&quot; name=&quot;email&quot; ref={register} /&gt; &lt;br /&gt; firstname &lt;input name=&quot;firstname&quot; ref={register} /&gt; &lt;br /&gt; &lt;input type=&quot;submit&quot; /&gt; &lt;/form&gt; &lt;/div&gt; ); } </code></pre> <p>Additionally, if the only reason for the useState hook is to store the value for <code>defaultValues</code>, you don't need it at all and can clean up the code to be:</p> <pre><code>function LoginFile() { const { register, handleSubmit, errors, reset } = useForm({ defaultValues: { email: &quot;&quot;, firstname: &quot;&quot; }, }); useEffect(() =&gt; { axios.get(&quot;http://localhost:4000/users/1&quot;).then((res) =&gt; { reset(res.data); }); }, [reset]); return ( &lt;div&gt; &lt;form onSubmit={handleSubmit(onSubmit)}&gt; Email &lt;input type=&quot;email&quot; name=&quot;email&quot; ref={register} /&gt; &lt;br /&gt; firstname &lt;input name=&quot;firstname&quot; ref={register} /&gt; &lt;br /&gt; &lt;input type=&quot;submit&quot; /&gt; &lt;/form&gt; &lt;/div&gt; ); } </code></pre>
15,417,619
How do you update Xcode on OSX to the latest version?
<p>What is the easiest way to update Xcode on OSX?</p> <p>I see this in the terminal:</p> <pre><code>$ brew install xxxxxxx Warning: Your Xcode (4.3.3) is outdated Please install Xcode 4.6. </code></pre> <p>But when I go to open up <code>Xcode &gt; Preferences &gt; Downloads</code>, it says there are no updates?</p>
15,417,752
14
0
null
2013-03-14 18:42:14.45 UTC
31
2022-08-26 19:22:01.717 UTC
null
null
null
null
639,988
null
1
256
xcode|macos|homebrew
664,581
<ol> <li><p>Open up App Store</p> <p><img src="https://i.stack.imgur.com/BVp6D.png" alt="enter image description here" /></p> </li> <li><p>Look in the top right for the updates section (may also be in lefthand column &quot;Updates&quot;..)</p> <p><img src="https://i.stack.imgur.com/Skf8z.png" alt="enter image description here" /></p> </li> <li><p>Find Xcode &amp; click Update <img src="https://i.stack.imgur.com/FovPK.png" alt="enter image description here" /></p> </li> </ol>
22,055,889
How to test a Controller Concern in Rails 4
<p>What is the best way to handle testing of concerns when used in Rails 4 controllers? Say I have a trivial concern <code>Citations</code>.</p> <pre><code>module Citations extend ActiveSupport::Concern def citations ; end end </code></pre> <p>The expected behavior under test is that any controller which includes this concern would get this <code>citations</code> endpoint.</p> <pre><code>class ConversationController &lt; ActionController::Base include Citations end </code></pre> <p>Simple.</p> <pre><code>ConversationController.new.respond_to? :yelling #=&gt; true </code></pre> <p>But what is the right way to test this concern in isolation? </p> <pre><code>class CitationConcernController &lt; ActionController::Base include Citations end describe CitationConcernController, type: :controller do it 'should add the citations endpoint' do get :citations expect(response).to be_successful end end </code></pre> <p>Unfortunately, this fails.</p> <pre><code>CitationConcernController should add the citations endpoint (FAILED - 1) Failures: 1) CitationConcernController should add the citations endpoint Failure/Error: get :citations ActionController::UrlGenerationError: No route matches {:controller=&gt;"citation_concern", :action=&gt;"citations"} # ./controller_concern_spec.rb:14:in `block (2 levels) in &lt;top (required)&gt;' </code></pre> <p>This is a contrived example. In my app, I get a different error.</p> <pre><code>RuntimeError: @routes is nil: make sure you set it in your test's setup method. </code></pre>
22,058,647
4
0
null
2014-02-26 23:34:12.43 UTC
27
2020-11-23 10:42:51.47 UTC
null
null
null
null
224,872
null
1
48
ruby-on-rails|rspec|controller|activesupport-concern
22,613
<p>You will find many advice telling you to use shared examples and run them in the scope of your included controllers.</p> <p>I personally find it over-killing and prefer to perform unit testing in isolation, then use integration testing to confirm the behavior of my controllers.</p> <p><strong>Method 1: without routing or response testing</strong></p> <p>Create a fake controller and test its methods:</p> <pre><code>describe MyControllerConcern do before do class FakesController &lt; ApplicationController include MyControllerConcern end end after do Object.send :remove_const, :FakesController end let(:object) { FakesController.new } it 'my_method_to_test' do expect(object).to eq('expected result') end end </code></pre> <p><strong>Method 2: testing response</strong></p> <p>When your concern contains routing or you need to test for response, rendering etc... you need to run your test with an anonymous controller. This allow you to gain access to all controller-related rspec methods and helpers:</p> <pre><code>describe MyControllerConcern, type: :controller do controller(ApplicationController) do include MyControllerConcern def fake_action; redirect_to '/an_url'; end end before do routes.draw { get 'fake_action' =&gt; 'anonymous#fake_action' } end describe 'my_method_to_test' do before do get :fake_action end it do expect(response).to redirect_to('/an_url') end end end </code></pre> <p>As you can see, we define the anonymous controller with <code>controller(ApplicationController)</code>. If your test concerne another class than <code>ApplicationController</code>, you will need to adapt this.</p> <p>Also for this to work properly you must configure the following in your <em>spec_helper.rb</em> file:</p> <pre><code>config.infer_base_class_for_anonymous_controllers = true </code></pre> <p><strong>Note: keep testing that your concern is included</strong></p> <p>It is also important to test that your concern class is included in your target classes, one line suffice:</p> <pre><code>describe SomeTargetedController do it 'includes MyControllerConcern' do expect(SomeTargetedController.ancestors.include? MyControllerConcern).to be(true) end end </code></pre>
2,470,285
Foreign keys in django admin list display
<p>If a django model contains a foreign key field, and if that field is shown in list mode, then it shows up as <em>text</em>, instead of displaying a <em>link</em> to the foreign object.</p> <p>Is it possible to automatically display all foreign keys as links instead of flat text?</p> <p>(of course it is possible to do that on a field by field basis, but is there a general method?)</p> <p><strong>Example</strong>:</p> <pre><code>class Author(models.Model): ... class Post(models.Model): author = models.ForeignKey(Author) </code></pre> <p>Now I choose a ModelAdmin such that the author shows up in list mode:</p> <pre><code>class PostAdmin(admin.ModelAdmin): list_display = [..., 'author',...] </code></pre> <p>Now in list mode, the author field will just use the <code>__unicode__</code> method of the <code>Author</code> class to display the author. On the top of that I would like a <em>link</em> pointing to the url of the corresponding author in the admin site. Is that possible?</p> <p><strong>Manual method</strong>:</p> <p>For the sake of completeness, I add the manual method. It would be to add a method <code>author_link</code> in the <code>PostAdmin</code> class:</p> <pre><code>def author_link(self, item): return '&lt;a href="../some/path/%d"&gt;%s&lt;/a&gt;' % (item.id, unicode(item)) author_link.allow_tags = True </code></pre> <p>That will work for that particular field but that is <strong>not</strong> what I want. I want a general method to achieve the same effect. (One of the problems is how to figure out automatically the path to an object in the django admin site.)</p>
2,470,606
3
0
null
2010-03-18 13:55:21.007 UTC
15
2021-04-21 08:26:49.937 UTC
null
null
null
null
262,667
null
1
38
django|django-admin|foreign-keys
25,274
<p>I don't think there is a mechanism to do what you want automatically out of the box.</p> <p>But as far as determining the path to an admin edit page based on the id of an object, all you need are two pieces of information:</p> <p>a) <code>self.model._meta.app_label</code></p> <p>b) <code>self.model._meta.module_name</code></p> <p>Then, for instance, to go to the edit page for that model you would do:</p> <pre><code>'../%s_%s_change/%d' % (self.model._meta.app_label, self.model._meta.module_name, item.id) </code></pre> <p>Take a look at <code>django.contrib.admin.options.ModelAdmin.get_urls</code> to see how they do it.</p> <p>I suppose you could have a callable that takes a model name and an id, creates a model of the specified type just to get the label and name (no need to hit the database) and generates the URL a above.</p> <p>But are you sure you can't get by using inlines? It would make for a better user interface to have all the related components in one page...</p> <p><strong>Edit:</strong> </p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="noreferrer">Inlines</a> (linked to docs) allow an admin interface to display a parent-child relationship in one page instead of breaking it into two. </p> <p>In the Post/Author example you provided, using inlines would mean that the page for editing Posts would also display an inline form for adding/editing/removing Authors. Much more natural to the end user.</p> <p>What you can do in your admin list view is create a callable in the Post model that will render a comma separated list of Authors. So you will have your Post list view showing the proper Authors, and you edit the Authors associated to a Post directly in the Post admin interface.</p>
48,931,958
Fill Proportionally in UIStackView
<p>I am using Storyboard to create a layout which consists of a UITableView and a UIView at the bottom. I am using UIStackView and playing them vertically. I want the UITableView to take 80% of the height and UIView (footer) to take 20%. I am using Fill Proportionally option of UIStackView and even through in Xcode preview it looks good but when the app is run it does not render correctly. Here is what I want it to look like: </p> <p><a href="https://i.stack.imgur.com/Cyhae.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cyhae.png" alt="enter image description here"></a></p> <p>And here is what it looks like when it is run: </p> <p><a href="https://i.stack.imgur.com/Bt5n0m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Bt5n0m.png" alt="enter image description here"></a></p> <p>Ideas? </p>
48,932,048
2
0
null
2018-02-22 16:04:02.867 UTC
12
2018-02-22 16:48:04.64 UTC
2018-02-22 16:35:32.073 UTC
null
5,175,709
null
810,815
null
1
22
ios|autolayout|uistackview
30,598
<p>You will need to set an explicit constraint to make tableView.height 4x bigger than your view size. They don't have intrinsic content size, so the <code>stackView</code> does not &quot;know&quot; how to properly fill the space.</p> <p>Also, set the distribution mode to <code>.fill</code>, because <code>.fillProportionally</code> uses intrinsic content size to determine proper distribution (excerpt from <a href="https://developer.apple.com/documentation/uikit/uistackviewdistribution" rel="noreferrer">docs</a>):</p> <blockquote> <p>case fillProportionally</p> <p>A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis.</p> </blockquote> <p>Using constraints we are setting the size explicitly, not using intrinsic content size - thus <code>.fillProportionally</code> does not work. I assume in that case the <code>stackView</code> uses values returned by <code>view.intrinsicContentSize</code> directly. However, constraints will not change <code>view.intrinsicContentSize</code>.</p> <p>If you would be doing it in code, you could do it with this:</p> <pre><code>tableView.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 4).isActive = true </code></pre> <p>In storyboards, control drag from <code>tableView</code> to the <code>myView</code> and select <code>Equal Heights</code>:</p> <p><a href="https://i.stack.imgur.com/SGx6q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SGx6q.png" alt="enter image description here" /></a></p> <p>Then select the created constraint and set the appropriate multiplier:</p> <p><a href="https://i.stack.imgur.com/Nn6rs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Nn6rs.png" alt="enter image description here" /></a></p>
1,203,087
Why is Graphics.MeasureString() returning a higher than expected number?
<p>I'm generating a receipt and am using the Graphics object to call the DrawString method to print out the required text.</p> <pre><code>graphics.DrawString(string, font, brush, widthOfPage / 2F, yPoint, stringformat); </code></pre> <p>This works fine for what I needed it to do. I always knew what I was printing out, so I could manually trim any strings so it would fit properly on 80mm receipt paper. Then I had to add an extra bit of functionality that would make this more flexible. The user could pass in strings that would be added to the bottom.</p> <p>Since I didn't know what they were going to put, I just created my own word wrap function that takes in a number of characters to wrap at and the string itself. In order to find out the number of characters, I was doing something like this:</p> <pre><code>float width = document.DefaultPageSettings.PrintableArea.Width; int max = (int)(width / graphics.MeasureString("a", font).Width); </code></pre> <p>Now the width is returning me 283, which in mm is about 72, which makes sense when you account for margins on 80mm paper.</p> <p>But the MeasureString method is returning 10.5 on a Courier New 8pt font. So instead of getting around what I expected to be 36 - 40, I'm getting 26, resulting in 2 lines of text being turned into 3-4.</p> <p>The units for PrintableArea.Width are 1/100th of an inch, and the PageUnit for the graphics object is Display (which says is typically 1/100th of an inch for printers). So why am I only getting 26 back?</p>
6,404,811
2
0
null
2009-07-29 21:14:25.973 UTC
33
2022-09-20 01:07:30.577 UTC
null
null
null
null
74,022
null
1
50
c#|measurement|printdocument
27,276
<p>From WindowsClient.net:</p> <blockquote> <p>GDI+ adds a small amount (1/6 em) to each end of every string displayed. This 1/6 em allows for glyphs with overhanging ends (such as italic '<em>f</em>'), and also gives GDI+ a small amount of leeway to help with grid fitting expansion.</p> <p>The default action of <code>DrawString</code> will work against you in displaying adjacent runs:</p> <ul> <li>Firstly the default StringFormat adds an extra 1/6 em at each end of each output;</li> <li>Secondly, when grid fitted widths are less than designed, the string is allowed to contract by up to an em.</li> </ul> <p>To avoid these problems:</p> <ul> <li>Always pass <code>MeasureString</code> and <code>DrawString</code> a StringFormat based on the typographic string format (<code>StringFormat.GenericTypographic</code>).<br /> Set the Graphics <code>TextRenderingHint</code> to <code>TextRenderingHintAntiAlias</code>. This rendering method uses anti-aliasing and sub-pixel glyph positioning to avoid the need for grid-fitting, and is thus inherently resolution independent.</li> </ul> </blockquote> <hr /> <p>There are two ways of drawing text in .NET:</p> <ul> <li>GDI+ (<code>graphics.MeasureString</code> and <code>graphics.DrawString</code>)</li> <li>GDI (<code>TextRenderer.MeasureText</code> and <code>TextRenderer.DrawText</code>)</li> </ul> <p>From Michael Kaplan's (rip) excellent blog <a href="http://archive.is/pFPia" rel="nofollow noreferrer">Sorting It All Out</a>, In .NET 1.1 everything used <strong>GDI+</strong> for text rendering. But there were some problems:</p> <blockquote> <ul> <li>There are some performance issues caused by the somewhat stateless nature of GDI+, where device contexts would be set and then the original restored after each call.</li> <li>The shaping engines for international text have been updated many times for Windows/Uniscribe and for Avalon (Windows Presentation Foundation), but have not been updated for GDI+, which causes international rendering support for new languages to not have the same level of quality.</li> </ul> </blockquote> <p>So they knew they wanted to change the .NET framework to stop using <strong>GDI+</strong>'s text rendering system, and use <strong>GDI</strong>. At first they hoped they could simply change:</p> <pre><code>graphics.DrawString </code></pre> <p>to call the old <code>DrawText</code> API instead of GDI+. But they couldn't make the text-wrapping and spacing match exactly as what GDI+ did. So they were forced to keep <code>graphics.DrawString</code> to call GDI+ (compatiblity reasons; people who were calling <code>graphics.DrawString</code> would suddenly find that their text didn't wrap the way it used to).</p> <p>A new static <code>TextRenderer</code> class was created to wrap GDI text rendering. It has two methods:</p> <pre><code>TextRenderer.MeasureText TextRenderer.DrawText </code></pre> <blockquote> <p><strong>Note:</strong> <code>TextRenderer</code> is a wrapper around GDI, while <code>graphics.DrawString</code> is still a wrapper around GDI+.</p> </blockquote> <hr /> <p>Then there was the issue of what to do with all the existing .NET controls, e.g.:</p> <ul> <li><code>Label</code></li> <li><code>Button</code></li> <li><code>TextBox</code></li> </ul> <p>They wanted to switch them over to use <code>TextRenderer</code> (i.e. GDI), but they had to be careful. There might be people who depended on their controls drawing like they did in .NET 1.1. And so was born &quot;<em>compatible text rendering</em>&quot;.</p> <p>By default controls in application behave like they did in .NET 1.1 (they are &quot;<em>compatible</em>&quot;).</p> <p>You <strong>turn off</strong> compatibility mode by calling:</p> <pre><code>Application.SetCompatibleTextRenderingDefault(false); </code></pre> <p>This makes your application better, faster, with better international support. To sum up:</p> <pre><code>SetCompatibleTextRenderingDefault(true) SetCompatibleTextRenderingDefault(false) ======================================= ======================================== default opt-in bad good the one we don't want to use the one we want to use uses GDI+ for text rendering uses GDI for text rendering graphics.MeasureString TextRenderer.MeasureText graphics.DrawString TextRenderer.DrawText Behaves same as 1.1 Behaves *similar* to 1.1 Looks better Localizes better Faster </code></pre> <hr /> <p>It's also useful to note the mapping between GDI+ <code>TextRenderingHint</code> and the corresponding <a href="http://msdn.microsoft.com/en-us/library/dd145037%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>LOGFONT</code> Quality</a> used for GDI font drawing:</p> <pre><code>TextRenderingHint mapped by TextRenderer to LOGFONT quality ======================== ========================================================= ClearTypeGridFit CLEARTYPE_QUALITY (5) (Windows XP: CLEARTYPE_NATURAL (6)) AntiAliasGridFit ANTIALIASED_QUALITY (4) AntiAlias ANTIALIASED_QUALITY (4) SingleBitPerPixelGridFit PROOF_QUALITY (2) SingleBitPerPixel DRAFT_QUALITY (1) else (e.g.SystemDefault) DEFAULT_QUALITY (0) </code></pre> <hr /> <h2>Samples</h2> <p>Here's some comparisons of GDI+ (graphics.DrawString) verses GDI (TextRenderer.DrawText) text rendering:</p> <p><strong>GDI+</strong>: <code>TextRenderingHintClearTypeGridFit</code>, <strong>GDI</strong>: <code>CLEARTYPE_QUALITY</code>:</p> <p><img src="https://i.stack.imgur.com/b5S0T.png" alt="enter image description here" /></p> <p><strong>GDI+</strong>: <code>TextRenderingHintAntiAlias</code>, <strong>GDI</strong>: <code>ANTIALIASED_QUALITY</code>:</p> <p><img src="https://i.stack.imgur.com/VdZMM.png" alt="enter image description here" /></p> <p><strong>GDI+</strong>: <code>TextRenderingHintAntiAliasGridFit</code>, <strong>GDI</strong>: <em>not supported, uses ANTIALIASED_QUALITY</em>:</p> <p><img src="https://i.stack.imgur.com/Y4nSW.png" alt="enter image description here" /></p> <p><strong>GDI+</strong>: <code>TextRenderingHintSingleBitPerPixelGridFit</code>, <strong>GDI</strong>: <code>PROOF_QUALITY</code>:</p> <p><img src="https://i.stack.imgur.com/ZB7hz.png" alt="enter image description here" /></p> <p><strong>GDI+</strong>: <code>TextRenderingHintSingleBitPerPixel</code>, <strong>GDI</strong>: <code>DRAFT_QUALITY</code>:</p> <p><img src="https://i.stack.imgur.com/VBoXk.png" alt="enter image description here" /></p> <p>i find it odd that <code>DRAFT_QUALITY</code> is identical to <code>PROOF_QUALITY</code>, which is identical to <code>CLEARTYPE_QUALITY</code>.</p> <p><strong>See also</strong></p> <ul> <li><a href="http://blogs.msdn.com/b/jfoscoding/archive/2005/10/13/480632.aspx" rel="nofollow noreferrer">UseCompatibleTextRendering - Compatible with whaaaaaat?</a></li> <li><a href="http://www.siao2.com/2005/06/27/432986.aspx" rel="nofollow noreferrer">Sorting it all out: A quick look at Whidbey's TextRenderer</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/dd145037%28v=vs.85%29.aspx" rel="nofollow noreferrer">MSDN: LOGFONT Structure</a></li> <li><a href="http://blogs.msdn.com/b/cjacks/archive/2006/05/19/gdi-vs-gdi-text-rendering-performance.aspx" rel="nofollow noreferrer">AppCompat Guy: GDI vs. GDI+ Text Rendering Performance</a></li> <li><a href="http://windowsclient.net/articles/gdiptext.aspx" rel="nofollow noreferrer">GDI+ Text, Resolution Independence, and Rendering Methods. Or - Why does my text look different in GDI+ and in GDI?</a></li> </ul>
2,485,635
Best current framework for unit testing EJB3 / JPA
<p>Starting a new project using EJB 3 / JPA, mainly stateless session beans and batch jobs. I've used JUnit in the past on standard Java webapps and it seemed to work pretty well. In EJB2 unit testing was a pain and required a running container such as JBoss to make the calls into. Now that we're going to be working in EJB3 / JPA I'd like to know what companies are using to write and run these tests. Are Junit and JMock still considered relevant or are there other newer frameworks that have come around that we should investigate?</p>
2,498,289
5
0
null
2010-03-21 02:26:39.397 UTC
14
2017-07-13 14:18:31.34 UTC
2010-03-24 17:36:22.273 UTC
null
70,604
null
277,160
null
1
21
java|unit-testing|jpa|jakarta-ee|ejb-3.0
28,861
<p>IMHO, yes they are still relevant. </p> <p>With EJB3, you can test you EJB either like regular POJO, or as managed bean using an embedded EJB container. </p> <p>Same for JPA, you can either embed a JPA implementation for your test and use an in-memory database, or you can mock the data layer completely.</p> <p>For my last EJB project I had written a bit of <a href="http://www.ewernli.com/web/guest/45" rel="nofollow noreferrer">glue code</a> to test the EJB because embedded EJB container were not mature enough, but now I would go for an embedded EJB container + JUnit.</p> <p>A few resources</p> <ul> <li>Blog post: <a href="http://www.adam-bien.com/roller/abien/entry/how_to_unit_test_ejb" rel="nofollow noreferrer">How to unit test EJB 3 in 0.8 seconds</a></li> <li>SO question: <a href="https://stackoverflow.com/questions/1733805/where-can-i-find-good-unit-testing-resources-for-ejb-and-j2ee">Good unit testing resource for EJB</a></li> </ul> <p>But there are many others easily findable</p>
2,363,040
How to "enable" HTML5 elements in IE 8 that were inserted by AJAX call?
<p><em>See the solution at the bottom of the question.</em></p> <p>IE 8 (and lower) does not work good with unknown elements (ie. HTML5 elements), one cannot style them , or access most of their props. Their are numerous work arounds for this for example: <a href="http://remysharp.com/2009/01/07/html5-enabling-script/" rel="nofollow noreferrer">http://remysharp.com/2009/01/07/html5-enabling-script/</a></p> <p>The problem is that this works great for static HTML that was available on page load, but when one creates HTML5 elements afterward (for example AJAX call containing them, or simply creating with JS), it will mark these newly added elements them as <code>HTMLUnknownElement</code> as supposed to <code>HTMLGenericElement</code> (in IE debugger).</p> <p>Does anybody know a work around for that, so that newly added elements will be recognized/enabled by IE 8?</p> <p>Here is a test page:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;TIME TEST&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;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;time&gt;some time&lt;/time&gt; &lt;hr&gt; &lt;script type="text/javascript"&gt; $("time").text("WORKS GREAT"); $("body").append("&lt;time&gt;NEW ELEMENT&lt;/time&gt;"); //simulates AJAX callback insertion $("time").text("UPDATE"); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In IE you will see the: UPDATE , and NEW ELEMENT. In any other modern browser you will see UPDATE, and UPDATE</p>
2,987,541
5
1
null
2010-03-02 12:30:07.98 UTC
7
2015-08-04 07:02:33.78 UTC
2015-08-04 07:02:33.78 UTC
null
82,004
null
82,004
null
1
28
javascript|jquery|ajax|internet-explorer|html
25,239
<p>for all html5 issues in IE7 i use <a href="http://html5shim.googlecode.com/" rel="noreferrer">html5shiv</a> and to accommodate the html5 elements coming back in ajax calls i use <a href="http://jdbartlett.github.com/innershiv/" rel="noreferrer">innershiv</a>.</p> <p>these two small plugins worked for me like a charm so far.</p> <p>-- Praveen Gunasekara</p>
3,078,387
Software patching at a billion miles
<p>Could someone here shed some light about how NASA goes about designing their spacecraft architecture to ensure that they are able to patch bugs in the deployed code? </p> <p>I have never built any “real time” type systems and this is a question that has come to mind after reading this article: </p> <p><a href="http://pluto.jhuapl.edu/overview/piPerspective.php?page=piPerspective_05_21_2010" rel="noreferrer">http://pluto.jhuapl.edu/overview/piPerspective.php?page=piPerspective_05_21_2010</a></p> <blockquote> <p>“One of the first major things we’ll do when we wake the spacecraft up next week will be uploading almost 20 minor bug fixes and other code enhancements to our fault protection (or “autopilot response”) software.”</p> </blockquote>
3,081,050
5
5
null
2010-06-20 06:09:40.733 UTC
17
2010-06-20 22:04:30.817 UTC
null
null
null
null
314,661
null
1
32
debugging|real-time
798
<p>I've been a developer on public telephone switching system software, which has pretty severe constraints on reliability, availability, survivability, and performance that approach what spacecraft systems need. I haven't worked on spacecraft (although I did work with many former shuttle programmers while at IBM), and I'm not familiar with VXworks, the operating system used on many spacecraft (including the Mars rovers, which have a phenomenal operating record).</p> <p>One of the core requirements for patchability is that a system should be designed from the ground up for patching. This includes module structure, so that new variables can be added, and methods replaced, without disrupting current operations. This often means that both old and new code for a changed method will be resident, and the patching operation simply updates the dispatching vector for the class or module.</p> <p>It is just about mandatory that the patching (and un-patching) software is integrated into the operating system.</p> <p>When I worked on telephone systems, we generally used patching and module-replacement functions in the system to load and test our new features as well as bug fixes, long before these changes were submitted for builds. Every developer needs to be comfortable with patching and replacing modules as part of their daly work. It builds a level of trust in these components, and makes sure that the patching and replacement code is exercised routinely.</p> <p>Testing is far more stringent on these systems than anything you've ever encountered on any other project. Complete and partial mock-ups of the deployment system will be readily available. There will likely be virtual machine environments as well, where the complete load can be run and tested. Test plans at all levels above unit test will be written and formally reviewed, just like formal code inspections (and those will be routine as well).</p> <p>Fault tolerant system design, including software design, is essential. I don't know about spacecraft systems specifically, but something like high-availability clusters is probably standard, with the added capability to run both synchronized and unsynchronized, and with the ability to transfer information between sides during a failover. An added benefit of this system structure is that you can split the system (if necessary), reload the inactive side with a new software load, and test it in the production system without being connected to the system network or bus. When you're satisfied that the new software is running properly, you can simply failover to it. </p> <p>As with patching, every developer should know how to do failovers, and should do them both during development and testing. In addition, developers should know every software update issue that can force a failover, and should know how to write patches and module replacement that avoid required failovers whenever possible.</p> <p>In general, these systems are designed from the ground up (hardware, operating system, compilers, and possibly programming language) for these environments. I would not consider Windows, Mac OSX, Linux, or any unix variant, to be sufficiently robust. Part of that is realtime requirements, but the whole issue of reliability and survivability is just as critical.</p> <p>UPDATE: As another point of interest, here's a <a href="http://marsandme.blogspot.com/" rel="noreferrer">blog by one of the Mars rover drivers</a>. This will give you a perspective on the daily life of maintaining an operating spacecraft. Neat stuff!</p>
3,216,340
How to represent an Enum in an Interface?
<p>How could I define an Interface which has a method that has <code>Enum</code> as a paramater when enums cannot be defined in an interface?</p> <p>For an <code>Enum</code> is not a reference type so an <code>Object</code> type cannot be used as the type for the incoming param, so how then?</p>
3,216,355
5
0
null
2010-07-09 20:30:12.32 UTC
1
2020-07-07 21:37:31.99 UTC
2020-07-07 21:37:31.99 UTC
null
285,795
null
93,468
null
1
36
c#|enums|interface
67,286
<pre><code>interface MyInterface { void MyMethod(Enum @enum); } </code></pre>
3,006,153
Ampersand vs plus for concatenating strings in VB.NET
<p>In VB.NET, is there any advantage to using <code>&amp;</code> to concatenate strings instead of <code>+</code>?</p> <p>For example</p> <pre><code>Dim x as String = "hello" + " there" </code></pre> <p>vs.</p> <pre><code>Dim x as String = "hello" &amp; " there" </code></pre> <p>Yes, I know for a lot of string concatenations I'd want to use <code>StringBuilder</code>, but this is more of a general question.</p>
3,006,235
5
1
null
2010-06-09 13:21:29.867 UTC
10
2020-01-14 13:53:12.2 UTC
2013-03-19 09:44:06.147 UTC
null
63,550
null
109,360
null
1
59
vb.net|string-concatenation
70,681
<p>I've heard good, strong arguments in favor of both operators. Which argument wins the day depends largely on your situation. The one thing I can say is that you should standardize on one or the other. Code that mixes the two is asking for confusion later.</p> <p>The two arguments I remember right now for favoring <code>&amp;</code>:</p> <ul> <li>If you're not using <code>Option Strict</code> and have two numeric strings, it's easy for the compiler to confuse your meaning of of the <code>+</code> operator with, you know, arithmetic addition</li> <li>If you're updating a lot of older vb6-era code it helps not to have to convert the concatenation operators ( and remember: we want consistency).</li> </ul> <p>And for <code>+</code>:</p> <ul> <li>If you have a mixed vb/C# shop, it's nice to only have one concatenation operator. It makes it easier to move code between languages and means just that much less of a context switch for programmers when moving back and forth between languages</li> <li><code>&amp;</code> is almost unique to VB, while <code>+</code> between strings is understood in many languages to mean concatenation, so you gain a little something in readability.</li> </ul>
3,143,498
Why check this != null?
<p>Occasionally I like to spend some time looking at the .NET code just to see how things are implemented behind the scenes. I stumbled upon this gem while looking at the <code>String.Equals</code> method via Reflector.</p> <p><strong>C#</strong></p> <pre><code>[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public override bool Equals(object obj) { string strB = obj as string; if ((strB == null) &amp;&amp; (this != null)) { return false; } return EqualsHelper(this, strB); } </code></pre> <p><strong>IL</strong></p> <pre><code>.method public hidebysig virtual instance bool Equals(object obj) cil managed { .custom instance void System.Runtime.ConstrainedExecution.ReliabilityContractAttribute::.ctor(valuetype System.Runtime.ConstrainedExecution.Consistency, valuetype System.Runtime.ConstrainedExecution.Cer) = { int32(3) int32(1) } .maxstack 2 .locals init ( [0] string str) L_0000: ldarg.1 L_0001: isinst string L_0006: stloc.0 L_0007: ldloc.0 L_0008: brtrue.s L_000f L_000a: ldarg.0 L_000b: brfalse.s L_000f L_000d: ldc.i4.0 L_000e: ret L_000f: ldarg.0 L_0010: ldloc.0 L_0011: call bool System.String::EqualsHelper(string, string) L_0016: ret } </code></pre> <p>What is the reasoning for checking <code>this</code> against <code>null</code>? I have to assume there is purpose otherwise this probably would have been caught and removed by now.</p>
3,143,558
6
5
null
2010-06-29 18:11:24.387 UTC
17
2014-06-13 03:31:08.953 UTC
2010-07-25 15:03:52.227 UTC
null
158,779
null
158,779
null
1
74
c#|.net|clr|reflector
8,362
<p>I assume you were looking at the .NET 3.5 implementation? I believe the .NET 4 implementation is slightly different.</p> <p>However, I have a sneaking suspicion that this is because it's possible to call even virtual instance methods non-virtually <em>on a null reference</em>. Possible in IL, that is. I'll see if I can produce some IL which would call <code>null.Equals(null)</code>.</p> <p>EDIT: Okay, here's some interesting code:</p> <pre><code>.method private hidebysig static void Main() cil managed { .entrypoint // Code size 17 (0x11) .maxstack 2 .locals init (string V_0) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldnull IL_0005: call instance bool [mscorlib]System.String::Equals(string) IL_000a: call void [mscorlib]System.Console::WriteLine(bool) IL_000f: nop IL_0010: ret } // end of method Test::Main </code></pre> <p>I got this by compiling the following C# code:</p> <pre><code>using System; class Test { static void Main() { string x = null; Console.WriteLine(x.Equals(null)); } } </code></pre> <p>... and then disassembling with <code>ildasm</code> and editing. Note this line:</p> <pre><code>IL_0005: call instance bool [mscorlib]System.String::Equals(string) </code></pre> <p>Originally, that was <code>callvirt</code> instead of <code>call</code>.</p> <p>So, what happens when we reassemble it? Well, with .NET 4.0 we get this:</p> <pre><code>Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Test.Main() </code></pre> <p>Hmm. What about with .NET 2.0?</p> <pre><code>Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at System.String.EqualsHelper(String strA, String strB) at Test.Main() </code></pre> <p>Now that's more interesting... we've clearly managed to get into <code>EqualsHelper</code>, which we wouldn't have normally expected.</p> <p>Enough of string... let's try to implement reference equality ourselves, and see whether we can get <code>null.Equals(null)</code> to return true:</p> <pre><code>using System; class Test { static void Main() { Test x = null; Console.WriteLine(x.Equals(null)); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object other) { return other == this; } } </code></pre> <p>Same procedure as before - disassemble, change <code>callvirt</code> to <code>call</code>, reassemble, and watch it print <code>true</code>...</p> <p>Note that although another answers references <a href="https://stackoverflow.com/questions/2679080/this-null-how-can-it-be-possible">this C++ question</a>, we're being even more devious here... because we're calling a <em>virtual</em> method non-virtually. Normally even the C++/CLI compiler will use <code>callvirt</code> for a virtual method. In other words, I think in this particular case, the only way for <code>this</code> to be null is to write the IL by hand.</p> <hr> <p>EDIT: I've just noticed something... I wasn't actually calling the right method in <em>either</em> of our little sample programs. Here's the call in the first case:</p> <pre><code>IL_0005: call instance bool [mscorlib]System.String::Equals(string) </code></pre> <p>here's the call in the second:</p> <pre><code>IL_0005: call instance bool [mscorlib]System.Object::Equals(object) </code></pre> <p>In the first case, I <em>meant</em> to call <code>System.String::Equals(object)</code>, and in the second, I <em>meant</em> to call <code>Test::Equals(object)</code>. From this we can see three things:</p> <ul> <li>You need to be careful with overloading.</li> <li>The C# compiler emits calls to the <em>declarer</em> of the virtual method - not the most specific <em>override</em> of the virtual method. IIRC, VB works the opposite way</li> <li><code>object.Equals(object)</code> is happy to compare a null "this" reference</li> </ul> <p>If you add a bit of console output to the C# override, you can see the difference - it won't be called unless you change the IL to call it explicitly, like this:</p> <pre><code>IL_0005: call instance bool Test::Equals(object) </code></pre> <p>So, there we are. Fun and abuse of instance methods on null references.</p> <p>If you've made it this far, you might also like to look at my blog post about <a href="http://msmvps.com/blogs/jon_skeet/archive/2008/12/10/value-types-and-parameterless-constructors.aspx" rel="nofollow noreferrer">how value types <em>can</em> declare parameterless constructors</a>... in IL.</p>
2,381,789
use CSS sprites for list (<li>) background image
<p>Is it possible to use CSS sprites for the list background image? Normally, I render my sprites with CSS like this:</p> <pre><code>.sprite { background: url(sprite.png) no-repeat top left;} .sprite-checkmark { background-position: 0 -24px; width: 24px; height: 23px; } .sprite-comment { background-position: 0 -48px; width: 14px; height: 14px; } &lt;div class="sprite sprite-checkmark"&gt;&lt;/div&gt; </code></pre> <p>Is it possible to use sprites for the bullets of &lt;li&gt; elements? There are CSS properties called list-style-image, and list-style-position, but I'm not sure how to make it work without the existence of properties like list-style-image-width and list-style-image-height as well.</p> <p>Thanks.</p>
7,017,227
7
0
null
2010-03-04 18:37:27.48 UTC
4
2015-02-22 04:25:01.583 UTC
null
null
null
null
2,749
null
1
35
html|css|css-sprites
56,712
<p>You can also use</p> <pre><code>li:before { background:url(..) no-repeat -##px -##px; width:##px; height:##px; display:block; position:absolute; content: " "; top:##px; left:##px; } </code></pre> <p>and thus get an additional element added to the DOM and give that the background image.</p>
2,680,389
How to remove all files ending with ~ made by Emacs
<p>Whenever I edit files on emacs, it seems a temporary file is created with the same name with ~ appended to it. Does anyone know an quick/easy way to delete all of these files in the working directory?</p>
2,680,682
7
1
null
2010-04-21 04:48:39.737 UTC
18
2014-09-05 19:05:02.633 UTC
2010-04-21 13:53:09.57 UTC
null
4,958
null
235,771
null
1
45
emacs|backup
37,294
<p>While all the others answers here correctly explain how to remove the files, you ought to understand what's going on. Those files ending in ~ are <em>backup</em> files, automatically created by Emacs. They can be useful sometimes. If you're annoyed by the files and want to delete them every time, then you either </p> <p>(1). prevent the creation of backup files:</p> <pre><code>(setq make-backup-files nil) </code></pre> <p>or </p> <p>(2). Have it save the backup files in some other directory, where they won't bother you unless you go looking for them. I have the following in my .emacs:</p> <pre><code>(setq backup-directory-alist '(("." . "~/.emacs.d/backup")) backup-by-copying t ; Don't delink hardlinks version-control t ; Use version numbers on backups delete-old-versions t ; Automatically delete excess backups kept-new-versions 20 ; how many of the newest versions to keep kept-old-versions 5 ; and how many of the old ) </code></pre> <p>(Only the first line is crucial.) To see documentation about <code>backup-directory-alist</code>, type <kbd>C-h v backup-directory-alist</kbd>.</p>
2,630,370
C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly
<p>Code below is working well as long as I have class <code>ClassSameAssembly</code> in same assembly as class <code>Program</code>. But when I move class <code>ClassSameAssembly</code> to a separate assembly, a <code>RuntimeBinderException</code> (see below) is thrown. Is it possible to resolve it? </p> <pre><code>using System; namespace ConsoleApplication2 { public static class ClassSameAssembly { public static dynamic GetValues() { return new { Name = "Michael", Age = 20 }; } } internal class Program { private static void Main(string[] args) { var d = ClassSameAssembly.GetValues(); Console.WriteLine("{0} is {1} years old", d.Name, d.Age); } } } </code></pre> <p><code>Microsoft.CSharp.RuntimeBinder.RuntimeBinderException</code>: <strong>'object' does not contain a definition for 'Name'</strong></p> <pre><code>at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at ConsoleApplication2.Program.Main(String[] args) in C:\temp\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 23 </code></pre>
2,630,439
8
3
null
2010-04-13 14:34:00.523 UTC
12
2018-07-19 10:28:16.18 UTC
2016-01-22 08:46:51.583 UTC
null
1,811,525
null
234,591
null
1
90
dynamic|c#-4.0|anonymous-types
40,078
<p>I believe the problem is that the anonymous type is generated as <code>internal</code>, so the binder doesn't really "know" about it as such.</p> <p>Try using ExpandoObject instead:</p> <pre><code>public static dynamic GetValues() { dynamic expando = new ExpandoObject(); expando.Name = "Michael"; expando.Age = 20; return expando; } </code></pre> <p>I know that's somewhat ugly, but it's the best I can think of at the moment... I don't think you can even use an object initializer with it, because while it's strongly typed as <code>ExpandoObject</code> the compiler won't know what to do with "Name" and "Age". You <em>may</em> be able to do this:</p> <pre><code> dynamic expando = new ExpandoObject() { { "Name", "Michael" }, { "Age", 20 } }; return expando; </code></pre> <p>but that's not much better...</p> <p>You could <em>potentially</em> write an extension method to convert an anonymous type to an expando with the same contents via reflection. Then you could write:</p> <pre><code>return new { Name = "Michael", Age = 20 }.ToExpando(); </code></pre> <p>That's pretty horrible though :(</p>
2,347,770
How do you clear the console screen in C?
<p>Is there a "proper" way to clear the console window in C, besides using <code>system("cls")</code>?</p>
2,347,811
14
2
null
2010-02-27 15:10:41.6 UTC
26
2022-07-13 02:34:40.017 UTC
2017-10-21 20:21:14.497 UTC
null
7,659,995
null
183,441
null
1
69
c|windows|console|console-application
457,490
<p>Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at <a href="http://wikipedia.org/wiki/Conio.h" rel="noreferrer">conio.h</a> or <a href="http://wikipedia.org/wiki/Curses_(programming_library)" rel="noreferrer">curses</a>, according to your needs?</p> <p>Portability is an issue, no matter what library is used.</p>
25,027,813
AngularJS/javascript converting a date String to date object
<p>Im stuck on a problem and would appreciate any help. I have read through lot of the discussions already but they dont seem to work for me. </p> <pre><code>//I have a date as a string which I want to get to a date format of dd/MM/yyyy var collectionDate = '2002-04-26T09:00:00'; //used angularjs date filter to format the date to dd/MM/yyyy collectionDate = $filter('date')(collectionDate, 'dd/MM/yyyy'); //This outputs 26/04/2002 as a string </code></pre> <p>How do I convert it to a date object? The reason I want to do this is because I want to use it in a google charts directive where one of the columns has to be a date. I do not want to have the column type as string: </p> <p>eg: </p> <pre><code>var data = new google.visualization.DataTable(); data.addColumn('date', 'Dates'); data.addColumn('number', 'Upper Normal'); data.addColumn('number', 'Result'); data.addColumn('number', 'Lower Normal'); data.addRows(scope.rows);................. </code></pre>
25,254,797
4
0
null
2014-07-30 02:24:10.79 UTC
4
2017-03-08 19:30:15.77 UTC
2015-07-29 12:21:46.75 UTC
null
3,576,214
null
2,789,797
null
1
26
javascript|angularjs|date
143,328
<p>This is what I did on the controller</p> <pre><code>var collectionDate = '2002-04-26T09:00:00'; var date = new Date(collectionDate); //then pushed all my data into an array $scope.rows which I then used in the directive </code></pre> <p>I ended up formatting the date to my desired pattern on the directive as follows. </p> <pre><code>var data = new google.visualization.DataTable(); data.addColumn('date', 'Dates'); data.addColumn('number', 'Upper Normal'); data.addColumn('number', 'Result'); data.addColumn('number', 'Lower Normal'); data.addRows(scope.rows); var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"}); formatDate.format(data, 0); //set options for the line chart var options = {'hAxis': format: 'dd/MM/yyyy'} //Instantiate and draw the chart passing in options var chart = new google.visualization.LineChart($elm[0]); chart.draw(data, options); </code></pre> <p>This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.</p>
10,814,828
REDIS - Get value of multiple keys
<p>How do I get the value of multiple keys from redis using a sorted set?</p> <pre><code>zadd Users 0 David zadd Users 5 John zadd Users 15 Linda zrevrange Users 0 -1 withscores </code></pre> <p>This will have two users in it.</p> <p>How can I retrieve the users with key 'David' and 'Linda' in one query?</p>
10,817,335
4
0
null
2012-05-30 10:52:01 UTC
5
2014-11-14 13:38:20.353 UTC
2012-05-30 13:11:33.99 UTC
null
1,114,486
null
763,285
null
1
14
redis
43,331
<p>There are multiple ways to do it without introducing a new command in Redis.</p> <p>For instance, you can fill a temporary set with the names you are interested in, then calculate the intersection between the temporary set and the zset:</p> <pre><code>multi sadd tmp David Linda ... and more ... zinterstore res 2 tmp Users weights 0 1 zrange res 0 -1 withscores del tmp res exec </code></pre> <p>With pipelining, this will only generate one roundtrip and you can fill an arbitrary number of input parameters in tmp.</p> <p>With Redis 2.6, you can also wrap these lines into a server-side Lua script to finally get a command accepting an input list and returning the result you want:</p> <pre><code>eval "redis.call( 'sadd', 'tmp', unpack(KEYS) ); redis.call( 'zinterstore', 'res', 2, 'tmp', 'Users', 'weights', 0, 1 ); local res = redis.call( 'zrange', 'res', 0, -1, 'withscores' ); redis.call( 'del', 'res', 'tmp' ) ; return res " 2 David Linda </code></pre> <p>You can safely assume no new command will be added to Redis if it can easily been implemented using scripting.</p>
10,590,978
How to publish nuget prerelease version package
<p>I understand how to publish a nuget package using nuget command line </p> <p><a href="http://docs.nuget.org/docs/reference/command-line-reference" rel="noreferrer">nuget command line</a> </p> <p>But I Have searched around I don't find docs about how to publish a nuget prerelease package </p> <p><img src="https://i.stack.imgur.com/YFlp5.jpg" alt="enter image description here"></p>
10,605,480
3
0
null
2012-05-14 21:00:53.813 UTC
8
2021-08-30 05:45:47.893 UTC
2013-05-06 23:21:50.463 UTC
null
96,864
null
96,864
null
1
81
package|nuget|pack
34,647
<p>You only need to specify a version string that uses SemVer format (e.g. 1.0-beta) instead of the usual format (e.g. 1.0) and NuGet will automatically treat it as a prerelease package.</p> <p>"As of NuGet 1.6, NuGet supports the creation of prerelease packages by specifying a prerelease string in the version number according to the Semantic Versioning (SemVer) specification." <a href="http://docs.nuget.org/ndocs/create-packages/prerelease-packages">See NuGetDocs - Prerelease Versions</a></p>
6,119,867
stocks splitting api google or yahoo
<p>I am looking for a way to get stock splitting information. Using the yahoo stock API I can get all types of info on any symbol but I don't think I can get the split ratio or even whether it split. Does anyone know of a way of getting this info?</p>
6,123,886
2
0
null
2011-05-25 05:21:02.69 UTC
11
2020-07-22 15:07:57.353 UTC
2014-06-10 19:37:06.92 UTC
null
881,229
null
503,513
null
1
7
yahoo-finance|google-finance
8,609
<p>This is how the <a href="http://www.quantmod.com/">quantmod</a> <a href="http://www.r-project.org">R</a> package does it. The split information is in the "Dividend Only" CSV:<br> <a href="http://ichart.finance.yahoo.com/x?s=IBM&amp;a=00&amp;b=2&amp;c=1962&amp;d=04&amp;e=25&amp;f=2011&amp;g=v&amp;y=0&amp;z=30000">http://ichart.finance.yahoo.com/x?s=IBM&amp;a=00&amp;b=2&amp;c=1962&amp;d=04&amp;e=25&amp;f=2011&amp;g=v&amp;y=0&amp;z=30000</a></p>
19,472,058
Angular JS and Directive Link and $timeout
<p>i have a problem with a very basic example with AngularJS and directives. I want to create a directive that show a webcam image with webrtc. My code show the stream perfectly but if i add a timeout ( for example to refresh a canvas ) the $timeout don't work this is the code:</p> <pre><code>wtffDirectives.directive('scannerGun',function($timeout){ return { restrict: 'E', template: '&lt;div&gt;' + '&lt;video ng-hide="videoStatus"&gt;&lt;/video&gt;' + '&lt;canvas id="canvas-source"&gt;&lt;/canvas&gt;' + '&lt;/div&gt;', replace: true, transclude: true, scope: false, link: function postLink($scope, element){ $scope.canvasStatus = true; $scope.videoStatus = false; width = element.width = 320; height = element.height = 0; /* this method draw the webcam image into a canvas */ var drawVideoCanvas = function(){ sourceContext.drawImage(vid,0,0, vid.width, vid.height); }; /* start the timeout that take a screenshot and draw the source canvas */ var update = function(){ var timeout = $timeout(function(){ console.log("pass"); //the console log show only one "pass" //drawVideoCanvas(); }, 2000); }; /* this work perfectly and reproduct into the video tag the webcam */ var onSuccess = function onSuccess(stream) { // Firefox supports a src object if (navigator.mozGetUserMedia) { vid.mozSrcObject = stream; } else { var vendorURL = window.URL || window.webkitURL; vid.src = vendorURL.createObjectURL(stream); } /* Start playing the video to show the stream from the webcam*/ vid.play(); update(); }; var onFailure = function onFailure(err) { if (console &amp;&amp; console.log) { console.log('The following error occured: ', err); } return; }; var vid = element.find('video')[0]; var sourceCanvas = element.find('canvas')[0]; var sourceContext = sourceCanvas.getContext('2d'); height = (vid.videoHeight / ((vid.videoWidth/width))) || 250; vid.setAttribute('width', width); vid.setAttribute('height', height); navigator.getMedia ( // ask only for video { video: true, audio: false }, onSuccess, onFailure ); } } }); </code></pre> <p>What is the problem? why the $timeout don't work in this conditions? and finally have a solution?</p> <p>thank's in advance</p>
19,472,376
3
0
null
2013-10-19 22:58:01.827 UTC
1
2017-02-08 14:34:40.423 UTC
2017-02-08 14:34:15.667 UTC
null
381,422
null
1,745,729
null
1
34
javascript|angularjs|angularjs-directive|timeout
51,087
<p>In your code your comment says 'show only one "pass"'. Timeout only executes one time, after the specified, delay. </p> <p>Perhaps you want setInterval (if you're pre angular 1.2)/ $interval (new to 1.2) which sets up a recurring call. Here's the setInterval version:</p> <pre><code>var timeout = setInterval(function(){ // do stuff $scope.$apply(); }, 2000); </code></pre> <p>I included $apply as a reminder that since this is an external jQuery call you need to tell angular to update the DOM (if you make any appropriate changes). ($timeout being an angular version automatically updates the DOM)</p>
32,344,017
Check If field exists in an sub-document of an Array
<p>I have a schema that is similar to this. </p> <pre class="lang-js prettyprint-override"><code>{id: Number, line_items: [{ id: String, quantity: Number, review_request_sent :Boolean }], total_price: String, name: String, order_number: Number } </code></pre> <p>What I want to find is all documents that don't have the field review_request_sent set for all items in the array.</p> <p>Example </p> <pre class="lang-js prettyprint-override"><code>{ id: 1, line_items: [ { id: 43, review_request_sent: true } ] }, { id: 2, line_items: [ { id: 1, review_request_sent: false }, { id: 39 }, ] }, { id: 3, line_items: [ { id: 23, review_request_sent: true }, { id: 85, review_request_sent: true }, { id: 12, review_request_sent: false } ] } </code></pre> <p>I would want help with a query/find that will return only the second document because it does not have the review_request_sent field in all its items in its array.</p>
32,344,116
4
0
null
2015-09-02 03:05:07.36 UTC
4
2020-10-13 07:18:45.69 UTC
2019-07-13 19:10:25.447 UTC
null
6,887,435
null
841,818
null
1
22
mongodb|mongoose|mongodb-query
43,759
<p>You basically want <a href="http://docs.mongodb.org/master/reference/operator/query/elemMatch/" rel="noreferrer"><strong><code>$elemMatch</code></strong></a> and the <a href="http://docs.mongodb.org/master/reference/operator/query/exists/" rel="noreferrer"><strong><code>$exists</code></strong></a> operator, as this will inspect each element to see if the condition "field not exists" is true for any element:</p> <pre class="lang-js prettyprint-override"><code>Model.find({ "line_items": { "$elemMatch": { "review_request_sent": { "$exists": false } } } },function(err,docs) { }); </code></pre> <p>That returns the second document only as the field is not present in one of the array sub-documents:</p> <pre class="lang-js prettyprint-override"><code>{ "id" : 2, "line_items" : [ { "id" : 1, "review_request_sent" : false }, { "id" : 39 } ] } </code></pre> <p>Note that this "differs" from this form:</p> <pre class="lang-js prettyprint-override"><code>Model.find({ "line_items.review_request_sent": { "$exists": false } },function(err,docs) { }) </code></pre> <p>Where that is asking does "all" of the array elements not contain this field, which is not true when a document has at least one element that has the field present. So the <code>$eleMatch</code> makes the condition be tested against "each" array element, and thus you get the correct response.</p> <hr> <p>If you wanted to update this data so that any array element found that did not contain this field was to then receive that field with a value of <code>false</code> ( presumably ), then you could even write a statement like this:</p> <pre class="lang-js prettyprint-override"><code> Model.aggregate( [ { "$match": { "line_items": { "$elemMatch": { "review_request_sent": { "$exists": false } } } }}, { "$project": { "line_items": { "$setDifference": [ {"$map": { "input": "$line_items", "as": "item", "in": { "$cond": [ { "$eq": [ { "$ifNull": [ "$$item.review_request_sent", null ] }, null ]}, "$$item.id", false ] } }}, [false] ] } }} ], function(err,docs) { if (err) throw err; async.each( docs, function(doc,callback) { async.each( doc.line_items, function(item,callback) { Model.update( { "_id": doc._id, "line_items.id": item }, { "$set": { "line_items.$.review_request_sent": false } }, callback ); }, callback ); }, function(err) { if (err) throw err; // done } ); } ); </code></pre> <p>Where the <code>.aggregate()</code> result not only matches the documents, but filters out content from the array where the field was not present, so as to just return the "id" of that particular sub-document.</p> <p>Then the looped <code>.update()</code> statements match each found array element in each document and adds the missing field with a value at the matched position.</p> <p>In that way you will have the field present in all sub-documents of every document where it was missing before.</p> <p>If you want to do such a thing, then it would also be wise to change your schema to make sure the field is always there as well:</p> <pre class="lang-js prettyprint-override"><code>{id: Number, line_items: [{ id: String, quantity: Number, review_request_sent: { type: Boolean, default: false } }], total_price: String, name: String, order_number: Number } </code></pre> <p>So the next time you add new items to the array in your code the element will always exist with it's default value if not otherwise explicitly set. And it is probably a goood idea to do so, as well as setting <code>required</code> on other fields you always want, such as "id".</p>
47,310,537
How to change zsh-autosuggestions color
<p>I am new at <code>zsh</code>.</p> <p>I've installed the plugin <code>zsh-autosuggestions</code> in <a href="https://github.com/robbyrussell/oh-my-zsh" rel="noreferrer">oh-my-zsh</a> using instruction mentioned <a href="https://github.com/zsh-users/zsh-autosuggestions" rel="noreferrer">here</a>. I am using Linux (Fedora 26).</p> <p>What my problem is I want to change the color of the text which comes in suggestion because the current one is not visible in <a href="http://ethanschoonover.com/solarized" rel="noreferrer">Solarized</a> dark color scheme.</p> <p><a href="https://i.stack.imgur.com/3sypL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3sypL.png" alt="enter image description here"></a></p> <p>It is visible in light theme </p> <p><a href="https://i.stack.imgur.com/smiwv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/smiwv.png" alt="enter image description here"></a></p> <p>And it works fine as I can pick the current suggestion by pressing <kbd>→</kbd> key.</p> <p>My question is that how can I change this suggested text color? I read <a href="https://github.com/zsh-users/zsh-autosuggestions#configuration" rel="noreferrer">here</a> that there is a constant <code>ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE</code>, but I am unable to locate that nither in <code>~/.zshrc</code> file nor in <code>$ZSH_CUSTOM/plugins/zsh-autosuggestions</code> directory.</p> <p>Can anyone tell me where can I find that and how can I change that? Also please suggest the color which will be suitable for both dark and light theme.</p> <p>Also please correct if I am going wrong.</p> <p>Regards.</p>
47,313,453
3
0
null
2017-11-15 14:54:50.543 UTC
16
2019-12-17 01:10:16.933 UTC
null
null
null
null
4,590,997
null
1
63
linux|zsh|oh-my-zsh|zshrc|zsh-completion
32,169
<p>You can edit your ~/.zshrc and change/add the variable: <code>ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=value'</code></p> <p>I have just tested the value from <code>fg=8</code> to <code>fg=5</code>. I think <code>fg</code> stands for Foreground.</p> <p><code>ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=5'</code></p> <p>**OBS: Add the above line at the end of your zshrc (after loading the plugin) ** </p> <p>I found another reference <a href="https://github.com/zsh-users/zsh-autosuggestions/issues/12" rel="noreferrer">here</a>.</p>
19,158,327
Android Linear Layout Weight Programmatically
<p>I want to add three linear layouts to an activity programatically each of same width. the problem is i am not able to set the weights of these layouts programmatically. I could do this within xml, but I want to do this in program. here is what I want: <img src="https://i.stack.imgur.com/2503h.jpg" alt="enter image description here"></p>
19,158,669
4
0
null
2013-10-03 11:44:16.277 UTC
4
2019-05-14 15:32:06.887 UTC
2019-05-14 15:32:06.887 UTC
null
648,265
null
1,841,812
null
1
28
android|android-linearlayout|android-layout-weight
38,017
<p>Here its the solution </p> <pre><code> LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100); lp.weight = 1; </code></pre> <p>See Full Solution </p> <pre><code>LinearLayout ll1, ll2, ll3; /* Find these LinearLayout by ID i.e ll1=(LinearLayout)findViewById(R.id.ll1); */ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100); lp.weight = 1; ll1.setLayoutParams(lp); ll2.setLayoutParams(lp); ll3.setLayoutParams(lp); </code></pre>
25,604,969
Setting a system variable within a maven profile
<p>Is it possible within maven to set a system property that is attainable from within a java class.</p> <p>I have seen that this is possible (<a href="https://stackoverflow.com/questions/9622121/pass-a-java-parameter-from-maven">here</a>) within the surefire plugin as follows;</p> <pre><code>String param = System.getProperty("my_parameter1"); &lt;configuration&gt; &lt;systemPropertyVariables&gt; &lt;my_property1&gt;${my_property1}&lt;/my_property1&gt; &lt;/systemPropertyVariables&gt; &lt;/configuration&gt; </code></pre> <p>However I would like to get a handle on the environment I am working in, I am already passing prod or dev as a maven profile argument - is it possible somehow to get a handle in the code on this either from setting a variable in the profile i call and then calling system.getProperty or some other way?</p> <p>Thanks</p> <p><strong>my pom file</strong></p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;core&lt;/groupId&gt; &lt;artifactId&gt;core&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;build&gt; &lt;sourceDirectory&gt;src&lt;/sourceDirectory&gt; &lt;testSourceDirectory&gt;test&lt;/testSourceDirectory&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;warSourceDirectory&gt;WebContent&lt;/warSourceDirectory&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.17&lt;/version&gt; &lt;configuration&gt; &lt;parallel&gt;methods&lt;/parallel&gt; &lt;threadCount&gt;10&lt;/threadCount&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;sonar-maven-plugin&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;src&lt;/directory&gt; &lt;excludes&gt; &lt;exclude&gt;**/*.java&lt;/exclude&gt; &lt;/excludes&gt; &lt;/resource&gt; &lt;resource&gt; &lt;directory&gt;resources&lt;/directory&gt; &lt;includes&gt; &lt;include&gt;**/*.png&lt;/include&gt; &lt;/includes&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;commons-dbcp&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-lang&lt;/groupId&gt; &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-codec&lt;/groupId&gt; &lt;artifactId&gt;commons-codec&lt;/artifactId&gt; &lt;version&gt;1.9&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-core&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.mariadb.jdbc&lt;/groupId&gt; &lt;artifactId&gt;mariadb-java-client&lt;/artifactId&gt; &lt;version&gt;1.1.7&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.11&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.mockito&lt;/groupId&gt; &lt;artifactId&gt;mockito-all&lt;/artifactId&gt; &lt;version&gt;1.9.5&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.facebook4j&lt;/groupId&gt; &lt;artifactId&gt;facebook4j-core&lt;/artifactId&gt; &lt;version&gt;[2.0,)&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.relayrides&lt;/groupId&gt; &lt;artifactId&gt;pushy&lt;/artifactId&gt; &lt;version&gt;0.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.16&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.mail&lt;/groupId&gt; &lt;artifactId&gt;javax.mail&lt;/artifactId&gt; &lt;version&gt;1.5.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;4.3.6.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.mail&lt;/groupId&gt; &lt;artifactId&gt;javax.mail-api&lt;/artifactId&gt; &lt;version&gt;1.5.2&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.activation&lt;/groupId&gt; &lt;artifactId&gt;activation&lt;/artifactId&gt; &lt;version&gt;1.1.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.threewks.thundr&lt;/groupId&gt; &lt;artifactId&gt;thundr-mailgun&lt;/artifactId&gt; &lt;version&gt;1.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.commons&lt;/groupId&gt; &lt;artifactId&gt;commons-io&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; &lt;artifactId&gt;gson&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;profiles&gt; &lt;profile&gt; &lt;id&gt;DEV&lt;/id&gt; &lt;properties&gt; &lt;swifte.url&gt;jdbc:mariadb://ip:3306/swifte?autoReconnect=true&lt;/swifte.url&gt; &lt;swifte.username&gt;user&lt;/swifte.username&gt; &lt;swifte.password&gt;pass&lt;/swifte.password&gt; &lt;/properties&gt; &lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;resources&lt;/directory&gt; &lt;includes&gt; &lt;include&gt;JavaPNSDev.p12&lt;/include&gt; &lt;/includes&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/build&gt; &lt;/profile&gt; &lt;profile&gt; &lt;id&gt;PROD&lt;/id&gt; &lt;properties&gt; &lt;swifte.url&gt;jdbc:mariadb://ip:3306/swifte?autoReconnect=true&lt;/swifte.url&gt; &lt;swifte.username&gt;username&lt;/swifte.username&gt; &lt;swifte.password&gt;pass&lt;/swifte.password&gt; &lt;/properties&gt; &lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;resources&lt;/directory&gt; &lt;includes&gt; &lt;include&gt;JavaPNSProd.p12&lt;/include&gt; &lt;/includes&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; &lt;/project&gt; </code></pre>
25,605,901
1
0
null
2014-09-01 11:34:52.563 UTC
6
2018-04-08 07:49:25.33 UTC
2017-05-23 12:25:13.057 UTC
null
-1
null
287,732
null
1
28
java|maven|environment-variables
50,904
<p>You should check out the <a href="http://www.mojohaus.org/exec-maven-plugin/" rel="noreferrer"><strong>exec-maven-plugin</strong></a>.</p> <p>With the following configuration (notice the <code>&lt;systemProperties&gt;</code>)...</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;java&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;mainClass&gt;com.example.Main&lt;/mainClass&gt; &lt;arguments&gt; &lt;argument&gt;argument1&lt;/argument&gt; &lt;/arguments&gt; &lt;systemProperties&gt; &lt;systemProperty&gt; &lt;key&gt;hello.world&lt;/key&gt; &lt;value&gt;Hello Stack Overflow!&lt;/value&gt; &lt;/systemProperty&gt; &lt;/systemProperties&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>...and the following class...</p> <pre><code>package com.example; public class Main { public static void main(String[] args) { String prop = System.getProperty("hello.world"); System.out.println(prop); } } </code></pre> <p>...and running a <code>package</code> (notice the phase in the configuration - you can change if you want, maybe to install), it prints out the value <code>Hello Stack Overflow!</code> from the key <code>hello.world</code>. So basically, the plugin executes your program when you build.</p> <p>See also the <a href="http://www.mojohaus.org/exec-maven-plugin/exec-mojo.html" rel="noreferrer"><code>exec:exec</code></a> goal. In the example, I used the <a href="http://www.mojohaus.org/exec-maven-plugin/java-mojo.html" rel="noreferrer"><code>exec:java</code></a> goal, but the two are different in how they function.</p> <blockquote> <p><a href="http://www.mojohaus.org/exec-maven-plugin/exec-mojo.html" rel="noreferrer"><code>exec:exec</code></a> executes programs and Java programs in a separate process.</p> <p><a href="http://www.mojohaus.org/exec-maven-plugin/java-mojo.html" rel="noreferrer"><code>exec:java</code></a> executes Java programs in the same VM.</p> </blockquote> <hr> <p><strong>UPDATE</strong></p> <blockquote> <p>Currently I am setting some values in properties based on the profile in my maven pom file. Is it possible to set this system property in the profile ? because really, i only have one pom file for dev and prod and its within the profile i would need to set it.</p> </blockquote> <p>Yes, just use the <code>${property.name}</code> in the <code>&lt;value&gt;</code> element of the system property element. For example:</p> <pre><code>&lt;profiles&gt; &lt;profile&gt; &lt;activation&gt; &lt;activeByDefault&gt;true&lt;/activeByDefault&gt; &lt;/activation&gt; &lt;id&gt;world&lt;/id&gt; &lt;properties&gt; &lt;hello.world&gt;Hello World!&lt;/hello.world&gt; &lt;/properties&gt; &lt;/profile&gt; &lt;profile&gt; &lt;activation&gt; &lt;activeByDefault&gt;false&lt;/activeByDefault&gt; &lt;/activation&gt; &lt;id&gt;stack&lt;/id&gt; &lt;properties&gt; &lt;hello.world&gt;Hello Stack Overflow&lt;/hello.world&gt; &lt;/properties&gt; &lt;/profile&gt; &lt;/profiles&gt; </code></pre> <p>And the plugin <code>&lt;systemProperties&gt;</code>:</p> <pre><code>&lt;systemProperties&gt; &lt;systemProperty&gt; &lt;key&gt;hello.world&lt;/key&gt; &lt;value&gt;${hello.world}&lt;/value&gt; &lt;/systemProperty&gt; &lt;/systemProperties&gt; </code></pre> <p>Just by changing the profile, to either <code>stack</code> or <code>world</code>, the message will print <code>Hello Stack Overflow</code> or <code>Hello World</code>, respectively.</p> <hr> <p><strong>UPDATE 2</strong></p> <p>Another plugin is the <a href="http://www.mojohaus.org/properties-maven-plugin/index.html" rel="noreferrer">properties-maven-plugin</a>. Nothing's been done on it in a while, but from a few tests, the necessary functionality is there.</p> <p>It has a <a href="http://www.mojohaus.org/properties-maven-plugin/set-system-properties-mojo.html" rel="noreferrer"><code>set-system-properties</code></a> goal along with some other <a href="http://www.mojohaus.org/properties-maven-plugin/plugin-info.html" rel="noreferrer">useful goals</a> to help ease properties management</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;properties-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0-alpha-2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;!-- any phase before your app deploys --&gt; &lt;phase&gt;prepare-package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;set-system-properties&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;properties&gt; &lt;property&gt; &lt;name&gt;hello.world.two&lt;/name&gt; &lt;value&gt;Hello World!&lt;/value&gt; &lt;/property&gt; &lt;/properties&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre>
8,471,551
What is STATE_SAVING_METHOD parameter in JSF 2.0
<p>I am not able to understand what is the function of this line in web.xml</p> <pre><code>&lt;context-param&gt; &lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt; &lt;param-value&gt;server&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>I have read that the NetBeans default is <em>client</em>. I've just faced an issue that I have many beans in my application, and the <code>&lt;param-value&gt;</code> was set to client, so I was getting </p> <blockquote> <p>java.io.NotSerializableException</p> </blockquote> <p>error although my beans were Serializable (i.e. they implemented the Serializable interface.). My beans were in <em>@ViewScope</em>. But when I changed it to server, things are going to work. Why? What is the difference when I use client and server. Can anyone explain me with the help of an example.</p> <p>Thanks</p>
8,474,609
2
0
null
2011-12-12 08:23:03.347 UTC
23
2015-03-01 16:14:08.8 UTC
2013-09-10 01:45:13.57 UTC
null
814,702
null
1,000,510
null
1
48
jsf-2
53,924
<blockquote> <pre><code>java.io.NotSerializableException </code></pre> </blockquote> <p>This kind of exception has usually a message in the root cause which shows the fully qualified class name of the class which doesn't implement <code>Serializable</code>. You should pay close attention to this message to learn about which class it is talking about and then let it implement <code>Serializable</code> accordingly.</p> <p>Often, making <em>only</em> your managed bean classes serializable is not always sufficient. You also need to ensure that <strong>each of its properties</strong> is also serializable. Most standard types like <code>String</code>, <code>Long</code>, etc implement all already <code>Serializable</code>. But (custom) complex types such as nested beans, entities or EJBs should each also be serializable. If something is not really implementable as <code>Serializable</code>, such as <code>InputStream</code>, then you should either redesign the model or make it <code>transient</code> (and keep in mind that it will be <code>null</code> after deserialization).</p> <hr> <blockquote> <p><em>What is the difference when i use client and server</em></p> </blockquote> <p>First some background information: <a href="https://stackoverflow.com/questions/5474316/why-does-jsf-need-to-save-the-state-of-ui-components-on-the-server-side">Why JSF saves the state of UI components on server?</a></p> <p>The main technical difference is that the <code>client</code> setting stores the entire view state as the value of the <code>javax.faces.ViewState</code> hidden input field in the generated HTML output and that the <code>server</code> setting stores it in the session along with an unique ID which is in turn referenced as the value of the <code>javax.faces.ViewState</code> hidden input field. </p> <p>So, setting to <code>client</code> increases the network bandwidth usage but decreases the server memory usage and setting to <code>server</code> does the other way round. Setting to <code>client</code> has however an additional functional advantage: it prevents <code>ViewExpiredException</code>s when the session has expired or when the client opens too many views. </p>
328,061
How to make a surface with a transparent background in pygame
<p>Can someone give me some example code that creates a surface with a transparent background in pygame?</p>
328,067
3
0
null
2008-11-29 21:58:40.3 UTC
9
2020-10-24 11:29:49.25 UTC
null
null
null
Paul Eden
3,045
null
1
45
python|transparency|pygame
42,562
<p>This should do it:</p> <pre><code>image = pygame.Surface([640,480], pygame.SRCALPHA, 32) image = image.convert_alpha() </code></pre> <p>Make sure that the color depth (32) stays explicitly set else this will not work.</p>
39,418,491
AnyString() as parameter for unit test
<p>I have to deal with a legacy application that has no tests. So before I begin refactoring I want to make sure everything works as it is.</p> <p>Now imagine the following situation:</p> <pre><code>public SomeObject doSomething(final OtherObject x, final String something) { if(x == null) throw new RuntimeException("x may not be null!"); ... } </code></pre> <p>Now I want to test that null check, so to be sure it works and I don't lose it once I refactor.</p> <p>So I did this</p> <pre><code>@Test(expected = RuntimeException.class) public void ifOtherObjectIsNullExpectRuntimeException() { myTestObject.doSomething(null, "testString"); } </code></pre> <p>Now, this works of course.</p> <p>But instead of "testString" I'd like to pass in a random String.</p> <p>So I tried with:</p> <pre><code>@Test(expected = RuntimeException.class) public void ifOtherObjectIsNullExpectRuntimeException() { myTestObject.doSomething(null, Mockito.anyString()); } </code></pre> <p>But this is not allowed., as I get <blockquote>org.mockito.exceptions.misusing.InvalidUseOfMatchersException: ... You cannot use argument matchers outside of verifications or stubbing</blockquote></p> <p>I do understand the meaning of this, but I wonder whether I can still manage to do what I want without parameterizing my test or the like. The only libraries I may use are Junit, AssertJ, Mockito and Powermock.</p> <p>Any ideas?</p>
39,418,972
4
0
null
2016-09-09 19:27:14.297 UTC
1
2019-08-07 17:00:50.027 UTC
null
null
null
user4063815
null
null
1
4
java|junit|mockito|powermock|assertj
56,546
<p>Well, like Mockito is trying to tell you via that exception, that's not really how you'd use <code>anyString</code>. Such methods are only to be used by mocks. </p> <p>So, why not try testing with an actual random string? My personal favorite in such a scenario: <a href="https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html#randomUUID()" rel="nofollow"><code>java.util.UUID.randomUUID()</code></a><code>.toString()</code>. This will virtually always generate a brand new string that has never been used for your test before.</p> <p>I'd also like to add that if you are writing tests for your <code>SomeObject</code> class that you should avoid mocking <code>SomeObject</code>'s behavior. From your example, you weren't exactly doing that, but it looked like you might be going down that route. Mock the dependencies of the implementation you're trying to test, not the implementation itself! This is very important; otherwise you aren't actually testing anything.</p>
22,181,264
Prevent cell numbers from incrementing in a formula in Excel
<p>I have a formula in Excel that needs to be run on several rows of a column based on the numbers in that row divided by one constant. When I copy that formula and apply it to every cell in the range, all of the cell numbers increment with the row, including the constant. So:</p> <pre><code>B1=127 C4='=IF(B4&lt;&gt;"",B4/B1,"")' </code></pre> <p>If I copy cell C4 and paste it down column C, the formula becomes</p> <pre><code>=IF(B5&lt;&gt;"",B5/B2,"") =IF(B6&lt;&gt;"",B6/B3,"") etc. </code></pre> <p>when what I need it to be is </p> <pre><code>=IF(B5&lt;&gt;"",B5/B1,"") =IF(B6&lt;&gt;"",B6/B1,"") etc. </code></pre> <p>Is there a simple way to prevent the expression from incrementing?</p>
22,181,304
4
0
null
2014-03-04 19:34:46.85 UTC
9
2021-11-16 17:26:39.453 UTC
2015-06-13 20:37:53.863 UTC
null
445,131
null
1,533,046
null
1
73
excel
176,257
<p>There is something called 'locked reference' in excel which you can use for this, and you use <code>$</code> symbols to lock a range. For your example, you would use:</p> <pre><code>=IF(B4&lt;&gt;"",B4/B$1,"") </code></pre> <p>This locks the <code>1</code> in <code>B1</code> so that when you copy it to rows below, <code>1</code> will remain the same.</p> <p>If you use <code>$B$1</code>, the range will not change when you copy it down a row or across a column.</p>
22,096,274
Object Serialization to JSON (using Gson). How to set field names in UpperCamelCase?
<p>I need to serialize a list of simple Java objects to JSON using Google Gson library.</p> <p>The object:</p> <pre><code>public class SimpleNode { private String imageIndex; private String text; public String getImageIndex() { return imageIndex; } public void setImageIndex(String imageIndex) { this.imageIndex = imageIndex; } public String getText() { return text; } public void setText(String text) { this.text = text; } } </code></pre> <p>I have written the following code for serialization:</p> <pre><code> List&lt;SimpleNode&gt; testNodes = repository.getElements(0); Gson gson = new Gson(); String jsonNodesAsString = gson.toJson(testNodes); </code></pre> <p>It works, but the field name of the JSON objects is lowerCamelCase. Like this:</p> <pre><code>[ { "imageIndex": "1", "text": "Text 1" }, { "imageIndex": "2", "text": "Text 2" } ] </code></pre> <p>How do I get a JSON with UpperCamelCase field name, like this:</p> <pre><code>[ { "ImageIndex": "1", "Text": "Text 1" }, { "ImageIndex": "2", "Text": "Text 2" } ] </code></pre> <p>I think that I can rename member variables in to UpperCamelCase, but may be there is another way?</p>
22,096,369
1
0
null
2014-02-28 13:17:27.617 UTC
8
2016-10-26 07:16:22.177 UTC
2016-10-26 07:16:22.177 UTC
null
1,075,341
null
1,735,047
null
1
34
java|json|serialization|gson
34,981
<p>Taken from the docs:</p> <p>Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e. camel cased names starting with lower case --- "sampleFieldNameInJava") to a Json field name (i.e. sample_field_name_in_java or SampleFieldNameInJava). See the FieldNamingPolicy class for information on the pre-defined naming policies.</p> <p>It also has an annotation based strategy to allows clients to define custom names on a per field basis. Note, that the annotation based strategy has field name validation which will raise "Runtime" exceptions if an invalid field name is provided as the annotation value.</p> <p>The following is an example of how to use both Gson naming policy features:</p> <pre><code>private class SomeObject { @SerializedName("custom_naming") private final String someField; private final String someOtherField; public SomeObject(String a, String b) { this.someField = a; this.someOtherField = b; } } SomeObject someObject = new SomeObject("first", "second"); Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); String jsonRepresentation = gson.toJson(someObject); System.out.println(jsonRepresentation); </code></pre> <p>======== OUTPUT ========</p> <pre><code>{"custom_naming":"first","SomeOtherField":"second"} </code></pre> <p>However, for what you want, you could just use this:</p> <pre><code>Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); </code></pre> <p>By using the UPPER_CAMEL_CASE option, you'll achieve your goal.</p>
22,177,590
Click by bounds / coordinates
<p>I know it is possible for Espresso to click by bounds the way <a href="https://stackoverflow.com/questions/20519905/uiautomator-click-on-a-imagebutton-with-no-text-or-content-desc">UiAutomator does</a>. (x and y coordinates) I have read through the documentation but I can't seem to find it. Any help is appreciated. Thanks</p> <p><strong>Edit</strong><br/> I found <a href="https://android-test-kit.googlecode.com/git/docs/javadocs/apidocs/com/google/android/apps/common/testing/ui/espresso/action/Tapper.html" rel="noreferrer">this link</a>, but no examples how to use it, My main concern with this is the <code>UiController</code> is or how to use it. </p>
22,798,043
3
0
null
2014-03-04 16:33:10.863 UTC
4
2018-01-25 15:39:10.273 UTC
2017-05-23 12:26:06.337 UTC
null
-1
null
1,642,079
null
1
30
android|android-testing|android-espresso
12,479
<p>Espresso has the <a href="http://code.google.com/p/android-test-kit/source/browse/espresso/lib/src/main/java/com/google/android/apps/common/testing/ui/espresso/action/GeneralClickAction.java"><code>GeneralClickAction</code></a>, this is the underlying implementation of ViewActions <code>click()</code>, <code>doubleClick()</code>, and <code>longClick()</code>.</p> <p>The <code>GeneralClickAction</code>'s constructor takes a <code>CoordinatesProvider</code> as second argument. So the basic idea is to create a static <code>ViewAction</code> getter which provides a custom <code>CoordinatesProvider</code>. Something like this:</p> <pre><code>public static ViewAction clickXY(final int x, final int y){ return new GeneralClickAction( Tap.SINGLE, new CoordinatesProvider() { @Override public float[] calculateCoordinates(View view) { final int[] screenPos = new int[2]; view.getLocationOnScreen(screenPos); final float screenX = screenPos[0] + x; final float screenY = screenPos[1] + y; float[] coordinates = {screenX, screenY}; return coordinates; } }, Press.FINGER); } </code></pre> <p>A general advice with Espresso: instead of looking for documentation (there's virtually none), look at the source code. Espresso is open source and the source code itself is of really good quality.</p>
36,627,613
SQL query to check if a name begins and ends with a vowel
<p>I want to query the list of <code>CITY</code> names from the table <code>STATION(id, city, longitude, latitude)</code> which have vowels as both their first and last characters. The result cannot contain duplicates.</p> <p>For this is I wrote a query like <code>WHERE NAME LIKE 'a%'</code> that had 25 conditions, each vowel for every other vowel, which is quite unwieldy. Is there a better way to do it?</p>
36,627,696
33
2
null
2016-04-14 15:29:19.14 UTC
28
2022-08-16 19:23:55.63 UTC
2017-04-10 20:54:01.887 UTC
null
7,802,200
null
5,735,244
null
1
76
mysql|sql|select
303,700
<p>You could use a <a href="http://dev.mysql.com/doc/refman/5.7/en/regexp.html#operator_regexp" rel="noreferrer">regular expression</a>:</p> <pre><code>SELECT DISTINCT city FROM station WHERE city RLIKE '^[aeiouAEIOU].*[aeiouAEIOU]$' </code></pre>
35,268,857
Bootstrap datepicker in modal not working
<p>I've tried to google and search SO for a similar question, but haven't found anything as of yet. I have an issue where I create and open a modal from jquery and try to access a date picker, however it doesn't activate the datepickers JS.</p> <pre><code>$("[id=add]").click(function () { $("#myModal .modal-header h4").html("Request for Change"); $("#myModal .modal-body").html('&lt;form class="form-horizontal" role="form"&gt;&lt;br /&gt;&lt;br /&gt;&lt;label class="col-sm-2 control-label"&gt;Date Required&lt;/label&gt;&lt;div class="col-sm-3"&gt;&lt;div class="input-group date col-sm-8"&gt;&lt;input type="text" class="form-control" id="DateRequired"&gt;&lt;span class="input-group-addon"&gt;&lt;i class="glyphicon glyphicon-th"&gt;&lt;/i&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;'); $("#myModal").modal("show"); }); </code></pre> <p>(Apologies about the long line length, however I have removed as much as I can - just showing the code which relates to the problem now.)</p> <p>I have these scripts referenced at the top:</p> <pre><code>&lt;script src="http://code.jquery.com/jquery-1.11.0.min.js"&gt;&lt;/script&gt; &lt;script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery.tablesorter.min.js"&gt;&lt;/script&gt; </code></pre> <p>And in the same <code>&lt;script&gt; &lt;/script&gt;</code> tag as the jquery function above, at the very top I have:</p> <pre><code>$('.input-group.date').datepicker({ format: "dd/mm/yyyy", startDate: "01-01-2015", endDate: "01-01-2020", todayBtn: "linked", autoclose: true, todayHighlight: true }); </code></pre> <p>I have this code used in an similar way (except no jquery modal - simply on a cshtml page) that works correctly. I don't know why this way won't work. I've used developer tools to try to trace an issue, but there are no errors - the scripts load correctly however when clicking the Date Required it doesn't fire to the jquery for datepicker.</p> <p>Am I using the Jquery html wrong to create the modal? </p> <p>Cheers</p>
35,269,000
10
2
null
2016-02-08 11:44:26.83 UTC
1
2020-01-14 22:19:27.76 UTC
2016-02-16 13:41:01.52 UTC
null
1,016,716
null
1,267,690
null
1
19
javascript|jquery|html|datepicker
62,220
<p><strong>The datepicker is hiding behind the modal.</strong></p> <p>Set datepicker's <code>z-index</code> above the modal's which is <code>1050</code>.</p> <p>Additionally wrap your datepicker code in bootstrap's modal shown event.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#myModal').on('shown.bs.modal', function() { $('.input-group.date').datepicker({ format: "dd/mm/yyyy", startDate: "01-01-2015", endDate: "01-01-2020", todayBtn: "linked", autoclose: true, todayHighlight: true, container: '#myModal modal-body' }); }); $("[id=add]").click(function() { $("#myModal .modal-header h4").html("Request for Change"); $("#myModal .modal-body").html('&lt;form class="form-horizontal" role="form"&gt;&lt;br /&gt;&lt;br /&gt;&lt;label class="col-sm-2 control-label"&gt;Date Required&lt;/label&gt;&lt;div class="col-sm-3"&gt;&lt;div class="input-group date col-sm-8"&gt;&lt;input type="text" class="form-control" id="DateRequired"&gt;&lt;span class="input-group-addon"&gt;&lt;i class="glyphicon glyphicon-th"&gt;&lt;/i&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/form&gt;'); $("#myModal").modal("show"); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;script src="//code.jquery.com/jquery-1.11.0.min.js"&gt;&lt;/script&gt; &lt;script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"&gt;&lt;/script&gt; &lt;style&gt; .datepicker { z-index: 1600 !important; /* has to be larger than 1050 */ } &lt;/style&gt; &lt;div class="well"&gt; &lt;button type="button" id="add"&gt;Add&lt;/button&gt; &lt;/div&gt; &lt;div id="myModal" class="modal"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h4&gt;&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Note: I added bootstrap v3.3.6 CSS and removed the local reference to the tablesorter script for the demo.</p>
28,572,700
I am trying to set maxFileSize but it is not honored
<p>I am developing an application utilizing JHipster. I have added the following to my application-dev.yml file:</p> <pre><code>spring: profiles: active: dev multipart: maxFileSize: -1 </code></pre> <p>But I am still getting an error when I try to try to upload a file > 1MB:</p> <pre><code>Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (20663006) exceeds the configured maximum (10485760) </code></pre> <p>What am I missing? It seems this should be pretty straight forward.</p> <p><strong>Update 1</strong></p> <p>I un-nested it from <code>spring</code> config as suggested by Andy, but still got the error. Updated yml file:</p> <pre><code>server: port: 8080 multipart: maxFileSize: -1 spring: profiles: active: dev datasource: ... </code></pre> <p><strong>Update 2</strong></p> <p>Ran into this issue again on newer version of Sprint Boot and had to change to this:</p> <pre><code>spring: http: multipart: max-file-size: 30MB max-request-size: 30MB </code></pre>
28,572,901
7
1
null
2015-02-17 22:51:24.213 UTC
9
2020-04-17 06:51:13.663 UTC
2016-12-16 17:28:27.893 UTC
null
4,410,762
null
4,410,762
null
1
53
spring-boot|jhipster
53,897
<p>In addition to configuring max file size, you may also need to configure max request size if you have a single file that's greater than 10MB or you want to upload multiple files in the same request with sizes that total more than 10MB.</p> <p>The exact properties that need to be used depend on the version of Spring Boot that you are using as they <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes#multipart-support" rel="noreferrer">changed in 1.4</a>:</p> <h3>Spring Boot 1.3.x and earlier</h3> <ul> <li><code>multipart.maxFileSize</code></li> <li><code>multipart.maxRequestSize</code></li> </ul> <h3>Spring Boot 1.4.x and 1.5.x</h3> <ul> <li><code>spring.http.multipart.maxFileSize</code></li> <li><code>spring.http.multipart.maxRequestSize</code></li> </ul> <h3>Spring Boot 2.x</h3> <ul> <li><code>spring.servlet.multipart.maxFileSize</code></li> <li><code>spring.servlet.multipart.maxRequestSize</code></li> </ul>
20,688,851
java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
<p>I use maven to manage my web project dependency. I add apache poi dependency into my pom file. it does not show error when complied. but when it runs, it will throw RuntimeException at my MainApplication() class. while it gives that java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook</p> <p>I have a MainApplication class. </p> <pre><code>public class MainApplication extends Application { private Set&lt;Class&lt;?&gt;&gt; classes = new HashSet&lt;Class&lt;?&gt;&gt;(); HashSet&lt;Object&gt; singletons = new HashSet&lt;Object&gt;(); public MainApplication() { try { ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("applicationContext.xml"); singletons.add(springContext.getBean("transformService", DataTransformService.class)); } public Set&lt;Class&lt;?&gt;&gt; getClasses() { return classes; } protected ApplicationContext springContext; public Set&lt;Object&gt; getSingletons() { return singletons; } </code></pre> <p>}</p> <p>Below is what i add</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi&lt;/artifactId&gt; &lt;version&gt;3.8-beta3&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.mail&lt;/groupId&gt; &lt;artifactId&gt;mail&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;version&gt;1.1.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-codec&lt;/groupId&gt; &lt;artifactId&gt;commons-codec&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.14&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/reportv2]] StandardWrapper.Throwable: java.lang.RuntimeException: Failed to construct public com.osg.application.MainApplication() at org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:144) [:] at org.jboss.resteasy.spi.ResteasyDeployment.createApplication(ResteasyDeployment.java:243) [:] at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:191) [:] at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:67) [:] at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:36) [:] at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1208) [:6.0.0.Final] at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:955) [:6.0.0.Final] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:188) [:6.0.0.Final] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) [:6.0.0.Final] at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181) [:6.0.0.Final] at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285) [:1.1.0.Final] at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261) [:1.1.0.Final] at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88) [:6.0.0.Final] at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100) [:6.0.0.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) [:6.0.0.Final] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [:6.0.0.Final] at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) [:6.0.0.Final] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [:6.0.0.Final] at org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53) [:6.0.0.Final] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [:6.0.0.Final] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [:6.0.0.Final] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654) [:6.0.0.Final] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951) [:6.0.0.Final] at java.lang.Thread.run(Thread.java:695) [:1.6.0_65] Caused by: java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook at java.lang.Class.getDeclaredConstructors0(Native Method) [:1.6.0_65] at java.lang.Class.privateGetDeclaredConstructors(Class.java:2446) [:1.6.0_65] at java.lang.Class.getDeclaredConstructors(Class.java:1872) [:1.6.0_65] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:227) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:930) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:903) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) [:3.0.5.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) [:3.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) [:3.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) [:3.0.5.RELEASE] at org.springframework.context.support.ClassPathXmlApplicationContext.&lt;init&gt;(ClassPathXmlApplicationContext.java:139) [:3.0.5.RELEASE] at org.springframework.context.support.ClassPathXmlApplicationContext.&lt;init&gt;(ClassPathXmlApplicationContext.java:83) [:3.0.5.RELEASE] at com.osg.application.MainApplication.&lt;init&gt;(MainApplication.java:19) [:] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [:1.6.0_65] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) [:1.6.0_65] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) [:1.6.0_65] at java.lang.reflect.Constructor.newInstance(Constructor.java:513) [:1.6.0_65] at org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:132) [:] ... 23 more </code></pre>
20,693,788
1
0
null
2013-12-19 18:17:23.43 UTC
1
2014-02-20 19:13:50.24 UTC
2014-02-20 19:13:50.24 UTC
null
1,165,907
null
3,120,272
null
1
4
excel|apache-poi|runtimeexception
42,419
<p><a href="http://poi.apache.org/overview.html#components" rel="noreferrer">Apache POI provides a components page</a> which details all of the different parts of the project, what jars you need, and what Maven artifacts you need. If you look there you'll see the following:</p> <pre><code>|Component | Application type | Maven artifactId | Notes |Common SS | Excel XLS and XLSX | poi-ooxml | WorkbookFactory and friends all require poi-ooxml, not just core poi | </code></pre> <p>As that clearly states, if you want to use all of the common <code>org.apache.poi.ss</code> classes, you need to depend on <code>poi-ooxml</code> and not just on <code>poi</code></p> <p>Secondly, compile time != run time. Just because a jar was sucked down by maven and made available to compile with, doesn't mean it'll be there when your code runs. You also need to ensure you package your dependencies with your code, or otherwise ensure they're on the classpath at runtime. </p> <p>You seem (from the stacktrace) to be writing a web application, so you'll need to ensure that all your dependencies get put into the war in <code>/WEB-INF/lib/</code> so they're there at runtime.</p> <p>Finally, POI 3.8 beta 3 is a very odd version to use. You should either go with the latest stable (right now 3.9), or the latest beta (right not 3.10 beta 2). See the <a href="http://poi.apache.org/index.html" rel="noreferrer">POI homepage</a> for details of the current releases.</p>
36,013,063
What is the purpose of meshgrid in Python / NumPy?
<p>Can someone explain to me what is the purpose of <code>meshgrid</code> function in Numpy? I know it creates some kind of grid of coordinates for plotting, but I can't really see the direct benefit of it.</p> <p>I am studying "Python Machine Learning" from Sebastian Raschka, and he is using it for plotting the decision borders. See input 11 <a href="https://github.com/rasbt/python-machine-learning-book/blob/master/code/ch03/ch03.ipynb" rel="noreferrer">here</a>.</p> <p>I have also tried this code from official documentation, but, again, the output doesn't really make sense to me.</p> <pre><code>x = np.arange(-5, 5, 1) y = np.arange(-5, 5, 1) xx, yy = np.meshgrid(x, y, sparse=True) z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) h = plt.contourf(x,y,z) </code></pre> <p>Please, if possible, also show me a lot of real-world examples.</p>
36,014,586
9
1
null
2016-03-15 13:43:43.957 UTC
255
2022-07-17 08:54:41.13 UTC
2018-09-07 10:11:57.713 UTC
null
670,206
null
3,441,597
null
1
463
python|numpy|multidimensional-array|mesh|numpy-ndarray
299,719
<p>The purpose of <code>meshgrid</code> is to create a rectangular grid out of an array of x values and an array of y values.</p> <p>So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a rectangular grid, we need every combination of the <code>x</code> and <code>y</code> points.</p> <p>This is going to be 25 points, right? So if we wanted to create an x and y array for all of these points, we <em>could</em> do the following.</p> <pre><code>x[0,0] = 0 y[0,0] = 0 x[0,1] = 1 y[0,1] = 0 x[0,2] = 2 y[0,2] = 0 x[0,3] = 3 y[0,3] = 0 x[0,4] = 4 y[0,4] = 0 x[1,0] = 0 y[1,0] = 1 x[1,1] = 1 y[1,1] = 1 ... x[4,3] = 3 y[4,3] = 4 x[4,4] = 4 y[4,4] = 4 </code></pre> <p>This would result in the following <code>x</code> and <code>y</code> matrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.</p> <pre><code>x = 0 1 2 3 4 y = 0 0 0 0 0 0 1 2 3 4 1 1 1 1 1 0 1 2 3 4 2 2 2 2 2 0 1 2 3 4 3 3 3 3 3 0 1 2 3 4 4 4 4 4 4 </code></pre> <p>We can then plot these to verify that they are a grid:</p> <pre><code>plt.plot(x,y, marker='.', color='k', linestyle='none') </code></pre> <p><a href="https://i.stack.imgur.com/kZNzz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kZNzz.png" alt="enter image description here"></a></p> <p>Obviously, this gets very tedious especially for large ranges of <code>x</code> and <code>y</code>. Instead, <code>meshgrid</code> can actually generate this for us: all we have to specify are the unique <code>x</code> and <code>y</code> values.</p> <pre><code>xvalues = np.array([0, 1, 2, 3, 4]); yvalues = np.array([0, 1, 2, 3, 4]); </code></pre> <p>Now, when we call <code>meshgrid</code>, we get the previous output automatically.</p> <pre><code>xx, yy = np.meshgrid(xvalues, yvalues) plt.plot(xx, yy, marker='.', color='k', linestyle='none') </code></pre> <p><a href="https://i.stack.imgur.com/1xeW8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1xeW8.png" alt="enter image description here"></a></p> <p>Creation of these rectangular grids is useful for a number of tasks. In the example that you have provided in your post, it is simply a way to sample a function (<code>sin(x**2 + y**2) / (x**2 + y**2)</code>) over a range of values for <code>x</code> and <code>y</code>. </p> <p>Because this function has been sampled on a rectangular grid, the function can now be visualized as an "image".</p> <p><a href="https://i.stack.imgur.com/K5BCm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/K5BCm.png" alt="enter image description here"></a></p> <p>Additionally, the result can now be passed to functions which expect data on rectangular grid (i.e. <code>contourf</code>)</p>
20,330,174
AVCapture capturing and getting framebuffer at 60 fps in iOS 7
<p>I'm developping an app which requires capturing framebuffer at as much fps as possible. I've already figured out how to force iphone to capture at 60 fps but</p> <pre><code>- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection </code></pre> <p>method is being called only 15 times a second, which means that iPhone downgrades capture output to 15 fps.</p> <p>Has anybody faced such problem? Is there any possibility to increase capturing frame rate?</p> <p><strong>Update</strong> my code:</p> <pre><code>camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if([camera isTorchModeSupported:AVCaptureTorchModeOn]) { [camera lockForConfiguration:nil]; camera.torchMode=AVCaptureTorchModeOn; [camera unlockForConfiguration]; } [self configureCameraForHighestFrameRate:camera]; // Create a AVCaptureInput with the camera device NSError *error=nil; AVCaptureInput* cameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:camera error:&amp;error]; if (cameraInput == nil) { NSLog(@"Error to create camera capture:%@",error); } // Set the output AVCaptureVideoDataOutput* videoOutput = [[AVCaptureVideoDataOutput alloc] init]; // create a queue to run the capture on dispatch_queue_t captureQueue=dispatch_queue_create("captureQueue", NULL); // setup our delegate [videoOutput setSampleBufferDelegate:self queue:captureQueue]; // configure the pixel format videoOutput.videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey, nil]; // Add the input and output [captureSession addInput:cameraInput]; [captureSession addOutput:videoOutput]; </code></pre> <p>I took <code>configureCameraForHighestFrameRate</code> method here <a href="https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVCaptureDevice_Class/Reference/Reference.html">https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVCaptureDevice_Class/Reference/Reference.html</a></p>
20,332,209
3
0
null
2013-12-02 14:04:26.91 UTC
21
2017-04-12 08:41:47.673 UTC
2013-12-03 14:21:14.117 UTC
null
962,658
null
962,658
null
1
19
ios|iphone|camera|avcapturesession|frame-rate
23,168
<p>I am getting samples at 60 fps on the iPhone 5 and 120 fps on the iPhone 5s, both when doing real time motion detection in captureOutput and when saving the frames to a video using AVAssetWriter.</p> <p>You have to set thew AVCaptureSession to a format that supports 60 fps:</p> <pre><code>AVsession = [[AVCaptureSession alloc] init]; AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *capInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&amp;error]; if (capInput) [AVsession addInput:capInput]; for(AVCaptureDeviceFormat *vFormat in [videoDevice formats] ) { CMFormatDescriptionRef description= vFormat.formatDescription; float maxrate=((AVFrameRateRange*)[vFormat.videoSupportedFrameRateRanges objectAtIndex:0]).maxFrameRate; if(maxrate&gt;59 &amp;&amp; CMFormatDescriptionGetMediaSubType(description)==kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { if ( YES == [videoDevice lockForConfiguration:NULL] ) { videoDevice.activeFormat = vFormat; [videoDevice setActiveVideoMinFrameDuration:CMTimeMake(10,600)]; [videoDevice setActiveVideoMaxFrameDuration:CMTimeMake(10,600)]; [videoDevice unlockForConfiguration]; NSLog(@"formats %@ %@ %@",vFormat.mediaType,vFormat.formatDescription,vFormat.videoSupportedFrameRateRanges); } } } prevLayer = [AVCaptureVideoPreviewLayer layerWithSession: AVsession]; prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; [self.view.layer addSublayer: prevLayer]; AVCaptureVideoDataOutput *videoOut = [[AVCaptureVideoDataOutput alloc] init]; dispatch_queue_t videoQueue = dispatch_queue_create("videoQueue", NULL); [videoOut setSampleBufferDelegate:self queue:videoQueue]; videoOut.videoSettings = @{(id)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA)}; videoOut.alwaysDiscardsLateVideoFrames=YES; if (videoOut) { [AVsession addOutput:videoOut]; videoConnection = [videoOut connectionWithMediaType:AVMediaTypeVideo]; } </code></pre> <p>Two other comment if you want to write to a file using AVAssetWriter. Don't use the pixelAdaptor, just ad the samples with </p> <pre><code>[videoWriterInput appendSampleBuffer:sampleBuffer] </code></pre> <p>Secondly when setting up the assetwriter use</p> <pre><code>[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings sourceFormatHint:formatDescription]; </code></pre> <p>The sourceFormatHint makes a difference in writing speed.</p>
6,161,418
Android - Failed to find an AVD compatible with target 'Android 1.6' error
<p>I'm trying to run a Hello World app for Android for the first time, but I keep getting a:</p> <pre><code>Failed to find an AVD compatible with target 'Android 1.6' </code></pre> <p>error when I try to create an AVD.</p> <p>I have tried the following solution in order to fix the issue:</p> <ul> <li>Checked that I have the right packages installed. I have Android SDK Tools Revision 11, Android SDK Platform-Tools Revision 4, SDK Platforms 4, 7, 8, 9, 10, 11 and 12, Android Compatability package.</li> <li>I've checked that my PATH environment variable is pointing to the right places for the Tools and the Platform-Tools folders.</li> <li>Played around with setting the project at different platform levels etc.</li> <li>Switching off my Virus Protection temporarily</li> </ul> <p>I always get a similar error message, though.</p> <p>This is what I get in the eclipse console when I try to launch.</p> <pre><code>[2011-05-28 11:43:47 - HelloAndroid] ------------------------------ [2011-05-28 11:43:47 - HelloAndroid] Android Launch! [2011-05-28 11:43:47 - HelloAndroid] adb is running normally. [2011-05-28 11:43:47 - HelloAndroid] Performing com.androidbook.hello.HelloActivity activity launch [2011-05-28 11:43:47 - HelloAndroid] Failed to find an AVD compatible with target 'Android 1.6'. [2011-05-28 11:44:27 - SDK Manager] could not create file 'C:\Windows\system32\config\systemprofile\.android\avd\Gingerbread.avd\sdcard.img', aborting... [2011-05-28 11:44:27 - SDK Manager] could not write to 'C:\Windows\system32\config\systemprofile\.android\avd\Gingerbread.avd\sdcard.img', aborting... [2011-05-28 11:44:27 - SDK Manager] Failed to create the SD card. [2011-05-28 11:45:09 - HelloAndroid] Still no compatible AVDs with target 'Android 1.6': Aborting launch. [2011-05-28 11:45:09 - HelloAndroid] Performing com.androidbook.hello.HelloActivity activity launch [2011-05-28 11:45:11 - HelloAndroid] Launch canceled! </code></pre> <p>I notice that my packages are installed at:</p> <pre><code>C:\Program Files\Android\android-sdk </code></pre> <p>because thats what is says at the top of the Android SDK and AVD manager when the Installed Packages option is selected. But when I choose the Virtual Devices option, the location it is looking for the virtual devices in:</p> <pre><code>C:\Windows\system32\config\systemprofile\.android\avd. </code></pre> <p>In the book that I'm following there is a screenshot of his SDK and AVD Manager looking for the virtual devices in a </p> <pre><code>C:\Documents and Setting\Dave\.android\avd </code></pre> <p>folder. Will it make any difference to me if I change where the Manager looks for this stuff? Can anyone tell me how I can do that?</p> <p>Grateful for any help on this. I just want to get cracking!</p> <p>Many thanks</p>
6,161,805
4
0
null
2011-05-28 11:42:17.76 UTC
1
2014-04-15 16:43:50.533 UTC
null
null
null
null
2,106,959
null
1
7
android|eclipse
40,547
<p>In this end I solved in by the following method:</p> <p>I set a new environment variable ANDROID_SDK_HOME to the same location as my HOME environment variable which is C:\Users\MyName (This was suggested by one of the commenters in <a href="http://techtraveller.blogspot.com/2009/07/android-fixed-unknown-virtual-device.html" rel="noreferrer">this</a> article)</p> <p>This changed the location that the Android SDK and AVD manager was looking for virtual devices in. When I added a new device then, I didn't seem to get any problem (Actually as I did this in the process of launching my app, I actually had to close everything down and relaunch so it could find the AVD that I had just created).</p> <p>I'm amazed at how long the AVD actually takes to fully fire-up and install my 10 line app. It literally took about 5 minutes so I could see "Hello World".</p> <p>Still... victory is mine!</p>
34,864,824
Twitter Bootstrap: margin-bottom built in css class
<p>Is there built in margin bottom class to use? I tried with <code>bottom5</code> like</p> <pre><code>&lt;div class="col-lg-2 bottom5"&gt;&lt;/div&gt; </code></pre> <p>but this doesn't work.</p>
34,865,025
6
1
null
2016-01-18 21:59:35.16 UTC
3
2020-06-17 01:15:16.86 UTC
2016-01-18 22:04:05.11 UTC
null
3,874,768
null
1,765,862
null
1
17
css|twitter-bootstrap|twitter-bootstrap-3
67,143
<p>There is no bootstrap class for margins like you describe. The reasons would be the need for classes for margins 0 to 10s or 100s, as well as the need for multiple units, such as <code>px</code>, <code>em</code>, <code>%</code>, etc.</p> <p>You can make your own classes fairly easy. Even easier with sublime text-editor and multi-select.</p> <p>That being said, you don't want to abstract every style rule into the html. Original CSS is useful for something particular to your element, such as margins. Using bootstrap classes for every style would lead to difficult to read HTML.</p> <p>This Question is tagged Bootstrap 3, but when you update to Bootstrap 4, there is a <a href="https://getbootstrap.com/docs/4.0/utilities/spacing/" rel="noreferrer">built in utility for this</a>.</p>
1,602,831
One file per component or several files per component?
<p>Should I wrap all the files I want to install in individual components? What is the advantage of putting several files in one component?</p>
1,604,348
2
2
null
2009-10-21 18:51:32.103 UTC
25
2019-10-31 00:29:19.08 UTC
2019-06-24 16:42:54.42 UTC
null
142,162
null
122,732
null
1
69
wix|windows-installer|wix3
20,497
<p>One reason for "one file per component" is <a href="http://support.microsoft.com/kb/290997" rel="noreferrer">resiliency</a>. When an application is started, Windows Installer can check whether the <a href="https://stackoverflow.com/questions/2003043/what-is-the-wix-keypath-attribute">keypath</a> of any component is missing. If the keypath is missing, the component is reinstalled/repaired. </p> <p>If a component has multiple files, then <strong>only one file</strong> can be the keypath. In wix you indicate this by setting <code>KeyPath=yes</code> on a <a href="http://wix.sourceforge.net/manual-wix3/wix_xsd_file.htm" rel="noreferrer">File</a> element. The other files will then not be fully protected by Windows Installer resiliency. They will only be reinstalled if the keypath file goes missing.</p> <p>Another reason to have "one file per component" is when installing files to locations where they may already be present (e.g. an application upgrade, or when installing to <code>c:\windows\system32</code>). Windows installer determines whether a component needs to be installed by checking the keypath. If the keypath is a file and the file is already there (with the same version or higher) then the component is <strong>not</strong> installed. That's a problem if the <em>other</em> files in the component actually needed to be installed/upgraded.</p>
2,246,206
What is the equivalent in F# of the C# default keyword?
<p>I'm looking for the equivalent of C# <code>default</code> keyword, e.g:</p> <pre><code>public T GetNext() { T temp = default(T); ... </code></pre> <p>Thanks</p>
2,246,216
2
0
null
2010-02-11 17:17:36.03 UTC
9
2020-06-21 15:44:58.513 UTC
2010-06-25 22:17:50.423 UTC
null
161,331
null
161,331
null
1
85
c#|f#|default|keyword|c#-to-f#
11,874
<p>I found this in a blog: "<a href="http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!725.entry" rel="noreferrer">What does this C# code look like in F#? (part one: expressions and statements)</a>"</p> <blockquote> <p>C# has an operator called "default" that returns the zero-initialization value of a given type:</p> <pre><code>default(int) </code></pre> <p>It has limited utility; most commonly you may use default(T) in a generic. F# has a similar construct as a library function:</p> <pre><code>Unchecked.defaultof&lt;int&gt; </code></pre> </blockquote>
66,082,776
Uncommon homebrew error: "Unknown command: switch"
<p>I am in the process of trying to restart some legacy project that demands the use of an older version of openssl.</p> <p>I have found good input on the issue <a href="https://stackoverflow.com/a/61086871/921573">here</a>, which worked on one of my machines but not the other, which gives me the following error:</p> <pre><code>$ brew switch openssl 1.0.2t Error: Unknown command: switch </code></pre> <p>The error does not seem to be very common, nothing helpful is showing up on a google/stackoverflow search.</p> <p>What I have tried so far:</p> <ul> <li>resolved all warnings shown by <code>brew doctor</code></li> <li>run <code>brew update &amp;&amp; brew upgrade</code></li> <li>updated Xcode Command Line Tools</li> <li>reinstalled openssl</li> </ul> <p>What can I do to fix this?</p>
66,101,345
2
2
null
2021-02-06 22:48:36.767 UTC
4
2022-02-07 14:16:29.247 UTC
null
null
null
null
921,573
null
1
24
openssl|homebrew|macos-catalina
38,034
<p>As I commented above, <a href="https://github.com/Homebrew/discussions/discussions/339" rel="noreferrer">Homebrew got rid of the <code>switch</code> command</a> entirely, which is why it says &quot;Unknown command&quot;.</p> <p>But rbenv provides a tap that you can install openssl from. You can run the command below:</p> <pre><code>brew install rbenv/tap/[email protected] </code></pre> <p>If you're installing [email protected] for Ruby purposes, <a href="https://github.com/rbenv/ruby-build/issues/1353#issuecomment-573414540" rel="noreferrer">this thread</a> tells you how to do that as well. For example:</p> <pre><code>CONFIGURE_OPTS=&quot;--with-openssl-dir=$(brew --prefix [email protected])&quot; RUBY_CONFIGURE_OPTS=&quot;--with-openssl-dir=$(brew --prefix [email protected])&quot; rbenv install 2.7.2 </code></pre>
57,243,677
Proportional height (or width) in SwiftUI
<p>I started exploring SwiftUI and I can't find a way to get a simple thing: I'd like a View to have proportional height (basically a percentage of its parent's height). Let's say I have 3 views vertically stacked. I want:</p> <ul> <li>The first to be 43% (of its parent's height) high</li> <li>The second to be 37% (of its parent's height) high</li> <li>The last to be 20% (of its parent's height) high</li> </ul> <p>I watched this interesting video from the WWDC19 about custom views in SwiftUI (<a href="https://developer.apple.com/videos/play/wwdc2019/237/" rel="noreferrer">https://developer.apple.com/videos/play/wwdc2019/237/</a>) and I understood (correct me if I'm wrong) that basically a View never has a size per se, the size is the size of its children. So, the parent view asks its children how tall they are. They answer something like: &quot;half your height!&quot; and then... what? How does the layout system (that is different from the layout system we are used to) manage this situation?</p> <p>If you write the below code:</p> <pre><code>struct ContentView : View { var body: some View { VStack(spacing: 0) { Rectangle() .fill(Color.red) Rectangle() .fill(Color.green) Rectangle() .fill(Color.yellow) } } } </code></pre> <p>The SwiftUI layout system sizes each view to be 1/3 high and this is right according to the video I posted here above. You can wrap the rectangles in a frame this way:</p> <pre><code>struct ContentView : View { var body: some View { VStack(spacing: 0) { Rectangle() .fill(Color.red) .frame(height: 200) Rectangle() .fill(Color.green) .frame(height: 400) Rectangle() .fill(Color.yellow) } } } </code></pre> <p>This way the layout system sizes the first rectangle to be 200 high, the second one to be 400 high and the third one to fit all the left space. And again, this is fine. What you can't do (this way) is specifying a proportional height.</p>
57,244,001
1
3
null
2019-07-28 18:08:05.083 UTC
10
2021-08-18 21:21:37.48 UTC
2021-08-18 21:21:37.48 UTC
null
1,291,872
null
1,291,872
null
1
66
ios|swift|autolayout|swiftui
31,298
<p>You can make use of <code>GeometryReader</code>. Wrap the reader around all other views and use its closure value <code>metrics</code> to calculate the heights:</p> <pre><code>let propHeight = metrics.size.height * 0.43 </code></pre> <p>Use it as follows:</p> <pre><code>import SwiftUI struct ContentView: View { var body: some View { GeometryReader { metrics in VStack(spacing: 0) { Color.red.frame(height: metrics.size.height * 0.43) Color.green.frame(height: metrics.size.height * 0.37) Color.yellow } } } } import PlaygroundSupport PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView()) </code></pre>
6,042,829
How can i open a url in web browser (such as IE) and pass credentials
<p>I want to open a page that required Basic authentication. I want to pass the Basic authentication header to the browser along with the URL.</p> <p>How can i do that?</p>
6,043,412
5
5
null
2011-05-18 09:53:55.867 UTC
6
2017-09-24 16:47:45.683 UTC
2011-05-18 10:53:26.953 UTC
null
41,956
null
243,967
null
1
16
c#|.net|.net-4.0
49,275
<p>Via a header you can:</p> <pre><code>string user = "uuuuuuu"; string pass = "ppppppp"; string authHdr = "Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(user + ":" + pass)) + "\r\n"; webBrowserCtl.Navigate("http://example.com", null, null, authHdr); </code></pre> <p>given that this needs to be done on a per-request basis, an easier option for basic auth is to just;</p> <pre><code>webBrowserCtl.Navigate("http://uuuuuuu:[email protected]", null, null, authHdr); </code></pre>
6,193,126
How to get row count from EXEC() in a TSQL SPROC?
<p>I have a TSQL sproc that builds a query as and executes it as follows:</p> <pre><code>EXEC (@sqlTop + @sqlBody + @sqlBottom) </code></pre> <p>@sqlTop contains something like SELECT TOP(x) col1, col2, col3... </p> <p>TOP(x) will limit the rows returned, so later I want to know what the actual number of rows in the table is that match the query.</p> <p>I then replace @sqlTop with something like:</p> <pre><code>EXEC ('SELECT @ActualNumberOfResults = COUNT(*) ' + @sqlBody) </code></pre> <p>I can see why this is not working, and why a value not declared error occurs, but I think it adequately describes what I'm trying to accomplish.</p> <p>Any ideas?</p>
6,193,212
7
0
null
2011-05-31 20:23:00.217 UTC
1
2021-03-26 18:00:03.393 UTC
null
null
null
null
172,359
null
1
25
tsql|sql-server-2008|stored-procedures
63,735
<p>You could instead have the dynamic query return the result as a row set, which you would then insert into a table variable (could be a temporary or ordinary table as well) using the <code>INSERT ... EXEC</code> syntax. Afterwards you can just read the saved value into a variable using <code>SELECT @var = ...</code>:</p> <pre><code>DECLARE @rowcount TABLE (Value int); INSERT INTO @rowcount EXEC('SELECT COUNT(*) ' + @sqlBody); SELECT @ActualNumberOfResults = Value FROM @rowcount; </code></pre>
6,293,498
Check whether user has a Chrome extension installed
<p>I am in the process of building a Chrome extension, and for the whole thing to work the way I would like it to, I need an external JavaScript script to be able to detect if a user has my extension installed. </p> <p>For example: A user installs my plugin, then goes to a website with my script on it. The website detects that my extension is installed and updates the page accordingly.</p> <p>Is this possible?</p>
6,293,601
16
3
null
2011-06-09 13:27:16.853 UTC
59
2021-07-14 21:59:40.02 UTC
2013-01-16 23:10:26.743 UTC
null
122,162
user179169
null
null
1
125
javascript|google-chrome|google-chrome-extension
135,229
<p>I am sure there is a direct way (calling functions on your extension directly, or by using the JS classes for extensions), but an indirect method (until something better comes along):</p> <p>Have your Chrome extension look for a specific DIV or other element on your page, with a very specific ID.</p> <p>For example:</p> <pre><code>&lt;div id="ExtensionCheck_JamesEggersAwesomeExtension"&gt;&lt;/div&gt; </code></pre> <p>Do a <code>getElementById</code> and set the <code>innerHTML</code> to the version number of your extension or something. You can then read the contents of that client-side.</p> <p>Again though, you should use a direct method if there is one available.</p> <hr> <p><strong>EDIT: Direct method found!!</strong></p> <p>Use the connection methods found here: <a href="https://developer.chrome.com/extensions/extension#global-events" rel="noreferrer">https://developer.chrome.com/extensions/extension#global-events</a></p> <p>Untested, but you should be able to do...</p> <pre><code>var myPort=chrome.extension.connect('yourextensionid_qwerqweroijwefoijwef', some_object_to_send_on_connect); </code></pre>
5,827,944
Git error on commit after merge - fatal: cannot do a partial commit during a merge
<p>I ran a <code>git pull</code> that ended in a conflict. I resolved the conflict and everything is fine now (I used mergetool also).</p> <p>When I commit the resolved file with <code>git commit file.php -m "message"</code> I get the error:</p> <pre><code>fatal: cannot do a partial commit during a merge. </code></pre> <p>I had the same issue before and using <code>-a</code> in commit worked perfectly. I think it's not the perfect way because I don't want to commit all changes. I want to commit files separately with separate comments. How can I do that? Why doesn't git allow users to commit files separately after a merge? I could not find a satisfactory answer to this problem.</p>
8,062,976
20
3
null
2011-04-29 04:36:59.377 UTC
72
2022-08-28 01:58:32.477 UTC
2021-09-23 19:24:15.793 UTC
null
967,621
null
134,143
null
1
334
git|commit|git-merge|git-merge-conflict
367,130
<p>I found that adding "-i" to the commit command fixes this problem for me. The -i basically tells it to stage additional files before committing. That is:</p> <pre><code>git commit -i myfile.php </code></pre>
6,275,299
How to disable copy/paste from/to EditText
<p>In my application, there is a registration screen, where i do not want the user to be able to copy/paste text into the <code>EditText</code> field. I have set an <code>onLongClickListener</code> on each <code>EditText</code> so that the context menu showing copy/paste/inputmethod and other options does not show up. So the user won't be able to copy/ paste into the Edit fields.</p> <pre><code> OnLongClickListener mOnLongClickListener = new OnLongClickListener() { @Override public boolean onLongClick(View v) { // prevent context menu from being popped up, so that user // cannot copy/paste from/into any EditText fields. return true; } }; </code></pre> <p>But the problem arises if the user has enabled a third-party keyboard other than the Android default, which may have a button to copy/paste or which may show the same context menu. So how do i disable copy/paste in that scenario ?</p> <p>Please let me know if there are other ways to copy/paste as well. (and possibly how to disable them)</p> <p>Any help would be appreciated.</p>
12,331,404
31
4
null
2011-06-08 07:05:12.15 UTC
30
2022-03-07 07:05:17.793 UTC
2011-12-08 11:28:57.97 UTC
null
68,805
null
607,968
null
1
147
android-widget|android-edittext|android|android-keypad
127,438
<p>If you are using API level 11 or above then you can stop copy,paste,cut and custom context menus from appearing by.</p> <pre><code>edittext.setCustomSelectionActionModeCallback(new ActionMode.Callback() { public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } public void onDestroyActionMode(ActionMode mode) { } public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } }); </code></pre> <p><strong>Returning false from onCreateActionMode(ActionMode, Menu) will prevent the action mode from being started(Select All, Cut, Copy and Paste actions).</strong></p>
4,979,252
JSLint error: "Move the invocation into the parens that contain the function"
<p>What does <strong>JSLint</strong> mean by this error? And how should it be rewritten?</p> <p><code>Error: Problem at line 78 character 3: Move the invocation into the parens that contain the function: })(jQuery); </code></p>
4,979,255
1
0
null
2011-02-12 16:48:57.423 UTC
14
2015-11-24 16:17:25.043 UTC
2015-11-24 16:17:25.043 UTC
null
509,670
null
509,670
null
1
74
javascript|jquery|debugging|compiler-errors|jslint
25,663
<p>To pass JSLint's criteria, it needs to be written like this:</p> <p><code>}(jQuery));</code></p> <p>Though I think that particular criteria is a bit subjective. Both ways seem fine in my opinion.</p> <p><code>(function () {})()</code> makes a bit more sense to me since you wrap the full function, then call it</p> <p><code>(function () {}())</code> looks like you're wrapping the result of the function call in a parens ...</p>
24,884,174
Generate random number in Laravel
<p>Please am working on a Project on Laravel and I wanted to Generate a Random Number in this format: one character in any position order and the rest integers. Example: C87465398745635, 87474M745436475, 98487464655378J8 etc. and this is my Controller: </p> <pre><code> function generatePin( $number ) { $pins = array(); for ($j=0; $j &lt; $number; $j++) { $string = str_random(15); $pin = Pin::where('pin', '=', $string)-&gt;first(); if($pin){ $j--; }else{ $pins[$j] = $string; } } return $pins; } </code></pre> <p>But it seems to be Generating something else like this: ZsbpEKw9lRHqGbv, i7LjvSiHgeGrNN8, pyJEcjhjd3zu9Su I have tried all I could but no success, Please any helping solution will be appreciated, Thanks</p>
24,884,343
6
1
null
2014-07-22 09:53:39.947 UTC
3
2021-03-03 14:08:41.52 UTC
2014-07-22 10:00:31.94 UTC
null
1,269,513
null
3,798,413
null
1
18
php|string|random|laravel
106,860
<p>If you want to generate the random string like you said, replace: </p> <pre><code>$string = str_random(15); </code></pre> <p>with</p> <pre><code>// Available alpha caracters $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // generate a pin based on 2 * 7 digits + a random character $pin = mt_rand(1000000, 9999999) . mt_rand(1000000, 9999999) . $characters[rand(0, strlen($characters) - 1)]; // shuffle the result $string = str_shuffle($pin); </code></pre> <p>Edit: </p> <p>Before, the code wasn't generating a random alpha character all the time. Thats because Laravel's <code>str_random</code> generates a random alpha-numeric string, and sometimes that function returned a numeric value (<a href="http://laravel.com/api/function-str_random.html" rel="noreferrer">see docs</a>).</p>
19,419,374
Android convert date and time to milliseconds
<p>I have one date and time format as below:</p> <pre><code>Tue Apr 23 16:08:28 GMT+05:30 2013 </code></pre> <p>I want to convert into milliseconds, but I actually dont know which format it is. Can anybody please help me.</p>
19,419,480
10
0
null
2013-10-17 06:06:51.477 UTC
8
2019-12-12 08:35:00.603 UTC
null
null
null
null
644,603
null
1
49
android|datetime
110,137
<blockquote> <p>Update for <a href="https://developer.android.com/reference/java/time/format/DateTimeFormatter?hl=en" rel="noreferrer">DateTimeFormatter</a> introduced in API 26. </p> </blockquote> <p>Code can be written as below for API 26 and above</p> <pre><code>// Below Imports are required for this code snippet // import java.util.Locale; // import java.time.LocalDateTime; // import java.time.ZoneOffset; // import java.time.format.DateTimeFormatter; String date = "Tue Apr 23 16:08:28 GMT+05:30 2013"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); LocalDateTime localDate = LocalDateTime.parse(date, formatter); long timeInMilliseconds = localDate.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli(); Log.d(TAG, "Date in milli :: FOR API &gt;= 26 &gt;&gt;&gt; " + timeInMilliseconds); // Output is -&gt; Date in milli :: FOR API &gt;= 26 &gt;&gt;&gt; 1366733308000 </code></pre> <p>But as of now only 6% of devices are running on 26 or above. So you will require backward compatibility for above classes. <a href="https://stackoverflow.com/users/132047/jake-wharton">JakeWharton</a> has been written <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer">ThreeTenABP</a> which is based on <a href="https://github.com/ThreeTen/threetenbp" rel="noreferrer">ThreeTenBP</a>, but specially developed to work on Android. <em>Read more about <a href="https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project">How and Why ThreeTenABP should be used instead-of java.time, ThreeTen-Backport, or even Joda-Time</a></em></p> <p>So using ThreeTenABP, above code can be written as (and verified on API 16 to API 29)</p> <pre><code>// Below Imports are required for this code snippet // import java.util.Locale; // import org.threeten.bp.OffsetDateTime; // import org.threeten.bp.format.DateTimeFormatter; DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss OOOO yyyy", Locale.ROOT); String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013"; long timeInMilliseconds = OffsetDateTime.parse(givenDateString, formatter) .toInstant() .toEpochMilli(); System.out.println("Date in milli :: USING ThreeTenABP &gt;&gt;&gt; " + timeInMilliseconds); // Output is -&gt; Date in milli :: USING ThreeTenABP &gt;&gt;&gt; 1366713508000 </code></pre> <p>Ole covered summarised information (for Java too) in his answer, you should look into.</p> <hr> <blockquote> <p>Below is old approach (and previous version of this answer) which should not be used now</p> </blockquote> <p>Use below method </p> <pre><code>String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); try { Date mDate = sdf.parse(givenDateString); long timeInMilliseconds = mDate.getTime(); System.out.println("Date in milli :: " + timeInMilliseconds); } catch (ParseException e) { e.printStackTrace(); } </code></pre> <hr> <p>Read more about <a href="http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">date and time pattern strings</a>.</p>
41,100,333
Difference between docker run --user and --group-add parameters
<p>What is the difference between <code>docker run</code> parameters:</p> <pre><code> -u, --user="" Sets the username or UID used and optionally the groupname or GID for the specified command. The followings examples are all valid: --user [user | user:group | uid | uid:gid | user:gid | uid:group ] Without this argument the command will be run as root in the container. </code></pre> <p>and </p> <pre><code> --group-add=[] Add additional groups to run as </code></pre> <p>?</p>
41,101,828
2
0
null
2016-12-12 11:55:36.71 UTC
7
2016-12-12 16:31:34.39 UTC
null
null
null
null
6,128,602
null
1
38
docker
73,553
<p><code>docker run --user=demo_user &lt;image_name&gt; &lt;command&gt;</code> runs a container with the given command as <strong>demo_user</strong> <a href="https://i.stack.imgur.com/shNJb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/shNJb.png" alt="enter image description here"></a></p> <p><code>docker run --user=demo_user:group1 &lt;image_name&gt; &lt;command&gt;</code> runs a container with the given command as <strong>demo_user</strong> whose primary group is set to <strong>group1</strong> <a href="https://i.stack.imgur.com/L36Ku.png" rel="noreferrer"><img src="https://i.stack.imgur.com/L36Ku.png" alt="enter image description here"></a></p> <p><code>docker run --user=demo_user:group1 --group-add group2 &lt;image_name&gt; &lt;command&gt;</code> runs a container with the given command as <strong>demo_user</strong> whose primary group is set to <strong>group1</strong> and <strong>group2</strong> as secondary group of the user <a href="https://i.stack.imgur.com/QP8hv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QP8hv.png" alt="enter image description here"></a></p> <p>NOTE: users and groups used for these options MUST have been created in the image of which we are creating a container. If <code>--group-add</code> option alone is specified without <code>--user</code> and the image does NOT have any user declared(user should have been created but not declared via USER instruction in Dockerfile from which the image got created), group modifications happen to the <code>root</code> user in the container.</p> <p>If <code>--group-add</code> option alone is specified without <code>--user</code> and the image does have the user declared( via USER instruction in Dockerfile from which the image got created), group modifications happen to the declared user in the container.</p>
41,675,077
How can I filter array of state in react?
<p>I have order reducer, which has many states.</p> <pre><code>const initialState = { channel: null, order: {}, fetching:true, menu: [], categories: [], subcategories: [], currentCategoryId: 1, currentSubcategoryId: 5, currentMenu: [], }; </code></pre> <p>What I want to filter is <code>menu</code>. <code>menu</code> is array of state which has objects of <code>menu_item</code> I have <code>currentCategoryId</code> and <code>currentSubcategoryId</code>. What I want to do with these states is that by using <code>currentCategoryId</code> and <code>currentSubcategoryId</code> to filter <code>menu</code> and put filtered states to <code>currentMenu</code>.</p> <pre><code>case Constants.ORDER_CHANNEL_CONNECTED: return {...state,currentMenu: action.menu.map((menu) =&gt; { if(state.currentCategoryId == menu.category_id){ return menu; } else return false;}} </code></pre> <p>So to do that I made code like above. Even though it returns some filtered value, it shows same number of array with many false values. I want to find other approaches to do that..</p> <p>How can I do this? </p> <p>Thanks in advance.</p>
41,675,421
4
0
null
2017-01-16 11:11:44.293 UTC
1
2020-08-04 11:16:36.7 UTC
null
null
null
null
6,303,312
null
1
4
reactjs|filter|redux
77,334
<p>Please use the <code>filter</code> function:</p> <pre><code>{...state,currentMenu: action.menu.filter((menu) =&gt; state.currentCategoryId == menu.category_id)} </code></pre> <p>P.S: I agree with the below answer, it's better to use Immutable.js</p>
60,121,962
This class is visible to consumers via SomeModule -> SomeComponent, but is not exported from the top-level library entrypoint
<p>I upgraded all my angular library to <code>angular 9.0.0</code> using <code>ng update</code> and when I try to build them I got below error.</p> <p><strong>Error:</strong></p> <blockquote> <p>Unsupported private class SomeComponent. This class is visible to consumers via SomeModule -> SomeComponent, but is not exported from the top-level library entrypoint.</p> </blockquote> <p>Anyone solved this error?</p>
60,122,077
4
0
null
2020-02-07 22:27:13.847 UTC
11
2022-08-26 20:04:54.167 UTC
2020-02-09 09:25:29.037 UTC
null
1,000,551
null
537,647
null
1
87
angular|angular-library|angular9
37,893
<p>This error happens if any component is exported in <code>NgModule</code>and not included in your <code>public_api.ts</code>, <code>Angular 9</code> will throw an error now.</p> <p>This error was not coming in <code>Angular 8</code> but after upgrading to <code>Angular 9</code> it started showing.</p> <p>If you exported any <code>service</code>, <code>module</code> or <code>component</code>, etc in <code>NgModule</code> make sure to include them in <code>public_api.ts</code> or else <code>angular 9</code> will throw error now.</p> <p><strong>Fix: add your component to the <code>public_api.ts</code></strong></p> <pre><code>export * from './lib/components/some-me/some-me.component'; </code></pre>
26,553,924
What is the difference in Swift between 'unowned(safe)' and 'unowned(unsafe)'?
<p>Apple's <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html"><em>Swift Programming Language Guide</em></a> mentions the <em>capture specifiers</em> <code>unowned(safe)</code> and <code>unowned(unsafe)</code>, in addition to <code>weak</code> and <code>unowned</code>. </p> <p>I (think I) understand the differences between <code>weak</code> and <code>unowned</code>; but what is the difference between <code>unowned(safe)</code> and <code>unowned(unsafe)</code>? The guide doesn't say.</p> <hr> <p>Please: Don't rely on simply stating an Objective-C equivalent.</p>
26,557,046
4
0
null
2014-10-24 18:19:33.597 UTC
13
2021-05-21 01:03:25.59 UTC
2014-10-24 18:40:59.35 UTC
null
656,912
null
656,912
null
1
37
memory-management|swift|automatic-ref-counting
9,236
<p>From what I understand, although I can't find a definitive source from Apple, <code>unowned</code> can be broken into two flavors, <code>safe</code> and <code>unsafe</code>.</p> <p>A bare <code>unowned</code> is <code>unowned(safe)</code>: it is a specially wrapped reference which will throw an exception when a dealloced instance is referenced.</p> <p>The special case is <code>unowned(unsafe)</code>: it is the Swift equivalent of Objective C's <code>@property (assign)</code> or <code>__unsafe_unretained</code>. It should not be used in a Swift program, because its purpose is to bridge to code written in Objective C.</p> <p>So, you will see <code>unowned(unsafe)</code> when looking at the import wrapper for Cocoa classes, but don't use it unless you have to, and you will know when you have to.</p> <hr> <p><strong>Update</strong></p> <p><code>__unsafe_unretained</code> is a simple pointer. It will not know when the instance being pointed at has be dealloced, so when it's dereferenced, the underlying memory could be garbage.</p> <p>If you have a defect where a dealloced <code>__unsafe_unretained</code> variable is being used, you will see erratic behavior. Sometimes enough of that memory location is good enough so the code will run, sometimes it will have been partially overwritten so you will get very odd crashes, and sometimes that memory location will contain a new object so you will get unrecognized selector exceptions.</p> <p><a href="https://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4">Transitioning to ARC Release Notes</a></p> <blockquote> <p><code>__unsafe_unretained</code> specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.</p> </blockquote>
27,784,528
numpy division with RuntimeWarning: invalid value encountered in double_scalars
<p>I wrote the following script:</p> <pre><code>import numpy d = numpy.array([[1089, 1093]]) e = numpy.array([[1000, 4443]]) answer = numpy.exp(-3 * d) answer1 = numpy.exp(-3 * e) res = answer.sum()/answer1.sum() print res </code></pre> <p>But I got this result and with the error occurred:</p> <pre><code>nan C:\Users\Desktop\test.py:16: RuntimeWarning: invalid value encountered in double_scalars res = answer.sum()/answer1.sum() </code></pre> <p>It seems to be that the input element were too small that python turned them to be zeros, but indeed the division has its result.</p> <p>How to solve this kind of problem?</p>
27,784,588
2
0
null
2015-01-05 17:15:04.447 UTC
20
2019-06-18 21:57:10.327 UTC
null
null
null
null
2,330,923
null
1
100
python|numpy|warnings
346,020
<p>You can't solve it. Simply <code>answer1.sum()==0</code>, and you can't perform a division by zero. </p> <p>This happens because <code>answer1</code> is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.</p> <p><code>nan</code> is returned in this case because of the division by zero.</p> <p>Now to solve your problem you could:</p> <ul> <li>go for a library for high-precision mathematics, like <a href="https://code.google.com/p/mpmath/" rel="noreferrer">mpmath</a>. But that's less fun.</li> <li>as an alternative to a bigger weapon, do some math manipulation, as detailed below.</li> <li>go for a tailored <code>scipy/numpy</code> function that does exactly what you want! Check out @Warren Weckesser answer.</li> </ul> <p>Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:</p> <pre><code>exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y))) = exp(log(exp(-x)*[1+exp(-y+x)])) = exp(log(exp(-x) + log(1+exp(-y+x))) = exp(-x + log(1+exp(-y+x))) </code></pre> <p>where above <code>x=3* 1089</code> and <code>y=3* 1093</code>. Now, the argument of this exponential is</p> <p><code>-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06</code></p> <p>For the denominator you could proceed similarly but obtain that <code>log(1+exp(-z+k))</code> is already rounded to <code>0</code>, so that the argument of the exponential function at the denominator is simply rounded to <code>-z=-3000</code>. You then have that your result is</p> <pre><code>exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) = exp(-266.99999385580668) </code></pre> <p>which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number <code>1089</code> in the numerator and the first number <code>1000</code> at the denominator):</p> <pre><code>exp(3*(1089-1000))=exp(-267) </code></pre> <p>For the sake of it, let's see how close we are from the solution of Wolfram alpha (<a href="http://www.wolframalpha.com/input/?i=Log%5B%28exp%5B-3*1089%5D%2Bexp%5B-3*1093%5D%29%2F%28%5Bexp%5B-3*1000%5D%2Bexp%5B-3*4443%5D%29%5D" rel="noreferrer">link</a>):</p> <pre><code>Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -&gt; -266.999993855806522267194565420933791813296828742310997510523 </code></pre> <p>The difference between this number and the exponent above is <code>+1.7053025658242404e-13</code>, so the approximation we made at the denominator was fine.</p> <p>The final result is </p> <pre><code>'exp(-266.99999385580668) = 1.1050349147204485e-116 </code></pre> <p>From wolfram alpha is (<a href="http://www.wolframalpha.com/input/?i=%28exp%5B-3*1089%5D%2Bexp%5B-3*1093%5D%29%2F%28%5Bexp%5B-3*1000%5D%2Bexp%5B-3*4443%5D%29" rel="noreferrer">link</a>)</p> <pre><code>1.105034914720621496.. × 10^-116 # Wolfram alpha. </code></pre> <p>and again, it is safe to use numpy here too.</p>
43,940,857
after upgrade to 2.7 ClassNotFoundException: org.mockito.exceptions.Reporter when run test
<p>I try to set up junit, mokito and powermock together but when I ran a test I get ClassNotFoundException :(</p> <pre><code>testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:2.7.22' androidTestCompile 'org.mockito:mockito-core:2.7.22' androidTestCompile "org.mockito:mockito-android:2.7.22" testCompile 'org.robolectric:robolectric:3.3.2' testCompile 'org.hamcrest:hamcrest-core:1.3' testCompile 'org.powermock:powermock-core:1.6.6' testCompile 'org.powermock:powermock-module-junit4:1.6.6' testCompile 'org.powermock:powermock-module-junit4-rule:1.6.6' testCompile 'org.powermock:powermock-api-mockito:1.6.6' testCompile 'org.powermock:powermock-classloading-xstream:1.6.6'` </code></pre> <p>I also tried adding cglib by adding:</p> <pre><code>testCompile 'cglib:cglib:3.1' testCompile 'cglib:cglib-nodep:3.1' </code></pre> <p>but without of lack.</p> <p>could any one share working configuration or point me out what is wrong.</p> <p>My stacktrace when I ran a test:</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/mockito/exceptions/Reporter at sun.reflect.GeneratedSerializationConstructorAccessor5.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48) at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:251) at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139) at org.powermock.api.extension.reporter.AbstractMockingFrameworkReporterFactory.getInstanceForClassLoader(AbstractMockingFrameworkReporterFactory.java:41) at org.powermock.api.extension.reporter.AbstractMockingFrameworkReporterFactory.create(AbstractMockingFrameworkReporterFactory.java:35) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.getMockingFrameworkReporter(JUnit4TestSuiteChunkerImpl.java:140) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:119) at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53) at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused by: java.lang.ClassNotFoundException: org.mockito.exceptions.Reporter at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:190) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:77) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:67) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 21 more </code></pre>
44,883,638
4
0
null
2017-05-12 15:00:48.313 UTC
1
2018-10-17 06:23:46.773 UTC
null
null
null
null
1,461,568
null
1
34
java|junit|mockito|powermock
36,916
<p>That's what worked for me: </p> <pre><code>testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:2.8.0' testCompile 'org.powermock:powermock-api-mockito2:1.7.0RC2' testCompile 'org.powermock:powermock-module-junit4:1.7.0' testCompile 'org.powermock:powermock-core:1.7.0' testCompile 'org.powermock:powermock-module-junit4-rule:1.7.0' </code></pre> <p>using Mockito2 fixed the problem for me. </p>
21,577,573
Intellij IDEA can not resolve symbol with Play framework
<p>I am using IDEA 13 with Play 2.2.1 and was doing the examples on the <a href="http://www.playframework.com/documentation/2.2.x/JavaTodoList" rel="noreferrer">play site</a>.</p> <pre><code>public static Result index() { return redirect(routes.Application.tasks()); } </code></pre> <p>IDEA says "cannot resolve method redirect(?)" and red underlines routes.Application.tasks()</p> <p>I have done "compile" and then "idea" from the play console.</p>
21,596,223
7
1
null
2014-02-05 12:39:53.6 UTC
7
2019-12-09 09:25:35.09 UTC
null
null
null
null
2,239,106
null
1
31
intellij-idea|playframework
33,681
<p>I had a similar problem when testing my controller. I solved it by <code>"File" &gt; "Open Project"</code> and choose the base folder of the Play framework project (delete all idea settings file from the folder before so that it will reimport using the SBT settings).</p> <p>The last version of the SBT support for IDEA did 90% of the work. Then F4 to enter module settings dialog. Set up your project dependencies like in the picture below (the bright red folder have been set by IDEA and do not exist yet in my project so do not worry if they do in yours). It is a matter of including managed classes and generated code in the code that idea will use and index.</p> <p><img src="https://i.stack.imgur.com/fzemG.png" alt="enter image description here"></p> <p>now I can use code like this from within IDEA and debug it no problem.</p> <pre><code>Result result = Helpers.callAction(controllers.routes.ref.CrudController.createEntity(CrudEntities.contact.name()), new FakeRequest().withJsonBody(paramJson) ); </code></pre> <p>your way of doing it should work as well.</p>
32,997,269
COPYing a file in a Dockerfile, no such file or directory?
<p>I have a Dockerfile set up in my root (~) folder. The first three lines of my file look like this:</p> <pre><code>COPY file1 /root/folder/ COPY file2 /root/folder/ COPY file3 /root/folder/ </code></pre> <p>but it returns the following error for each line:</p> <blockquote> <p>No such file or directory</p> </blockquote> <p>The files are in the same directory as my Dockerfile and I am running the command <code>docker build - &lt; Dockerfile</code> in the same directory in terminal as well.</p> <p>What am I doing wrong here exactly?</p>
32,997,442
22
1
null
2015-10-07 16:09:13.45 UTC
18
2022-06-18 20:01:35.2 UTC
2017-01-22 16:45:32.187 UTC
null
1,323,398
null
2,485,799
null
1
150
docker
252,148
<p>The COPY instruction in the <code>Dockerfile</code> copies the files in <code>src</code> to the <code>dest</code> folder. Looks like you are either missing the <code>file1</code>, <code>file2</code> and <code>file3</code> or trying to build the <code>Dockerfile</code> from the wrong folder. </p> <p><a href="https://docs.docker.com/reference/builder/#copy" rel="noreferrer">Refer Dockerfile Doc</a></p> <p>Also the command for building the <code>Dockerfile</code> should be something like.</p> <pre><code>cd into/the/folder/ docker build -t sometagname . </code></pre>
9,338,180
Why HotSpot will optimize the following using hoisting?
<p>In the "Effective Java", the author mentioned that</p> <pre><code>while (!done) i++; </code></pre> <p>can be optimized by HotSpot into </p> <pre><code>if (!done) { while (true) i++; } </code></pre> <p><br> I am very confused about it. The variable <code>done</code> is usually not a <em>const</em>, why can compiler optimize that way?</p>
9,338,302
4
0
null
2012-02-18 03:12:18.173 UTC
13
2021-02-19 07:21:28.523 UTC
2018-03-28 11:07:04.943 UTC
null
814,702
null
705,414
null
1
23
java|jvm-hotspot
2,900
<p>The author assumes there that the variable <code>done</code> is a local variable, which does not have any requirements in the Java Memory Model to expose its value to other threads without synchronization primitives. Or said another way: the value of <code>done</code> won't be changed or viewed by any code other than what's shown here.</p> <p>In that case, since the loop doesn't change the value of <code>done</code>, its value can be effectively ignored, and the compiler can hoist the evaluation of that variable outside the loop, preventing it from being evaluated in the "hot" part of the loop. This makes the loop run faster because it has to do less work.</p> <p>This works in more complicated expressions too, such as the length of an array:</p> <pre><code>int[] array = new int[10000]; for (int i = 0; i &lt; array.length; ++i) { array[i] = Random.nextInt(); } </code></pre> <p>In this case, the naive implementation would evaluate the length of the array 10,000 times, but since the variable array is never assigned and the length of the array will never change, the evaluation can change to:</p> <pre><code>int[] array = new int[10000]; for (int i = 0, $l = array.length; i &lt; $l; ++i) { array[i] = Random.nextInt(); } </code></pre> <p>Other optimizations also apply here unrelated to hoisting.</p> <p>Hope that helps.</p>
9,051,516
clojure and leiningen - using a git repository as dependency
<p>Is it possible to have leiningen pull a project directly from a git repository (on github) as a dependency?</p> <p>Using Bundler with Ruby, it is possible to map a gem to a git repo, allowing for rapid development and integration of dependent projects.</p> <p><strong>Update</strong> </p> <p>Based on the accepted answer, there is now a leiningen plugin for managing git-deps: <a href="https://github.com/tobyhede/lein-git-deps" rel="noreferrer">https://github.com/tobyhede/lein-git-deps</a></p>
47,482,800
4
0
null
2012-01-29 06:56:00.723 UTC
14
2021-03-16 18:40:39.2 UTC
2012-01-30 01:57:43.22 UTC
null
14,971
null
14,971
null
1
38
git|clojure|github|dependency-management|leiningen
7,150
<h1>Answer for 2017: Use <a href="https://github.com/LonoCloud/lein-voom/" rel="nofollow noreferrer"><em>lein-voom</em></a></h1> <p>You can use <a href="https://github.com/LonoCloud/lein-voom/" rel="nofollow noreferrer"><em><strong>lein-voom</strong></em></a> to pull and build project dependencies from GitHub or other Git repositories. It works by letting you annotate your dependence vector-pair entries with <em>voom</em>-specific meta data. Here's an example from the README:</p> <pre><code>^{:voom {:repo "https://github.com/ring-clojure/ring" :branch "1.3"}} [ring/ring-core "1.3.0-RC1-20140519_142204-gaf0379b"] </code></pre> <p>The main use case given for <em>voom</em> is allowing teams that maintain multiple Clojure projects in separate Git repositories to easily depend on the current version of one or more of the projects from another without having to constantly deploy development snapshot releases.</p> <p>I prefer <em>lein-voom</em> over <em>lein-git-deps</em> (the plugin recommended in the previously-accepted answer from 2012) for a few reasons:</p> <ol> <li><p>The fact that the specification is given through meta-data makes this plugin more flexible and easily extensible. It already has an option for specifying a specific branch/tag of the repository. You could add other key/value pairs to the map for additional fine-grained control without too much work.</p></li> <li><p>You can simply delete the meta-data from your dependence entry for stable releases; i.e., there's no need to move entries around / refactor your <code>project.clj</code> once your dependence moves from GitHub into Clojars.</p></li> <li><p>At the time of writing (November 2017), <em>lein-voom</em> has been updated in the past couple of months, whereas <em>lein-git-deps</em> has been stagnant for 4 years.</p></li> </ol>
64,331,095
How to add a button to every row in MUI DataGrid
<p>I cant add a button into every row of MUI <code>DataGrid</code>. I have a MUI <code>DataGrid</code> which I render like this:</p> <pre><code>&lt;DataGrid rows={rows} columns={columns} pageSize={5} checkboxSelection /&gt; </code></pre> <p>I have added into the columns variable 'actions' column where the button should be. rows are just a a data object I get from the props. how can I add a button into every row (for editing the row)? I have tried mapping the data array but it is not possible to add JSX button into every object of data.</p>
64,331,367
3
2
null
2020-10-13 08:03:30.877 UTC
9
2021-11-01 02:07:01.853 UTC
2021-11-01 02:07:01.853 UTC
null
9,449,426
null
14,420,292
null
1
22
reactjs|datagrid|material-ui
48,223
<p>You can add your custom component by overriding <a href="https://mui.com/components/data-grid/columns/#render-cell" rel="noreferrer"><code>GridColDef.renderCell</code></a> method and return whatever element you want.</p> <p>The example below displays an action column that renders a single button in each row. When clicking the button, it alerts the current row data in json string:</p> <pre class="lang-js prettyprint-override"><code>const columns: GridColDef[] = [ { field: &quot;id&quot;, headerName: &quot;ID&quot;, width: 70 }, { field: &quot;action&quot;, headerName: &quot;Action&quot;, sortable: false, renderCell: (params) =&gt; { const onClick = (e) =&gt; { e.stopPropagation(); // don't select this row after clicking const api: GridApi = params.api; const thisRow: Record&lt;string, GridCellValue&gt; = {}; api .getAllColumns() .filter((c) =&gt; c.field !== &quot;__check__&quot; &amp;&amp; !!c) .forEach( (c) =&gt; (thisRow[c.field] = params.getValue(params.id, c.field)) ); return alert(JSON.stringify(thisRow, null, 4)); }; return &lt;Button onClick={onClick}&gt;Click&lt;/Button&gt;; } }, ]; </code></pre> <p><a href="https://codesandbox.io/s/64331095cant-add-a-button-to-every-row-in-material-ui-table-vmnd9?file=/demo.tsx" rel="noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit 64331095/cant-add-a-button-to-every-row-in-material-ui-table" /></a></p>
30,141,204
Calling R as a web service with parameters and load a JSON?
<p>I am pretty new with <code>R</code>. What I am trying to do is to be able to load a URL from another application (Java) which will run an <code>R</code> script and output a <code>JSON</code> so my application can work with it.</p> <p>I understand there are some frameworks like <code>shiny</code> which act as web servers for R, but I can't find documentation on those frameworks on how to pass parameters via the URL so R can use them.</p> <p>Ideally I will need to call a URL like:</p> <pre><code>http://127.0.0.1/R/param1/param2 </code></pre> <p>And that URL will call an R script which will use <code>param1</code> and <code>param2</code> to perform some functions and return a <code>JSON</code> which I will then read from my app.</p>
30,579,225
3
4
null
2015-05-09 14:38:33.007 UTC
11
2020-06-29 16:46:19.977 UTC
2015-05-09 21:25:04.05 UTC
null
3,093,387
null
402,933
null
1
19
json|r|web-services|shiny
12,681
<p>If you have not done so yet please checkout <a href="http://deployr.revolutionanalytics.com/" rel="nofollow noreferrer">[DeployR]</a>. You can also post questions to the <strong>DeployR Google Group</strong> for help.</p> <p>For full disclose I am one of the authors of <strong>DeployR</strong></p> <p><strong>Overview</strong></p> <p>DeployR is an integration technology for deploying R analytics inside web, desktop,mobile,and dashboard applications as well as backend systems. DeployR turns your R scripts into analytics web services, so R code can be easily executed by applications running on a secure server.</p> <p>Using analytics web services, DeployR also solves key integration problems faced by those adopting R-based analytics alongside existing IT infrastructure. These services make it easy for application developers to collaborate with data scientists to integrate R analytics into their applications without any R programming knowledge.</p> <p>DeployR is available in two editions: <strong>DeployR Open</strong> and <strong>DeployR Enterprise</strong>. <strong>DeployR</strong> Open is a free, open source solution that is ideal for prototyping, building, and deploying non-critical business applications. <strong>DeployR Enterprise</strong> scales for business-critical applications and offers support for production-grade workloads, as well as seamless integration with popular enterprise security solutions such as single sign-on (SSO), Lightweight Directory Access Protocol (LDAP), Active Directory, or Pluggable Authentication Modules (PAM).</p> <blockquote> <p>I am pretty new with R</p> </blockquote> <p>Prefect. DeployR is intended for both the Data Scientist as well as the application developer who might not know R.</p> <blockquote> <p>What I am trying to do is to be able to load a URL from another application (Java) which will run an R script and output a JSON so my application can work with it.</p> </blockquote> <p>DeployR does this quit well. To aid in the communication between your application and the DeployR server (that will be executing your R) there are the <a href="http://deployr.revolutionanalytics.com/docanddown/#clientlib" rel="nofollow noreferrer">DeployR Client libraries</a>.</p> <p>Depending on your needs, DeployR has out-of-the-box 'client library' support in:</p> <ul> <li><a href="https://github.com/deployr/java-client-library" rel="nofollow noreferrer">Java-client-library</a>: <code>https://github.com/deployr/java-client-library</code></li> <li><a href="https://github.com/deployr/dotnet-client-library" rel="nofollow noreferrer">.NET-client-library</a>: <code>https://github.com/deployr/dotnet-client-library</code></li> <li><a href="https://github.com/deployr/js-client-library" rel="nofollow noreferrer">JavaScript and Node.js-library</a>: <code>https://github.com/deployr/js-client-library</code></li> </ul> <p>DeployR also supports the <a href="http://deployr.revolutionanalytics.com/documents/dev/rbroker/" rel="nofollow noreferrer">RBroker Framework</a> </p> <p>should your use-case or runtime anticipate a high-volume workload or the need for periodic, scheduled or batch processing.</p> <blockquote> <p>I understand there are some frameworks like shiny which act as web servers for R, but I can't find documentation on those frameworks on how to pass parameters via the URL so R can use them</p> </blockquote> <p>DeployR acts as your analytics engine through its APIS. Basically think of it as turning your R scripts into secure analytic web services to be consumed like any other web service.</p> <p><strong>Pass parameters</strong></p> <p>Passing parameters to an R Script in DeployR is easy, however you have to understand that you are passing parameters to an R Script from a language that is not R. As such, there is some 'Data Encoding' that needs to be done. For example, turn your Java String into an <code>R character</code> or your Java boolean to an <code>R logical</code>... The DeployR Client library or RBroker makes this easy.</p> <p>It sounds like you are using Java, so first review the Java tutorial <strong>java-example-client-basics</strong> <code>https://github.com/deployr/java-example-rbroker-basics</code> to give you some context then checkout the many Java examples under <strong>java-example-client-data-io</strong> <code>https://github.com/deployr/java-example-client-data-io</code>. The example source is fully available so that should give you everything you need in order to understand how to do basic I/O from your application to the DeployR server for your R analytics.</p> <blockquote> <p>Ideally I will need to call a URL like: <code>http://127.0.0.1/R/param1/param2</code></p> </blockquote> <p>I suggest using the <strong>DeployR Client libraries</strong> for your communication as described above, it does just that.</p> <p>As always post questions to the <em>DeployR Google Group</em> <code>https://groups.google.com/forum/#!forum/deployr</code> for help.</p>
10,806,345
@RunWith(MockitoJUnitRunner.class) vs MockitoAnnotations.initMocks(this)
<p>While writing a new jUnit4 test, I'm wondering whether to use <code>@RunWith(MockitoJUnitRunner.class)</code> or <code>MockitoAnnotations.initMocks(this)</code>.</p> <p>I created a new test &amp; the wizard automatically generated a test with the Runner. Javadocs for MockitoJUnitRunner state the following:</p> <blockquote> <p>Compatible with JUnit 4.4 and higher, this runner adds following behavior:</p> <p>Initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method. Validates framework usage after each test method.</p> </blockquote> <p>It's not clear to me whether using the Runner has any advantage over the <code>initMocks()</code> method I have been using in past.</p>
10,812,752
2
1
null
2012-05-29 20:34:46.337 UTC
51
2020-09-13 00:40:41.763 UTC
2020-09-13 00:40:41.763 UTC
null
1,173,112
null
289,918
null
1
140
java|junit4|mockito
123,893
<p><code>MockitoJUnitRunner</code> gives you automatic validation of framework usage, as well as an automatic <code>initMocks()</code>.</p> <p>The automatic validation of framework usage is actually worth having. It gives you better reporting if you make one of these mistakes.</p> <ul> <li><p>You call the static <code>when</code> method, but don't complete the stubbing with a matching <code>thenReturn</code>, <code>thenThrow</code> or <code>then</code>. <em>(Error 1 in the code below)</em></p></li> <li><p>You call <code>verify</code> on a mock, but forget to provide the method call that you are trying to verify. <em>(Error 2 in the code below)</em></p></li> <li><p>You call the <code>when</code> method after <code>doReturn</code>, <code>doThrow</code> or <code>doAnswer</code> and pass a mock, but forget to provide the method that you are trying to stub. <em>(Error 3 in the code below)</em></p></li> </ul> <p>If you don't have validation of framework usage, these mistakes are not reported until the <em>following</em> call to a Mockito method. This might be </p> <ul> <li>in the same test method (like error 1 below), </li> <li>in the next test method (like error 2 below), </li> <li>in the next test class. </li> </ul> <p>If they occur in the last test that you run (like error 3 below), they won't be reported at all.</p> <p>Here's how each of those types of errors might look. Assume here that JUnit runs these tests in the order they're listed here.</p> <pre><code>@Test public void test1() { // ERROR 1 // This compiles and runs, but it's an invalid use of the framework because // Mockito is still waiting to find out what it should do when myMethod is called. // But Mockito can't report it yet, because the call to thenReturn might // be yet to happen. when(myMock.method1()); doSomeTestingStuff(); // ERROR 1 is reported on the following line, even though it's not the line with // the error. verify(myMock).method2(); } @Test public void test2() { doSomeTestingStuff(); // ERROR 2 // This compiles and runs, but it's an invalid use of the framework because // Mockito doesn't know what method call to verify. But Mockito can't report // it yet, because the call to the method that's being verified might // be yet to happen. verify(myMock); } @Test public void test3() { // ERROR 2 is reported on the following line, even though it's not even in // the same test as the error. doReturn("Hello").when(myMock).method1(); // ERROR 3 // This compiles and runs, but it's an invalid use of the framework because // Mockito doesn't know what method call is being stubbed. But Mockito can't // report it yet, because the call to the method that's being stubbed might // be yet to happen. doReturn("World").when(myMock); doSomeTestingStuff(); // ERROR 3 is never reported, because there are no more Mockito calls. } </code></pre> <p>Now when I first wrote this answer more than five years ago, I wrote</p> <blockquote> <p>So I would recommend the use of the <code>MockitoJUnitRunner</code> wherever possible. However, as Tomasz Nurkiewicz has correctly pointed out, you can't use it if you need another JUnit runner, such as the Spring one.</p> </blockquote> <p>My recommendation has now changed. The Mockito team have added a new feature since I first wrote this answer. It's a JUnit rule, which performs exactly the same function as the <code>MockitoJUnitRunner</code>. But it's better, because it doesn't preclude the use of other runners.</p> <p>Include </p> <pre><code>@Rule public MockitoRule rule = MockitoJUnit.rule(); </code></pre> <p>in your test class. This initialises the mocks, and automates the framework validation; just like <code>MockitoJUnitRunner</code> does. But now, you can use <code>SpringJUnit4ClassRunner</code> or any other JUnitRunner as well. From Mockito 2.1.0 onwards, there are additional options that control exactly what kind of problems get reported.</p>
7,549,177
Expires vs max-age, which one takes priority if both are declared in a HTTP response?
<p>If a HTTP response that returns both Expires and max-age indications which one is used?</p> <pre><code>Cache-Control: max-age=3600 Expires: Tue, 15 May 2008 07:19:00 GMT </code></pre> <p>Considering that each one refers to a different point in time.</p>
7,549,558
2
0
null
2011-09-25 22:56:54.437 UTC
9
2019-10-22 06:28:40.903 UTC
2014-01-23 20:56:48.07 UTC
null
2,642,204
null
307,976
null
1
49
http|http-headers|cache-control|http-caching
25,214
<p>See this answer:</p> <p><a href="https://stackoverflow.com/questions/3740952/difference-between-three-htaccess-expire-rules/3746325#3746325">Difference between three .htaccess expire rules</a></p> <blockquote> <p>If a response includes both an Expires header and a max-age directive, <strong>the max-age directive overrides the Expires header</strong>, even if the Expires header is more restrictive. This rule allows an origin server to provide, for a given response, a longer expiration time to an HTTP/1.1 (or later) cache than to an HTTP/1.0 cache. This might be useful if certain HTTP/1.0 caches improperly calculate ages or expiration times, perhaps due to desynchronized clocks.</p> </blockquote>
18,892,560
Is there any way in Elasticsearch to get results as CSV file in curl API?
<p>I am using elastic search. I need results from elastic search as a CSV file. Any curl URL or any plugins to achieve this?</p>
22,945,812
9
1
null
2013-09-19 10:46:24.35 UTC
17
2022-04-05 09:43:44.323 UTC
2019-08-11 19:02:43.183 UTC
null
10,607,772
null
1,410,115
null
1
61
csv|elasticsearch
90,646
<p>I've done just this using cURL and <a href="http://stedolan.github.io/jq/">jq</a> ("like <code>sed</code>, but for JSON"). For example, you can do the following to get CSV output for the top 20 values of a given facet:</p> <pre><code>$ curl -X GET 'http://localhost:9200/myindex/item/_search?from=0&amp;size=0' -d ' {"from": 0, "size": 0, "facets": { "sourceResource.subject.name": { "global": true, "terms": { "order": "count", "size": 20, "all_terms": true, "field": "sourceResource.subject.name.not_analyzed" } } }, "sort": [ { "_score": "desc" } ], "query": { "filtered": { "query": { "match_all": {} } } } }' | jq -r '.facets["subject"].terms[] | [.term, .count] | @csv' "United States",33755 "Charities--Massachusetts",8304 "Almshouses--Massachusetts--Tewksbury",8304 "Shields",4232 "Coat of arms",4214 "Springfield College",3422 "Men",3136 "Trees",3086 "Session Laws--Massachusetts",2668 "Baseball players",2543 "Animals",2527 "Books",2119 "Women",2004 "Landscape",1940 "Floral",1821 "Architecture, Domestic--Lowell (Mass)--History",1785 "Parks",1745 "Buildings",1730 "Houses",1611 "Snow",1579 </code></pre>
35,582,521
How to calculate receptive field size?
<p>I'm reading paper about using CNN(Convolutional neural network) for object detection.</p> <p><a href="https://www.cs.berkeley.edu/~rbg/papers/r-cnn-cvpr.pdf" rel="noreferrer">Rich feature hierarchies for accurate object detection and semantic segmentation</a></p> <p>Here is a quote about receptive field:</p> <pre><code>The pool5 feature map is 6x6x256 = 9216 dimensional. Ignoring boundary effects, each pool5 unit has a receptive field of 195x195 pixels in the original 227x227 pixel input. A central pool5 unit has a nearly global view, while one near the edge has a smaller, clipped support. </code></pre> <p>My questions are:</p> <ol> <li>What is definition of receptive field?</li> <li>How they compute size and location of receptive field?</li> <li>How we can compute bounding rect of receptive field using caffe/pycaffe? </li> </ol>
35,582,860
6
2
null
2016-02-23 16:11:44.917 UTC
9
2019-12-11 17:25:49.513 UTC
2019-12-04 14:48:28.153 UTC
null
3,104,974
null
1,179,925
null
1
21
deep-learning|computer-vision|receptive-field
26,972
<p>1) It is the size of the area of pixels that impact the output of the last convolution. </p> <p>2) For each convolution and pooling operation, compute the size of the output. Now find the input size that results in an output size of 1x1. Thats the size of the receptive field</p> <p>3) You don't need to use a library to do it. For every 2x2 pooling the output size is reduced by half along each dimension. For strided convolutions, you also divide the size of each dimension by the stride. You may have to shave off some of the dimension depending on if you use padding for your convolutions. The simplest case is to use padding = floor(kernel size/2), so that a convolution dose not have any extra change on the output size. </p>
3,865,934
Self Executing functions in PHP5.3?
<p>I was trying to borrow some programing paradigms from JS to PHP (just for fun). Is there a way of doing:</p> <pre><code>$a = (function(){ return 'a'; })(); </code></pre> <p>I was thinking that with the combination of <code>use</code> this can be a nice way to hide variables JS style</p> <pre><code>$a = (function(){ $hidden = 'a'; return function($new) use (&amp;$hidden){ $hidden = $new; return $hidden; }; })(); </code></pre> <p>right now I need to do:</p> <pre><code>$temp = function(){....}; $a = $temp(); </code></pre> <p>It seems pointless...</p>
3,865,976
1
4
null
2010-10-05 16:59:02.007 UTC
10
2016-06-29 06:11:47.13 UTC
null
null
null
null
87,222
null
1
36
php|lambda|closures|php-5.3
14,111
<p><a href="http://wiki.php.net/rfc/fcallfcall" rel="noreferrer">Function Call Chaining, e.g. <code>foo()()</code> is in discussion for PHP5.4.</a> Until then, use <code>call_user_func</code>:</p> <pre><code>$a = call_user_func(function(){ $hidden = 'a'; return function($new) use (&amp;$hidden){ $hidden = $new; return $hidden; }; }); $a('foo'); var_dump($a); </code></pre> <p>gives:</p> <pre><code>object(Closure)#2 (2) { ["static"]=&gt; array(1) { ["hidden"]=&gt; string(3) "foo" } ["parameter"]=&gt; array(1) { ["$new"]=&gt; string(10) "&lt;required&gt;" } } </code></pre> <p>As of PHP7, you can immediately execute anonymous functions like this:</p> <pre><code>(function() { echo 123; })(); // will print 123 </code></pre>
18,249,847
How to build a protocol on top of tcp?
<p>I was searching a lot but I could not find any resources which go through the building of an own protocol which uses TCP as a transport layer. What are the necessary steps? The protocol should be some kind of "Control protocol" for devices. So I can send commands to devices and control them and get information back.</p> <p>So how would one implement a custom protocol? Is it all about defininig <code>what</code> commands can be sent and <code>how</code> the receiver reacts to different commands? Say I am defining some custom commands with <code>xml</code> send them over the wire/air, using tcp, and have some logic there which reacts to the sent command and replies. Is this a way one could implement a "protocol" ? Is this even called a "protocol"? </p> <p>kind regards.</p>
18,250,112
1
1
null
2013-08-15 09:27:30.827 UTC
18
2021-06-11 05:58:50.273 UTC
2016-02-02 07:51:37.62 UTC
null
1,291,235
null
1,291,235
null
1
21
networking|tcp|network-programming|protocols
16,857
<p>As long as you can write a specification that defines the data you send through the TCP socket, you've got your own protocol.</p> <p>It's mostly about defining commands and payloads. You've got to serialize your command packet before putting them through TCP. Endianness is a common pitfall if you pack the packet in <em>binary format</em>. XML and JSON are common <em>text-based</em> data exchange formats. Personally I'm pro-JSON.</p> <p>Do refer to <a href="http://bsonspec.org/" rel="nofollow noreferrer">BSON</a>, <a href="https://msgpack.org/" rel="nofollow noreferrer">MessagePack</a> or <a href="https://github.com/google/protobuf" rel="nofollow noreferrer">protobuf</a> for binary serialization. They pack the <strong>typed</strong> data into binary so they are usually more performant, more compact in size and have better type checking than text based serialization. They also handle endian conversion, packet versioning and provide drivers/bindings in various languages. The server and client could have been written in different languages.</p> <p><strong>EDIT: added RFC samples</strong></p> <p>Seeing the comment by Ross Patterson, I also recommend reading RFC for protocol definition references. <a href="https://www.rfc-editor.org/rfc/rfc2326" rel="nofollow noreferrer">RTSP</a> and <a href="https://www.rfc-editor.org/rfc/rfc2616" rel="nofollow noreferrer">HTTP</a> are text protocols, <a href="https://www.rfc-editor.org/rfc/rfc3550" rel="nofollow noreferrer">RTP</a> and media formats (<a href="https://www.rfc-editor.org/rfc/rfc3640" rel="nofollow noreferrer">MPEG4 AV</a>, <a href="https://www.rfc-editor.org/rfc/rfc6184" rel="nofollow noreferrer">H-264</a>) are binary protocols.</p> <p><strong>EDIT:</strong></p> <p><a href="http://www.infoq.com/interviews/protocol-serialization-todd-montgomery" rel="nofollow noreferrer">Demystifying Protocols and Serialization Performance with Todd Montgomery</a></p>
18,320,731
Jackson @JsonProperty(required=true) doesn't throw an exception
<p>I am using jackson 2.2 annotation @JsonProperty with required set to true. While deserializing json file which doesn't contain that property via ObjectMapper readValue() method no exception is being thrown. Is it supposed to work in a different way or did I missed something?</p> <p>My dto class:</p> <pre><code>public class User { public enum Gender {MALE, FEMALE} ; public static class Name { private String _first, _last; public String getFirst() { return _first; } public String getLast() { return _last; } public void setFirst(String s) { _first = s; } public void setLast(String s) { _last = s; } } private Gender _gender; private Name _name; private boolean _isVerified; private byte[] _userImage; @JsonProperty(value ="NAAME",required = true) public Name getName() { return _name; } @JsonProperty("VERIFIED") public boolean isVerified() { return _isVerified; } @JsonProperty("GENDER") public Gender getGender() { return _gender; } @JsonProperty("IMG") public byte[] getUserImage() { return _userImage; } @JsonProperty(value ="NAAME",required = true) public void setName(Name n) { _name = n; } @JsonProperty("VERIFIED") public void setVerified(boolean b) { _isVerified = b; } @JsonProperty("GENDER") public void setGender(Gender g) { _gender = g; } @JsonProperty("IMG") public void setUserImage(byte[] b) { _userImage = b; } } </code></pre> <p>This is how do I deserialize the class:</p> <pre><code>public class Serializer { private ObjectMapper mapper; public Serializer() { mapper = new ObjectMapper(); SimpleModule sm = new SimpleModule("PIF deserialization"); mapper.registerModule(sm); } public void writeUser(File filename, User user) throws IOException { mapper.writeValue(filename, user); } public User readUser(File filename) throws IOException { return mapper.readValue(filename, User.class); } } </code></pre> <p>This is how it is actually called:</p> <pre><code> Serializer serializer = new Serializer(); User result = serializer.readUser(new File("user.json")); </code></pre> <p>Actuall json looks like:</p> <pre><code>{"GENDER":"FEMALE","VERIFIED":true,"IMG":"AQ8="} </code></pre> <p>I would expect that since _name is not specified in json file and is required that the exception will be thrown.</p>
18,324,899
2
0
null
2013-08-19 18:37:57.287 UTC
4
2017-08-29 02:41:58.253 UTC
2016-03-18 08:49:33.13 UTC
null
918,959
null
1,221,966
null
1
58
java|json|jackson
105,759
<p>As per Jackson annotations <a href="http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonProperty.html#required%28%29">javadocs</a>: "Note that as of 2.0, this property is NOT used by BeanDeserializer: support is expected to be added for a later minor version."</p> <p>That is: no validation is performed using this settings. It is only (currently) used for generating JSON Schema, or by custom code.</p>
1,747,519
How to hide Gtk Popup Window when user clickes outside the window
<p>I have developed one popup window (Non decorated) using GTK+ and glade tool in C. It popup on its parent window when a button clicked. I want to destroy or hide this popup window when user clicks out side this window. User can click on parent window or any other window. I have tried to capture <code>GDK_FOCUS_CHANGE</code> event but I am not able to capture this event. Is there any way to achieve this? How do I know that click is on other window then pop up window? How is it clear that pop up window has lost it's focus? So that I can hide it. The relevant code is as follow:</p> <pre><code>/* * Compile me with: gcc -o popup popup.c $(pkg-config --cflags --libs gtk+-2.0 gmodule-2.0) */ #include &lt;gtk/gtk.h&gt; static void on_popup_clicked (GtkButton*, GtkWidget*); static gboolean on_popup_window_event(GtkWidget*, GdkEventExpose*); int main (int argc, char *argv[]) { GtkWidget *window, *button, *vbox; gtk_init (&amp;argc, &amp;argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (window), "Parent window"); gtk_container_set_border_width (GTK_CONTAINER (window), 10); gtk_widget_set_size_request (window, 300, 300); gtk_window_set_position (GTK_WINDOW (window),GTK_WIN_POS_CENTER); button = gtk_button_new_with_label("Pop Up"); g_signal_connect (G_OBJECT (button), "clicked",G_CALLBACK (on_popup_clicked),(gpointer) window); vbox = gtk_vbox_new (FALSE, 3); gtk_box_pack_end(GTK_BOX (vbox), button, FALSE, FALSE, 5); gtk_container_add (GTK_CONTAINER (window), vbox); gtk_widget_show_all (window); gtk_main (); return 0; } void on_popup_clicked (GtkButton* button, GtkWidget* pWindow) { GtkWidget *popup_window; popup_window = gtk_window_new (GTK_WINDOW_POPUP); gtk_window_set_title (GTK_WINDOW (popup_window), "Pop Up window"); gtk_container_set_border_width (GTK_CONTAINER (popup_window), 10); gtk_window_set_resizable(GTK_WINDOW (popup_window), FALSE); gtk_window_set_decorated(GTK_WINDOW (popup_window), FALSE); gtk_widget_set_size_request (popup_window, 150, 150); gtk_window_set_transient_for(GTK_WINDOW (popup_window),GTK_WINDOW (pWindow)); gtk_window_set_position (GTK_WINDOW (popup_window),GTK_WIN_POS_CENTER); g_signal_connect (G_OBJECT (button), "event", G_CALLBACK (on_popup_window_event),NULL); GdkColor color; gdk_color_parse("#3b3131", &amp;color); gtk_widget_modify_bg(GTK_WIDGET(popup_window), GTK_STATE_NORMAL, &amp;color); gtk_widget_show_all (popup_window); } gboolean on_popup_window_event(GtkWidget *popup_window, GdkEventExpose *event) { if(event-&gt;type == GDK_FOCUS_CHANGE) gtk_widget_hide (popup_window); return FALSE; } </code></pre> <p>Here I am not able to hide this pop up window when user clicks on parent window or on other window. How can I do this? </p> <p>I have to stick with Gtk+2.14 version.</p>
1,748,436
3
2
null
2009-11-17 09:11:50.06 UTC
9
2015-11-01 11:34:23.69 UTC
2009-11-17 17:04:41.28 UTC
null
140,814
null
202,635
null
1
13
c|gtk
12,276
<p>Changes:</p> <ul> <li>switch from <code>GTK_WINDOW_POPUP</code> to <code>GTK_WINDOW_TOPLEVEL</code>, counter-intuitive, but I could not figure out how to get a popup to accept focus.</li> <li>add <code>gtk_window</code> hints to prevent popup from showing in taskbar and pager</li> <li>intentionally set the focus on the popup window</li> <li>set the <code>GDK_FOCUS_CHANGE_MASK</code> on the <code>GDK_WINDOW</code> with <code>gtk_widget_set_events</code> (required for the next step)</li> <li>connect to the <code>focus-out-event</code> of the popup window</li> <li>change the signal handler to handle a different signal</li> </ul> <p>I would also suggest reading the GTK+ source to see how it handles popup windows for tooltips and menus when they are shown... but those are usually destroyed based on the mouse moving out of range, not the popup losing focus, per se.</p> <pre><code> #include static void on_popup_clicked (GtkButton*, GtkWidget*); gboolean on_popup_focus_out (GtkWidget*, GdkEventFocus*, gpointer); int main (int argc, char *argv[]) { GtkWidget *window, *button, *vbox; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (window), "Parent window"); gtk_container_set_border_width (GTK_CONTAINER (window), 10); gtk_widget_set_size_request (window, 300, 300); gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER); button = gtk_button_new_with_label ("Pop Up"); g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (on_popup_clicked), (gpointer) window); vbox = gtk_vbox_new (FALSE, 3); gtk_box_pack_end (GTK_BOX (vbox), button, FALSE, FALSE, 5); gtk_container_add (GTK_CONTAINER (window), vbox); gtk_widget_show_all (window); gtk_main (); return 0; } void on_popup_clicked (GtkButton* button, GtkWidget* pWindow) { GtkWidget *popup_window; popup_window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (popup_window), "Pop Up window"); gtk_container_set_border_width (GTK_CONTAINER (popup_window), 10); gtk_window_set_resizable (GTK_WINDOW (popup_window), FALSE); gtk_window_set_decorated (GTK_WINDOW (popup_window), FALSE); gtk_window_set_skip_taskbar_hint (GTK_WINDOW (popup_window), TRUE); gtk_window_set_skip_pager_hint (GTK_WINDOW (popup_window), TRUE); gtk_widget_set_size_request (popup_window, 150, 150); gtk_window_set_transient_for (GTK_WINDOW (popup_window), GTK_WINDOW (pWindow)); gtk_window_set_position (GTK_WINDOW (popup_window), GTK_WIN_POS_CENTER); gtk_widget_set_events (popup_window, GDK_FOCUS_CHANGE_MASK); g_signal_connect (G_OBJECT (popup_window), "focus-out-event", G_CALLBACK (on_popup_focus_out), NULL); GdkColor color; gdk_color_parse ("#3b3131", &color); gtk_widget_modify_bg (GTK_WIDGET (popup_window), GTK_STATE_NORMAL, &color); gtk_widget_show_all (popup_window); gtk_widget_grab_focus (popup_window); } gboolean on_popup_focus_out (GtkWidget *widget, GdkEventFocus *event, gpointer data) { gtk_widget_destroy (widget); return TRUE; } </code></pre>
2,293,970
error: expected unqualified-id before ‘for’
<p>The following code returns this: <code>error: expected unqualified-id before ‘for’</code></p> <p>I can't find what is causing the error. Thanks for the help!</p> <pre><code>#include&lt;iostream&gt; using namespace std; const int num_months = 12; struct month { string name; int n_days; }; month *months = new month [num_months]; string m[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int n[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int i=0; i&lt;num_months; i++) { // will initialize the months } int main() { // will print name[i]: days[i] return 0; } </code></pre>
2,293,978
3
1
null
2010-02-19 03:59:34.39 UTC
5
2022-02-23 11:33:38.073 UTC
null
null
null
null
253,197
null
1
22
c++
77,355
<p>Your <code>for</code> loop is outside a function body.</p>
1,430,956
Should I output warnings to STDERR or STDOUT?
<p>I'm making a script that handles a predefined set of data, outputting to a file. I want to pop up a warning when one datum (which is always "Regular" in every set that I've had access to) is different stating that this value is unhandled (since I don't know how it affects the data). Should I output this warning to stderr or stdout?</p>
1,430,971
3
0
null
2009-09-16 04:34:26.537 UTC
11
2022-04-08 06:02:29.967 UTC
2009-09-16 04:39:52.72 UTC
null
34,799
null
34,799
null
1
36
warnings|stdout|stderr
8,938
<p>If I save the output of this script (i.e. stdout only) so that I could process it later, would that warning interfere with how the output is parsed? Moreover, if output is piped to another process, the warning should show up on the terminal, so the user sees it immediately.</p> <p>For those reasons, in general, you output warnings to stderr.</p>
8,790,079
Animate infinite scrolling of an image in a seamless loop
<p>Currently I have an image of clouds of 2048x435 that scrolls across a Landscaped oriented UIImageView of 1024x435 using CABasicAnimation. The cloud image scrolls as it should, however I am having some trouble trying to to get a duplicate clouds image to connect to the back of the the current clouds image so that there is no gap between the clouds images. I've been struggling for about a day trying to find a solution, so any help would be greatly appreciated. My current code:</p> <p>developing on Xcode 4.2 for iOS 5 with ARC non-storyboard ipad landscaped orientation.</p> <pre><code>-(void)cloudScroll { UIImage *cloudsImage = [UIImage imageNamed:@"TitleClouds.png"]; CALayer *cloud = [CALayer layer]; cloud.contents = (id)cloudsImage.CGImage; cloud.bounds = CGRectMake(0, 0, cloudsImage.size.width, cloudsImage.size.height); cloud.position = CGPointMake(self.view.bounds.size.width / 2, cloudsImage.size.height / 2); [cloudsImageView.layer addSublayer:cloud]; CGPoint startPt = CGPointMake(self.view.bounds.size.width + cloud.bounds.size.width / 2, cloud.position.y); CGPoint endPt = CGPointMake(cloud.bounds.size.width / -2, cloud.position.y); CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"]; anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; anim.fromValue = [NSValue valueWithCGPoint:startPt]; anim.toValue = [NSValue valueWithCGPoint:endPt]; anim.repeatCount = HUGE_VALF; anim.duration = 60.0; [cloud addAnimation:anim forKey:@"position"]; } -(void)viewDidLoad { [self cloudScroll]; [super viewDidLoad]; } </code></pre>
8,794,252
3
1
null
2012-01-09 14:39:37.367 UTC
15
2017-04-07 01:00:22.49 UTC
2012-01-09 20:08:55.683 UTC
null
77,567
null
1,089,875
null
1
22
objective-c|xcode|cocoa-touch|ipad
12,039
<p>You say that your image is 2048 wide and your view is 1024 wide. I don't know if this means you have duplicated the contents of a 1024-wide image to make a 2048-wide image.</p> <p>Anyway, here's what I suggest. We'll need to store the cloud layer and its animation in instance variables:</p> <pre><code>@implementation ViewController { CALayer *cloudLayer; CABasicAnimation *cloudLayerAnimation; } </code></pre> <p>Instead of setting the cloud layer's content to the cloud image, we set its background color to a pattern color created from the image. That way, we can set the layer's bounds to whatever we want and the image will be tiled to fill the bounds:</p> <pre><code>-(void)cloudScroll { UIImage *cloudsImage = [UIImage imageNamed:@"TitleClouds.png"]; UIColor *cloudPattern = [UIColor colorWithPatternImage:cloudsImage]; cloudLayer = [CALayer layer]; cloudLayer.backgroundColor = cloudPattern.CGColor; </code></pre> <p>However, a CALayer's coordinate system puts the origin at the lower left instead of the upper left, with the Y axis increasing up. This means that the pattern will be drawn upside-down. We can fix that by flipping the Y axis:</p> <pre><code> cloudLayer.transform = CATransform3DMakeScale(1, -1, 1); </code></pre> <p>By default, a layer's anchor point is at its center. This means that setting the layer's position sets the position of its center. It will be easier to position the layer by setting the position of its upper-left corner. We can do that by moving its anchor point to its upper-left corner:</p> <pre><code> cloudLayer.anchorPoint = CGPointMake(0, 1); </code></pre> <p>The width of the layer needs to be the width of the image plus the width of the containing view. That way, as we scroll the layer so that the right edge of the image comes into view, another copy of the image will be drawn to the right of the first copy.</p> <pre><code> CGSize viewSize = self.cloudsImageView.bounds.size; cloudLayer.frame = CGRectMake(0, 0, cloudsImage.size.width + viewSize.width, viewSize.height); </code></pre> <p>Now we're ready to add the layer to the view:</p> <pre><code> [self.cloudsImageView.layer addSublayer:cloudLayer]; </code></pre> <p>Now let's set up the animation. Remember that we changed the layer's anchor point, so we can control its position by setting the position of its upper-left corner. We want the layer's upper-left corner to start at the view's upper-left corner:</p> <pre><code> CGPoint startPoint = CGPointZero; </code></pre> <p>and we want the layer's upper-left corner to move left by the width of the image:</p> <pre><code> CGPoint endPoint = CGPointMake(-cloudsImage.size.width, 0); </code></pre> <p>The rest of the animation setup is the same as your code. I changed the duration to 3 seconds for testing:</p> <pre><code> cloudLayerAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; cloudLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; cloudLayerAnimation.fromValue = [NSValue valueWithCGPoint:startPoint]; cloudLayerAnimation.toValue = [NSValue valueWithCGPoint:endPoint]; cloudLayerAnimation.repeatCount = HUGE_VALF; cloudLayerAnimation.duration = 3.0; </code></pre> <p>We'll call another method to actually attach the animation to the layer:</p> <pre><code> [self applyCloudLayerAnimation]; } </code></pre> <p>Here's the method that applies the animation:</p> <pre><code>- (void)applyCloudLayerAnimation { [cloudLayer addAnimation:cloudLayerAnimation forKey:@"position"]; } </code></pre> <p>When the application enters the background (because the user switched to another app), the system removes the animation from the cloud layer. So we need to reattach it when we enter the foreground again. That's why we have the <code>applyCloudLayerAnimation</code> method. We need to call that method when the app enters the foreground.</p> <p>In <code>viewDidAppear:</code>, we can start observing the notification that tells us the app has entered the foreground:</p> <pre><code>- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; } </code></pre> <p>We need to stop observing the notification when our view disappears, or when the view controller is deallocated:</p> <pre><code>- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]; } </code></pre> <p>When the view controller actually receives the notification, we need to apply the animation again:</p> <pre><code>- (void)applicationWillEnterForeground:(NSNotification *)note { [self applyCloudLayerAnimation]; } </code></pre> <p>Here's all the code together for easy copy and paste:</p> <pre><code>- (void)viewDidLoad { [self cloudScroll]; [super viewDidLoad]; } -(void)cloudScroll { UIImage *cloudsImage = [UIImage imageNamed:@"TitleClouds.png"]; UIColor *cloudPattern = [UIColor colorWithPatternImage:cloudsImage]; cloudLayer = [CALayer layer]; cloudLayer.backgroundColor = cloudPattern.CGColor; cloudLayer.transform = CATransform3DMakeScale(1, -1, 1); cloudLayer.anchorPoint = CGPointMake(0, 1); CGSize viewSize = self.cloudsImageView.bounds.size; cloudLayer.frame = CGRectMake(0, 0, cloudsImage.size.width + viewSize.width, viewSize.height); [self.cloudsImageView.layer addSublayer:cloudLayer]; CGPoint startPoint = CGPointZero; CGPoint endPoint = CGPointMake(-cloudsImage.size.width, 0); cloudLayerAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; cloudLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; cloudLayerAnimation.fromValue = [NSValue valueWithCGPoint:startPoint]; cloudLayerAnimation.toValue = [NSValue valueWithCGPoint:endPoint]; cloudLayerAnimation.repeatCount = HUGE_VALF; cloudLayerAnimation.duration = 3.0; [self applyCloudLayerAnimation]; } - (void)applyCloudLayerAnimation { [cloudLayer addAnimation:cloudLayerAnimation forKey:@"position"]; } - (void)viewDidUnload { [self setCloudsImageView:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]; } - (void)applicationWillEnterForeground:(NSNotification *)note { [self applyCloudLayerAnimation]; } </code></pre>
8,413,009
How to create the delay of 1 sec before set the alpha of View?
<p>In My Application i am going to set the alpha after one animation. As like:</p> <pre><code>hideMenu = AnimationUtils.loadAnimation( getApplication(), R.anim.menu_layout_hide); menuLayout.startAnimation(hideMenu); menuLayout.setVisibility(View.GONE); </code></pre> <p>But i want to set the delay of 1 Sec before the Alpha set th the View. as Because of that i am not able to see the Animation of that layout. So How it is possibe ?</p> <p>Thanks.</p>
8,413,164
5
1
null
2011-12-07 09:28:45.9 UTC
6
2018-02-08 10:56:24.123 UTC
null
null
null
null
881,635
null
1
45
android|xml|animation|android-animation|layout-animation
57,992
<p>In your animation <code>xml</code> file you can use <code>android:startOffset</code> attribute:</p> <pre><code>android:startOffset int. The amount of milliseconds the animation delays after start() is called. </code></pre>
19,411,510
How do you change background color in the settings of JetBrain's IDE?
<p>What are the settings to change the background color in JetBrains' IDE?</p> <ul> <li>Project explorer pane</li> <li>Console pane </li> <li>Code editor</li> <li>Other Panes </li> </ul> <p>I'm running v12.1.6 Ultimate Version. Are there major differences between different versions of the software?</p>
19,449,932
8
1
null
2013-10-16 18:56:47.12 UTC
18
2021-08-12 06:40:20.26 UTC
2017-05-08 06:01:49.267 UTC
null
2,254,878
null
897,756
null
1
79
intellij-idea|ide|settings
111,199
<h3>Console pane:</h3> <p><code>Settings / Editor / Colors &amp; Fonts / Console colors</code></p> <p>Console, background</p> <h3>Project view:</h3> <p><code>Settings / File colors</code></p> <p>Add (Alt+insert), choose 'project files' scope, select a color.</p> <p>Uncheck the 'Use in editor tabs' checkbox, make sure to check 'Use in project view'</p> <h3>Main view (general):</h3> <p><code>Settings / Editor / Color &amp; fonts / General</code></p> <p>Text, Default text</p>
919,921
no ocijdbc9 in java.library.path
<p>When I try to run Java application, I receive the following error:</p> <blockquote> <p><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no ocijdbc9 in java.library.path</code></p> </blockquote> <p>I don't have a file <code>ocijdbc9.*</code> on my PC, but I have <code>ocijdbc10.dll</code> in <code>%ORACLE_HOME%\bin</code>.</p> <p><code>%ORACLE_HOME%</code> is correctly specified, so I think the problem is that the application is searching for the wrong version (9 instead of 10).</p> <p>Both Oracle and Java Builder are freshly installed, so the problem may be in project preferences? Do you have any ideas on how to search for the place where the wrong version is specified?</p>
919,988
4
0
null
2009-05-28 09:11:19.253 UTC
1
2018-09-28 14:06:42.127 UTC
2018-09-28 14:05:30.6 UTC
null
241,164
null
26,276
null
1
3
java|oracle|linker|linker-errors
38,157
<p>You're missing a file from your java CLASSPATH.</p> <p>You need to add the OCI jar to your classpath.</p> <p>For my oracle 10.0.2 install on windows it's located in </p> <pre><code>%ORACLE_HOME%\jdbc\lib\ojdbc14.jar </code></pre> <p>If your application requires ocijdbc9 then you'll have to download it from somewhere and add it to the CLASSPATH. I don't know where to download it from, try the oracle site</p>
1,013,916
How to enable JMX on Weblogic 10.x
<p>I have an application that is JMX enabled. It has its own JMX Agent and some MBeans. When I launch the application in WebLogic, I am able to connect to the JMX agent via the RMI url and perform the operations on MBeans via "<strong>JConsole</strong>". </p> <p>But when I get into the Weblogic console, I can not see any JMX consoles! How can I enable the JMX console in Weblogic ?</p>
1,099,117
4
0
null
2009-06-18 17:02:14.953 UTC
3
2012-06-05 11:44:31.103 UTC
2012-05-02 11:40:02.403 UTC
null
741,249
null
119,512
null
1
6
weblogic|jmx
41,354
<p>hope this helps,refer to this url -> <a href="http://forums.oracle.com/forums/thread.jspa?messageID=3570887" rel="nofollow noreferrer">http://forums.oracle.com/forums/thread.jspa?messageID=3570887</a> </p>
856,575
SQL Server 2008 takes up a lot of memory?
<p>I am conducting stress tests on my database, which is hosted on SQL Server 2008 64-bit running on a 64-bit machine with 10 GB of RAM.</p> <p>I have 400 threads. Each thread queries the database every second, but the query time does not take time, as the SQL profiler says that, but after 18 hours SQL Server uses up 7.2 GB of RAM and 7.2 GB of virtual memory.</p> <p>Is this normal behavior? How can I adjust SQL Server to clean up unused memory?</p>
856,607
4
2
null
2009-05-13 07:38:55.17 UTC
5
2022-08-12 15:53:38.77 UTC
2011-03-15 00:04:52.28 UTC
null
496,830
null
42,749
null
1
11
sql-server|sql-server-2008|memory-consumption
39,747
<p>SQL Server is designed to use as much memory as it can get its hands on, to improve performance by caching loads of stuff in memory. The recommendation is to use dedicated machines for SQL Server, which makes this a perfectly valid approach, as it isn't expecting anybody else to need the memory. So you shouldn't worry about this; it's perfectly normal.</p> <p>That said, if you're on a development machine rather than a live environment, you may wish to limit the amount of memory to stop your box being taken over. In this case the easiest ways is to open SQL Server Management Studio, right-click on the server and select "Properties", then on the "Memory" tab you can set the maximum server memory.</p>
897,552
Assert that arrays are equal in Visual Studio 2008 test framework
<p>Is there an easy way to check in a unit test that two arrays are equal (that is, have the same number of elements, and each element is the same?).</p> <p>In Java, I would use <code>assertArrayEquals (foo, bar);</code>, but there seems to be no equivalent for C#. I tried <code>Assert.AreEqual(new string[]{"a", "b"}, MyFunc("ab"));</code>, but even though the function returns an array with "a", "b" the check still fails</p> <p>This is using Visual Studio 2008 Team Suite, with the built-in unit test framework.</p>
897,570
4
0
null
2009-05-22 12:14:22.3 UTC
8
2010-05-04 22:07:10.367 UTC
null
null
null
null
39,912
null
1
86
c#|visual-studio-2008|unit-testing
39,703
<p>It's <code>CollectionAssert.AreEqual</code>, see also the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert(VS.80).aspx" rel="noreferrer">documentation for CollectionAssert</a>.</p>
22,356,313
Define Changeset for insert query in liquibase
<p>I have two table as following :</p> <pre><code>CREATE TABLE StudentMaster ( sId SERIAL, StudentName VARCHAR(50) ); CREATE TABLE StudentClassMap ( studnetId BIGINT UNSIGNED NOT NULL, studentClass VARCHAR(10), FOREIGN KEY (studnetId) REFERENCES StudentMaster (sId) ); </code></pre> <p>This is my insert query.</p> <pre><code>INSERT INTO StudentMaster (studentName) values ('Jay Parikh'); INSERT INTO StudentClassMap (studnetId, studentClass) values ((SELECT sId from StudentMaster where studentName='Jay Parikh'), 'M.Sc. 1st Year'); </code></pre> <p>I want to define <strong>ChangeSet</strong> for thes queries in <strong><code>liquibase</code></strong>.</p> <p>For First query <strong>ChangeSet</strong> will be :</p> <pre><code>&lt;changeSet author="unknown" id="insert-example"&gt; &lt;insert tableName="StudentMaster "&gt; &lt;column name="studentName" value="Jay Parikh"/&gt; &lt;/insert&gt; &lt;/changeSet&gt; </code></pre> <p>But I don't know how to define <strong>ChangeSet</strong> for another query.<br> Any help ? Thanks in advance.</p>
22,362,273
1
0
null
2014-03-12 15:30:37.427 UTC
1
2016-04-21 16:27:54.23 UTC
null
null
null
null
1,152,398
null
1
16
mysql|sql|liquibase|changeset|insert-query
42,484
<p>Use the valueComputed attribute:</p> <pre><code>&lt;changeSet author="unknown" id="insert-example-2"&gt; &lt;insert tableName="StudentClassMap"&gt; &lt;column name="studentId" valueComputed="(SELECT sId from StudentMaster where studentName='Jay Parikh')"/&gt; &lt;column name="studentClass" value="McSc. 1st Year"/&gt; &lt;/insert&gt; &lt;/changeSet&gt; </code></pre>
22,126,299
Change apk name with Gradle
<p>I have an Android project which uses Gradle for build process. Now I want to add two extra build types staging and production, so my build.gradle contains:</p> <pre><code>android { buildTypes { release { runProguard false proguardFile getDefaultProguardFile('proguard-android.txt') } staging { signingConfig signingConfigs.staging applicationVariants.all { variant -&gt; appendVersionNameVersionCode(variant, defaultConfig) } } production { signingConfig signingConfigs.production } } } </code></pre> <p>and my appndVersionNameVersionCode looks like:</p> <pre><code>def appendVersionNameVersionCode(variant, defaultConfig) { if(variant.zipAlign) { def file = variant.outputFile def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk") variant.outputFile = new File(file.parent, fileName) } def file = variant.packageApplication.outputFile def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk") variant.packageApplication.outputFile = new File(file.parent, fileName) } </code></pre> <p>If I execute task <em>assembleStaging</em> then I get proper name of my apk, but when I execute <em>assembleProduction</em> then I get changed names of my apk (like in staging case). For example:</p> <pre><code>MyApp-defaultFlavor-production-9.9.9-999.apk MyApp-defaultFlavor-production-9.9.9-999.apk </code></pre> <p>It looks like in production build type is executed <em>appendVersionNameVersionCode</em>. How can I avoid it?</p>
22,126,638
8
1
null
2014-03-02 10:14:28.78 UTC
18
2022-09-09 19:11:00.377 UTC
2015-07-08 12:11:58.617 UTC
null
1,331,451
null
343,096
null
1
44
android|gradle|apk|android-gradle-plugin
38,091
<p>As CommonsWare wrote in his comment, you should call <code>appendVersionNameVersionCode</code> only for staging variants. You can easily do that, just slightly modify your <code>appendVersionNameVersionCode</code> method, for example:</p> <pre><code>def appendVersionNameVersionCode(variant, defaultConfig) { //check if staging variant if(variant.name == android.buildTypes.staging.name){ if(variant.zipAlign) { def file = variant.outputFile def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk") variant.outputFile = new File(file.parent, fileName) } def file = variant.packageApplication.outputFile def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk") variant.packageApplication.outputFile = new File(file.parent, fileName) } } </code></pre>
30,520,265
Migrating from Spring 3 to Spring 4 - org.springframework.scheduling.quartz.CronTriggerBean
<p>I'm trying to migrate from spring 3.0.5 to spring 4.1.X .</p> <p>Spring 3 has Class named as "org.springframework.scheduling.quartz.CronTriggerBean"</p> <p>But Spring 4 doesn't include this class name.</p> <blockquote> <p>[5/28/15 20:10:16:798 EDT] 00000092 ClassPathXmlA W org.springframework.context.support.AbstractApplicationContext __refresh Exception encountered during context initialization - cancelling refresh attempt org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.scheduling.quartz.CronTriggerBean] for bean with name 'beanIdName' defined in class path resource [config/spring/WxsCacheContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.scheduling.quartz.CronTriggerBean at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1328)</p> </blockquote> <p>I have tried alternative like "spring-support" which has the same class. But no luck.</p> <p>After getting that jar, it is giving errors about the quartz</p> <blockquote> <p>[5/28/15 15:37:02:665 EDT] 0000006e SystemOut O ERROR (?:?) - java.lang.Exception: Bean from SpringUtils.getSpringBean(hostnameVerifierSetter) error message: Unable to initialize group definition. Group resource name [classpath*:beanRefFactory.xml], factory key [beanContext]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanContext' defined in URL [file:/C:/Program%20Files%20(x86)/IBM/WebSphere/AppServer/profiles/AppSrv01/installedApps/cellName/Project.ear/configurations/beanRefFactory.xml]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org.quartz.impl.JobDetailImpl</p> </blockquote>
30,530,557
2
1
null
2015-05-29 02:43:25.833 UTC
1
2016-12-14 03:11:23.987 UTC
2016-07-11 19:53:33.45 UTC
null
2,057,902
null
2,057,902
null
1
30
java|spring|spring-mvc|scheduled-tasks|quartz-scheduler
30,769
<p>From Spring 3.1+, Change the Class names for the CronTriggerFactoryBean &amp; JobDetailFactoryBean as like below</p> <pre><code> org.springframework.scheduling.quartz.CronTriggerBean org.springframework.scheduling.quartz.CronTriggerFactoryBean org.springframework.scheduling.quartz.JobDetailBean org.springframework.scheduling.quartz.JobDetailFactoryBean </code></pre> <p>So your steps are:</p> <p>Change</p> <blockquote> <p>CronTriggerBean to CronTriggerFactoryBean<br> JobDetailBean to JobDetailFactoryBean</p> </blockquote>
29,402,155
Android unit test not mocked
<p>I followed this guide <a href="https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support">https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support</a> but i am stuck with this error:</p> <pre><code>junit.framework.AssertionFailedError: Exception in constructor: testSaveJson (java.lang.RuntimeException: Method put in org.json.JSONObject not mocked. See https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support for details. </code></pre> <p>I modified by Gradle build like the guide says but it doesn't make a difference</p> <pre><code> testOptions { unitTests.returnDefaultValues = true } </code></pre>
30,759,769
5
1
null
2015-04-01 22:46:35.253 UTC
8
2021-10-18 08:08:38.5 UTC
2015-06-10 14:39:47.13 UTC
null
346,232
null
1,634,451
null
1
57
android|unit-testing|junit
26,304
<p>JSON is bundled up with the Android SDK, so you'll just be hitting a stub. You can pull in a JSON jar, which will provide real objects to use.</p> <p>To do this, you'll need to add this to your build.gradle:</p> <pre><code>testImplementation 'org.json:json:20140107' </code></pre> <p>Alternatively, you can download and include the jar.</p> <pre><code>testCompile files('libs/json.jar') </code></pre> <p>Note that the latest version of JSON is built for Java 8, so you'll need to grab <a href="http://mvnrepository.com/artifact/org.json/json/20140107" rel="noreferrer">20140107</a> You may also need to clean and rebuild the project.</p>
25,113,692
Create executable Jar file under Eclipse
<p>I created a Java application and I want to create jar file for this application. This application imported other external jar files by Build Path>Add External Jar File. How can I generate executable JAR file for this application in Ubuntu with these external libraries dependencies?</p>
25,114,143
2
2
null
2014-08-04 07:30:16.617 UTC
1
2020-12-16 13:56:37.91 UTC
2014-08-04 08:19:35.05 UTC
null
146,073
null
3,766,188
null
1
12
java|eclipse
73,058
<p>To create a new runnable JAR file in the workbench:</p> <ol> <li>From the menu bar's File menu, select Export.</li> <li>Expand the Java node and select Runnable JAR file. Click Next.</li> <li>In the Runnable JAR File Specification page, select a 'Java Application' launch configuration to use to create a runnable JAR.</li> <li>In the Export destination field, either type or click Browse to select a location for the JAR file.</li> <li>Select an appropriate library handling strategy.</li> <li>Optionally, you can also create an ANT script to quickly regenerate a previously created runnable JAR file.</li> </ol>
19,856,192
Run OpenGL on AWS GPU instances with CentOS
<p>I need to execute some off-screen rendering program on AWS EC2 GPU instance with CentOS. However, while I found that Ubuntu is very easy to setup, I cannot let CentOS work properly. </p> <p>The goal is to run some essential utility/test tool on EC2 GPU instance (without screen or X client). In the following article, I will describe how the Ubuntu can be setup and how CentOS/Amazon Linux AMI fails. </p> <h2>Ubuntu</h2> <p>On ubuntu 12.04, everything works very smoothly. The EC2 environment I used are: </p> <ul> <li>Instance type: Both CG1 and G2 were tested and worked properly. </li> <li>AMI image: Ubuntu Server 12.04.3 LTS for HVM Instances (ami-b93264d0 in US-East)</li> <li>Most of the other settings are default. </li> </ul> <p>After the instance is launched, the following commands are executed:</p> <pre><code># Install the Nvidia driver sudo apt-add-repository ppa:ubuntu-x-swat/x-updates sudo apt-get update sudo apt-get install nvidia-current # Driver installation needs reboot sudo reboot now # Install and configure X window with virtual screen sudo apt-get install xserver-xorg libglu1-mesa-dev freeglut3-dev mesa-common-dev libxmu-dev libxi-dev sudo nvidia-xconfig -a --use-display-device=None --virtual=1280x1024 sudo /usr/bin/X :0 &amp; # OpenGL programs are now workable. Ex. glxinfo, glxgears DISPLAY=:0 glxinfo </code></pre> <p>The <code>glxgears</code> can also run in the background without physical screen or X client:</p> <pre><code>$ DISPLAY=:0 glxgears 95297 frames in 5.0 seconds = 19059.236 FPS 95559 frames in 5.0 seconds = 19111.727 FPS 94173 frames in 5.0 seconds = 18834.510 FPS </code></pre> <h2>CentOS or Amazon Linux AMI</h2> <p>Both "CentOS" and "Amazon Linux AMI" are derived from Red Hat Enterprise edition. However, I cannot make any of them work.</p> <p>A few days ago, AWS <a href="http://aws.typepad.com/aws/2013/11/build-3d-streaming-applications-with-ec2s-new-g2-instance-type.html">announced their new G2 instance type</a>. In this article, the <a href="https://aws.amazon.com/marketplace/pp/B00FYCDDTE">Amazon Linux AMI with NVIDIA Drivers</a> is recommended for Linux platform. In this AMI, the Nvidia driver, X window and OpenGL libraries are all installed. However, I just get GLX error messages when trying to execute OpenGL programs. </p> <p>The EC2 instance is launched with the following setting: </p> <ul> <li>AMI image: Amazon Linux AMI with NVIDIA GRID GPU Driver (ami-637c220a in US-East)</li> <li>Instance type: G2</li> <li>Most of the other settings are default</li> </ul> <p>After booted, the steps to reproduce this issue is very simple:</p> <pre><code>sudo X :0 &amp; # Start the X window glxinfo glxgears </code></pre> <p>The output is:</p> <pre><code>$ glxinfo name of display: :0 Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Error: couldn't find RGB GLX visual or fbconfig Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". Xlib: extension "GLX" missing on display ":0". $ glxgears Xlib: extension "GLX" missing on display ":0". Error: couldn't get an RGB, Double-buffered visual </code></pre> <p>The following error is found in <code>/var/log/Xorg.0.log</code>:</p> <pre><code>[139017.484] (EE) Failed to initialize GLX extension (Compatible NVIDIA X driver not found) </code></pre> <p>I have googled and tried a lot of possible solution, such as:</p> <ul> <li>Use the clean CentOS HVM AMI and install Nvidia driver manually</li> <li>Tried both CG1/G2 instance types</li> <li>Regenerate the X window config with nvidia-xconfig</li> <li>Use Xvfb instead of X window</li> <li>Reinstall Nvidia driver after mesa libraries are installed</li> </ul> <p>... but none of them works. </p> <p>Does anyone have a concrete solution for this issue? Everything I mentioned should be reproducible (I tried many times). I'll appreciate if you can provide reproducible instructions to make OpenGL (GLX) works on EC2 GPU instances with CentOS/Amazon Linux AMI. </p>
19,875,706
2
1
null
2013-11-08 09:59:06.217 UTC
20
2017-01-22 23:07:02.64 UTC
2013-11-09 09:14:16.86 UTC
null
606,314
null
606,314
null
1
23
opengl|amazon-web-services|amazon-ec2|centos|gpu
11,685
<p><code>lspci | grep VGA</code></p> <p>You should see the <code>busID</code> is <code>0:3:0</code>.</p> <p>Using sudo, add this into your xorg.conf like so:</p> <pre><code>Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "GRID K520" BusID "0:3:0" EndSection </code></pre> <p>This should fix GLX failures.</p>
8,159,233
TypeError: Illegal Invocation on console.log.apply
<p>If you run this in the chrome console:</p> <pre><code>console.log.apply(null, [array]) </code></pre> <p>Chrome gives you back an error:</p> <pre><code>// TypeError: Illegal Invocation </code></pre> <p>Why? <em>(Tested on Chrome 15 via OSX)</em></p>
8,159,338
1
0
null
2011-11-16 21:50:50.27 UTC
22
2017-09-10 14:52:24.057 UTC
2016-02-09 09:48:17.843 UTC
null
4,464,702
null
332,578
null
1
132
javascript|google-chrome|console
27,205
<p>It may not work in cases when execution context changed from console to any other object:</p> <blockquote> <p>This is expected because console.info expects its "this" reference to be console, not window.</p> <pre><code>console.info("stuff") stuff undefined console.info.call(this, "stuff") TypeError: Illegal invocation console.info.call(console, "stuff") stuff undefined </code></pre> <p>This behavior is expected.</p> </blockquote> <p><a href="https://bugs.chromium.org/p/chromium/issues/detail?id=48662" rel="noreferrer">https://bugs.chromium.org/p/chromium/issues/detail?id=48662</a></p>
1,597,732
PHP: Force file download and IE, yet again
<p>Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. </p> <p>My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. </p> <p>Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=_blank" link (forced by Google). </p> <p>All other browsers work fine in all cases. </p> <p>Here are my headers (captured through Fiddler): </p> <pre><code>HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 </code></pre> <p>I want IE's regular left-click behavior to work. Any ideas? </p>
1,597,946
4
0
null
2009-10-20 22:45:22.087 UTC
9
2014-07-21 16:58:35.85 UTC
2012-05-06 17:33:20.083 UTC
null
1,205,135
null
16,668
null
1
9
php|file|internet-explorer|download
25,379
<p>This will check for versions of IE and set headers accordingly.</p> <pre><code>// assume you have a full path to file stored in $filename if (!is_file($filename)) { die('The file appears to be invalid.'); } $filepath = str_replace('\\', '/', realpath($filename)); $filesize = filesize($filepath); $filename = substr(strrchr('/'.$filepath, '/'), 1); $extension = strtolower(substr(strrchr($filepath, '.'), 1)); // use this unless you want to find the mime type based on extension $mime = array('application/octet-stream'); header('Content-Type: '.$mime); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.sprintf('%d', $filesize)); header('Expires: 0'); // check for IE only headers if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false)) { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); } else { header('Pragma: no-cache'); } $handle = fopen($filepath, 'rb'); fpassthru($handle); fclose($handle); </code></pre>
1,511,129
boost::asio::ip::tcp::socket is connected?
<p>I want to verify the connection status before performing read/write operations.</p> <p>Is there a way to make an isConnect() method?</p> <p>I saw <a href="http://lists.boost.org/boost-users/2007/06/28936.php" rel="nofollow noreferrer">this</a>, but it seems "ugly".</p> <p>I have tested <a href="http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/reference/basic_stream_socket/is_open.html" rel="nofollow noreferrer">is_open()</a> function as well, but it doesn't have the expected behavior.</p>
1,512,608
4
2
null
2009-10-02 18:31:22.017 UTC
12
2021-06-23 15:53:07.023 UTC
2018-07-24 17:24:21.143 UTC
null
174,605
null
174,605
null
1
19
c++|sockets|boost-asio
25,446
<p>TCP is meant to be robust in the face of a harsh network; even though TCP provides what looks like a persistent end-to-end connection, it's all just a lie, each packet is really just a unique, unreliable datagram.</p> <p>The connections are really just virtual conduits created with a little state tracked at each end of the connection (Source and destination ports and addresses, and local socket). The network stack uses this state to know which process to give each incoming packet to and what state to put in the header of each outgoing packet.</p> <p><img src="https://i.stack.imgur.com/ubhDS.png" alt="Virtual TCP Conduit" /></p> <p>Because of the underlying — inherently connectionless and unreliable — nature of the network, the stack will only report a severed connection when the remote end sends a FIN packet to close the connection, or if it doesn't receive an ACK response to a sent packet (after a timeout and a couple retries).</p> <p>Because of the asynchronous nature of asio, the easiest way to be notified of a graceful disconnection is to have an outstanding <code>async_read</code> which will return <code>error::eof</code> immediately when the connection is closed. But this alone still leaves the possibility of other issues like half-open connections and network issues going undetected.</p> <p>The most effectively way to work around unexpected connection interruption is to use some sort of keep-alive or ping. This occasional attempt to transfer data over the connection will allow expedient detection of an unintentionally severed connection.</p> <p>The TCP protocol actually has a built-in <a href="http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html" rel="nofollow noreferrer">keep-alive mechanism</a> which can be configured in asio using <code>asio::tcp::socket::keep_alive</code>. The nice thing about TCP keep-alive is that it's transparent to the user-mode application, and only the peers interested in keep-alive need configure it. The downside is that you need OS level access/knowledge to configure the timeout parameters, they're unfortunately not exposed via a simple socket option and usually have default timeout values that are quite large (7200 seconds on Linux).</p> <p>Probably the most common method of keep-alive is to implement it at the application layer, where the application has a special noop or ping message and does nothing but respond when tickled. This method gives you the most flexibility in implementing a keep-alive strategy.</p>
1,343,874
Using loops to get at each item in a ListView?
<p>What is a nice and effective way of getting at each item in a ListView of more than one column using loops?</p> <p>After doing a fair bit of digging around I couldn't really find anything so I when I did find something I wanted to share it on here see if people have better ways of doing it. Also sort of like preempting a question that is bound to come up as I was scratching my head for a bit thinking how do ??? eerrrr .... I ?</p> <p>I like this website so I wanted to share my solution to the question above. Sort of backwards I know but still, I know it will help someone out somwhere. = )</p> <pre><code> private ArrayList getItemsFromListViewControl() { ArrayList lviItemsArrayList = new ArrayList(); foreach (ListViewItem itemRow in this.loggerlistView.Items) { //lviItemsArrayList.Add(itemRow.Text); &lt;-- Already included in SubItems so ... = ) for (int i = 0; i &lt; itemRow.SubItems.Count; i++) { lviItemsArrayList.Add(itemRow.SubItems[i].Text); // Do something useful here, for example the line above. } } return lviItemsArrayList; } </code></pre> <p>This returns a linear array based representation of all the items belong to a targeted ListView Control in an ArrayList collection object.</p>
1,347,193
5
3
null
2009-08-27 21:38:56.06 UTC
1
2020-11-13 19:53:11.127 UTC
2009-10-12 11:29:18.59 UTC
null
63,550
null
162,607
null
1
5
c#|winforms|listview|loops
60,222
<p>I suggest using IEnumerable as the return type of the method and using "yield return" to return each subitems.</p> <pre><code>private IEnumerable&lt;ListViewSubItem&gt; GetItemsFromListViewControl() { foreach (ListViewItem itemRow in this.loggerlistView.Items) { for (int i = 0; i &lt; itemRow.SubItems.Count; i++) { yield return itemRow.SubItems[i]); } } } </code></pre> <p>although if you are using .NET 3.5 I suggest using LINQ too.</p>
7,118,543
Does the Linux filesystem cache files efficiently?
<p>I'm creating a web application running on a Linux server. The application is constantly accessing a 250K file - it loads it in memory, reads it and sends back some info to the user. Since this file is read all the time, my client is suggesting to use something like memcache to cache it to memory, presumably because it will make read operations faster.</p> <p>However, I'm thinking that the Linux filesystem is probably already caching the file in memory since it's accessed frequently. Is that right? In your opinion, would memcache provide a real improvement? Or is it going to do the same thing that Linux is already doing?</p> <p>I'm not really familiar with neither Linux nor memcache, so I would really appreciate if someone could clarify this.</p>
7,118,584
5
4
null
2011-08-19 07:56:07.647 UTC
9
2013-03-09 22:18:37.78 UTC
2011-08-19 17:16:37.18 UTC
null
168,868
null
561,309
null
1
23
linux|filesystems|memcached
12,351
<p>Yes, if you do not modify the file each time you open it.</p> <p>Linux will hold the file's information in copy-on-write pages in memory, and "loading" the file into memory should be very fast (page table swap at worst).</p> <p>Edit: Though, as cdhowie points out, there is no 'linux filesystem'. However, I believe the relevant code is in linux's memory management, and is therefore independent of the filesystem in question. If you're curious, you can read in the linux source about handling vm_area_struct objects in linux/mm/mmap.c, mainly.</p>
7,559,880
LeaseExpiredException: No lease error on HDFS
<p>I am trying to load large data to HDFS and I sometimes get the error below. any idea why?</p> <p>The error:</p> <pre><code>org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException: No lease on /data/work/20110926-134514/_temporary/_attempt_201109110407_0167_r_000026_0/hbase/site=3815120/day=20110925/107-107-3815120-20110926-134514-r-00026 File does not exist. Holder DFSClient_attempt_201109110407_0167_r_000026_0 does not have any open files. at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1557) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1548) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFileInternal(FSNamesystem.java:1603) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFile(FSNamesystem.java:1591) at org.apache.hadoop.hdfs.server.namenode.NameNode.complete(NameNode.java:675) at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:557) at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1434) at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1430) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127) at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1428) at org.apache.hadoop.ipc.Client.call(Client.java:1107) at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:226) at $Proxy1.complete(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:82) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:59) at $Proxy1.complete(Unknown Source) at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.closeInternal(DFSClient.java:3566) at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.close(DFSClient.java:3481) at org.apache.hadoop.fs.FSDataOutputStream$PositionCache.close(FSDataOutputStream.java:61) at org.apache.hadoop.fs.FSDataOutputStream.close(FSDataOutputStream.java:86) at org.apache.hadoop.io.SequenceFile$Writer.close(SequenceFile.java:966) at org.apache.hadoop.io.SequenceFile$BlockCompressWriter.close(SequenceFile.java:1297) at org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat$1.close(SequenceFileOutputFormat.java:78) at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs$RecordWriterWithCounter.close(MultipleOutputs.java:303) at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs.close(MultipleOutputs.java:456) at com.my.hadoop.platform.sortmerger.MergeSortHBaseReducer.cleanup(MergeSortHBaseReducer.java:145) at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:178) at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:572) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:414) at org.apache.hadoop.mapred.Child$4.run(Child.java:270) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127) at org.apache.hadoop.mapred.Child.main(Child.java:264) </code></pre>
7,567,440
6
2
null
2011-09-26 18:55:50.217 UTC
9
2018-04-13 07:32:21.41 UTC
null
null
null
null
449,466
null
1
29
hadoop|hdfs
64,960
<p>I managed to fix the problem:</p> <p>When the job ends he deletes /data/work/ folder. If few jobs are running in parallel the deletion will also delete the files of the another job. actually I need to delete /data/work/.</p> <p>In other words this exception is thrown when the job try to access to files which are not existed anymore</p>