qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
21,807,142
I am trying to install <https://www.npmjs.org/package/sails-mongo> and it is getting 0.9.6 instead of 0.9.7 (as the latest). I have latest **node.js (0.10.25 64-bit)** and **mongodb (2.4.9 64-bit)** on Windows 7. `C:\my_project\backend>npm install sails-mongo` Anyways, I got fatal error: ``` npm http GET https://registry.npmjs.org/sails-mongo/0.9.6 npm http 304 https://registry.npmjs.org/sails-mongo/0.9.6 npm http GET https://registry.npmjs.org/underscore/1.4.4 npm http GET https://registry.npmjs.org/underscore.string/2.3.1 npm http GET https://registry.npmjs.org/async/0.2.9 npm http GET https://registry.npmjs.org/mongodb npm http 304 https://registry.npmjs.org/underscore/1.4.4 npm http 304 https://registry.npmjs.org/underscore.string/2.3.1 npm http 304 https://registry.npmjs.org/async/0.2.9 npm http 304 https://registry.npmjs.org/mongodb npm http GET https://registry.npmjs.org/bson/0.2.5 npm http GET https://registry.npmjs.org/kerberos/0.0.3 npm http 304 https://registry.npmjs.org/bson/0.2.5 npm http 304 https://registry.npmjs.org/kerberos/0.0.3 > kerberos@0.0.3 install C:\my_project\backend\node_modules\sails-mongo\node_modules\m ongodb\node_modules\kerberos > (node-gyp rebuild 2> builderror.log) || (exit 0) C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_modules\kerbe ros>node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_ modules\node-gyp\bin\node-gyp.js" rebuild kerberos.cc worker.cc security_credentials.cc security_buffer.cc security_buffer_descriptor.cc security_context.cc C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(179): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::Object ] C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xlocale(323): wa rning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\no de_modules\kerberos\build\kerberos.vcxproj] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(184): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::Object ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(184): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::FunctionTemplate ] C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xlocale(323): wa rning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\no de_modules\kerberos\build\kerberos.vcxproj] C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xlocale(323): wa rning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\no de_modules\kerberos\build\kerberos.vcxproj] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(179): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::Object ] C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xlocale(323): wa rning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\no de_modules\kerberos\build\kerberos.vcxproj] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(179): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::FunctionTemplate ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(218): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::Object ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(218): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::FunctionTemplate ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(218): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::Object ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(218): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::FunctionTemplate ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(179): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::Object ] C:\Users\myname\.node-gyp\0.10.25\deps\v8\include\v8.h(179): warning C4506: no definition for inline function 'v8::Persistent<T> v8::Persistent<T>::New(v8::H andle<T>)' [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_ modules\kerberos\build\kerberos.vcxproj] with [ T=v8::FunctionTemplate ] kerberos_sspi.c base64.c LINK : fatal error LNK1181: cannot open input file 'kernel32.lib' [C:\my_project\back end\node_modules\sails-mongo\node_modules\mongodb\node_modules\kerberos\build\k erberos.vcxproj] > bson@0.2.5 install C:\my_project\backend\node_modules\sails-mongo\node_modules\mongo db\node_modules\bson > (node-gyp rebuild 2> builderror.log) || (exit 0) C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_modules\bson> node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modu les\node-gyp\bin\node-gyp.js" rebuild bson.cc C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xlocale(323): wa rning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\no de_modules\bson\build\bson.vcxproj] C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\intrin.h(26): fa tal error C1083: Cannot open include file: 'ammintrin.h': No such file or direc tory [C:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_module s\bson\build\bson.vcxproj] sails-mongo@0.9.6 node_modules\sails-mongo β”œβ”€β”€ async@0.2.9 β”œβ”€β”€ underscore@1.4.4 β”œβ”€β”€ underscore.string@2.3.1 └── mongodb@1.3.23 (kerberos@0.0.3, bson@0.2.5) ``` It's here to make it easier for you: ``` LINK : fatal error LNK1181: cannot open input file 'kernel32.lib' [C:\my_project\back end\node_modules\sails-mongo\node_modules\mongodb\node_modules\kerberos\build\k erberos.vcxproj] ``` Any idea why? And how to fix this? **UPDATE 1:** I followed this article <http://blogs.msdn.com/b/saurabh_singh/archive/2009/01/30/getting-fatal-error-lnk1181-cannot-open-input-file-kernel32-lib.aspx> and it seems to fix one problem and now I got different error: ``` npm http GET https://registry.npmjs.org/sails-mongo/0.9.6 npm http 304 https://registry.npmjs.org/sails-mongo/0.9.6 npm http GET https://registry.npmjs.org/async/0.2.9 npm http GET https://registry.npmjs.org/underscore/1.4.4 npm http GET https://registry.npmjs.org/underscore.string/2.3.1 npm http GET https://registry.npmjs.org/mongodb npm http 304 https://registry.npmjs.org/async/0.2.9 npm http 304 https://registry.npmjs.org/underscore/1.4.4 npm http 304 https://registry.npmjs.org/mongodb npm http 304 https://registry.npmjs.org/underscore.string/2.3.1 npm http GET https://registry.npmjs.org/bson/0.2.5 npm http 304 https://registry.npmjs.org/bson/0.2.5 > bson@0.2.5 install c:\my_project\backend\node_modules\sails-mongo\node_modules\mongo db\node_modules\bson > (node-gyp rebuild 2> builderror.log) || (exit 0) c:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_modules\bson> node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modu les\node-gyp\bin\node-gyp.js" rebuild Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch. bson.cc c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xlocale(323): wa rning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [c:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\no de_modules\bson\build\bson.vcxproj] c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\intrin.h(26): fa tal error C1083: Cannot open include file: 'ammintrin.h': No such file or direc tory [c:\my_project\backend\node_modules\sails-mongo\node_modules\mongodb\node_module s\bson\build\bson.vcxproj] sails-mongo@0.9.6 node_modules\sails-mongo β”œβ”€β”€ underscore@1.4.4 β”œβ”€β”€ async@0.2.9 β”œβ”€β”€ underscore.string@2.3.1 └── mongodb@1.3.23 (bson@0.2.5) ```
2014/02/16
[ "https://Stackoverflow.com/questions/21807142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149367/" ]
kerberos needs python. Install [python for Windows](http://www.python.org/download/) and add to the environment variables.
Did you check if you are using correct software version ? If you are using 64bit OS, you have to install 64bit version Node.js(x64)
44,739,431
I have a class which gets a object from the external system. I want to validate my parameters are correct. It seems my object is not null even though I sent a wrong value to the service.Basically I want to check `mySalesOrderHeader` contains a valid order number or not. For example, `if (mySalesOrderHeader != null) { Do My Stuff}` I am checking this condition once `mySalesOrderHeader` is retrieved from the system. Inside my `if condition[Where {Do My Stuff}]` is located, I am accessing its property and checking its existence. ``` if(string.IsNullOrEmpty(mySalesOrderHeader.OrderNumber)){} ``` But in here it throws a null reference exception. How can I check a property is null, if my parent object does not have the value in it. **Note: I am using C# 3.0**
2017/06/24
[ "https://Stackoverflow.com/questions/44739431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145058/" ]
Use [Null-Conditional](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators) operator (C#6 feature). It tests for null before performing a member access Like this: ``` if (string.IsNullOrEmpty(mySalesOrderHeader?.OrderNumber)) { } ```
If the variable mySalesOrderHeader is null, you cannot access its properties otherwise exception will be thrown. So, you should check mySalesOrderHeader first. ``` if (string.IsNullOrEmpty(mySalesOrderHeader != null ? mySalesOrderHeader.OrderNumber : null)) { ... } ```
19,432,252
For the life of me I can't figure out the proper code to access the comment lines in my XML file. Do I use `findnodes`, `find`, `getElementByTagName` (doubt it). Am I even making the correct assumption that these comment lines are accessible? I would hope so, as I know I can add a comment. The type number for a comment node is 8, so they must be parseable. Ultimately, what I want tot do is delete them. ``` my @nodes = $dom->findnodes("//*"); foreach my $node (@nodes) { print $node->nodeType, "\n"; } <TT> <A>xyz</A> <!-- my comment --> </TT> ```
2013/10/17
[ "https://Stackoverflow.com/questions/19432252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880337/" ]
* If all you need to do is produce a copy of the XML with comment nodes removed, then the first parameter of `toStringC14N` is a flag that says whether you want comments in the output. Omitting all parameters implicitly sets the first to a false value, so ``` $doc->toStringC14N ``` will reproduce the XML trimmed of comments. *Note that the Canonical XML form specified by C14N doesn't include an XML declaration header. It is always XML 1.0 encoded in UTF-8.* * If you need to remove the comments from the in-memory structure of the document before processing it further, then `findnodes` with the XPath expression `//comment()` will locate them for you, and `unbindNode` will remove them from the XML. This program demonstrates ``` use strict; use warnings; use XML::LibXML; my $doc = XML::LibXML->load_xml(string => <<END_XML); <TT> <A>xyz</A> <!-- my comment --> </TT> END_XML # Print everything print $doc->toString, "\n"; # Print without comments print $doc->toStringC14N, "\n\n"; # Remove comments and print everything $_->unbindNode for $doc->findnodes('//comment()'); print $doc->toString; ``` **output** ``` <?xml version="1.0"?> <TT> <A>xyz</A> <!-- my comment --> </TT> <TT> <A>xyz</A> </TT> <?xml version="1.0"?> <TT> <A>xyz</A> </TT> ``` --- **Update** To select a *specific* comment, you can add a *predicate expression* to the XPath selector. To find the specific comment in your example data you could write ``` $doc->findnodes('//comment()[. = " my comment "]') ``` ***Note*** that the text of the comment includes *everything* except the leading and trailing `--`, so spaces are significant as shown in that call. If you want to make things a bit more lax, you could use `normalize=space`, which removes leading and trailing whitespace, and contracts every sequence of whitespace within the string to a single space. Now you can write ``` $doc->findnodes('//comment()[normalize-space(.) = "my comment"]') ``` And the same call would find your comment even if it looked like this. ``` <!-- my comment --> ``` Finally, you can make use of `contains`, which, as you would expect, simply checks whether one string *contains* another. Using that you could write ``` $doc->findnodes('//comment()[contains(., "comm")]') ``` The one to choose depends on your requirement and your situation.
I know it's not `XML::LibXML` but here you have another way to remove comments easily with `XML::Twig` module: ``` #!/usr/bin/env perl use warnings; use strict; use XML::Twig; my $twig = XML::Twig->new( pretty_print => 'indented', comments => 'drop' )->parsefile( shift )->print; ``` Run it like: ``` perl script.pl xmlfile ``` That yields: ``` <TT> <A>xyz</A> </TT> ``` The `comments` option has also the value `process` that lets you work with them using the `xpath` value of `#COMMENT`.
8,941,178
I'm using opengl, using the GLUT and GLEW libraries to create a plugin for a certain application. This plugin doesn't start with a simple int main(argc, argv). So i can't pass these values to glutInit(). I tried something like this: ``` glutInit(0, NULL); <--- Crash GLenum err = glewInit(); ``` But i crashed when it tried to call the glutInit() function. Can i reconstruct those params some how, so that it won't crash and still be able to use the Glut library..??
2012/01/20
[ "https://Stackoverflow.com/questions/8941178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874381/" ]
You might have to call `glutInit` with a valid `argv` parameter, even if you don't have any: ``` char *my_argv[] = { "myprogram", NULL }; int my_argc = 1; glutInit(&my_argc, my_argv); ``` Edit ---- It might also be that the first parameter is a pointer to an `int`, and it can't be NULL? Then it might be enough to only pass a valid `argc` parameter: ``` int my_argc = 0; glutInit(&my_argc, NULL); ```
I propose this as a de-facto standard for initializing glut applications. ``` static inline void glutInstall() { char *glut_argv[] = { "", (char *)0 }; int glut_argc = 0; glutInit(&my_argc, my_argv); } ``` This function can be modified on per-application basis to provide glut with the arguments it needs(if any), while permanently solving the issue of everyone asking why you are passing command line arguments to a 3rd party library.
29,744,264
With the same record as below, I use many ways to filter to get it, I don't know why there are some way work and some way are NOT work. Is there anything I should concern ``` //not work: filtered: { query: {"match_all": {}}, filter: {"term" : { "name": "Road to Rio 2016"} } //not work: filtered: { query: {"match_all": {}}, filter: {"term" : { "isTemplate": "N"} } //work: filtered: { query: {"match_all": {}}, filter: {"term" : { "teamId": 147} } //work: filtered: { query: {"match_all": {}}, filter: {"term" : { "programId": 12615} } ``` This is record which I get which the second two ways ``` "hits": [ { "_index": "bridge_tracker_cli_v0.0.7", "_type": "program", "_id": "12615", "_score": null, "_source": { "programId": 12615, "sportId": null, "name": "Road to Rio 2016", "description": "Program Overview", "isTemplate": "N", "editedById": 2170, "createdById": 1491, "clonedFromProgramId": 12608, "teamId": 147, "organizationId": 117, "createdAt": "2015-02-26T07:45:50.000Z", "updatedAt": "2015-04-13T04:47:41.000Z" }, "sort": [ 1424936750000 ] }, ``` Below is record mapping: ``` "_all": { "index_analyzer": "nGram_analyzer", "search_analyzer": "whitespace_analyzer" }, "properties": { "clonedFromProgramId": { "type": "long", "include_in_all": false }, "createdAt": { "type": "date", "format": "dateOptionalTime", "include_in_all": false }, "createdById": { "type": "long", "include_in_all": false }, "createdByScope": { "type": "string", "include_in_all": false }, "dateEdit": { "type": "date", "format": "dateOptionalTime", "include_in_all": false }, "description": { "type": "string" }, "editedById": { "type": "long", "include_in_all": false }, "editedByScope": { "type": "string", "include_in_all": false }, "isTemplate": { "type": "string" "include_in_all": false }, "name": { "type": "string" }, "organizationId": { "type": "long", "include_in_all": false }, "programId": { "type": "long" }, "updatedAt": { "type": "date", "format": "dateOptionalTime", "include_in_all": false } } ``` Below is analyzer: ``` "analysis": { "filter": { "nGram_filter": { "type": "nGram", "min_gram": 1, "max_gram": 20, "token_chars": [ "letter", "digit", "punctuation", "symbol" ] } }, "analyzer": { "nGram_analyzer": { "type": "custom", "tokenizer": "whitespace", "filter": [ "lowercase", "asciifolding", "nGram_filter" ] }, "whitespace_analyzer": { "type": "custom", "tokenizer": "whitespace", "filter": [ "lowercase", "asciifolding" ] } ```
2015/04/20
[ "https://Stackoverflow.com/questions/29744264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2805523/" ]
If you want to use term filters on string make sure to change index as not\_analyzed. But in this case full-text search won't work on this field. To make sure, both filters and full-text search to work change this field as multi-field. For example in the case of name, change the mapping to ``` "name":{ "type": "string", "fields": { "not_analyzed":{ "index": "not_analyzed" } } } ``` And use name.not\_analyzed for filtering.
For me it helped to set the field type to `keyword` instead of `string`.
7,733,039
I have an MVC3 project using the Entity Framework model in which I've marked up a class like this: ``` public partial class Product { public bool IsShipped { get { /* do stuff */ } } } ``` and which I want to use in a LINQ expression: ``` db.Products.Where(x => x.IsShipped).Select(...); ``` however, I get the following error: > > System.NotSupportedException was unhandled by user code Message=The > specified type member 'IsShipped' is not supported in LINQ to Entities. > Only initializers, entity members, and entity navigation properties > are supported. Source=System.Data.Entity > > > I've googled but not found anything definitive about this usage to I tried: ``` public partial class Product { public bool IsShipped() { /* do stuff */ } } db.Products.Where(x => x.IsShipped()).Select(...); ``` but then I get: > > System.NotSupportedException was unhandled by user code Message=LINQ > to Entities does not recognize the method 'Boolean IsShipped()' method, > and this method cannot be translated into a store expression. > > Source=System.Data.Entity > > > there's functionality there that I don't want to build into the LINQ query itself... what's a good way to handle this? **\* update \*** Darin makes the valid point that whatever is done in the implementation of `IsShipped` would need to be converted to a SQL query and the compiler probably doesn't know how to do it, thus retrieving all objects into memory seems the only choice (unless a direct query to the database is made). I tried it like this: ``` IEnumerable<Product> xp = db.Quizes .ToList() .Where(x => !x.IsShipped) .Select(x => x.Component.Product); ``` but it generates this error: > > A relationship multiplicity constraint violation occurred: An > EntityReference can have no more than one related object, but the > query returned more than one related object. This is a non-recoverable > error. > > > though curiously this works: ``` IEnumerable<Product> xp = db.Quizes .ToList() .Where(x => x.Skill.Id == 3) .Select(x => x.Component.Product); ``` why would that be? **\* update II \*** sorry, that last statement doesn't work either... **\* update III \*** I'm closing this question in favour of pursuing a solution as suggested here to flatten my logic into a query - the discussion will move to [this new post](https://stackoverflow.com/questions/7787625/flattening-a-loop-with-lookups-into-a-single-linq-expression). The second alternative, to retrieve the entire original query into memory, is likely unacceptable, but the third, of implementing the logic as a direct query to the database, remain to be explored. Thanks everyone for the valuable input.
2011/10/11
[ "https://Stackoverflow.com/questions/7733039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/709223/" ]
The only way to make this "DRY" (avoid repeating the logic inside of `IsShipped` in the `Where` clause again) and to avoid loading all data into memory before you apply the filter is to extract the content of `IsShipped` into an expression. You can then use this expression as parameter to `Where` and in `IsShipped` as well. Example: ``` public partial class Product { public int ProductId { get; set; } // <- mapped to DB public DateTime? ShippingDate { get; set; } // <- mapped to DB public int ShippedQuantity { get; set; } // <- mapped to DB // Static expression which must be understood // by LINQ to Entities, i.e. translatable into SQL public static Expression<Func<Product, bool>> IsShippedExpression { get { return p => p.ShippingDate.HasValue && p.ShippedQuantity > 0; } } public bool IsShipped // <- not mapped to DB because readonly { // Compile expression into delegate Func<Product, bool> // and execute delegate get { return Product.IsShippedExpression.Compile()(this); } } } ``` The you can perform the query like so: ``` var result = db.Products.Where(Product.IsShippedExpression).Select(...).ToList(); ``` Here you would have only one place to put the logic in (`IsShippedExpression`) and then use it for database queries and in your `IsShipped` property as well. Would I do this? In most cases probably no, because compiling the expression is slow. Unless the logic is very complex, likely a subject to change and I am in a situation where the performance of using `IsShipped` doesn't matter, I would repeat the logic. It's always possible to extract often used filters into an extension method: ``` public static class MyQueryExtensions { public static IQueryable<Product> WhereIsShipped( this IQueryable<Product> query) { return query.Where(p => p.ShippingDate.HasValue && p.ShippedQuantity >0); } } ``` And then use it this way: ``` var result = db.Products.WhereIsShipped().Select(...).ToList(); ``` You would have two places though the maintain the logic: the `IsShipped` property and the extension method, but then you can reuse it.
> > there's functionality there that I don't want to build into the LINQ query itself... what's a good way to handle this? > > > I assume you mean you want to perform queries that don't have anything to do with the DB. But your code doesn't match your intention. Look at this line: ``` db.Products.Where(x => x.IsShipped()).Select(...); ``` The part that says `db.Products` means you want to query the DB. To fix this, get an entity set in memory first. Then you can use Linq to Objects on it instead: ``` List<Product> products = db.Products .Where(x => x.SomeDbField == someValue) .ToList(); // Todo: Since the DB doesn't know about IsShipped, set that info here // ... var shippedProducts = products .Where(x => x.IsShipped()) .Select(...); ``` The `.ToList()` finishes off your initial DB query, and gives you an in-memory representation to work with and modify to your liking. After that point you can work with non-DB properties. Be careful that if you do further DB operations after `ToList` (such as editing DB properties on entities, querying off navigation properties, etc), then you'll be back in Linq to Entities land and will no longer be able to do Linq to Objects operations. You can't directly mix the two. And note that if `public bool IsShipped()` reads or writes DB properties or navigation properties, you might end up in Linq to Entities again if you're not careful.
12,991,267
I am able to get the device id and save it to my database, and when something happens, I try to send the push notification but it does not get delivered to the phone. Here is what I do in my PHP: ``` $url = 'https://android.googleapis.com/gcm/send'; $device_ids = array( $device_id ); $headers = array('Authorization: key=' . 'my_api_key', 'Content-Type: application/json'); $t_data = array(); $t_data['message'] = 'Someone commented on your business.'; $t_json = array( 'registration_ids' => $device_ids , 'data' => $t_data ); $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: key=my_id', 'Content-Type: application/json' ) ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $t_json ) ); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); ``` and here is the result I get from the curl\_exec call: ``` {"multicast_id":8714083978034301091,"success":1,"failure":0,"canonical_ids":0,"rβ€Œβ€‹esults":[{"message_id":"0:1350807053347963%9aab4bd8f9fd7ecd"}]} ``` One thing I am wondering is whether I have to do something extra in the app like write my own Reciever class? Thanks! EDIT: Here is my GCMIntentService class: ``` package com.problemio; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import java.util.Random; import java.util.concurrent.TimeUnit; import com.google.android.gcm.GCMBaseIntentService; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; import utils.GCMConstants; public class GCMIntentService extends GCMBaseIntentService { public GCMIntentService() { super(ProblemioActivity.SENDER_ID); } @Override protected void onRegistered(Context ctxt, String regId) { Log.d(getClass().getSimpleName(), "onRegistered: " + regId); Toast.makeText(this, regId, Toast.LENGTH_LONG).show(); } @Override protected void onUnregistered(Context ctxt, String regId) { Log.d(getClass().getSimpleName(), "onUnregistered: " + regId); } @Override protected void onMessage(Context ctxt, Intent message) { Bundle extras=message.getExtras(); for (String key : extras.keySet()) { Log.d(getClass().getSimpleName(), String.format("onMessage: %s=%s", key, extras.getString(key))); } } @Override protected void onError(Context ctxt, String errorMsg) { Log.d(getClass().getSimpleName(), "onError: " + errorMsg); } @Override protected boolean onRecoverableError(Context ctxt, String errorMsg) { Log.d(getClass().getSimpleName(), "onRecoverableError: " + errorMsg); return(true); } } ``` UPDATE: Looking at LogCat, it turned out that the message is getting to the device. But the device is not displaying the push notification for some reason.
2012/10/20
[ "https://Stackoverflow.com/questions/12991267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478573/" ]
From the response it seems that the message is delivered. On Android you should have a GCMIntentService class that extends GCMBaseIntentService, to receive the message on the device. You should check the gcm-demo-client that comes in the SDK samples for a good approach on how to implement this on the app. There you only need set the SENDER\_ID (your google proyect number) in the CommonUtilities class to receive messages from your server. More info [here](http://developer.android.com/intl/es/guide/google/gcm/demo.html). To generate the notification on the GCMIntentService you can use: ``` //Issues a notification to inform the user that server has sent a message. private static void generateNotification(Context context, String message, String title,) { int icon = R.drawable.logo; NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(context, AnActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Notification notification = new NotificationCompat.Builder(context) .setContentTitle(title) .setContentText(message) .setContentIntent(intent) .setSmallIcon(icon) .setLights(Color.YELLOW, 1, 2) .setAutoCancel(true) .setSound(defaultSound) .build(); notificationManager.notify(0, notification); } ``` Have you also registered the receiver on the manifest? Under the application tag? ``` <!-- BroadcastReceiver that will receive intents from GCM services and handle them to the custom IntentService. The com.google.android.c2dm.permission.SEND permission is necessary so only GCM services can send data messages for the app. --> <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <!-- Receives the actual messages. --> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <!-- Receives the registration id. --> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.google.android.gcm.demo.app" /> </intent-filter> </receiver> <!-- Application-specific subclass of GCMBaseIntentService that will handle received messages. By default, it must be named .GCMIntentService, unless the application uses a custom BroadcastReceiver that redefines its name. --> <service android:name=".GCMIntentService" /> ```
While sending notification from GCM Server, which url to be used? <https://android.googleapis.com/gcm/send> or <https://gcm-http.googleapis.com/gcm/send>
31,807,037
I have csv rows like this: ``` 'UTAS114_1','Aqua Sphere''\n' ``` But the line endings aren't understood by excel and everything goes into the first row. How do I fix them?
2015/08/04
[ "https://Stackoverflow.com/questions/31807037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4498553/" ]
It might be of interest that there's a [RFC for CSV](https://www.rfc-editor.org/rfc/rfc4180) and that explicitly uses CRLF as line separator as well: > > Each record is located on a separate line, delimited by a line break (CRLF). For example: > > > ``` aaa,bbb,ccc CRLF zzz,yyy,xxx CRLF ```
The problem is probably that the CSV was not generated on a Windows machine. Excel, I assume, expects `\r\n` at the end of every line.
23,741,454
I am trying to build a JavaScript initcap function which correctly converts the first *letter* in each word to upper case as the other letters to lower case. All examples I have found converts the first *character* which is incorrect, eg: joe smith (c e o) should convert to Joe Smith (C E O), not to Joe Smith (c E O) CSS transform is not an option as the value is returned to a server. Probably using regular expressions is the way to go but I am no expert at these. Any help ?
2014/05/19
[ "https://Stackoverflow.com/questions/23741454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089594/" ]
Just sort yourself and limit the output. ``` SELECT uuid FROM Run WHERE <some_condition> ORDER BY id DESC LIMIT 1; ```
I think the easiest way is using `limit` and `order by`: ``` select r.* from Run r where <some condition> order by id desc limit 1; ```
19,171,195
Alright, so the code is pretty straight forward. Generic class ourSet, that takes in some elements, puts it in a LinkedList, and does some functions on the two sets. My problem is actually quite unrelated the general concept of the project, its more in the "user input interface" I've created. I want it to take in some Strings and add it to the set, then while receiving the string "EXIT" (all caps), to exit the loop, and do the same for the next set. What is happening is that the do while loop is only sending the 1st, 3rd, 5th,.. for all odd numbers. ``` package set.pkgclass; import java.util.Scanner; import java.util.LinkedList; public class SetClass { public static void main(String[] args) { ourSet<String> set1 = new ourSet<String>(); ourSet<String> set2 = new ourSet<String>(); Scanner input = new Scanner(System.in); System.out.println("Please enter a string to put in set 1, " + "type EXIT (in all caps) to end."); do { set1.add(input.nextLine()); } while (!"EXIT".equals(input.nextLine())); System.out.println("Please enter a string to put in set 2, " + "type EXIT (in all caps) to end"); do { set2.add(input.nextLine()); } while (!"EXIT".equals(input.nextLine())); ourSet.intersection(set1,set2); ourSet.difference(set1, set2); ourSet.union(set1, set2); } } class ourSet<T>{ private LinkedList<T> mySet = new LinkedList<>(); public void add(T element){ mySet.add(element); } public void remove(T element){ mySet.remove(element); } public boolean membership(T element){ if(mySet.contains(element) == true) { return true; } else { return false; } } public static <T> void union(ourSet<T> s1, ourSet<T> s2){ System.out.print("The union is: "); for (int i=0; i < s1.mySet.size(); i++) { T t = s1.mySet.get(i); if (!s2.mySet.contains(t)){ s2.add(t); } } for (int i=0; i < s2.mySet.size(); i++){ T t = s2.mySet.get(i); System.out.print(t+", "); } System.out.println(); } public static <T> void intersection(ourSet<T> s1, ourSet<T> s2){ System.out.print("The intersection is: "); for (int i=0; i < s1.mySet.size(); i++) { T t = s1.mySet.get(i); if (s2.mySet.contains(t)) { System.out.print(t+", "); } } System.out.println(); } public static <T> void difference(ourSet<T> s1, ourSet<T> s2){ System.out.print("The difference is: "); for (int i=0; i < s1.mySet.size(); i++) { T t = s1.mySet.get(i); if (!s2.mySet.contains(t)) { System.out.print(t+", "); } } System.out.println(); } } ```
2013/10/04
[ "https://Stackoverflow.com/questions/19171195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2844764/" ]
The reason is, you're calling `input.nextLine()` *twice*: ``` do { set1.add(input.nextLine()); } while (!"EXIT".equals(input.nextLine())); ``` A much easier way than do-while is while: ``` while (!(String in = input.nextLine()).equals("EXIT")) { set1.add(in); } ```
You loop is doing exactly what you've told it to... * Read a line of text and add it to `set1` * Read a line of text and check to see if it equals `"EXIT"` * Repeat as required... So, every second request is being used to check for the exit state. Instead, you should assign the text from the input to a variable and use it to do you checks, for example... ``` do { String text = input.nextLine(); if (!"EXIT".equals(text)) { set1.add(); } } while (!"EXIT".equals(text)); ``` ps- Yes, I know, you could use `break` ;)
30,344,634
The goal of this code is that when you change the Section Bar radio input to yes two things happen. [JS Fiddle Link](http://jsfiddle.net/6o7nmgan/1/) 1. The .bar div is shown 2. The Section Foo radio button is changed to the No value **and** the .foo div is hidden Additionally, would it be possible to have the reverse happen when the Section Bar is changed back to no. The .bar div gets hidden, the .foo section is shown, and the Section Foo button is set back to yes value. Basically, the state of the second radio button effects the first button and runs the function it would if it was changed, but the first button does not effect the second when it is changed. ``` <form> <label>Section Foo</label> <input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" checked >Yes <input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no">No </form> <form> <label>Section Bar</label> <input class="enable" data-target=".bar" type="radio" name="enableBar" value="yes">Yes <input class="enable" data-target=".bar" type="radio" name="enableBar" value="no" checked>No </form> <div class="foo">Foo</div> <div class="bar">Bar</div> div { width: 500px; height: 200px; } .foo { display: block; background: red; } .bar { display: none; background: black; } $('.toggle').change(function () { var target = $(this).data("target"), element = $(this), name = element.val(), is_checked = element.prop('checked') if (name == 'yes') { $(target).slideDown(300); } else { $(target).slideUp(300); } }); $('.enable').change(function () { var target = $(this).data("target"), element = $(this), name = element.val(), is_checked = element.prop('checked') if (name == 'yes') { $(target).slideDown(300); $( ".toggle" ).prop("checked", true) // this changes the .toggle check, but does not run the function, also I'm not sure if it will always set it to the value of no. } else { $(target).slideUp(300); $( ".toggle" ).prop("checked", true) } }); ```
2015/05/20
[ "https://Stackoverflow.com/questions/30344634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693705/" ]
**Some basics about default value in C#:** When an instance of a class (or struct) is created, all fields are initialized to their respective default value. For reference types, it will be `null`. For value types, it will be equivalent to `0`. This is easily explains as the memory management ensures that new allocated memory is initialized to 0x0 bytes. Auto-properties hide the generated field, but there is one. So the same rules apply. **Now to answer your question**, the best way to make sure that values are initialized is to make a constructor with one parameter for each field/property and to hide the default constructor with no parameters: ``` public Yourtype(String param1, Int32 param2) { this.Variable1 = param1; this.Variable2 = param2; } private Yourtype() { } ``` Other alternatives is described in @Sean and @Alex answers if only a subset of properties/fields needs to be initialized/checked. But this hides some overhead (one `bool` for each property/field and some indirection).
For the reference types you'll need to add a flag: ``` string m_Variable1; bool m_IsVariable1Set; public string Variable1 { get{return m_Variable1;} set{m_IsVariable1Set = true; m_Variable1 = value;} } ``` For the value types you can use a nullable value ``` int? m_Variable2; int Variable2 { get{return m_Variable2.GetValueOrDefault();} set{m_Variable2 = value;} } ``` Which you can then check to see if it's been set by using `m_Variable2.HasValue`.
69,278,864
I was looking at some oracle code and found these case statements are joined with a + operator? what does it do here? Is it possible to avoid '+' and do the same thing? ``` case when t1.id is not null then 1 else 0 end + case when t2.id is not null then 2 else 0 end + case when t3.id is not null then 4 else 0 end filter, ```
2021/09/22
[ "https://Stackoverflow.com/questions/69278864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601357/" ]
Or, yet another option, `DECODE`: ``` select decode(t1.id, null, 0, 1) + decode(t2.id, null, 0, 2) + decode(t3.id, null, 0, 4) as filter from ... ```
> > Is it possible to avoid '+' and do the same thing? > > > In fact, yes. Assuming the `id`s all have the same type, you can use a `lateral join`: ``` from . . . -- all your existing stuff here cross join lateral (select count(id) as cnt from (select t1.id from dual union all t2.id from dual union all t3.id from dual ) x ) x ```
1,139,027
I have Windows 10 installed on a SSD drive and want to install Linux Mint on another HDD drive. Anyway, I don't know if my PC is UEFI (some parts are old, others recent, like the SSD) but I don't think so. Here are my partition. I want to install my whole linux (/, swap and /home) in /dev/sda1 How can I do that without screwing up my boot to windows which I need... you know... for steam ;) ? [![enter image description here](https://i.stack.imgur.com/aldJl.png)](https://i.stack.imgur.com/aldJl.png) **EDIT :** 2 more points : I'm wondering if I need a /boot partition, since there's a Windows 10 loader (`sdb1`)? And if I can test without it… Plus, in my BIOS, it's written `ASUS EFI BIOS`, is it UEFI or BIOS then?
2016/10/25
[ "https://superuser.com/questions/1139027", "https://superuser.com", "https://superuser.com/users/59808/" ]
The safest approach to installing Linux in a way that won't disrupt Windows is to use virtualization -- [VirtualBox](https://www.virtualbox.org/), [VMWare](http://www.vmware.com/), etc. Such tools let you run Linux within Windows (or vice-versa), so you needn't repartition your hard disk or mess with the delicate boot process. You'll also be able to run both OSes simultaneously, so you can do something in Linux at the same time you're doing something else in Windows. The drawback to virtualization is that you'll sacrifice some performance; the virtualized OS won't get full access to the hardware and so will perform more slowly than it would if it were installed natively. If you decide that virtualization is not for you, it looks to me as if your Windows is installed in BIOS/CSM/legacy mode. I say this because there doesn't seem to be an [EFI System Partition (ESP)](https://en.wikipedia.org/wiki/EFI_system_partition) in the partitions you've shown, and an ESP is more-or-less required for booting an EFI-based computer. To be 100% sure, though, see the instructions on [this page of mine](http://www.rodsbooks.com/refind/bootmode.html#windows) for identifying your Windows boot mode. You say that you want to install Linux in `/dev/sda1`. Be aware that, aside from virtualization and one or two other exotic installation methods, Linux *completely takes over* any partition(s) you give it. Thus, if you install Linux to `/dev/sda1`, any data on that partition will be *lost.* If that's fine, you can proceed; but if not, you should re-think your plans or move your data elsewhere. If you want the three partitions you mentioned, your `/dev/sda1` will be replaced with three or four new ones, depending on how you partition the disk. (Personally, I'd replace `/dev/sda1` with an extended partition and then create root (`/`), `/home`, and swap as logical partitions -- `/dev/sda5`, `/dev/sda6`, and `/dev/sda7` in Linux's nomenclature. There are other ways to do this, though.) As to the nitty-gritty details of installation, there are numerous tutorials on this subject. Try Googling "install Linux Mint," read a few pages (or watch videos, for video instructions), and if you have any questions, ask the authors or post your specific questions here or on the [Linux Mint forums.](https://forums.linuxmint.com/)
If your Asus mainboard is less than a few years old, it will most likely have UEFI at it's heart. Also if you can use your mouse within your "BIOS", it will indeed be an UEFI. (It still can be an UEFI if you can't use your mouse though!) There are ways upon ways to determine if your Windows was installed in UEFI or "Legacy" mode. I'll just share this link <http://www.eightforums.com/tutorials/29504-bios-mode-see-if-windows-boot-uefi-legacy-mode.html> with you, so you should be able to determine it for Windows. *If it is not installed in UEFI mode, the following might not be valid for you!* For nice partitioning you may use the scheme presented in <http://www.linuxtechi.com/linux-mint-18-installation-guide-with-screenshots/> . Some additional infos: * You do not necessarily have to define a seperate `/var` partition. Just add it's space requirements to your root `/` partition and only create a bigger root. The installer will then create `/var` and in the root partition. * You may do the same with `/home`, though it's relatively common to use a seperate partition. Again, it's your choice. * `/swap` is said to get double the amount of your RAM. Some say that's a bit anachronistic and unnessecary in times of two-digit GB amounts of RAM. If you have more than 8 GB of RAM, you may use 1.5 times the RAM amount for `/swap`, even less the more RAM you have. (Some people even say you can forgo using a `/swap` nowadays, but that can get a little risky.) Now to your special case for `/boot` and `/boot/efi`: You can create a second seperate EFI partition for your Linux, but you don't have to. If you don't want to, because you want to use the one from Windows, you may use the drop down menu, which can be seen in your screenshot, to choose the drive where the bootloader should be installed. (I hope I'm not remembering the menu incorrectly. Unfortunately I can not read French.) You would choose `/dev/sdb1` then. When I was installing Linux Mint as a dual boot next to (UEFI) Windows 10 but on a seperate drive, the Mint installer always used the already present ESP/EFI partition that the Windows installer had created. Even a newly created EFI partition on a seperate drive exclusively for Linux was ignored. I still don't know why. Fortunately the current Linux Mint installer didn't break my Windows boot. (Also I could manually move the necessary files to the second EFI partition and everything works like charm now.) What should happen is, that from then on instead of booting the Windows bootloader, a GRUB instance will load, giving you the possibility to boot Linux or Windows just as you wish. The GRUB and Linux loader will be added to the existing EFI partition. In your screenshot the entry for `/dev/sdb1` is slightly strange, because usually a FAT variant (most common is FAT32) is used for the EFI-partition. So if `/dev/sdb1` indeed is your EFI partition, Linux might not accept it. Instead it might create a seperate EFI partition on the drive you define in the drop down menu at the bottom. I can't tell the outcome as I have not yet encountered an NTFS formatted EFI partition. This might break your Windows boot temporarily, as the newly installed GRUB might then be unable to find your Windows bootloader. It should be possible to repair this afterwards though. After you have the two partitions settled in, I recommend using rEFInd for booting the OS of your choice. I found it much nicer to handle than GRUB.
35,023
I run apache2 on Ubuntu, i'm sure there is a configuration or permission problem causing this. When I attempt to update plugins through the admin control panel, after I enter the FTP login/pass and click Proceed. I get the error "Unable to locate WordPress Content directory (wp-content)." And wp-content does exist and have proper permissions from the default install.
2011/11/29
[ "https://wordpress.stackexchange.com/questions/35023", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10413/" ]
The FTP user account likely does not have access to the wp-content directory. Are you able to access wp-content using an FTP client with the same user account? Another solution is to change the owner of wp-content to www-data. You can do this from the command line by running `chown www-data:www-data wp-content/ -R`
What resolved for me on Lubuntu 14 was the following: ``` chown www-data:www-data /var/www/html -R ```
3,258,870
I have following two tables: ``` Person {PersonId, FirstName, LastName,Age .... } Photo {PhotoId,PersonId, Size, Path} ``` Obviously, PersonId in the Photo table is an FK referencing the Person table. I want to write a query to display all the fields of a Person , along with the number of photos he/she has in the Photo table. A row of the result will looks like `24|Ryan|Smith|28|6` How to write such query in tsql? Thanks,
2010/07/15
[ "https://Stackoverflow.com/questions/3258870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192727/" ]
You need a subquery in order to avoid having to repeat all the columns from `Person` in your group by clause. ``` SELECT p.PersonId, p.FirstName, p.LastName, p.Age, coalesce(ph.PhotoCount, 0) as Photocount FROM Person p LEFT OUTER JOIN (SELECT PersonId, COUNT(PhotoId) as PhotoCount FROM Photo GROUP BY PersonId) ph ON p.PersonId = ph.PersonId ```
``` SELECT p.PersonId, p.FirstName, p.LastName, p.Age, CASE WHEN t.ThePhotoCount IS NULL THEN 0 ELSE t.ThePhotoCount END AS TheCount --the above line could also use COALESCE FROM Person p LEFT JOIN (SELECT PersonId, COUNT(*) As ThePhotoCount FROM Photo GROUP BY PersonId) t ON t.PersonId = p.PersonID ```
16,863,014
For example there is a `-c` option in Ruby that checks syntax before running a code: ``` C:\>ruby --help Usage: ruby [switches] [--] [programfile] [arguments] -c check syntax only C:\>ruby -c C:\foo\ruby\my_source_code.rb Syntax OK ``` Is there a similar functionality in Go? P.S. An example from Ruby is only because I know it in Ruby. Not because of trolling or something.
2013/05/31
[ "https://Stackoverflow.com/questions/16863014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114926/" ]
Ruby is an interpreted language so a command that checks the syntax might make sense (since I assume you could potentially run the program even if there are syntax errors at some point). Go on the other hand is a compiled language so it cannot be run at all if there are syntax errors. As such, the simplest way to know if there are errors is to build the program with `go build`.
**golang syntax checker** Place the below code in a file called *gochk* in a bin dir and `chmod 0755`. Then run `gochk -- help` ``` #!/bin/bash # # gochk v1.0 2017-03-15 - golang syntax checker - ekerner@ekerner.com # see --help # usage and version if \ test "$1" = "-?" || \ test "$1" = "-h" || \ test "$1" = "--help" || \ test "$1" = "-v" || \ test "$1" = "--version" then echo "gochk v1.0 2017-03-15 - golang syntax checker - ekerner@ekerner.com"; echo echo "Usage:" echo " $0 -?|-h|--help|-v|--version # show this" echo " $0 [ file1.go [ file2.go . . . ] ] # syntax check" echo "If no args passed then *.go will be checked"; echo echo "Examples:" echo " $0 --help # show this" echo " $0 # syntax check *.go" echo " $0 cmd/my-app/main.go handlers/*.go # syntax check list"; echo echo "Authors:" echo " http://stackoverflow.com/users/233060/ekerner" echo " http://stackoverflow.com/users/2437417/crazy-train" exit fi # default to .go files in cwd gos=$@ if test $# -eq 0; then gos=$(ls -1 *.go 2>/dev/null) if test ${#gos[@]} -eq 0; then exit fi fi # test each one using gofmt # credit to Crazy Train at # http://stackoverflow.com/questions/16863014/is-there-a-command-line-tool-in-golang-to-only-check-syntax-of-my-source-code # for go in $gos; do gofmt -e "$go" >/dev/null done ```
60,905,571
I have this TextView which has gravity to center ``` <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="this is first line text\nsecond line" app:autoSizeMaxTextSize="18sp" app:autoSizeMinTextSize="12sp" app:autoSizeStepGranularity="1sp" app:autoSizeTextType="uniform" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> ``` [![enter image description here](https://i.stack.imgur.com/Wg8Eo.png)](https://i.stack.imgur.com/Wg8Eo.png) How it's possible to align `"second line"` to the start of first line `"this is first line text`" ?
2020/03/28
[ "https://Stackoverflow.com/questions/60905571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7542765/" ]
You can use below solutions, if you want to click on a **Continue with email** button: **- XPATH** **Example 1** ``` wait = WebDriverWait(Driver, 30) wait.until(EC.presence_of_element_located((By.XPATH, "//div[contains(text(),'Continue with email')]"))).click() ``` **Example 2** ``` wait = WebDriverWait(Driver, 30) wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='_bc4egv gs_copied']"))).click() ``` **- CSS Selector** ``` wait = WebDriverWait(Driver, 30) wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".\_18m31f1b:nth-child(1) .\_bc4egv"))).click() ``` Dont forget to add below imports ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By ```
Can you try this code ```py Element = Driver.find_element_by_xpath('//*[@id="site-content"]/div/div/div/div/div/div/div/div[2]/button') ```
472,579
My question is how to stop logs on mysql ``` log_error = /var/log/mysql/error.log i have commented already. ``` with slow queries too. But i have one more log file in /var/lib/mysql/hostname.log with hostname I mean that for example I am on server called hulk so the log will be hulk.log and so on. In that log are all queries. So the log is growing really fast and also is really big. So my question is how to disable this log ?
2013/01/26
[ "https://serverfault.com/questions/472579", "https://serverfault.com", "https://serverfault.com/users/144063/" ]
In MySQL 5.1.12+ add/change this in your `my.cnf` ``` general-log = 0 ``` In MySQL 5.1.11- remove this in your `my.cnf` ``` log ``` or ``` log = ``` Source: <http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_general_log> <http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_log>
`vim /etc/my.cnf` There are two lines you want to comment out: ``` log=... log-error=... ``` Restart mysql by `service mysql restart` or `service mysqld restart` Logging will be turned off now. Reverse the process when you want to turn it back on (if you do...) :)
155,731
I'm currently looking into getting a static IP address at home. I believe that if we are given a static IP address by our ISP that will be assigned to the router, rather than a specific computer. We have several computers that connect through the router (two desktops, a laptop, plus my iPhone and DS sometimes). Will all these computers have the same external IP address, or will it somehow be different for each one? And does it matter?
2010/06/23
[ "https://superuser.com/questions/155731", "https://superuser.com", "https://superuser.com/users/492/" ]
### Answers first > > Will all these computers have the same external IP address, or will it somehow be different for each one? And does it matter? > > > These computers, behind the router, will appear as just one computer from the outside (at least they will use the same IP address; websites are still able to distinguish them by using browser cookies and some information that the browser sends to the server). Generally it doesn't matter, but all limitations which are IP-based apply. For example, if your IP is banned from editing some site, all of the computers behind the same router will be banned. ### What is Static IP Actually, you should distinguish between static vs dynamic IPs (it's a method of assignment), "real" IPs vs IPs from the private ranges, and internal vs external IP addresses. Static means that you insert the IP address in the network settings directly, it is pre-assigned to this machine, and it is always the same. The machine doesn't need to ask anybody to know its own IP address. Dynamic IP means that you do not assign any particular address in the network settings. Instead, it is assigned automatically (via DHCP). For this automatic configuration to work, there needs to be a device on the network, which gives IP addresses. This is called DHCP server. Usually, it's home router's task. It doesn't matter in what way the address (and other network settings) were chosen, as long as they are correct. These are only two different ways to configure the network. ### External and internal IPs There are not enough possible IPv4 addresses available. To workaround this limitation, addresses from the private ranges (10.x.x.x, 172.16.x.x, 192.168.x.x) are used in the internal network, and the "real" public IP is used as a single gateway for the whole network. This is called Network Address Translation. Most home routers do this. ``` ( Internet, outer network ) \ \ 1.2.3.4 (external IP) | [ NAT device ] | 192.168.1.1 (internal private IP) | \_________________ \ \ \ \ 192.168.1.2 192.168.1.3 [ PC of Alice ] [ Bob's laptop ] ``` It doesn't matter if your external IP is assigned statically or not (usually it is dynamic, given via DHCP, even if it appears to be the same most of the time), it doesn't matter if your internal addresses are assigned statically or dynamically. The network works as long as it is configured consistently, and all computers know that they should send everything to the router, and the router knows how to rewrite address for the outer network. You will appear as using 1.2.3.4 IP address to most of the sites (you may go to ipchicken.com to check). And if you don't have Java installed, they will not be able to say what is your internal address (but Java plugin may report it; probably Flash and Silverlight can do it too). It may happen, that the outer address of the router is from the private range too (e.g. 10.1.1.1). This means that there is at least yet another NAT before the internet. ### When a static "real" IP is necessary? There is a situation, when you want to have your external IP to be static and not from the private range ("real" IP). Usually, this is the case when you run servers at home. You don't want them to change their IP addresses spontaneously (but you can use dyndns to deal with it). And you don't want your server to have an address from the private range, because then nobody from the outside can connect it. If it uses a private IP, you need to configure routers all the way to the outside to make server connectable from the outside. If your router's external address is not from a private range (is a "real" IP), you need to configure only your own router. But if router's external address is from a private range, you depend on your ISP to configure their routers for you (good luck with that).
I am very curious why you think you might want a static IP instead of the more typical dynamic IP. I'm not sure what advantage you think you might gain from this. Since almost every ISP client uses dynamic IPs, every site on the Internet has to deal with them properly. If you just want to reliably access your home's IP address from another location then I suggest using one of the "free" dynamic DNS services, for example [dyndns.com](http://dyndns.com). You could also [search superuser.com](https://superuser.com/search?q=dynamic+dns) for more info on dynamic DNS services. Perhaps you have a need for a static IP which dynamic DNS cannot address. But usually the best reason to get a static IP is it is an easy way to send more money to your ISP every month.
38,906
So, we uploaded the managed package and installed it in a new org (as the clients would) but when accessing a vf page we get the error ``` SObject row was retrieved via SOQL without querying the requested field: namespace__MyObject__c.namespace__CustomField__c ``` The problem is that on the developer org everything works fine and on that VF Page we are not actually referencing any value that was the result of a query. Any idea why this is happening? Note: We follow [this](https://salesforce.stackexchange.com/questions/775/visualforce-error-using-standard-controller-in-managed-package) and tried appending namespace\_\_ as: ``` {!namespace__CustomObject__c.namespace__CustomField__c} ``` But then the error we were getting at the subscriber org started happening at the developer org. --- I'm referencing the custom fields like this: ``` <form action="https://someurl.com/{!Object__c.Custom_Field__c}” method="post" enctype="multipart/form-data"> <input type="hidden" name="key" value="{!Object__c.Custom_Field2__c}” /> //some other stuff </form> ```
2014/06/06
[ "https://salesforce.stackexchange.com/questions/38906", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/7463/" ]
There's a glitch with Visualforce pages regarding namespaces. The workaround is to always use a Visualforce input or output element. ``` <!-- this is bad --> {!Account.PackagedField__c} <!-- this is good --> <apex:outputField value="{!Account.PackagedField__c}" /> ``` After installing the package in another org, you'll see that salesforce magically patches the reference: ``` <!-- after installation, in installed org --> <apex:outputField value="{!Account.namespace__PackagedField__c}" /> ``` I uncovered this glitch on a project I was working for between 2012 and early this year. As far as I know, it's still not listed on Known Issues, nor does there appear to be timeline to fix this glitch. Note also that it doesn't "always" happen, but you should nevertheless always use this design pattern to avoid the problem. *Edit*: Also, I recall that this problem would occasionally cause the managed package upload to fail and/or the install to fail with nothing more than a generic Internal Server Error with the usual numbered error code.
I have suffered this error in the past as well, and we followed the same approach as [sfdcfox](https://salesforce.stackexchange.com/users/2984/sfdcfox). In our Visualforce pages, we added a list of outputfields linked to the related sObject fields, and set rendered attribute to false to avoid displaying them: ``` <apex:outputField value="{!MyCustomObject__c.MyCustomField__c}" rendered="false"/> ```
53,097,668
i need to write a program that will get from the user 5 number (a b c d e) and will print the lowest and the highest number. how can i do it and use less if-elss condition? i cant use arry or loops. ``` if (a>b) { min=b ; max=a ; }else { min=a ; max=b ; int temp = a ; a=b ; b=temp ; } if (b>c) { min=c ; }else { if(c>max) { max=c ;} int temp = b ; b=c ; c=temp ; } if (c>d) { min=d ; }else { if(d>max) { max=d ;} int temp = c ; c=d ; d=temp ; } if (d>e) { min=e ; }else { if(e>max) { max=e ;} int temp = d ; d=e ; e=temp ;} ```
2018/11/01
[ "https://Stackoverflow.com/questions/53097668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10579425/" ]
One option would be to just add the five input numbers to an array, and then use streams to find the min and max values: ``` int a = myScanner.nextInt(); int b = myScanner.nextInt(); int c = myScanner.nextInt(); int d = myScanner.nextInt(); int e = myScanner.nextInt(); int[] vals = {a, b, c, d, e}; int min = Arrays.stream(vals).min().getAsInt(); int max = Arrays.stream(vals).max().getAsInt(); System.out.println(min); System.out.println(max); ``` Another option might be to use a collection (e.g. a list) to store the five input numbers. Then, we could sort that collection, and find the min/max this way. Using some kind of collection is probably the best way to do this. **Edit:** If you *must* use `if` statements, then one option might be to compare the first two and second two numbers in pairs, then find the min/max from the resulting three numbers. I adapted the `min` and `max` methods from [this Code Review](https://codereview.stackexchange.com/questions/58747/find-min-of-3-numbers-hardcoded) question. It finds the min and max of three numbers, so we only need to come up with additional logic to reduce your five inputs down to three. ``` public static int min(int a, int b, int c) { if (a <= b && a <= c) return a; if (b <= a && b <= c) return b; return c; } public static int max(int a, int b, int c) { if (a >= b && a >= c) return a; if (b >= a && b >= c) return b; return c; } // now the logic for your inputs a, b, c, d, e int min1 = a <= b ? a : b; int min2 = c <= d ? c : d; int max1 = a >= b ? a : b; int max2 = c >= d ? c : d; int finalmin = min(min1, min2, e); int finalmax = max(max1, max2, e); ```
I think streams is like using loops, so make simple: ``` int min = a; int max = a; if (max < b) {max = b;} if (min > b) {min = b;} if (max < c) {max = c;} if (min > c) {min = c;} ... System.out.println(min); System.out.println(max); ```
2,061,222
I've always used dictionaries. I write in Python.
2010/01/13
[ "https://Stackoverflow.com/questions/2061222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
A dictionary is a general concept that maps keys to values. There are many ways to implement such a mapping. A hashtable is a specific way to implement a dictionary. Besides hashtables, another common way to implement dictionaries is [red-black trees](http://en.wikipedia.org/wiki/Red-black_tree). Each method has it's own pros and cons. A red-black tree can always perform a lookup in O(log N). A hashtable can perform a lookup in O(1) time although that can degrade to O(N) depending on the input.
Dictionary is implemented using hash tables. In my opinion the difference between the 2 can be thought of as the difference between Stacks and Arrays where we would be using arrays to implement Stacks.
286
When I lift weights, I lift heavy. I expect to be sore afterwards because I know I've pushed myself hard. Unfortunately, sometimes I push myself too far and get very bad delayed onset muscle soreness (DOMS). What can I do either before working out to prevent excessive soreness or after working out to relieve the soreness?
2011/03/02
[ "https://fitness.stackexchange.com/questions/286", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/35/" ]
I'm personally not convinced that stopping DOMS is a good idea. The processes behind super-compensation (which is what makes your muscles stronger) are not completely understood and there is some initial evidence that DOMS is part of this process. This implies that reducing DOMS will reduce the weight-building effect. I will say that, from my personal experience, more training reduces DOMS. Specifically, as an ultra runner, as I start doing back-to-back long distance (two days of long runs) then my DOMS starts reducing - to the point where I've done 80km in a weekend and had no DOMS. Secondly, if you're going to use a NSAID (like aspirin or ibuprofen) then make sure you are normally hydrated. There is increasing evidence that they can harm your liver or kidneys when associated with dehydration or alcohol.
It is a well answered question but I wanted to add extra information about DOMS here Muscle soreness may occur after an acute training session, especially resistance training. The soreness manifests itself as stiffness, tenderness, inflammation and/or pain, and as it occurs between 24–48 hours following the training session is referred to as delayed-onset muscle soreness (DOMS). The exact mechanism for DOMS is not fully understood but it appears that acute exercise, especially eccentric contractions, causes damage to the ultrastructure, potentially the Z-lines, of the muscle cell. Plasma creatine kinase is used as a marker for muscle damage.
47,565,554
I really need the help of a code guru or expert on this one. What I can’t figure out is why in my existing code below, once a new tab has been created, after calling the add\_new\_tab() function that, when I change my active tab to another tab , and then click back on the newly created tab, that I see that the active class does not get applied to the LI as well as the tab content doesn’t get switched. I am tearing the hair out of my head trying to figure this one out when everything else works as it should (just not with the newly created tab). Here is my html markup: ``` <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-1.12.4.js"></script> <style type="text/css"> ul.tabs { margin: 0; padding: 0; float: left; list-style: none; height: 32px; border-bottom: 1px solid rgb(109,109,109); border-left: 1px solid rgb(109,109,109); width: 100%; display: flex; position: relative; } ul.tabs li { float: left; margin: 0; padding: 0; height: 32px; line-height: 32px; border-top: 1px solid rgb(109,109,109); border-right: 1px solid rgb(109,109,109); border-bottom: 1px solid rgb(109,109,109); border-left: none; margin-bottom: -1px; background: #e0e0e0; overflow: hidden; } ul.tabs li a { text-decoration: none; color: #000; display: block; font-size: 8pt; padding: 0 20px; border: 1px solid #fff; outline: none; } ul.tabs li a:hover { background: #ccc; } html ul.tabs li.active, html ul.tabs li.active a:hover { background: #fff; border-bottom: 0; font-weight: bold; } .tab_container { border: 1px solid rgb(109,109,109); border-top: none; clear: both; float: left; width: 100%; background: #fff; width: 100%; height: 500px; padding: 2px; } .tab_wrapper { background: rgb(231,231,226); height: 100%; } .tab_content { padding: 10px; } </style> <script type="text/javascript"> $(document).ready(function() { init_form() }); function init_form() { //INITIALIZE TABS $(".tab_content").hide(); //Hide all content $("ul.tabs li:first").addClass("active").show(); //Activate first tab $(".tab_content:first").show(); //Show first tab content //On Click Event $("ul.tabs li").on('click', function() { $("ul.tabs li").removeClass("active"); //Remove any "active" class $(this).addClass("active"); //Add "active" class to selected tab $(".tab_content").hide(); //Hide all tab content var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content $(activeTab).fadeIn(); //Fade in the active content return false; }); } function add_new_tab() { var num_tabs = $("ul.tabs li").length var fileno = ( $("#fileno").val() ) ? $("#fileno").val() : '(New)' //debug: alert(num_tabs) if (num_tabs == 0) { $(".tabs").show() $(".tab_container").show() } $("ul.tabs li").removeClass("active"); //Remove any previous "active" class set on any tabs $(".tab_content").hide(); //Hide all previous tab content $("ul.tabs").append("<div class='close_wrapper'><li class='active'><a href='#tab" + num_tabs + "'>"+ fileno +"</a><span class='close'></span></li></div>").show() $(".tab_wrapper").append("<div id='tab" + num_tabs +"' class='tab_content'>I've inserted a new tab for you</div>").hide().fadeIn() //INSERTS NEW TAB CONTENT } </script> </head> <body> </body> </html> ```
2017/11/30
[ "https://Stackoverflow.com/questions/47565554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3724302/" ]
Please try using jQuery on with filter. simple use of on does not ad listener to the newly created elements. ``` $( "document" ).on( "click", "ul.tabs li", function() { $("ul.tabs li").removeClass("active"); //Remove any "active" class $(this).addClass("active"); //Add "active" class to selected tab $(".tab_content").hide(); //Hide all tab content var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content $(activeTab).fadeIn(); //Fade in the active content return false; }); ```
Click events are not attached for the newly created li. Try this. ``` $("ul.tabs").on('click', 'li' ,function() { /* Your function code goes here. */ }); ```
18,026,128
I want to do the following steps: 1. Take a list of check box values and make them into a string array in JavaScript. 2. Take the array and send it to a server-side function. 3. Take the array server side and make it into DataTable. 4. Take the DataTable and send it as a TVP to a stored procedure. I've gotten this to work from server-side on. Where I have trouble is going from JavaScript to server. With my current code, I get this error: > > There are not enough fields in the Structured type. Structured types must have at least one field. > > > How can I pass the JavaScript array to a web method? ``` <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </form> ``` ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.Web.Script.Services; using System.Web.Services; namespace SendTVP { public partial class _default : System.Web.UI.Page { //page variables string filterList = string.Empty; DataTable dt = new DataTable(); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString; using (var con = new SqlConnection(cs)) { using (var cmd = new SqlCommand("spFilterPatientsByRace",con)) { con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = new SqlParameter(); //required for passing a table valued parameter param.SqlDbType = SqlDbType.Structured; param.ParameterName = "@Races"; //adding the DataTable param.Value = dt; cmd.Parameters.Add(param); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind(); } } } [ScriptMethod] [WebMethod] //this method will take JS array as a parameter and turn it into a DataTable public void TableFilter(string filterList) { DataTable filter = new DataTable(); filter.Columns.Add(new DataColumn() { ColumnName = "Races" }); dt.Columns.Add(new DataColumn() { ColumnName = "Races" }); foreach (string s in filterList.Split(',')) { filter.Rows.Add(s); } dt = filter; } } } ``` If this is a complete asinine way to do it, revisions are more than welcome :)
2013/08/02
[ "https://Stackoverflow.com/questions/18026128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/645070/" ]
The problem here is that you have two methods on your web form which require a post back cycle. * When you call the `WebMethod`, it will create an instance of the `_default` class and set the `dt` variable, but do nothing with it. * When you call `Button1_Click`, a new instance of the `_default` class is created, so the `dt` variable is set to `new DataTable();`. Thus, your parameter has no columns or other data. You'll want to do your processing of the `DataTable` in one method, presumably the `TableFilter` method.
I would suggest using [JSON](http://www.json.org/), which is a subset of javascript, to represent the data you are passing. An example of JSON would be: ``` [ "string1", "string2" ] ``` or ``` { "property1": "a", "property2": "b" } ``` Where the first is a valid javascript array and the second is a valid javascript object when passed directly to the browser in a `<script>` tag. [JQuery](http://api.jquery.com/jQuery.parseJSON/) has various methods for dealing with JSON and you can look at [JSON.NET](http://json.codeplex.com/) or [ServiceStack.Text](https://github.com/ServiceStack/ServiceStack.Text) on the .NET side for deserializing JSON into a C# object. [Edit] Though I should point out that it is difficult to get JSON deserialized into a C# `DataTable` because `DataTable` has a lot of properties that you would not necessarily need on the client. Your best bet would be to deserialize to a `List<T>` and iterating through that list adding to the `DataTable` rows as needed.
10,953,237
The [DirectComponent documentation](http://camel.apache.org/direct.html) gives the following example: ``` from("activemq:queue:order.in") .to("bean:orderServer?method=validate") .to("direct:processOrder"); from("direct:processOrder") .to("bean:orderService?method=process") .to("activemq:queue:order.out"); ``` Is there any difference between that and the following? ``` from("activemq:queue:order.in") .to("bean:orderServer?method=validate") .to("bean:orderService?method=process") .to("activemq:queue:order.out"); ``` I've tried to find documentation on what the behaviour of the to() method is on the Java DSL, but beyond the [RouteDefinition javadoc](http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/model/ProcessorDefinition.html#to%28java.lang.String%29) (which gives the very curt "Sends the exchange to the given endpoint") I've come up blank :(
2012/06/08
[ "https://Stackoverflow.com/questions/10953237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37941/" ]
In the very case above, you will not notice much difference. The "direct" component is much like a method call. Once you start build a bit more complex routes, you will want to segment them in several different parts for multiple reasons. You can, for instance, create "sub routes" that could be reused among multiple routes in your Camel context. Much like you segment out methods in regular programming to allow reusability and make code more clear. The same goes for sub routes using, for instance the direct component. The same approach can be extended. Say you want multiple protocols to be used as endpoints to your route. You can use the direct endpoint to create the main route, something like this: ``` // Three endpoints to one "main" route. from("activemq:queue:order.in") .to("direct:processOrder"); from("file:some/file/path") .to("direct:processOrder"); from("jetty:http://0.0.0.0/order/in") .to("direct:processOrder"); from("direct:processOrder") .to("bean:orderService?method=process") .to("activemq:queue:order.out"); ``` Another thing is that one route is created for each "from()" clause in DSL. A route is an artifact in Camel, and you could do certain administrative tasks towards it with the Camel API, such as start, stop, add, remove routes dynamically. The "to" clause is just an endpoint call. Once starting to do some real cases with somewhat complexity in Camel, you will note that you cannot get too many "direct" routes.
[Direct Component](http://camel.apache.org/direct.html) is used to name the logical segment of the route. This is similar process to naming procedures in structural programming. In your example there is no difference in message flow. In the terms of structural programming, we could say that you make a kind of [inline expansion](http://en.wikipedia.org/wiki/Inline_expansion) to your route.
5,160,102
I'm currently working on a remote control software. The unit delivers the following string (without any linebreak or something): ``` ...some_general_infomations,param1=value1,param2=value2,param3=value3,paramN=valueN,... ``` I need somehow to assign these values to some variables. Since the length of this string is varying, I can't work with substrings (correct me if I'm wrong). What is the most efficient (and fastest) way to do this? EDIT: @Darin's solution worked fine for most of the messages, but this one here is really tricky: ``` CFG=0<\r><\n>BOU=0<\r><\n>ALA:D1=132,D2=0,D3=0<\r><\n>COD1:S=13<\r><\n>-C1=5,N1=12345678,CLS=0,VAL=0<\r><\n>-C2=5,N2=,CLS=0,VAL=0<\r><\n>COD2:S=0<\r><\n>-C1=0,N1=,CLS=0,VAL=0<\r><\n>ENT:APPEL1=0,APPEL2=0<\r><\n>USI:DEP=0,AES=1,V8K=1,FIL=1,DSP=0,RSC=1,AL3=0,TDA=1,A64=0,CCS=0,RES=0,xxx=0,xxx=0,5AS=1<\r><\n>PERF:<\r><\n>-DMIN=0,0,<\r><\n>OK<\r><\n> ``` I need at least to get the values for S, C1, N1. Even if I remove the line feeds, these parameters are divided either by a comma or by a colon. How could I handle this string?
2011/03/01
[ "https://Stackoverflow.com/questions/5160102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686793/" ]
A good 'ol split should work: ``` var input = "...some_general_infomations,param1=value1,param2=value2,paramN=valueN"; var tokens = input.Split(','); if (tokens.Length > 0) { foreach (var token in tokens) { var parts = token.Split('='); if (parts.Length > 1) { string paramName = parts[0]; string paramValue = parts[1]; } } } ```
Regular expressions are the standard way to do that; something like so: ``` /,([^=]+)=([^,$]+)/ ```
12,316,015
I've a method '`getAllIDs()`' which is used for getting the ids for specific table in database. It is used by many methods in my project. ``` public static int[] getAllIDs (String TableName, String WhereClause, String trxName) { ArrayList<Integer> list = new ArrayList<Integer>(); StringBuffer sql = new StringBuffer("SELECT "); sql.append(TableName).append("_ID FROM ").append(TableName); if (WhereClause != null && WhereClause.length() > 0) sql.append(" WHERE ").append(WhereClause); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.toString(), trxName); rs = pstmt.executeQuery(); while (rs.next()) list.add(new Integer(rs.getInt(1))); } } ``` Whereclause is the conditional part of query. There is a chance for sql injection due to this whereclause. So I need to modify this method to set the parameter using prepared statement parameter setting. Problem I faced because '`getAllIDs()`' don't know how many parameters for each whereclause. Parameters will be different for each whereclause, it can be any number. For some class, parameters will be 3 and for some it will be 2, etc having different data types. So how can i use setstring(), setint() etc. Explain me with the code which I posted.
2012/09/07
[ "https://Stackoverflow.com/questions/12316015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1654377/" ]
There are several possible ways to do this. A simple one could be to make the `WhereClause` behave like a map where you keep parameter names and values. Then you define the prepared statement template based on the keys and fill it with values. You may need a smarter data structure if you want to join the where clauses with AND/OR keywords or use different operators for each clause: = / < / > / NOT / IS NULL etc, all this dynamically. If you can make use of more sophisticated libraries, the Criteria API in Hibernate or other ORM tools can be really suitable for this kind of usecase.
Most are suggesting a complete ORM solution like Hibernate or JPA. It will take some effort to integrate either of these if you need it for just this one query, but I'm going to guess that this is not the only query subject to SQL injection and the setup can be reused for some/most/all the queries in the app. However, a quick-and-dirty solution is to create methods for each variation of the criteria if there are only a few of them. Each method would accept the exact type of parameter(s) required and know how to bind these arguments into a preparedStatement. There could be a factory method in the class (called by these methods) that would be passed table name, txn name, etc. and would return the SELECT and FROM clauses. Regardless of the solution you choose, the callers of getAllIds() will need to change.
32,328,133
Its seems like in new chrome version on MacOs on Linux Mint and on Windows geolocations doesnt works! Its returns error: "ERROR(2): Network location provider at '<https://www.googleapis.com/>' : Returned error code 403." Does anyone has same problem?
2015/09/01
[ "https://Stackoverflow.com/questions/32328133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218661/" ]
Must be a bug in the latest version of Chrome, also happens in the page of Google Maps API: <https://developers.google.com/maps/documentation/javascript/examples/map-geolocation> Hopefully it will be fixed fast. Edited: Try now, it works :)
i didn't get any solution for "`Returned error code 403`" but i found one solution to get current location if google api fails ``` if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { current_location_lat = position.coords.latitude; current_location_lon = position.coords.longitude; }, function (error) { //if error occurred by google api $.getJSON("http://ipinfo.io", function (ipinfo) { var latLong = ipinfo.loc.split(","); current_location_lat = latLong[0]; current_location_lon = latLong[1]; }); }); } else { // Browser doesn't support Geolocation alert("Error: Your browser doesn\'t support geolocation"); } ```
6,568,632
I wrote the following code to get the time ``` public String getTime() { final Calendar cld = Calendar.getInstance(); String time = cld.get(Calendar.HOUR) + ":" + (cld.get(Calendar.MINUTE)); try { Date date = new SimpleDateFormat("HH:mm").parse(time); time = new SimpleDateFormat("HH:mm").format(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return time; } ``` This always give me time like 11:59 01:07 But I need in 24 hrs format like: 11:59 13:07 How to change the code.
2011/07/04
[ "https://Stackoverflow.com/questions/6568632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637236/" ]
Use `HOUR_OF_DAY` instead of `HOUR`.
Here's the code: ``` Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); String time = hour + ":" + minute; ```
41,289,394
I have a default message on the top of a donation form and I would like it to change dynamically depending on which amount the user hovers or clicks. Each amount as well as "€Other" should have a corresponding message. For Example: "with €5.00 we can accomplish this..." With €10.00 we could do that..." These messages should change accordingly on hover but also remain visible if the corresponding option is selected. If the user deselects a previously selected option or if no option is selected, the default message should reappear. I've tried different methods without success, I would really appreciate some help making this happen. **[FIDDLE](https://jsfiddle.net/davidxmartins/bje4umbL/)** **HTML** ``` <p>Choose below the amount of your donation</p> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> <input type="hidden" name="cmd" value="_donations"> <input type="hidden" name="business" value="louzanimalespaypal@gmail.com"> <label><input type="checkbox" name="amount" class="checkbutton" value="5,00"><span>€05.00</span></label> <label><input type="checkbox" name="amount" class="checkbutton" value="10,00"><span>€10.00</span></label> <label><input type="checkbox" name="amount" class="checkbutton" value="15,00"><span>€15.00</span></label> <label><input type="checkbox" name="amount" class="checkbutton" value="20,00"><span>€20.00</span></label> <input type="number" class="textBox" name="amount" placeholder="€ Other"> <input type="hidden" name="item_name" value="Donation"> <input type="hidden" name="item_number" value="Donation"> <input type="hidden" name="currency_code" value="EUR"> <input type="hidden" name="lc" value="PT"> <input type="hidden" name="bn" value="Louzanimales_Donation_WPS_PT"> <input type="hidden" name="return" value="http://www.louzanimales.py/agradecimentos.htm"> <br style="clear: both;"/> <input class="donation-button" type="submit" value="Send Donation"> </form> ``` **JavaScript** ``` $('input.checkbutton').on('change', function() { $('input.checkbutton').not(this).prop('checked', false); }); $(".textBox").focus(function() { $(".checkbutton").prop("checked", false); }); $(".checkbutton").change(function() { if($(this).is(":checked")) { $(".textBox").val(""); } }); ``` **CSS** ``` body { box-sizing: border-box; padding: 50px; font-family: sans-serif; font-size: 18px; text-align: center; } label { margin: 1%; float: left; background: #ccc; text-align: center; width: 18%; } label:hover { background: grey; color: #fff; } label span { text-align: center; box-sizing: border-box; padding: 10px 0; display: block; } label input { display: none; left: 0; top: -10px; } input:checked + span { background-color: black; color: #fff; } /* Hide HTML5 Up and Down arrows in input type="number" */ input[type=number] {-moz-appearance: textfield;} input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; appearance: none; margin: 0; } .textBox { margin: 1%; float: left; background: #ccc; border: 0; padding: 10px 0; text-align: center; font-family: sans-serif; font-size: 18px; width: 18%; -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */ -moz-box-sizing: border-box; /* For all Gecko based browsers */ box-sizing: border-box; } .textBox:focus { box-shadow:none; box-shadow:inset 0 0 4px 0 #000; -moz-box-shadow:inset 0 0 4px 0 #000; -wevkit-box-shadow:inset 0 0 4px 0 #000; } .donation-button { width: 98%; margin: 1%; border: 0; background: grey; color: white; text-align: center; font-family: sans-serif; font-size: 18px; padding: 10px 0 10px 0; -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */ -moz-box-sizing: border-box; /* For all Gecko based browsers */ box-sizing: border-box; } .donation-button:hover { background: black; } ```
2016/12/22
[ "https://Stackoverflow.com/questions/41289394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341263/" ]
You can use data attributes for input fields, and data can hold text. Also, to achieve desired functionality, you could set 'flag' which will check if option is selected and 'lock' text (so it will not change on hover). Something like this: ```js locked=false; $('input.checkbutton').on('change', function() { $('#desc').text( $(this).data('text') ); if($(this).prop('checked')) { locked=true; } else { locked=false; } $('input.checkbutton').not(this).prop('checked', false); }); $(".textBox").focus(function() { $(".checkbutton").prop("checked", false); }); $(".checkbutton").change(function() { if($(this).is(":checked")) { $(".textBox").val(""); } }); default_text="Choose below the amount of your donation"; $( 'label').hover( function() { if(!locked) $('#desc').text( $(this).children().data('text') ); }, function() { if(!locked) $('#desc').text( default_text ); } ); ``` ```css body { box-sizing: border-box; padding: 50px; font-family: sans-serif; font-size: 18px; text-align: center; } label { margin: 1%; float: left; background: #ccc; text-align: center; width: 18%; } label:hover { background: grey; color: #fff; } label span { text-align: center; box-sizing: border-box; padding: 10px 0; display: block; } label input { display: none; left: 0; top: -10px; } input:checked + span { background-color: black; color: #fff; } /* Hide HTML5 Up and Down arrows in input type="number" */ input[type=number] {-moz-appearance: textfield;} input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; appearance: none; margin: 0; } .textBox { margin: 1%; float: left; background: #ccc; border: 0; padding: 10px 0; text-align: center; font-family: sans-serif; font-size: 18px; width: 18%; -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */ -moz-box-sizing: border-box; /* For all Gecko based browsers */ box-sizing: border-box; } .textBox:focus { box-shadow:none; box-shadow:inset 0 0 4px 0 #000; -moz-box-shadow:inset 0 0 4px 0 #000; -wevkit-box-shadow:inset 0 0 4px 0 #000; } .donation-button { width: 98%; margin: 1%; border: 0; background: grey; color: white; text-align: center; font-family: sans-serif; font-size: 18px; padding: 10px 0 10px 0; -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */ -moz-box-sizing: border-box; /* For all Gecko based browsers */ box-sizing: border-box; } .donation-button:hover { background: black; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="desc">Choose below the amount of your donation</p> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> <input type="hidden" name="cmd" value="_donations"> <input type="hidden" name="business" value="louzanimalespaypal@gmail.com"> <label><input type="checkbox" name="amount" class="checkbutton" value="5,00" data-text="With 5 euros we can..."><span>€05.00</span></label> <label><input type="checkbox" name="amount" class="checkbutton" value="10,00" data-text="With 10 euros we can..."><span>€10.00</span></label> <label><input type="checkbox" name="amount" class="checkbutton" value="15,00" data-text="With 15 euros we can..."><span>€15.00</span></label> <label><input type="checkbox" name="amount" class="checkbutton" value="20,00" data-text="With 20 euros we can..."><span>€20.00</span></label> <input type="number" class="textBox" name="amount" placeholder="€ Other"> <input type="hidden" name="item_name" value="Donation"> <input type="hidden" name="item_number" value="Donation"> <input type="hidden" name="currency_code" value="EUR"> <input type="hidden" name="lc" value="PT"> <input type="hidden" name="bn" value="Louzanimales_Donation_WPS_PT"> <input type="hidden" name="return" value="http://www.louzanimales.py/agradecimentos.htm"> <br style="clear: both;"/> <input class="donation-button" type="submit" value="Send Donation"> </form> ``` P.S. If i didn't understand your requirements, and you want text changing on hover, even when option is selected, you can just remove `locked` var... EDIT: I think it is perfect now: <https://jsfiddle.net/y05uzdzc/> based on your description.
When I run into stuff like this, I pick or create a way to easily distinguish one input from the others. Unique ID's make it quick, and easy to find. In this example, your 5 Euro donation would get the ID of donation-5. ``` $("body").on("mouseover", "input", function () { if ($(this).attr("id") === "donation-5") { // --> DO your hover thing. } else if (so forth and so on...){ // ..... } }) ``` Also, I'd consider using HTML5 button tags. **Ah yes... Nearly forgot, you want to monitor two event types** You'll need two 'event listeners': *The one I listed above,* as well as the one that follows: ``` $("body").on("click", "input", function () { if ($(this).attr("id") === "donation-5") { // --> DO your hover thing. } else if (so forth and so on...){ // ..... } }) ```
6,082,029
I am looking for a way to use the IN keyword in JasperReport. My query looks like: ``` SELECT * FROM table_name WHERE CID IN (145,45, 452); ``` following that in jasper report I can setup this; ``` SELECT * FROM table_name WHERE CID IN ($P{MY_CIDS}); ``` and from my Java I would send `$P{MY_CIDS}` as a `String`, so my query will look like ``` SELECT * FROM table_name WHERE CID IN ("145,45, 452"); ``` My questions is how to transform in SQL `"145,45, 452"` to a valid query so it would take into consideration each value separately `145`, `45`, `452` All help is appreciated.
2011/05/21
[ "https://Stackoverflow.com/questions/6082029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222159/" ]
``` WHERE FIND_IN_SET(CID, "145,45,452") ``` But this query will always cause table fullscan. So I suggest you to rewrite your code and use proper `IN (A, B, C)` syntax.
``` SELECT * FROM table_name WHERE CID IN ($P!{MY_CIDS}); ``` Just use ``` $P!{MY_CIDS} ``` (**exclamation mark** between $P and {MY\_CIDS}). Jasper will now concatinate the Strings like this: ``` "SELECT * FROM table_name WHERE CID IN (" +"145,45,452" +")"; ``` resulting in: ``` SELECT * FROM table_name WHERE CID IN (145,45,452); ``` Took me a long time to get that but now it works for me."
421,430
Recently I purchased 2 RAM carriers from a local supplier: Micron Memory Upgrade 8GB 1867MHZ DDR3 SO-DIMM PC3L-14900S (8GBx2) I wanted to upgrade from my current 8GB to 24GB. However, a few days after installing, I ran into the screen going weird (for a few seconds). Please see the attached picture. In addition, today the screen went blank for a few seconds, then came back but I couldn't interact with it at all, then I had to manually restart it by pressing the on button. And tonight, my iMac just restarted itself for unknown reason. I used Memtest86 to scan for errors (for the whole system). After 6 hours, it found nothing, RAM included. I also used Rember software to double check if RAM are working probably, and again, found no errors. Lastly, I used Mac's diagnostics by pressing D when the computer is turning on, and it found no errors. These issues never occurred during the 6 years I've been using it, only almost right after I installed these 2 pieces of RAM, so I assume the problem is the RAM. What could possibly be the problem? Is it the RAM? The RAM slots? Any advice is appreciated. [![enter image description here](https://i.stack.imgur.com/yYSRP.jpg)](https://i.stack.imgur.com/yYSRP.jpg) [![enter image description here](https://i.stack.imgur.com/rJ1xb.png)](https://i.stack.imgur.com/rJ1xb.png) [![enter image description here](https://i.stack.imgur.com/zEX9e.png)](https://i.stack.imgur.com/zEX9e.png) [![enter image description here](https://i.stack.imgur.com/XR80o.jpg)](https://i.stack.imgur.com/XR80o.jpg) [![enter image description here](https://i.stack.imgur.com/HQcQW.jpg)](https://i.stack.imgur.com/HQcQW.jpg)
2021/05/28
[ "https://apple.stackexchange.com/questions/421430", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/419061/" ]
You could always take out the RAM and see if the problem still occurs. It could just be a coincidence that the problem started after the RAM was installed, in which case you've got another problem!
Check that the two 4GB RAM SO-DIMMS specs match precisely to the two 8GB SO-DIMMS. Specs should be exactly the same except for the RAM capacity. The RAM you bought is definitely within spec. Micron is very good RAM. Apple has used Micron RAM in the past. It's still possible you have some bad RAM and you would have to run the tests for many hours perhaps days to catch a failure when it happens. Definitely try taking out the two 8GB memory SO-DIMMS and see if the problem goes away after a few days of heavy use. Also try just the two 8GB SO-DIMMS by themselves. Then try an 8GB and a 4GB SO-DIMM and swap for the other pair. To trouble-shoot which RAM stick is bad. Try putting the RAM SO-DIMMS in alternating slots. Many computers use alternate slots as channels. Slot 1 & 3 and Slot 2 & 4. It might make a difference when using different sized RAM SO-DIMM's. (Apple doesn't document this, it's just something many computers do with the slot channel arrangement) Apple might not actually do this, it's hard to tell. They list bank0/DIMM0, bank0/DIMM1, bank1/DIMM0, bank1/DIMM1 in the System Information -> Memory view. But it is worth a try to alternate the sizes. 4GB 8GB 4GB 8GB Instead of 4GB 4GB 8GB 8GB It will still run best with all four slots with the same sized SO-DIMMS.
26,352,834
I was trying to modify `A Records` for my domain name. i entered two different value in the name field inside `A Records`: ``` 1. <balnk>.example.com 2. www.example.com ``` Now if i type `example.com` it doen't work but `www.example.com` works. How can i make `example.com` working ?
2014/10/14
[ "https://Stackoverflow.com/questions/26352834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1049104/" ]
You should create A Record for naked domain with wildcard simbol `@` ``` @ A RECORD 127.0.0.1 (depending on your server ip) www CNAME example.com ```
More details about "how" you're trying to configure the A-records would be helpful (DNS application, web interface, etc.), but at its core, consider using the `@` configuration for your naked domain A-record (`example.com`), instead of a `<blank>`. Separately, consider using a CNAME or other redirect for `www.example.com` to `example.com`. Depending on your circumstances, putting some thought into these options may give you better results and/or performance. Check [this page](http://support.dnsimple.com/articles/differences-between-a-cname-alias-url/) out for different redirection options and the implications.
33,405,710
Is there any way to set a date picker to display a specific time on load? I have four date picker instances initiated from four text fields for Start Time, Finish Time, Start Date and Finish Date using the squimer/datePickerDialog subclass from GitHub that pops up in a UIAlertView. In my app a default start time would be 7:00 AM and a default finish time would be 5:00 PM and let the user adjust around those times. All I can see is that you can set the datePicker.defaultDate to currentDate, minimumDate or maximumDate and only once. Is it possible set the defaultDate to hardcoded strings of sTime = "07:00" and fTime = "17:00" in my calls from the ViewController? Any help would be appreciated. **EDIT:** This is how I am calling the subclass from my viewController ``` @IBAction func setFT(sender: UITextField) { resignKeyboardCompletely(sender) DatePickerDialog().show("Pick a Finish Time", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Time) { (timeFinish) -> Void in self.dateFormatter.dateFormat = "HH:mm" let finTime = self.dateFormatter.stringFromDate(timeFinish) self.finishTime.text = finTime } defaults.setObject(finishTime.text, forKey: "finishTime") print(finishTime.text) } ``` Note that throughout this I am also trying to maintain persistence through NSUser Defaults.
2015/10/29
[ "https://Stackoverflow.com/questions/33405710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3118171/" ]
Are you looking for setting the time through a string. If that''s the case you can use a date formatter like this. ``` let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.dateFromString("17:00") datePicker.date = date ``` Adding an init to the [Picker class](https://github.com/squimer/DatePickerDialog-iOS-Swift) ``` init(time:String) { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) setupView() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" if let date = dateFormatter.dateFromString("17:00") { datePicker.date = date } } ```
I got here as it seemed setting the start date wasn't working. Turns out you need to set the initial date after setting the min and max dates.
49,539,674
I have an issue with my `append` function. I was trying to show an image within a select `option` by using values from a database which works fine but users can add more `option`s dynamically by generating a select `option` using the `append` function - but I'm getting this error; > > Uncaught SyntaxError: missing ) after argument list... > > > Here's the code that works fine; ``` <select data-show-subtext="true" class=" selectpicker bs-select form- control" data-live-search="true" data-size="8" name="city"> <option value=""></option> <?php foreach($get_drawing as $row): $image=$row->image; ?> <option data-subtext="<img width='28%' height='90%'' src='<?=base_url("drawing/fabricator/admin_3/".$row->image);?>'>" value="<?php echo $row->drawing_id; ?>" > <?php echo $row->drawing_name;?> </option> ``` And here's the `append` code: ``` $('#add').click(function(){ j++; $('#dynamic_field').append('<div id="row'+j+'" class="row" style="margin-bottom:15px;"><hr><div class=col-sm-1 form-group-sm" style="margin-top:25px; margin-bottom:10px;"><button type="button" name="remove" id="'+j+'" class="btn btn-danger btn_remove"> <i class="fa fa-close"></i></button></div><div class="col-sm-2 form-group-sm"> <label class="control-label">Drawing</label> <select data-show-subtext="true" class=" selectpicker bs-select form-control" data-live-search="true" data-size="8" name="city"><option value=""></option><?php foreach($get_drawing as $row): ?><option data-subtext=<img width='28%' height='90%'' src='<?=base_url("drawing/fabricator/admin_3/".$row->image);?>'>" value="<?php echo $row->drawing_id; ?>" ><?php echo $row->drawing_name;?> </option><?php endforeach; ?></select></div><div class="col-sm-1 form-group-sm"><label class="control-label">Type</label><input type="text" placeholder="Bed Front" class="form-control sm" name="type" value="22"/> </div><div class="col-sm-2 form-group-sm"><label class="control-label">Profile Series</label><input type="text" placeholder="Bed Front" class="form-control" value="22" name="pf"/> </div><div class="col-sm-2 form-group-sm"><label class="control-label">Location</label><input type="text" placeholder="Bed Front" class="form-control" value="22" name="location"/></div><div class="col-sm-1 form-group-sm"><label class="control-label">Width</label><input type="text" placeholder="Bed Front" class="form-control" value="22" name="width"/> </div><div class="col-md-1 form-group-sm"><label class="control-label">Height</label> <input type="text" placeholder="Bed Front" class="form-control" value="22" name="height"/> </div> <div class="col-md-1 form-group-sm"><label class="control-label">Quantity</label> <input type="text" placeholder="Bed Front" class="form-control" value="22" name="quantity"/> </div> <div class="col-md-1 form-group-sm"> <label class="control-label">Fixed</label> <input type="text" placeholder="Height" class="form-control" value="" name="fixed_height"/><br><input type="text" placeholder="Height" class="form-control" value="" name="fixed_width"/></div></div>'); $('.selectpicker').selectpicker('render'); }); ``` According to my knowledge the problem is with this line but I don't know how to correct the code in my `append` function because if I change it, it doesn't work. ``` data-subtext="<img width='28%' height='90%'' src='<?=base_url("drawing/fabricator/admin_3/".$row->image);?>'>" ``` Thanks in advance.
2018/03/28
[ "https://Stackoverflow.com/questions/49539674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3903365/" ]
I think you should set fetch type to lazy : (`fetch = FetchType.LAZY`), or remove it, it's LAZY by default for @OneToMany. This way hibernate (not spring), will do a simple select query on your Job table. But if you keep it to EAGER, hibenate will always use join on User table to get it's data, on the other side, with LAZY mode, the query to get User data will be fired only when you do `job.getCreator()`, but in this case the transaction/session should be kept open. Regards,
Create a query. I.e. ``` @Query(value = "SELECT * FROM JOB WHERE USER_ID = ?1", nativeQuery = true) Job getByUserId(Integer userId); ``` [Source](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#_native_queries)
36,308,224
I have a requirement, where I need to delete thousands of files efficiently. At present, files are deleted in a sequential manner. I want to speed up the deletions, by calling delete in an asynchronous manner, using std::async(). Current Flow: 1. Get the list of files 2. For each file call delete() Desired Flow: 1. Get the list of files 2. For each file: 1. Call AsyncDelete() using std::async() 2. Store the future object in a vector 3. Wait for each of the deletes to be completed and then return I will launch each of the async tasks using `std::launch::async`, so that it runs on a separate thread. I have following questions: 1. Is async() suited for workloads involving multiple tasks? Or is it better to use threads for such tasks? I read a chapter (Item 35: Prefer task-based programming to thread-based) in Scott Myer's book "Effective Modern C++", where he recommends using task based programming instead of thread-based. 2. How costly is each "async()" call? Does it have any overhead like a thread creation overhead? I am planning to control the number of async tasks called per cycle. For e.g. if 10,000 files are to be deleted, I will call just 100 deletes per cycle, instead of spawning 10,000 async() tasks in one go. I hope the standard library implementation efficiently handles multiple async calls (for e.g. using a thread pool). 3. future() object returned by async() exposes both get() and wait() methods. I read that, get() internally calls wait(). Is it enough to call get() on each of the futures stored in a vector? 4. What if a get() never returns? Is it advisable to use wait\_for() with a time out?
2016/03/30
[ "https://Stackoverflow.com/questions/36308224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2256902/" ]
You may find this doesn't actually help as much as you would like. The file system is likely to have kernel level locks (to ensure consistency), and having many threads hitting these locks it likely to cause trouble. I suggest 1. Get the list of files. 2. Divide the list into (say) ten equal chunks (represented by iterator pairs). 3. Launch ten threads which each delete their own chunk of the list. 4. Wait for the ten threads to finish. 5. Experiment with different values of ten.
The bottleneck is the I/O operations and OS level file system operations, delegating thousands of threads to do this is not likely to alleviate that bottleneck -- in fact, you're likely to find that this method will actually slow things down. As others have mentioned, depending on the size of the files, it might be better to store the data in an internal database rather than abusing the file system. Otherwise, I'd probably recommend using *one* thread for file deletion, then you can just wait (or not wait) for the thread to complete. --- To answer one of your questions about how costly `async` is: the implementation of `std::async` is compiler and OS specific and would be comparable to the overhead of the native threading implementation is on your machine. Really, the best thing to do is to benchmark it yourself.
52,791,908
I need to delete an item from my linked list. I am willing to start at the front of the list by redirecting my header (called carbase) to the next one in the list. When i run the function it does free the data of my struct. However, the pointer has not shifted. ``` struct carinfo_t *removeCarinfo(struct carinfo_t *carbase, char *merk, char *model, int year){ struct carinfo_t *curr = carbase; while(curr != NULL){ int a, b, c; a = strcmp(curr->brand, merk); b = strcmp(curr->model, model); c = curr->year; if (a == 0 && b == 0 && c == year){ //verwijderen wanneer dit waar is if(curr = carbase) //als het de eerste in de lijst is carbase = carbase->next; freeCarinfo(curr); return carbase; } curr = curr->next; } } ```
2018/10/13
[ "https://Stackoverflow.com/questions/52791908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10401097/" ]
Rewrite the method this way. ``` public Wedding getWeddingAt(String date, String venue) { for (Wedding w : wedArr) { if (w.getWeddingDate().equals(date) && w.getVenue().equals(venue)) { return w; } } return null; } ```
Your code will say this obviously beacise it is possible that you code will not go into the if block and temp varialble remain unintilized . So , anyone using it need to check null value before using this temp variable . There are several ways you can remove this error : 1. Ignore this error. As this error will not stop running your code . 2. you can use optional intead of returing null , after this your method will lokks like below method : ``` public Optional<Wedding> getWeddingsOnDay(String date, String venue){ Optional<Wedding> temp; for (int loop = 0; loop < counter; loop++) { if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue)) { temp = Optional.of(wedArr[loop]);} else{ temp = Optional.empty(); } } return temp; } ``` 3. You need not to use temp at all just return **wedArr[loop] or null**
39,071,503
Here is my HTML: ```css .parent{ position: fixed; border: 1px solid; height: 43%; width: 300px; } .first_el{ display:block; border: 1px solid green; height: 30px; /* constant */ } .second_el{ border: 1px solild red; height: 100%; /* dynamic */ overflow: scroll; } ``` ```html <div class="parent"> <span class="first_el">title</span> <div class="second_el"> one<br>two<br> three<br> four<br> five<br> six<br> seven<br> eight<br>nine<br> </div> </div> ``` As you can see, the second element is out of its parent. question is how can I set the whole of it into its parent for all screen-sizes? Noted that I can use `calc(100%-30px)` as the `height` of `.second_el` and then the problem will be solved. But as i know `calc` for old browsers doesn't support `calc()`, Thus I don't want to use it. Is there any alternative? *(also I don't want to use `box-sizing: border-box;`, because of old browsers)*
2016/08/22
[ "https://Stackoverflow.com/questions/39071503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5259594/" ]
You can use jQuery for this to set the height programatically, and bind a handler on resize. ``` function setSecondChildHeight() { var BORDER_WIDTH = 1; var parentHeight = $('.parent').outerHeight(); var firstChildHeight = $('.first_el').outerHeight(); var secondChildHeight = parentHeight - firstChildHeight + 2 * BORDER_WIDTH; $('.second_el').height(secondChildHeight); } $(window).resize(setSecondChildHeight); $(function() { setSecondChildHeight(); }); ``` Here's an example fiddle: <https://jsfiddle.net/15wam02w/>
try this code ```css .parent{ position: fixed; border: 1px solid; height: 43%; width: 300px; padding-bottom:30px; overflow:hidden; } .first_el{ display:block; border: 1px solid green; height: 30px; /* same as class .parent padding-bottom */ overflow:hidden; } .second_el{ border: 1px solild red; height:100%; overflow-y: scroll; overflow-x: hidden; } ``` ```html <div class="parent"> <span class="first_el">title</span> <div class="second_el"> one<br>two<br> three<br> four<br> five<br> six<br> seven<br> eight<br>nine<br> </div> </div> ```
16,553,415
If I have: ``` function firstFunction(){ var counter = 0; secondFunction(); secondFunction(); secondFunction(); secondFunction(); } function secondFunction(){ counter++; } ``` I get an error because of the local scope of the variable, but how else am I to do something like this without using global variables?
2013/05/14
[ "https://Stackoverflow.com/questions/16553415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388017/" ]
One way is to use a closure: ``` (function() { var counter = 0; function firstFunction() { secondFunction(); secondFunction(); secondFunction(); secondFunction(); } function secondFunction() { counter++; } })(); ``` Alternately, you could pass in the value of `counter` to `secondFunction`, like this: ``` function firstFunction() { var counter = 0; counter = secondFunction(counter); counter = secondFunction(counter); counter = secondFunction(counter); counter = secondFunction(counter); } function secondFunction(counter) { return ++counter; } ```
As an addition to Elliot Bonneville's answer, you can also do this: ``` var firstFunction = (function() { var counter = 0, secondFunction = function { counter++; }; return function() { counter = 0;//initialize counter to 0 secondFunction(); return counter; }; }; console.log(firstFunction());//logs 1, because counter was set to 1 and returned ``` This is all getting a bit much, but google *"JavaScript module pattern"* and look into it. You'll soon find out what makes this code tick: ``` var counterModule = (function() { var counter = 0, secondFunction = function { counter++; }, firstFunction = function() { counter = 0;//initialize counter to 0 secondFunction(); }, getCounter = function() { return counter; } setCounter = function(val) { counter = +(val); }; return {firstFunction: firstFunction, getCounter: getCounter, setCounter: setCounter}; }; console.log(counterModule.firstFunction());//undefined console.log(counterModule.getCounter());//1 console.log(counterModule.secondFunction());//ERROR ``` It's all about exposure of certain closure variables... Keep working at it, this is an important pattern to understand, I promise!
1,863,470
Evaluate the following limit: $$L=\lim\_{x\to 0} \frac{(1+x)^{1/x}-e+\frac{ex}{2}}{x^2}$$ Using $\ln(1+x)=x-x^2/2+x^3/3-\cdots$ I got $(1+x)^{1/x}=e^{1-x/2+x^2/3-\cdots}$ Could some tell me how to proceed further?
2016/07/18
[ "https://math.stackexchange.com/questions/1863470", "https://math.stackexchange.com", "https://math.stackexchange.com/users/352447/" ]
You can proceed in the following manner \begin{align} L &= \lim\_{x \to 0}\dfrac{(1 + x)^{1/x} - e + \dfrac{ex}{2}}{x^{2}}\notag\\ &= e\lim\_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1\right) - 1 + \dfrac{x}{2}}{x^{2}}\notag\\ &= e\lim\_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1\right) - \exp\left(\log\left(1 - \dfrac{x}{2}\right)\right)}{x^{2}}\notag\\ &= e\lim\_{x \to 0}\exp\left(\log\left(1 - \dfrac{x}{2}\right)\right)\cdot\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)\right) - 1}{x^{2}}\notag\\ &= e\lim\_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)\right) - 1}{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}\cdot\dfrac{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}{x^{2}}\notag\\ &= e\lim\_{x \to 0}\dfrac{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}{x^{2}}\notag\\ &= e\lim\_{x \to 0}\dfrac{\left(1 - \dfrac{x}{2} + \dfrac{x^{2}}{3} + o(x^{2})\right) - 1 + \left(\dfrac{x}{2} + \dfrac{x^{2}}{8} + o(x^{2})\right)}{x^{2}}\text{ (using Taylor series)}\notag\\ &= e\left(\frac{1}{3} + \frac{1}{8}\right)\notag\\ &= \frac{11e}{24}\notag \end{align} The above approach uses the standard limit $$\lim\_{t \to 0}\frac{\exp(t) - 1}{t} = 1$$ Taylor series is used only when necessary and this approach avoids any multiplication/division of infinite series.
It's a well-known fact that $$\log(1+x)=x-\dfrac{x^2}2+\dfrac{x^3}3+\underset{x\to 0}{o}(x^3)$$ Hence we get $$\dfrac 1x\log(1+x)=1+u(x)$$ where $$u(x)=-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)$$ Notice that $$\lim\_{x\to 0} u(x)=0$$ We can write $$(1+x)^{1/x}=ee^{u(x)}$$ But we know that $$e^u=1+u+\dfrac{u^2}2+\underset{u\to 0}o(u^2)$$ Now using the identity $$(a+b+c)^2=a^2+b^2+c^2+2ab+2bc+2ac$$ we quickly find, since we only need the terms whose degrees are less than three (the other terms are all some $\underset{x\to 0}o(x^2)$), that $$(u(x))^2=\left(-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)\right)^2=\dfrac{x^2}4+\underset{x\to 0}o(x^2)$$ Hence, since $\displaystyle\lim\_{x\to 0}u(x)=0$, we see than an $\underset{u\to 0}o(u^2)$ function is an $o(x^2)$ when $x$ tends to $0$. This leads to $$\begin{align\*}(1+x)^{1/x} & = e\left(1+\left(-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)\right)+\dfrac 12\left(\dfrac{x^2}4+\underset{x\to 0}o(x^2)\right)+\underset{x\to 0}{o}(x^2)\right)\\ & = e-\dfrac{ex}2+\dfrac{11e}{24}x^2+\underset{x\to 0}o(x^2)\end{align\*}$$ And so : $$\dfrac{(1+x)^{1/x}-e+\dfrac{ex}2}{x^2}=\dfrac{11e}{24}+\underset{x\to 0}o(1)$$ which means exactly that $$\lim\_{x\to 0}\dfrac{(1+x)^{1/x}-e+\dfrac{ex}2}{x^2}=\dfrac{11e}{24}$$
29,111,571
I'm trying to get my Passport local strategy working. I've got this middleware set up: ``` passport.use(new LocalStrategy(function(username, password, done) { //return done(null, user); if (username=='ben' && password=='benny'){ console.log("Password correct"); return done(null, true); } else return done(null, false, {message: "Incorrect Login"}); })); ``` but then in here ``` app.use('/admin', adminIsLoggedIn, admin); function adminIsLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page res.redirect('/'); } ``` it always fails and redirects to the home page. I can't figure out why this is happening? Why won't it authenticate? In my console I can see that's `Password Correct` is printing. Why won't it work?
2015/03/17
[ "https://Stackoverflow.com/questions/29111571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675976/" ]
I also had the same problem, could not find any solution on the web but i figured it out. ``` app.use(require("express-session")({ secret: "This is the secret line", resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); app.use(bodyParser.urlencoded({extended: true})); ``` express-session requirement and use should be before any other use. Try this i am sure this would work, worked for me!!
I have to agree with @karan525. However, I made sure to test the portion of my code at different locations on my app page. Where it finally worked for me was towards the start but after any configuration files. ``` // Session app.use(session({ secret: 'not so secret', resave: true, saveUninitialized: true, })); // Passport middleware app.use(passport.initialize()); app.use(passport.session()); ```
66,559
I'm just wondering if there are any **2D** alternatives to Unity (excluding KDE, XFCE, LXDE, etc.) that have a modern look to them. I like Unity (since I'm newer to Ubuntu) but I just think an alternative would be cool. Replies would be appreciated. PS: My computer is a few years old and **only has 2d acceleration.**
2011/10/15
[ "https://askubuntu.com/questions/66559", "https://askubuntu.com", "https://askubuntu.com/users/27283/" ]
Gnome 3 has a very modern look and scales nicely on older hardware: ![](https://i.stack.imgur.com/XXBW0.png) You can install Gnome 3 by [clicking here ![Install gnome-shell](https://hostmar.co/software-small)](http://apt.ubuntu.com/p/gnome-shell) or by entering the following in a terminal: ``` sudo apt-get install gnome-shell ``` Once Gnome 3 is installed, simply log out, click the gear icon next to your name on the login screen and select "Gnome".
Ok, so I installed Pantheon, and except for the exclusion of a background, it is ok for me. Case closed.
12,863,663
My question involves how to go about dealing with complex nesting of **templates** (also called **partials**) in an AngularJS application. The best way to describe my situation is with an image I created: ![AngularJS Page Diagram](https://i.stack.imgur.com/V17C3.png) As you can see this has the potential to be a fairly complex application with lots of nested models. The application is single-page, so it loads an **index.html** that contains a div element in the DOM with the `ng-view` attribute. **For circle 1**, You see that there is a Primary navigation that loads the appropriate templates into the `ng-view`. I'm doing this by passing `$routeParams` to the main app module. Here is an example of what's in my app: ``` angular.module('myApp', []). config(['$routeProvider', function($routeProvider) { $routeProvider. when("/job/:jobId/zones/:zoneId", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/zone_edit.html' }). when("/job/:jobId/initial_inspection", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/initial_inspection.html' }). when("/job/:jobId/zones/:zoneId/rooms/:roomId", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/room_edit.html' }) }]); ``` **In circle 2**, the template that is loaded into the `ng-view` has an additional **sub-navigation**. This sub-nav then needs to load templates into the area below it - but since ng-view is already being used, I'm not sure how to go about doing this. I know that I can include additional templates within the 1st template, but these templates are all going to be pretty complex. I would like to keep all the templates separate in order to make the application easier to update and not have a dependency on the parent template having to be loaded in order to access its children. **In circle 3**, you can see things get even more complex. There is the potential that the sub-navigation templates will have a **2nd sub-navigation** that will need to load its own templates as well into the area in **circle 4** **How does one go about structuring an AngularJS app to deal with such complex nesting of templates while keeping them all separate from one another?**
2012/10/12
[ "https://Stackoverflow.com/questions/12863663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875342/" ]
I too was struggling with nested views in Angular. Once I got a hold of [ui-router](https://github.com/angular-ui/ui-router) I knew I was never going back to angular default routing functionality. Here is an example application that uses multiple levels of views nesting ``` app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) { // navigate to view1 view by default $urlRouterProvider.otherwise("/view1"); $stateProvider .state('view1', { url: '/view1', templateUrl: 'partials/view1.html', controller: 'view1.MainController' }) .state('view1.nestedViews', { url: '/view1', views: { 'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'}, 'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' }, 'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' } } }) .state('view2', { url: '/view2', }) .state('view3', { url: '/view3', }) .state('view4', { url: '/view4', }); }); ``` As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.
Angular ui-router supports nested views. I haven't used it yet but looks very promising. <http://angular-ui.github.io/ui-router/>
51,585,095
I previously had tensorflow with gpu support installed and working. I tried to install keras afterwhich nothing would work anymore. I have since uninstalled keras and tensorflow. I tried re-installing tensorfow with gpu support (now version 1.9) following the instructions on the tensorflow webpage <https://www.tensorflow.org/install/install_linux> (I am running ubuntu 18 by the way). I tried running the code ``` import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) ``` and I get the error ``` import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) Traceback (most recent call last): File "<ipython-input-2-25b92e4d5dec>", line 2, in <module> hello = tf.constant('Hello, TensorFlow!') AttributeError: module 'tensorflow' has no attribute 'constant' ``` I tried looking at other threads and there was a suggestion to capitalize the C in 'constant' but that didnt work either. Any suggestions would be great! Thanks
2018/07/29
[ "https://Stackoverflow.com/questions/51585095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9045339/" ]
I had same issue and I mistakenly named my file as `tensorflow.py`. Same issue would occur if folder name is tensorflow. I just renamed file with something else and it resolve the issue.
Follow these steps: 1. Create new virtualenv > > How to create virtuealenv (<https://linuxhostsupport.com/blog/how-to-install-virtual-environment-on-ubuntu-16-04/>) > > > 2. pip3 install requests 3. pip3 install -q -U tensor2tensor 4. pip3 install tensorflow For some reason the dependencies of the tensorflow remain in the system, so creating from scratch can solve the problem.
16,438,337
I think it is used to check the coding but when I tried it didn't respond. I mean it doesn't give any response and showing the data of current website.
2013/05/08
[ "https://Stackoverflow.com/questions/16438337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361745/" ]
The f12 is a shortcut to Open up [firebug](https://addons.mozilla.org/en-US/firefox/addon/firebug/) in firefox. To open up firebug you must firstly have it installed
In newer versions of Firefox (I have 91.12.0esr), there is an "experimental" setting in the about:config setting that can disable the F12 hotkey. Setting the `devtools.experiment.f12.shortcut_disabled` key to `true` causes the F12 key to bring up a temporary text box that says "To use the F12 shortcut, first open DevTools via the Web Developer menu." but thankfully no longer opens the DevTools bar. This should be the default behavior, IMHO, since only a small fraction of users will know or care about viewing the HTML source of the page.
227,407
In my story, there are a strange species from the *Homo* genus: hematophagous humans often called vampires (their scientific name is *Homo haematophagus*) (so, they are still humans, just not *Homo sapiens*). I think the /s/ and the /z/ consonants are the most common fricatives around the world (except for maybe the /f/ and the /v/ consonants, and the /h/ sound). However, in the most spoken language used by vampires, there are no the /s/ and the /z/ consonants. There are eight fricatives in that language: /f/, /v/, the sound corresponding to the French *ch* (as in French *cheval*) (*cheval* means horse), the sound corresponding to the French *j* (as in French *jeu*) (*jeu* means game), the sound corresponding to the voiceless English th (as in English thief), and the sound corresponding to the voiced English th (or the Albanese *dh*) (as in English brother), the /x/ sound (as in Spanish *ojo* which means eye), and the sound corresponding to the *g* in Spanish *amigo* (which means friend). There are also two nasal consonants: /m/ as in English mother, and /n/ as in English night. There are also six plosives: /p/ as in English principality, /b/ as in English beauty, /t/ as in English turtle, /d/ as in English dementia, /k/ as in English kilogram, and /g/ as in English green. There is the /l/ sound as in English lesbian. Also, the rhotic sound used in the most spoken language used by vampires is the voiced alveolar trill (the rhotic sound used in Slavic languages, some Germanic languages such as Dutch, and Icelandic, and most Italic languages such as Italian, and Romanian). In the most spoken language used by vampires, there are seven simple vowels: /a/ (as in French *abeille*) (*abeille* means bee), /i/ (as in English hippie) (hippie is also used in French), /u/ (as in French *ouvrier*) (*ouvrier* means worker), /y/ (as in French *univers*) (*univers* naturally means universe), the sound corresponding to the *a* in English fall (or the *o* in French *ordinateur*) (*ordinateur* means computer), the sound corresponding to the French *eu* (or the German *â*) (as in French *euphémisme*) (*euphémisme* naturally means euphemism), and the sound corresponding to the French *è* (as in French *pègre*) (*pègre* means underworld). Finally, in the most spoken language used by vampires, there are all the three semivowels used in French (in other words, the /j/ sound as in English yellow, and in French *hyène*, the /w/ sound as in English world, and in French *oiseau*, and the sound corresponding to the *u* in the French word *fruit*) (these three French words respectively mean hyena, bird, and fruit). So, I wonder why would a language created by mammals from the *Homo* genus lack both the /s/ and the /z/ consonants.
2022/03/28
[ "https://worldbuilding.stackexchange.com/questions/227407", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/71996/" ]
Centuries ago, one of the great kings of your vampire people was born with a speech impediment. He spoke with a severe lisp, and was never able to form the "s" or "z" sounds. In order to make him not feel like an oddball, the royal court began imitating the lisp. It soon became viewed as a sign of respect and had spread throughout the entire land. By the end of that king's reign, the lisp had become embedded in the linguistic tradition and the "s" and "z" sounds were gone forever.
**Hiss. . . .** Being the walking dead, vampires have lungs that don't work. This means they cannot blow up party balloons, and they cannot make sounds that require the release of air from the lungs. Some of these sounds can be worked around. For example one can make an /f/ sound by moving your lower lip forward over your upper row of teeth. This triggers a *popping* release of air from the mouth that replaces the typical *hissing* release of air from the lungs. Unfortunately esses and ezzes cannot be simulated this way.
44,708,300
I have a huge class with a lot of information. Some information of that I want to print to JSON, but not all information. When I serialize the Object to JSON it off course prints all information. So I thought I made a template Class for the data I do want to print in JSON. And then I want to copy all values that do exist in the template from the original class and skip the rest. Then I can serialize that template Class. For example: [![enter image description here](https://i.stack.imgur.com/koSyT.png)](https://i.stack.imgur.com/koSyT.png) Now what I try to accomplish is to copy the data from `place` to `placeJSON`. [![enter image description here](https://i.stack.imgur.com/hBeO3.png)](https://i.stack.imgur.com/hBeO3.png) So the result will be something like this:[![enter image description here](https://i.stack.imgur.com/rVRyw.png)](https://i.stack.imgur.com/rVRyw.png) I thought I should loop over all properties in `placeJSON` and if the same property name exist in `place` then I should copy that value. But it also needs to be done for nested classes like `Country`. How is this possible to do?
2017/06/22
[ "https://Stackoverflow.com/questions/44708300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2740744/" ]
So, usually this is done with a trigger. Anytime an insert or update is done on a table, a follow on insert would be done to your audit table. So, I'd really look into that. But if you don't want to go that route or this is a 3rd party system which you can't add triggers, you could just insert changes in a few ways. A quick way is using except. Basically it inserts records from the source table, into the audit table, when they don't match exactly. Here is an example. ``` declare @source table ( AccountNo int ,Address varchar(256) ,Salary decimal(16,4) ,PromotionDate datetime) insert into @source values (12345,'123 Main Street',60000,'20170115') declare @audit table ( AccountNo int ,Address varchar(256) ,Salary decimal(16,4) ,PromotionDate datetime ,RunDate datetime) --load the audit table with the current version of the source table insert into @audit select *, getdate() from @source --show that the tables match currently select * from @source select * from @audit --insert into @audit if there are any changes (notice we haven't made any updates yet) insert into @audit select AccountNo, Address, Salary, PromotionDate, getdate() from @source except select AccountNo, Address, Salary, PromotionDate, getdate() from @audit --show that a record WAS NOT inserted since there was no change. There is only 1 record, the orignal version select * from @audit --update the promotion and salary update @source set PromotionDate = '20170331' ,Salary = '65000' --insert into @audit if there are any changes insert into @audit select AccountNo, Address, Salary, PromotionDate, getdate() from @source except select AccountNo, Address, Salary, PromotionDate, getdate() from @audit --show that a record was inserted since there was a change select * from @audit ``` Then, all you have to do is select from the @audit table and order by RunDate and you can easily see what was changed quickly, versus pivoting the data and having 1 row for EVERY change for every account. In this example, you only see 1 extra row though there was a salary and promotion data change. You can use your LEAD and LAG functions, or self join on the top 1 where RunDate < RunDate to flag if the column changed but it's really unnecessary.
I'm not sure I have understood your requirement clearly but I would have looked for a solution using INSERT / UPDATE triggers to solve this kind of audit-trial tasks. Perhaps that would make things simpler.
37,936,571
I did search and looked at these below links but it didn't help . 1. [Point covering problem](https://stackoverflow.com/questions/2821603/point-covering-problem) 2. [Segments poked (covered) with points - any tricky test cases?](https://stackoverflow.com/questions/35824063/segments-poked-covered-with-points-any-tricky-test-cases) 3. [Need effective greedy for covering a line segment](https://stackoverflow.com/questions/3908139/need-effective-greedy-for-covering-a-line-segment) Problem Description: ``` You are given a set of segments on a line and your goal is to mark as few points on a line as possible so that each segment contains at least one marked point ``` Task. ``` Given a set of n segments {[a0,b0],[a1,b1]....[an-1,bn-1]} with integer coordinates on a line, find the minimum number 'm' of points such that each segment contains at least one point .That is, find a set of integers X of the minimum size such that for any segment [ai,bi] there is a point x belongs X such that ai <= x <= bi ``` Output Description: ``` Output the minimum number m of points on the first line and the integer coordinates of m points (separated by spaces) on the second line ``` Sample Input - I ``` 3 1 3 2 5 3 6 ``` Output - I ``` 1 3 ``` Sample Input - II ``` 4 4 7 1 3 2 5 5 6 ``` Output - II ``` 2 3 6 ``` I didn't understand the question itself. I need the explanation, on how to solve this above problem, but i don't want the code. Examples would be greatly helpful
2016/06/21
[ "https://Stackoverflow.com/questions/37936571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5420681/" ]
Maybe this formulation of the problem will be easier to understand. You have `n` people who can each tolerate a different range of temperatures `[ai, bi]`. You want to find the minimum number of rooms to make them all happy, i.e. you can set each room to a certain temperature so that each person can find a room within his/her temperature range. As for how to solve the problem, you said you *didn't* want code, so I'll just roughly describe an approach. Think about the coldest room you have. If making it one degree warmer won't cause anyone to no longer be able to tolerate that room, you might as well make the increase, since that can only allow more people to use that room. So the first temperature you should set is the *warmest one that the most cold-loving person can still tolerate*. In other words, it should be the smallest of the `bi`. Now this room will satisfy some subset of your people, so you can remove them from consideration. Then repeat the process on the remaining people. Now, to implement this efficiently, you might not want to literally do what I said above. I suggest sorting the people according to `bi` first, and for the `i`th person, try to use an existing room to satisfy them. If you can't, try to create a new one with the highest temperature possible to satisfy them, which is `bi`.
Here's the working code in C++ for anyone searching :) ``` #include <bits/stdc++.h> #define ll long long #define double long double #define vi vector<int> #define endl "\n" #define ff first #define ss second #define pb push_back #define all(x) (x).begin(),(x).end() #define mp make_pair using namespace std; bool cmp(const pair<ll,ll> &a, const pair<ll,ll> &b) { return (a.second < b.second); } vector<ll> MinSig(vector<pair<ll,ll>>&vec) { vector<ll> points; for(int x=0;x<vec.size()-1;) { bool found=false; points.pb(vec[x].ss); for(int y=x+1;y<vec.size();y++) { if(vec[y].ff>vec[x].ss) { x=y; found=true; break; } } if(!found) break; } return points; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin>>n; vector<pair<ll,ll>>v; for(int x=0;x<n;x++) { ll temp1,temp2; cin>>temp1>>temp2; v.pb(mp(temp1,temp2)); } sort(v.begin(),v.end(),cmp); vector<ll>res=MinSig(v); cout<<res.size()<<endl; for(auto it:res) cout<<it<<" "; } ```
4,912,485
I have implemented this security proccess in my project: [Spring Security 3 - MVC Integration Tutorial (Part 2)](http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html). My problem is that I need to turn it into an Ajax-based login. What do I need to do in order to make this XML suitable with just returning string/JSON to the client? I understand that the problem might be in the `form-login` tag. ``` <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <!-- This is where we configure Spring-Security --> <http auto-config="true" use-expressions="true" access-denied-page="/Management/auth/denied" > <intercept-url pattern="/Management/auth/login" access="permitAll"/> <intercept-url pattern="/Management/main/admin" access="hasRole('ROLE_ADMIN')"/> <intercept-url pattern="/Management/main/common" access="hasRole('ROLE_USER')"/> <form-login login-page="/Management/auth/login" authentication-failure-url="/Management/auth/login?error=true" default-target-url="/Management/main/common"/> <logout invalidate-session="true" logout-success-url="/Management/auth/login" logout-url="/Management/auth/logout"/> </http> <!-- Declare an authentication-manager to use a custom userDetailsService --> <authentication-manager> <authentication-provider user-service-ref="customUserDetailsService"> <password-encoder ref="passwordEncoder"/> </authentication-provider> </authentication-manager> <!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database --> <beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/> <!-- A custom service where Spring will retrieve users and their corresponding access levels --> <beans:bean id="customUserDetailsService" class="com.affiliates.service.CustomUserDetailsService"/> </beans:beans> ```
2011/02/06
[ "https://Stackoverflow.com/questions/4912485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/605141/" ]
Spring is shifting away from XML based configurations and towards Java `@Configuration` classes. Below is `@Configuration` version of the setup explained in the post above ([Spring Security Ajax login](https://stackoverflow.com/questions/4912485/spring-security-ajax-login/16577637#16577637)). Steps 2 & 3 remain the same, replace Step 1 with this code. The order is once again important, more specific definitions needs to be loaded before more generic ones, use `@Order(1)` and `@Order(2)` to control that. ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; @Configuration @EnableWebSecurity public class WebMvcSecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean(name = "requestCache") public RequestCache getRequestCache() { return new HttpSessionRequestCache(); } @Configuration @Order(1) public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { @Autowired private RequestCache requestCache; @Override protected void configure(HttpSecurity http) throws Exception { http .regexMatcher("/rest.*") .authorizeRequests() .antMatchers("/rest/calendar/**") .hasAuthority("ROLE_USER") .antMatchers("/rest/**") .permitAll() .and() .headers() .xssProtection() .and() .logout() .logoutUrl("/rest/security/logout-url") .and() .requestCache() .requestCache(requestCache) .and() .formLogin() .loginProcessingUrl("/rest/security/login-processing") .loginPage("/rest/security/login-page") .failureUrl("/rest/security/authentication-failure") .defaultSuccessUrl("/rest/security/default-target", false) .and() .httpBasic(); } } @Configuration @Order(2) public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired private RequestCache requestCache; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .regexMatchers("/calendar/.*") .hasAuthority("ROLE_USER") .regexMatchers("/.*") .permitAll() .and() .logout() .logoutUrl("/security/j_spring_security_logout") .and() .requestCache() .requestCache(requestCache) .and() .formLogin() .loginProcessingUrl("/security/j_spring_security_check") .loginPage("/login") .failureUrl("/login?login_error=t" ) .and() .httpBasic(); } } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/resources/**") .antMatchers("/sitemap.xml"); } } ```
You can use `HttpServletRequest.login(username,password)` to login, just like: ``` @Controller @RequestMapping("/login") public class AjaxLoginController { @RequestMapping(method = RequestMethod.POST) @ResponseBody public String performLogin( @RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response) { try { request.login(username,password); return "{\"status\": true}"; } catch (Exception e) { return "{\"status\": false, \"error\": \"Bad Credentials\"}"; } } ```
37,934,711
When I am trying to add a new Network Interface for Host only network, Virtual Box version :Version 5.0.22 r108108. I am getting a following error: ``` Could not find Host Interface Networking driver! Please reinstall. Result Code: E_FAIL (0x80004005) Component: HostNetworkInterfaceWrap Interface: IHostNetworkInterface {455f8c45-44a0-a470-ba20-27890b96dba9} ```
2016/06/21
[ "https://Stackoverflow.com/questions/37934711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5840664/" ]
You must reinstall the driver. Go to device manager, you will find an "unknown driver" missing then update it by pointing to this link: `C:\Program Files\Oracle\VirtualBox\drivers\network\netadp6\VBoxNetAdp6.inf`
In some cases, (worked for me) running and getting the latest update of vbox fix the problem. And got the Host Interface Networking driver automatically installed. The update I run was: VirtualBox-6.0.14-133895-Win
17,135
My Galaxy Nexus running 4.0.2 does not vibrate for any notifications while in "vibrate" mode. Haptic feedback works, and the phone vibrates when I receive phone calls, but not for notifications. The global vibrate setting under "Sound" in the menu is set to "Always", and individual apps like Gmail, Messaging, etc. have vibrate set to "Always". Any help appreciated! Thanks!
2011/12/19
[ "https://android.stackexchange.com/questions/17135", "https://android.stackexchange.com", "https://android.stackexchange.com/users/10743/" ]
There is a separate vibrate setting in the menu for sms messaging under Settings.
Try installing the [Llama app](https://market.android.com/details?id=com.kebab.Llama) then removing it. For some reason it fixes this, I had the same problem. There is a issue on the [tracker](http://code.google.com/p/android/issues/detail?id=23300#c8) that could help.
64,721,568
I would like to implement a button on a plotly chart that will copy the plot to the user's clipboard similar to how the snapshot button downloads a png of the plot as a file. I've referenced [this documentation](https://plotly-r.com/control-modebar.html#add-custom-modebar-buttons) to create a custom modebar button, but I'm not familiar enough with Javascript to know how to write that snippet (or if its even possible). Below is the R code I wrote to try it, but it doesn't work. A button does appear (although the image is not visible, but I can tell its there if I hover in the upper rightmost corner). But when I click it, the plot is not copied to the clipboard and the chrome console says: > > Uncaught TypeError: Plotly.execCommand is not a function > at Object.eval [as click] (eval at tryEval ((index):258), :2:15) > at HTMLAnchorElement. (:7:2055670) > > > Figure: [![Plotly modebar with my desired button](https://i.stack.imgur.com/3pECs.png)](https://i.stack.imgur.com/3pECs.png) My code: ```r library(plotly) library(shiny) d <- data.frame(xaxis = c(1,2,3,4,5), ydata = c(10,40,60,30,25)) p <- plot_ly() %>% add_trace(data = d, x = ~xaxis, y = ~ydata, type = "scatter", mode = "lines") plotClip <- list( name = "plotClip", icon = list( path = "plotClip.svg", transform = 'matrix(1 0 0 1 -2 -2) scale(0.7)' ), click = htmlwidgets::JS( 'function(gd) { Plotly.execCommand("copy"); alert("Copied the plot"); }' ) ) p <- p %>% config(modeBarButtonsToAdd = list(plotClip), displaylogo = FALSE, toImageButtonOptions= list(filename = "plot.png", format = "png", width = 800, height = 400)) ui <- fluidPage( plotlyOutput(outputId = "myplot") ) server <- function(input, output) { output$myplot <- renderPlotly({ p }) } shinyApp(ui, server) ``` Thanks for any insight on this!
2020/11/06
[ "https://Stackoverflow.com/questions/64721568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5442622/" ]
I don't know how to deal with the toolbar, but here is how to copy the image to the clipboard by clicking a button: ```r library(shiny) library(plotly) d <- data.frame(X1 = rnorm(50,mean=50,sd=10), X2 = rnorm(50,mean=5,sd=1.5), Y = rnorm(50,mean=200,sd=25)) ui <- fluidPage( title = 'Copy Plotly to clipboard', sidebarLayout( sidebarPanel( helpText(), actionButton('copy', "Copy") ), mainPanel( plotlyOutput('regPlot'), tags$script(' async function copyImage(url) { try { const data = await fetch(url); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log("Image copied."); } catch (err) { console.error(err.name, err.message); } } document.getElementById("copy").onclick = function() { var gd = document.getElementById("regPlot"); Plotly.Snapshot.toImage(gd, {format: "png"}).once("success", function(url) { copyImage(url); }); }') ) ) ) server <- function(input, output, session) { regPlot <- reactive({ plot_ly(d, x = d$X1, y = d$X2, mode = "markers") }) output$regPlot <- renderPlotly({ regPlot() }) } shinyApp(ui = ui, server = server) ``` --- EDIT ==== I found how to deal with the toolbar. This even doesn't require Shiny. ```r library(plotly) asd <- data.frame( week = c(1, 2, 3), a = c(12, 41, 33), b = c(43, 21, 23), c = c(43, 65, 43), d = c(33, 45, 83) ) js <- c( 'function (gd) {', ' Plotly.Snapshot.toImage(gd, { format: "png" }).once(', ' "success",', ' async function (url) {', ' try {', ' const data = await fetch(url);', ' const blob = await data.blob();', ' await navigator.clipboard.write([', ' new ClipboardItem({', ' [blob.type]: blob', ' })', ' ]);', ' console.log("Image copied.");', ' } catch (err) {', ' console.error(err.name, err.message);', ' }', ' }', ' );', '}' ) Copy_SVGpath <- "M97.67,20.81L97.67,20.81l0.01,0.02c3.7,0.01,7.04,1.51,9.46,3.93c2.4,2.41,3.9,5.74,3.9,9.42h0.02v0.02v75.28 v0.01h-0.02c-0.01,3.68-1.51,7.03-3.93,9.46c-2.41,2.4-5.74,3.9-9.42,3.9v0.02h-0.02H38.48h-0.01v-0.02 c-3.69-0.01-7.04-1.5-9.46-3.93c-2.4-2.41-3.9-5.74-3.91-9.42H25.1c0-25.96,0-49.34,0-75.3v-0.01h0.02 c0.01-3.69,1.52-7.04,3.94-9.46c2.41-2.4,5.73-3.9,9.42-3.91v-0.02h0.02C58.22,20.81,77.95,20.81,97.67,20.81L97.67,20.81z M0.02,75.38L0,13.39v-0.01h0.02c0.01-3.69,1.52-7.04,3.93-9.46c2.41-2.4,5.74-3.9,9.42-3.91V0h0.02h59.19 c7.69,0,8.9,9.96,0.01,10.16H13.4h-0.02v-0.02c-0.88,0-1.68,0.37-2.27,0.97c-0.59,0.58-0.96,1.4-0.96,2.27h0.02v0.01v3.17 c0,19.61,0,39.21,0,58.81C10.17,83.63,0.02,84.09,0.02,75.38L0.02,75.38z M100.91,109.49V34.2v-0.02h0.02 c0-0.87-0.37-1.68-0.97-2.27c-0.59-0.58-1.4-0.96-2.28-0.96v0.02h-0.01H38.48h-0.02v-0.02c-0.88,0-1.68,0.38-2.27,0.97 c-0.59,0.58-0.96,1.4-0.96,2.27h0.02v0.01v75.28v0.02h-0.02c0,0.88,0.38,1.68,0.97,2.27c0.59,0.59,1.4,0.96,2.27,0.96v-0.02h0.01 h59.19h0.02v0.02c0.87,0,1.68-0.38,2.27-0.97c0.59-0.58,0.96-1.4,0.96-2.27L100.91,109.49L100.91,109.49L100.91,109.49 L100.91,109.49z" CopyImage <- list( name = "Copy", icon = list( path = Copy_SVGpath, width = 111, height = 123 ), click = htmlwidgets::JS(js) ) plot_ly( asd, x = ~week, y = ~`a`, name = "a", type = "scatter", mode = "lines" ) %>% add_trace(y = ~`b`, name = "b", mode = "lines") %>% layout( xaxis = list(title = "Week", showgrid = FALSE, rangemode = "normal"), yaxis = list(title = "", showgrid = FALSE, rangemode = "normal"), hovermode = "x unified" ) %>% config(modeBarButtonsToAdd = list(CopyImage)) ```
I built upon Joe's answer to resolve his solution's limitations * Used Plotly.toImage instead of Plotly.Snapshot.toImage to enable users to either choose copied plot's size via toImageButtonOptions or default to whatever size is shown in shiny app. * added svg copy icon Limitations: * only works in localhost or shinyapps.io or shiny server pro, because all browers will block clipboard access unless website uses HTTPS or is localhost ``` library(tidyverse) library(plotly) # only works in shinyapps.io or localhost due to all browsers only allowing clipboard access over HTTPS or localhost plotly_add_copy_button <- function(pl) { # can also be htmlwidgets::JS("Plotly.Icons.disk") # download svg from eg https://uxwing.com/files-icon/ icon_copy_svg <- list( path = str_c( "M102.17,29.66A3,3,0,0,0,100,26.79L73.62,1.1A3,3,0,0,0,71.31,0h-46a5.36,5.36,0,0,0-5.36,5.36V20.41H5.36A5.36,5.36,0,0,0,0,25.77v91.75a5.36,", "5.36,0,0,0,5.36,5.36H76.9a5.36,5.36,0,0,0,5.33-5.36v-15H96.82a5.36,5.36,0,0,0,5.33-5.36q0-33.73,0-67.45ZM25.91,20.41V6h42.4V30.24a3,3,0,0,0,", "3,3H96.18q0,31.62,0,63.24h-14l0-46.42a3,3,0,0,0-2.17-2.87L53.69,21.51a2.93,2.93,0,0,0-2.3-1.1ZM54.37,30.89,72.28,47.67H54.37V30.89ZM6,116.89V26.", "37h42.4V50.65a3,3,0,0,0,3,3H76.26q0,31.64,0,63.24ZM17.33,69.68a2.12,2.12,0,0,1,1.59-.74H54.07a2.14,2.14,0,0,1,1.6.73,2.54,2.54,0,0,1,.63,1.7,2.", "57,2.57,0,0,1-.64,1.7,2.16,2.16,0,0,1-1.59.74H18.92a2.15,2.15,0,0,1-1.6-.73,2.59,2.59,0,0,1,0-3.4Zm0,28.94a2.1,2.1,0,0,1,1.58-.74H63.87a2.12,2.12,", "0,0,1,1.59.74,2.57,2.57,0,0,1,.64,1.7,2.54,2.54,0,0,1-.63,1.7,2.14,2.14,0,0,1-1.6.73H18.94a2.13,2.13,0,0,1-1.59-.73,2.56,2.56,0,0,1,0-3.4ZM63.87,83.", "41a2.12,2.12,0,0,1,1.59.74,2.59,2.59,0,0,1,0,3.4,2.13,2.13,0,0,1-1.6.72H18.94a2.12,2.12,0,0,1-1.59-.72,2.55,2.55,0,0,1-.64-1.71,2.5,2.5,0,0,1,.65", "-1.69,2.1,2.1,0,0,1,1.58-.74ZM17.33,55.2a2.15,2.15,0,0,1,1.59-.73H39.71a2.13,2.13,0,0,1,1.6.72,2.61,2.61,0,0,1,0,3.41,2.15,2.15,0,0,1-1.59.73H18.92a2.", "14,2.14,0,0,1-1.6-.72,2.61,2.61,0,0,1,0-3.41Zm0-14.47A2.13,2.13,0,0,1,18.94,40H30.37a2.12,2.12,0,0,1,1.59.72,2.61,2.61,0,0,1,0,3.41,2.13,2.13,0,0,1-1.58.", "73H18.94a2.16,2.16,0,0,1-1.59-.72,2.57,2.57,0,0,1-.64-1.71,2.54,2.54,0,0,1,.65-1.7ZM74.3,10.48,92.21,27.26H74.3V10.48Z" ), transform = 'scale(0.12)' ) plotly_copy_button <- list( name = "Copy to Clipboard", icon = icon_copy_svg, click = htmlwidgets::JS('function(gd) {copyPlot(gd)}') # JS function defined by us and added in ui.R ) pl <- pl %>% config( modeBarButtonsToAdd = list(plotly_copy_button), displaylogo = FALSE, toImageButtonOptions= list(format = "png", width = NULL, height = NULL) ) pl } # based on https://stackoverflow.com/questions/64721568/how-can-i-create-a-custom-js-function-to-copy-plotly-image-to-clipboard-in-r-shi # stackoverlow used Plotly.Snapshot.toImage, but need to use Plotly.toImage to control height width: https://github.com/plotly/plotly.js/issues/83 # see https://github.com/plotly/plotly.js/blob/master/src/plot_api/to_image.js for optional arguments # this JS function needs to be added to ui.R copy_plot_js <- 'function copyPlot(gd) { var toImageButtonOptions = gd._context.toImageButtonOptions; var opts = { format: toImageButtonOptions.format || "png", width: toImageButtonOptions.width || null, height: toImageButtonOptions.height || null }; Plotly.toImage(gd, opts).then(async function(url) { try { const data = await fetch(url); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log("Image copied."); } catch (err) { console.error(err.name, err.message); } }); alert("Copied the plot"); }' ``` [![enter image description here](https://i.stack.imgur.com/jNGs5.png)](https://i.stack.imgur.com/jNGs5.png)
28,363,952
I don't know why this wont work. I did everything like in this same treat [link](https://stackoverflow.com/questions/7689184/select-options-jquery-case-and-show-hide-form-fields) I would like to show show one of following div when option in select is selected. When I select some option all divs dissapears but but nothig shows. Here is my code: ``` <label class="label"> <span>Typ:</span> <select id="type" class="form-control"> <option value="1" selected="selected">Fotoroleta</option> <option value="2">Fototapeta</option> <option value="3">Obraz</option> <option value="4">Plakat</option> </select> </label> <div id="select_fotoroleta" class="field" > // some code </div> <div id="select_fototapeta" class="field" > // some code </div> <div id="select_obraz" class="field" > // some code </div> <div id="select_plakat" class="field" > // some code </div> <script type="text/javascript"> $('#type').change(function(){ var selection = $('#type').val(); $('.field').hide(); switch(selection){ case 0: $('#select_fotoroleta').show(); break; case 1: $('#select_fototapeta').show(); break; case 2: $('#select_obraz').show(); break; case 3: $('#select_plakat').show(); break; } }); </script> ```
2015/02/06
[ "https://Stackoverflow.com/questions/28363952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Convert your selection to a number. It is currently a string: ``` var selection = ~~$('#type').val(); ``` `~~` is a handly shortcut (instead of the slower `parseInt`). It is fine if you know the numbers are within the range of an int and not in octal format (yours are pure simple decimal values) **A much better option is to data-drive the selections:** Then you do not need a `switch` at all and it is quite easy to maintain for loads of links. e.g. your HTML could have something to match on in the target elements: ``` <div id="select_fotoroleta" data-id="1" class="field">select_fotoroleta</div> <div id="select_fototapeta" data-id="2" class="field">select_fototapeta</div> <div id="select_obraz" data-id="3" class="field">select_obraz</div> <div id="select_plakat" data-id="4" class="field">select_plakat</div> ``` then the code become only this: ``` $('#type').change(function () { $('.field').hide(); $('[data-id=' + $(this).val() + ']').show(); }); ``` **JSFiddle:** <http://jsfiddle.net/TrueBlueAussie/oa9z14sk/2/> To select the initial filter, trigger an initial `change` event: ``` $('#type').change(function () { $('.field').hide(); $('[data-id=' + $(this).val() + ']').show(); }).trigger('change'); ``` **JSFiddle:** <http://jsfiddle.net/TrueBlueAussie/oa9z14sk/3/> Another option (if your data suits it) is to use the `ID`s as the `value`s in the `select`: ``` <option value="select_fotoroleta" selected="selected">Fotoroleta</option> <option value="select_fototapeta">Fototapeta</option> <option value="select_obraz">Obraz</option> <option value="select_plakat">Plakat</optio> ``` Then the extra `data-id`'s are not needed and the code is even simpler: ``` $('#type').change(function () { $('.field').hide(); $('#' + $(this).val()).show(); }).trigger('change'); ``` **JSFiddle:** <http://jsfiddle.net/TrueBlueAussie/oa9z14sk/4/> **Update** As you also want to clear inputs inside divs when you change selection, change the code to add a `find('input').val('');` to the `hide()`: e.g. ``` $('#type').change(function () { $('.field').hide().find('input').val(''); $('#' + $(this).val()).show(); }).trigger('change'); ``` **JSFiddle:** <http://jsfiddle.net/TrueBlueAussie/oa9z14sk/6/>
please check the below code ``` <label class="label"> <span>Typ:</span> <select id="type" class="form-control"> <option value="1" selected="selected">Fotoroleta</option> <option value="2">Fototapeta</option> <option value="3">Obraz</option> <option value="4">Plakat</option> </select> </label> <div id="select_fotoroleta" class="field">// some code</div> <div id="select_fototapeta" class="field">// some code</div> <div id="select_obraz" class="field">// some code</div> <div id="select_plakat" class="field">// some code</div> <script> $('#type').change(function () { var selection = parseInt($('#type').val()); $('.field').hide(); switch (selection) { case 1: $('#select_fotoroleta').show(); break; case 2: $('#select_fototapeta').show(); break; case 3: $('#select_obraz').show(); break; case 4: $('#select_plakat').show(); break; default: $('.field').hide(); break; } }); </script> ``` fiddle: <http://jsfiddle.net/oa9z14sk/>
21,037,737
I am trying to print the hex value of an array, but I am getting an error. Code I have tried: ``` char Routing[29]; memset(&Routing,0x00,29); chdir("\\WWW"); tp = fopen("routing.csv", "a"); if(tp!=NULL){ if (SlaveNodeID != 0x00){ fseek(tp, (98 * SlaveNodeID), SEEK_SET); fprintf(tp, "\n %058x,",Routing); } ``` OUTPUT GOT: ``` 00000000000000000000000000000000000000000000000000a001ff30 ``` But i need an OUTPUT of ``` 0000000000000000000000000000000000000000000000000000000000 ``` I don't know why I am getting this `a001ff30` value..
2014/01/10
[ "https://Stackoverflow.com/questions/21037737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2901888/" ]
The line `char Routing[29];` creates an array of 29 characters and sets the address of this array to the variable Routing. `fprintf(tp, "\n %058x,",Routing);` prints out a 0 padded value of Routing, which is the address of the character array. You need to iterate over the array and print out each value individually. ```cpp for (i = 0; i < sizeof(Routing); i++) { fprintf (tp, "%02x", Routing[i]); } ``` With warnings enabled in gcc, you should see that this is an issue: `warning: format β€˜%x’ expects argument of type β€˜unsigned int’, but argument 2 has type β€˜char *’ [-Wformat=]`.
The easiest way to display every character in the array is as follows. I am providing a skeleton code. You can fill in the blanks yourself. ``` #include <stdio.h> int main(int argc, char* argv[]) { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < 10; i++) { printf("%x\n", array[i]); } } ```
33,683
Find the distribution functions of X+Y/X and X+Y/Z, given that X, Y, and Z have a common exponential distribution. I think the main thing is that I wanted to confirm the distribution I got for X+Y. I'm doing the integral, and my calculus is a little rusty. I'm getting -e^-ax - ae^-as with parameters x from -infinity to infinity. From there presumably I can just treat X+Y like one variable and then divide by z. Thanks so much!
2011/04/18
[ "https://math.stackexchange.com/questions/33683", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
If $X$ and $Y$ are independent exponential random variables, then $X+Y$ has a gamma distribution. Also, your integral shouldn't go from $-\infty$ to $\infty$, because exponentials can't be negative.
Thanks so much for your help. I'm still having some trouble, however. Currently for (X+Y)/X I have denoted X+Y = t, adn the distribution of T is \int \boldsymbol{\alpha e^{-\alpha x}(1+\alpha x + \frac{(\alpha x)^2}{2})}. Then doing the integral caculations for the distribution, I get \int \boldsymbol{\alpha e^{-\alpha t x}(1+\alpha t x + \frac{(\alpha t x)^2}{2})}. This seems right but for some reason I'm not getting the answer I'm supposed to. Is it because X+Y and X are related? Would this work for (X+Y)/Z? Thanks!
7,490,936
I'm using this regex to validate a scientific notation in a textbox but it's not working. This is not allowing to type anything. ``` regex = new Regex("[-+]?(0?|[1-9][0-9]*)(\\.[0-9]*[1-9])?([eE][-+]?(0|[1-9][0-9]*))?"); ``` Thanks in advance.
2011/09/20
[ "https://Stackoverflow.com/questions/7490936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/886921/" ]
The problem is that your regular expression matches the empty string. An easy solution could be to add `^` in front and `$` at the end to require the entire input string to match the regular expression. Here is a small test: ``` var numbers = new[] { "0", "1", "01", "+1", "-1", "+0", "-0", "1.9", "1.09", "1.90", "1e0", "1e01", "1e10" }; var regex = new Regex("^[-+]?(0?|[1-9][0-9]*)(\\.[0-9]*[1-9])?([eE][-+]?(0|[1-9][0-9]*))?$"); var valid = numbers .Select(n => regex.Match(n)) .Where(m => m.Success) .Select(m => m.Value); ``` Printing out the elements in `valid` will result in the following: ``` 0 1 +1 -1 +0 -0 1.9 1.09 1e0 1e10 ``` Notice how `01`, `1.90` and `1e01` doesn't match but I guess that is intentional.
Here's another tester that I find very useful: <http://gskinner.com/RegExr/> If you're just looking to match a floating point number that includes scientific notation while capturing the exponent, then try this: [-+]?[0-9]\*.?[0-9]+([eE][-+]?[0-9]+)? (From <http://www.regular-expressions.info/floatingpoint.html>)
27,509,542
In Objective C, a common practice is to often forgo checking for nil, instead relying on the fact that messaging nil silently fails. For example, to validate a string: ``` if ([myString length] > 1) { // Short and sweet ``` If `myString` is nil, this check will fail - as intended. It's a huge improvement over what one may assume would be the correct implementation, explicitly checking for nil: ``` if (myString && [myString length] > 1) { // Redundant nil check ``` However, particularly in the case of a web API, myString could conceivable equal `[NSNull null]` - similar to nil, but with different behavior. Of primary concern, is that messaging NSNull causes an exception. For example, our short simple solution from earlier will cause an exception: ``` // Causes an exception, because [NSNull null] is an object NSString *myString = (id)[NSNull null]; if ([myString length] > 1) { ``` To further complicate things, a simple nil check will actually **pass** because `[NSNull null]` is a valid object: ``` NSString *myString = (id)[NSNull null]; if (myString) { // Evals to YES ``` So, the only way to be completely safe is to both check for NSNull *and* do your regular implicit nil check, by calling a method: ``` if (myString != (id)[NSNull null] && [myString length] > 1) { // Short and sweet ``` **My Question:** is this really necessary? Is there a more concise option with less duplicate code, that I've overlooked? Are my conclusions, in fact, correct?
2014/12/16
[ "https://Stackoverflow.com/questions/27509542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310175/" ]
NSNull objects typically crop up with people reading JSON files containing null values. In that case, there is a chance that the server that supplied the null value thinks you should do something different than with no value. For example, if you get a dictionary and there might be a string stored under some key, you might get a string with non-zero length, you might get an empty string because the server sent you an empty string, you might get nothing because the server sent you nothing, or you might get [NSNull null] because the server sent you a null value. Up to you to decide if the empty string, nothing, and [NSNull null] need to be treated differently or not. By the way: I have always used some extensions to the NSDictionary class, for example - (NSString\*)stringForKey, which will return either an NSString or nil, 100% guaranteed. If you do that, all your error checking is in one method. And you can do things like converting NSNumber to NSString, or NSNull to nil, or NSDictionary etc. to nil, and never worry about it again. Of course you need to check if it is appropriate.
> > is this really necessary? > > > If some API can return `NSNull` instead of a string, then yes, you should check for it. It's usually not necessary since `NSNull` is not a string and won't be returned by most methods that would return a string. But a collection such as a dictionary, for example, can have any object as a value. If you're not sure that the value will be a string, you should take appropriate precautions. > > Is there a better way to handle the possibility of NSNull that I've overlooked? > > > Another way that you could do roughly the same thing but protect yourself from other types (`NSNumber`, for example) is to check the type of the thing that you get back rather than comparing specifically against `[NSNull null]`: ``` if ([myString isKindOfClass:[NSString class]] && [myString length] > 1) { //... ```
42,964,189
I have java program which is receiving time in Epoch in micro second as shown below ``` String time = "1487809901812"; ``` I need to convert this time from micro second to milli second before sending to some other system. I want final value to be like ``` String final = "1487809901.812"; //Note DOT here ``` I can easily do it by some string operation by placing dot before last three digits. But wondering is there any other way of doing it?
2017/03/22
[ "https://Stackoverflow.com/questions/42964189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
You can convert it into `double`, divide it by 1000 and use `String.format` to format it, e,g.: ``` String time = "1487809901812"; String milli = String.format("%.3f", Double.parseDouble(time)/1000.0); System.out.println(milli); ```
``` String time = "1487809901812"; time = new BigDecimal(Double.parseDouble(time)/1000).setScale(3, 4).toString(); System.out.println(time); //must be "1487809901.812"; ```
28,005,541
First I want to say that yes - I know there are ORMs like Morphia and Spring Data for MongoDB. I'm not trying to reinvent the weel - just to learn. So basic idea behind my AbstractRepository is to encapsulate logic that's shared between all repositories. Subclasses (repositories for specific entities) passes Entity class to . Converting entity beans (POJOs) to DBObject using Reflection was pretty streightforward. Problem comes with converting DBObject to entity bean. Reason? I need to convert whatever field type in DBObject to entity bean property type. And this is where I'm stuck. I'm unable to get entity bean class in AbstractRepository method `T getEntityFromDBObject(DBObject object)` I could pass entity class to this method but that would defeat the purpose of polymorphism. Another way would be to declare `private T type` property and then read type using Field. Defining additional property just so I can read doesn't sound right. So the question is - how would you map DBObject to POJO using reflection using less parameteres possible. Once again this is the idea: ``` public abstract class AbstractRepository<T> { T getEntityFromDBObject(DBObject object) { .... } } ``` And specific repository would look like this: ``` public class EntityRepository extends AbstractRepository<T> { } ``` Thanks! **Note: Ignore complex relations and references. Let's say it doesn't need to support references to another DBObjects or POJOs.**
2015/01/17
[ "https://Stackoverflow.com/questions/28005541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1357315/" ]
You need to build an instance of type T and fill it with the data that comes in Β΄DBObjectΒ΄: ``` public abstract class AbstractRepository<T> { protected final Class<T> entityClass; protected AbstractRepository() { // Don't remember if this reflection stuff throws any exception // If it does, try-catch and throw RuntimeException // (or assign null to entityClass) // Anyways, it's impossible that such exception occurs here Type t = this.getClass().getGenericSuperclass(); this.entityClass = ((Class<T>)((ParameterizedType)t).getActualTypeArguments()[0]); } T getEntityFromDBObject(DBObject object) { // Use reflection to create an entity instance // Let's suppose all entities have a public no-args constructor (they should!) T entity = (T) this.entityClass.getConstructor().newInstance(); // Now fill entity with DBObject's data // This is the place to fill common fields only, i.e. an ID // So maybe T could extend some abstract BaseEntity that provides setters for these common fields // Again, all this reflection stuff needs to be done within a try-catch block because of checked exceptions // Wrap the original exception in a RuntimeException and throw this one instead // (or maybe your own specific runtime exception for this case) // Now let specialized repositories fill specific fields this.fillSpecificFields(entity, object); return entity; } protected abstract void fillSpecificFields(T entity, DBObject object); } ``` If you don't want to implement the method `.fillSpecificFields()` in every entity's repository, then you'd need to use reflection to set every field (including common ones such as ID, so don't set them manually). If this is the case, you already have the entity class as a protected attribute, so it's available to every entity's repository. You need to iterate over *ALL* its fields, including the ones declared in superclasses (I believe you have to use method `.getFields()` instead of `.getDeclaredFields()`) and set the values via reflection. As a side note, I really don't know what data comes in that `DBObject` instance, and in what format, so please let me know if extracting fields' values from it results to be non trivial.
You've stumbled onto the problem of object mapping. There are a few libraries out there that look to help with this. You might check out [ModelMapper](http://modelmapper.org/) (author here).
17,282,799
I need help on sum date. My issue is that all entry date are located on the same column, like: 5/10/2013 5/13/2013 5/15/2013 5/16/2013 I need to sum and get total of 6 days.
2013/06/24
[ "https://Stackoverflow.com/questions/17282799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2517389/" ]
You're forgetting that programs are executed as individual instructions, and (at least in the simplest case) instructions execute sequentially. So for `if (a + 4 > 5)` an instruction will load `a` into a register, another instruction will add `4`, another instruction will compare the sum to `5`. Then an instruction will test the "condition code" from the compare and either execute the immediately following instruction (executing the "`if` body") or "jump" to a location in memory several (or several dozen) instructions away (skipping over the "`if` body"). There is digital logic in there, but it's at a lower level, deciding how to execute each individual instruction.
As the others above have stated, there are logic comparators that ultimately make these decisions. There are a ton of different implementations of comparators depending on the design needs (power, area, swing, clocked or not, ect.). The comparators are made out of a number of CMOS NMOS/CMOS gates. Look on the wikipedia page for comparators, and look at dynamic latched comparator. I do not have enough rep to post one unfortunately. This is an example of a dynamic latched comparator. Depending if implementation is active high or low, system would clock the architecture here to make comparison of two values and evaluate statement.
7,932,957
There is an existing function named "Compare," which is ``` int compare(void* A, void* B) { return (int)A - (int)B; } ``` I am aware that this is an atrocious practice, but I did not write that piece of code and it is being used in many places already. But this code was generating a compilation error under 64-bit, since void\* is no longer 32-bit, so I fixed the code to the following. ``` int compare(void* A, void* B) { return (long long)A - (long long)B; } ``` What is the likelihood of this function returning an incorrect result under current 64-bit Linux architecture? i.e, what is the likelihood of two virtual addresses being apart for more than 0x7FFFFFFF?
2011/10/28
[ "https://Stackoverflow.com/questions/7932957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/696596/" ]
This looks like a sort comparison function, so all that matters is the sign of the result. ``` int compare(void *A, void* B) { if (A < B) return -1; if (A > B) return 1; return 0; } ```
``` int compare (void*p, void*q) { return (p==q)?0:((char*)p < (char*)q)?-1:1; } ```
23,668,459
Can you please take a [look at this](http://jsfiddle.net/Behseini/56jhq/1/) demo and let me know how I can draw multiple circles in a canvas with different coordinate without repeating bunch of codes? As you can see on Demo and following code ``` var ctx = $('#canvas')[0].getContext("2d"); ctx.fillStyle = "#00A308"; ctx.beginPath(); ctx.arc(150, 50, 5, 0, Math.PI * 2, true); ctx.arc(20, 85, 5, 0, Math.PI * 2, true); ctx.arc(160, 95, 5, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ``` I tried to have them under `ctx` but it is not correct so I tried to use for loop to create 50 points but I have issue on repeating and adding code like ctx.fill(); for all of them. Can you please let me know how I can fix this? Thanks
2014/05/15
[ "https://Stackoverflow.com/questions/23668459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066197/" ]
``` ctx.beginPath(); points.forEach(point => { ctx.moveTo( point.x, point.y ); ctx.arc(point.x,point.y,1,0,Math.PI*2,false); }); ctx.fill(); ```
You can easily create several circles with a for loop. You really just need to draw an arc and fill it each time. Using your example, you could do something like this. ``` var ctx = $('#canvas')[0].getContext("2d"); ctx.fillStyle = "#00A308"; for (var i = 0; i < 3; i++) { ctx.arc(50 * (i+1), 50 + 15 * i, 5, 0, Math.PI * 2, true); ctx.fill(); } ```
8,044,549
unsure how to go about describing this but here i go: For some reason, when trying to create a release build version of my game to test, the enemy creation aspect of it isn't working. ``` Enemies *e_level1[3]; e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1); e_level1[1] = &Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1); e_level1[2] = &Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1); ``` Thats how i'm creating my enemies. Works fine when in the debug configuration but when i switch to the release config, it doesn't seem to initialize the enemies correctly. To me, this seems a bit strange that it works in debug but not in release, any help appreciated on what mostly is what i've done wrong.
2011/11/08
[ "https://Stackoverflow.com/questions/8044549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1015476/" ]
Other people have already pointed out the error, namely that the temporaries are getting destroyed straight away, but all of the answers so far are using manual memory management - it's more idiomatic in C++ to use e.g. `std::vector` for something like this, e.g. ``` std::vector<Enemies> enemies; enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1)); enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1)); enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1)); ``` Then you just access the `Enemies` instances as `enemies[0]` through `enemies[2]` and they get cleaned up automatically when the vector goes out of scope.
The code initializes the pointers to point to temporary objects that are immediately destroyed. Accessing temporaries that no longer exist through pointers or references is undefined behavior. You want: ``` Enemies *e_level1[3]; e_level1[0] = new Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1); e_level1[1] = new Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1); e_level1[2] = new Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1); ```
39,274,088
I am writing test cases for a GoLang application and i am using sqlmock for mocking the SQL queries but i am getting following error while executing **go test** Params: [ call to query , was not expected, next expectation is: ExpectedBegin => expecting database transaction Begin] Any idea on this?
2016/09/01
[ "https://Stackoverflow.com/questions/39274088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1386755/" ]
The error message means some SQL query was called which was not mocked.
I had same issue, because I used `NamedExec` (not `NamedQuery`) to perform my update, but was mocking `ExpectQuery` in test So, if you have expression (i.e. use `UPDATE` or `INSERT`), you should use `ExpectExec` if you have query (i.e. use `SELECT`), you should use `ExpectQuery` It's obvious, but I stuck with it for couple of hours
136,638
How can I compare the content of two (or more) large .resx files? With hundreds of Name/Value pairs in each file, it'd be very helpful to view a combined version. I'm especially interested in Name/Value pairs which are present in the neutral culture but are not also specified in a culture-specific version.
2008/09/25
[ "https://Stackoverflow.com/questions/136638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360388/" ]
Although it's not a diff tool per se, [RESX Synchronizer](http://www.screwturn.eu/ResxSync.ashx) may help you out here. Its main use is to update the localized .resx files with new entries from the neutral language one, and remove any deleted items. Possibly, the output generated by using it with the /v command line switch will be what you need. Otherwise, it does come with full C# source code, so possibly you can adapt it for your needs.
You can use a tool like TortoiseSVN's diff (if you're using Windows). Just select both files, right click and then select "diff" from the TortoiseSVN submenu.
5,258,035
Hi When migrating from ASP.NET to MVC ASP.NET it looks like the MVC is more AJAX friendly. but still I run into design issue, Does someone knows Microsoft intention about the design when calling AJAX methods? Where do I need to put this methods by default, in a separate controller, the same controller? Is there any kind of official info about it? Thanks
2011/03/10
[ "https://Stackoverflow.com/questions/5258035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650060/" ]
I don't think that there is any *official best practices*. Personally I like to follow [RESTful conventions](http://mvccontrib.codeplex.com/wikipage?title=SimplyRestfulRouting) when organizing cotrollers and actions no matter how those actions are consumed (AJAX or not).
You might wanna try on having a review on [some asp.net samples here](http://www.asp.net/mvc). This will give you some ideas. :)
55,803,526
I'm stuck between Firebase Real Time database and Firestore for my e-commerce app. I want to know which one is cheaper. I know there will be alot of reads in an e-commerce app, does this make Firestore more expensive?
2019/04/23
[ "https://Stackoverflow.com/questions/55803526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397434/" ]
You are doing this operation: ```py range(1, 4) + [1] ``` Which doesn't mean anything in this case. You have to do the `+ [1]` right after the `[5] * n` as in: ```py print([[5]*n+[1] for n in range(1, 4)]) ```
This will do the trick as contributors already have answered ``` [[5] * n + [1] for n in range(1, 4)] ``` But in your solution type of range(1, 4) will be , if you want to do some list operations on it like concatenation then you should do like: ``` list(range(1, 4)) + [1] ```
64,174,550
I'm getting this error every time I try to run the application though it compile well: **pool allocator: Specified pool size too big for this device** **Current file: /home/marco/Desktop/tools.c function: PTC3D line: 330** **This file was compiled: -ta=tesla:cc35,cc50,cc60,cc70,cc70,cc75,cc80** The strange thing is that I get this error only since I restarted the PC, while before I've never get it. I compile with: CC = nvc CFLAGS = -c -acc -ta=tesla:managed:cuda11.0 -Minfo=accel -w -O3 -DTEST\_CASE=3 LDFLAGS = -lm -acc -ta=tesla:managed:cuda11.0 In the code nothing has been changed so maybe it is related to the compiler. I installed a new program today and I could have touched something I shouldn't have.
2020/10/02
[ "https://Stackoverflow.com/questions/64174550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14190508/" ]
The message should just be a warning. The pool allocator will be by-passed and instead the CUDA Unified Memory API routines will be called directly for each allocation. You might see some performance degradation if you have a lot of small allocations since the API calls have a relatively high overhead, but shouldn't hurt functionality. The default CUDA Unified Memory pool size is 1GB, though this is modifiable by setting the environment variable NVCOMPILER\_ACC\_POOL\_SIZE. You might try setting the size to something smaller to see if it fixes the messages. Full details can be found at: <https://docs.nvidia.com/hpc-sdk/compilers/hpc-compilers-user-guide/index.html#acc-mem-unified> Exactly why the message starting appearing is unclear, but it's most likely hardware related, or possibly a CUDA driver issue. What device and CUDA driver are you using? Has anything changed with hardware?
I solved going in Software & Updates, in Additional Drivers, setting the recommended driver: NVIDIA driver meta package.
33,935,612
Hi I have an alert div as follows, ``` <div style="width: 12%;" ng-if="final_data.status =='confirmed'" class="alert alert-success" role="alert" align="left" ng-cloak> <span class="glyphicon glyphicon-ok"></span>&nbsp;&nbsp;confirmed</div> ``` The div will pop-up when the status becomes confirmed. How can I auto hide the div after displaying it? Any idea guys?
2015/11/26
[ "https://Stackoverflow.com/questions/33935612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5518196/" ]
You could use javascript to remove it: ``` setTimeout(function(){ var elements = document.getElementsByClassName('alert'); while(elements.length > 0){ elements[0].parentNode.removeChild(elements[0]); } },500); ```
You can watch, when status gets changed to "confirmed" and do something. ``` <div style="width: 12%;" ng-show="canShow" ng-if="final_data.status =='confirmed'" class="alert alert-success" role="alert" align="left" ng-cloak> <span class="glyphicon glyphicon-ok"></span>&nbsp;&nbsp;confirmed</div> $scope.canShow = true; $scope.$watch('final_data.status', function (newValue, oldValue)) { if(newValue === 'confirmed') { $timeout(function() { $scope.canShow = false; }, 1000); } }); ```
29,201,763
I tried to use Google Sign-in for my website, however, it keeps giving me 400 error. I referenced this article: <https://developers.google.com/identity/sign-in/web/sign-in>, and my code is really simple: ``` <html> <head> <title>Test Google Login</title> <script src="https://apis.google.com/js/platform.js" async defer></script> <meta name="google-signin-client_id" content="<CHANGE IT>"> <script> function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); } </script> </head> <body> <div class="g-signin2" data-onsuccess="onSignIn"></div> </body> </html> ``` When I click Sign-in button, it popups a window, and after logged in, it gave me 400 error as below: ``` 400. That’s an error. The requested URL was not found on this server. That’s all we know. ``` I guess it's redirect issue, but I don't know how to configure it. So I checked url it returned to me: ``` https://accounts.google.com/o/oauth2/auth?fetch_basic_profile=true&scope=email+profile+openid&response_type=permission&e=3100087&redirect_uri=storagerelay://http/127.0.0.1:8000?id%3Dauth867179&ss_domain=http://127.0.0.1:8000&client_id=378468243311-9dt7m9ufa9mee305j1b12815put5betb.apps.googleusercontent.com&openid.realm&hl=en&from_login=1&as=1b5f0a407ea58e11&pli=1&authuser=0 ``` Why is redirect\_uri "storagerelay://http/127.0.0.1:8000?id%3Dauth867179"?
2015/03/23
[ "https://Stackoverflow.com/questions/29201763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2310331/" ]
Redirect URIs ``` http://localhost:8000/ this **/** at end solve my problem ``` JavaScript origins ``` http://localhost:8000 ``` **NOTE: localhost and 127.0.0.1 conflicts can create problems for you sometime**
Replace everywhere`http://127.0.0.1:8000/` to `HTTP://localhost:8000/`even in your browser too. The Problem comes when you use `http://127.0.0.1:8000/` either in the developer console or a browser.
12,974,115
I want to open the pdf file in an iframe. I am using following code: ``` <a class="iframeLink" href="https://something.com/HTC_One_XL_User_Guide.pdf"> User guide </a> ``` It is opening fine in Firefox, but it is not opening in IE8. Does anyone know how to make it work also for IE ?
2012/10/19
[ "https://Stackoverflow.com/questions/12974115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753210/" ]
This is the code to link an HTTP(S) accessible PDF from an `<iframe>`: ``` <iframe src="https://research.google.com/pubs/archive/44678.pdf" width="800" height="600"> ``` Fiddle: <http://jsfiddle.net/cEuZ3/1545/> EDIT: and you can use Javascript, from the `<a>` tag (`onclick` event) to set iFrame' SRC attribute at run-time... EDIT 2: Apparently, it is a bug (but there are workarounds): [PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?](https://stackoverflow.com/questions/7588262/pdf-files-do-not-open-in-internet-explorer-with-adobe-reader-10-0-users-get-an)
Do it like this: Remember to close iframe tag. ``` <iframe src="http://samplepdf.com/sample.pdf" width="800" height="600"></iframe> ```
1,425,012
Is it possible to clear the output cache of one asp.net web application from inside another asp.net web application? Reason being... We have several wep applications structured like... * <http://www.website.com/intranet/cms/> * <http://www.website.com/area1/> * <http://www.website.com/area2/> Pages in /area1/ and /area2/ are cached and are managed through /intranet/cms/. When a page is edited using /intranet/cms/ I want to clear it out of the cache in the appropriate /area#/ application. I already tried using a VaryByCustom that looks up a guid stored in the HttpContext.Cache but that seems to be cached per web application, that doesn't work. Really if there were any way of passing data between web applications on a single server, that would solve my problem, since I can use that + VaryByCustom. Thanks! -Mike Thomas
2009/09/15
[ "https://Stackoverflow.com/questions/1425012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1573/" ]
The way I've done this in the past is to have a "hidden" page (in each of the `/areaX` sites) that does the flushing, reloading, etc. The page validates a shared secret query parameter before doing anything (to avoid DoS attacks). If valid the page would output an "OK" message once the operation is complete; generates a 404 error if the secret is invalid. If you want the flush to be on a per-item or per-group basis then add a second parameter that identifies that item/group. This method is also server technology independent, and can be triggered by other management tools if required.
One way I know of doing this is by using a shared resource as a dependency, usually a file. When the file is changed, the cache is cleared. I think you can use [HttpResponse.AddFileDependency](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.addfiledependency.aspx) for this. However, in these cases it's usually better to use an out-of-process cache such as [memcached](http://www.danga.com/memcached/). I haven't tested it myself, but this [link](http://jacksonito.blogspot.com/2007/03/aspnet-output-caching-using-memcached.html) deals on using memcached with OutputCache.
11,160
I want take a photo of a scene lit by a yellow-orange street light. Unlike many of the questions here, I don't want to balance the colours in the scene, rather I want the areas lit by that light to remain yellow. The street light is the dominant light source in the scene. What white balance settings do I need to capture the cast of a coloured light?
2011/04/21
[ "https://photo.stackexchange.com/questions/11160", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/3356/" ]
For my taste, "tungsten" has worked best in such situation. The street lights are actually way more yellow than standard tungsten, but the eye somewhat adjusts to the color cast, so the photo will be quite similar to what was actually seen. For example, this shot is a (resized) camera JPEG, tungsten WB: ![A bridge to the bright side](https://i.stack.imgur.com/ERciV.jpg) The grass and side of the bridge were lit by orange streetlights.
There is no simple answer to this as it depends on what the lighting produced by, there are several gasses and metal vapours used for street lights,some, such as metal halide are full spectrum, i.e. they contain all colours of the spectrum but just colour shifted, and some i.e. Sodium vapour are not full spectrum, without all the colours they will render as monochromatic and be impossible to balance. Add to that the problem of mixed light sources you will be faced with either a best average balance or doing several conversions and working with layers and layer masking to fix the colour issues!
19,071,933
I've been doing some tests with Valgrind to understand how functions are translated by the compiler and have found that, sometimes, functions written on different files perform poorly compared to functions written on the same source file due to not being inlined. Considering I have different files, each containing functions related to a particular area and all files share a common header declaring all functions, is this expected? Why doesn't the compiler inline them when they are written on different files but does when they are on the same page? If this behavior starts to cause performance issues, what is the recommended course of action, put all of the functions on the same file manually before compiling? example: ``` //source 1 void foo(char *str1, char *str2) { //here goes the code } //source 2 void *bar(int something, char *somethingElse) { //bar code foo(variableInsideBar, anotherVariableCreatedInsideBar); return variableInsideBar; } ``` Sample performance cost: On different files: 29920 Both on the same file: 8704 For bigger functions it is not as pronounced, but still happens.
2013/09/28
[ "https://Stackoverflow.com/questions/19071933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2264920/" ]
If you are using `gcc` you should try the options `-combine` and `-fwhole-program` and pass all the source files to the compiler in one invocation. Traditionally different C files are compiled separately, but it is becoming more common to optimize cross compilation units (files).
The *compiler proper* cannot inline functions defined in different translation units simply because it cannot see the definitions of these functions, i.e. it cannot see the source code for these functions. Historically, C compilers (and the language itself) were built around the principles of *independent translation*. Each translation unit is *compiled* from source code into an object code completely independently form other translation units. Only at the very last stage of translation all these disjoint pieces of object code are assembled together into a final program by so called *linker*. But in a traditional compiler implementation at that point it is already too late to inline anything. As you probably know, the language-level support for function inlining says that in order for a function to be "inlinable" in some translation unit it has to be defined in that translation unit, i.e. the source code for its body should be visible to the compiler in that translation unit. This requirement stems directly from the aforementioned principle of independent translation. Many modern compilers are gradually introducing features that overcome the limitations of the classic pure *independent translation*. They implement features like *global optimizations* which allow various optimizations that cross the boundaries of translation units. That potentially includes the ability to inline functions defined in other translation units. Consult your compiler documentation in order to see whether it can inline functions across translation units and how to enable this sort of optimizations. The reason such global optimizations are usually disabled by default is that they can significantly increase the translation time.
39,124,468
I am having few ISO8583 logs in a text file. I want to parse these logs from this text file and write them to any database with some descriptive information such as class of the message, message function, message origin, processing code, response code etc. I am new to the BASE24/ISO8583 and was trying to find any ready-made parser for this. Is there any such parser available ? Does jPOS provides such functionality ? **EDIT** I have the logs in ISO8583 format in ".log" file as given below: > > MTI : 0200 > > Field-3 : 201234 > > Field-4 : 000000010000 > > Field-7 : 0110722180 > > Field-11 : 123456 > > Field-44 : A5DFGR > > Field-105 : ABCDEFGHIJ 1234567890 > > > This is same as the format given in the link shared by you. It also consists of hex dump but I dont want to parse that. The code given in the link is doing packing and unpacking of the message where as what I am trying is to read these logs (in unpacked form) and write them into a database table. I think i need to write my own code for this and use the jPOS packagers in it.
2016/08/24
[ "https://Stackoverflow.com/questions/39124468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2710961/" ]
what is displayed in log file is parsed ISO.Hence you need not use jpos.jpos is only for packing and unpacking when you transmit the message. Assign the field to variable and write in DB for example,Field 39 is response code.
Using jpos is good idea. You should go for your custom packager design class.
837,167
About 10 years ago, I was using a computer language called INFO on an ancient Prime. It was a funky, but oddly useful language, and I'd like to find out more about it. For instance, can I get a copy that would run on a PC? However, if I google for "INFO" and "Computer Language," I'm not going to find it. I've tried. I think the company that created it was in the UK. It was so easy to learn, that I was programming the first day, and yet was capable of true oddness. The programs had line numbers, and if the numbers started with an odd number, the commands were SQL like and worked on the entire set. If they started with an even number, the commands were a block that dealt with each item in the set one at a time. So, a simple type of program could be something like this (I don't recall the syntax either) ``` 100 select * from user_table 110 join with address_table 120 exclude duplicate addresses 200 for each record in set 205 print firstname, lastname 210 print addressLine1 220 print City, State, Zip 300 display "address labels printed" ``` It was capable of quick and impressive applications, that were almost simple to understand, and yet had a sneaky power that I was only beginning to understand after two years at the job. How do I find it? Can I get a copy that will work on a PC?
2009/05/07
[ "https://Stackoverflow.com/questions/837167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22523/" ]
The easiest way is to not try and make a regex do this. Just loop over the string one character at a time. If you read a '(', increment a counter. If you read a ')', decrement that counter. If you read a comma, delete it if the counter is 0, otherwise leave it alone.
``` Sub Main() ' ' remove Commas from a string containing expression-like syntax ' (eg. 1,000,000 + IntPow(3,2) - 47 * Greep(9,3,2) $ 5,000.32 ) ' should become: 1000000 + IntPow(3,2) - 47 * Greep(9,3,2) $ 5000.32 ' Dim tInput As String = "1,000,000 + IntPow(3,2) - 47 * Greep(9,3,2) $ 5,000.32" Dim tChar As Char = Nothing Dim tResult As StringBuilder = New StringBuilder(tInput.Length) Dim tLevel As Integer = 0 For Each tChar In tInput Select Case tChar Case "(" tLevel += 1 tResult.Append(tChar) Case ")" tLevel -= 1 tResult.Append(tChar) Case "," ' Change this to your separator character. If 0 < tLevel Then tResult.Append(tChar) End If Case Else tResult.Append(tChar) End Select Next Console.ForegroundColor = ConsoleColor.Cyan Console.WriteLine(tInput) Console.WriteLine(String.Empty) Console.ForegroundColor = ConsoleColor.Yellow Console.WriteLine(tResult.ToString) Console.WriteLine() Console.ResetColor() Console.WriteLine(" -- PRESS ANY KEY -- ") Console.ReadKey(True) End Sub ```
58,962,313
Assume I have the following code: ``` template<bool t> class A{ class B{ class C{ public: void foo(); }; }; }; template<bool t> void A<t>::B::C::foo() { // some code } ``` when writing the definition of this function `foo()` , I wish to avoid writing the too-long nested name specifier `A<t>::B::C::` but use something like `aShortAlias<t>::foo()` instead. Is this possible with C++? Apparently using `using aShrtAlias<t> = typename A<t>::B::C` doesn't work. And I don't really want to use a `#define` as a workaround since it only do text-replacement(maybe there is some justification for `#define` here?).
2019/11/20
[ "https://Stackoverflow.com/questions/58962313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7005200/" ]
While you can create an alias: ``` template<bool T> using X = typename A<T>::B::C; ``` You cannot use that alias as a specifier in the declaration: ``` template<bool T> void X<T>::foo() // not allowed; doesn't compile { ... } ``` Afaik you need to use the fully qualified name in the declaration.
I think the best you can do is: ``` template <bool T> using aShortAlias = typename A<T>::B::C; template<> void aShortAlias<false>::foo() { } template<> void aShortAlias<true>::foo() { } ```
6,328,187
This code gives every step-result of computing factorial of given number but I want only the final. ``` #include <stdio.h> long int factorial(int n) { if (n <= 1) return(1); else n = n * factorial(n - 1); printf("%d\n", n); return(n); } main() { int n; printf("Enter n: "); scanf("%d", &n); //function call factorial(n); return 0; } ```
2011/06/13
[ "https://Stackoverflow.com/questions/6328187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700089/" ]
How about this ? ``` int final; final = factorial(n); printf("%d! = %d\n", n, final); ``` And stop using `printf` in the `factorial` function.
``` long int factorial(int n){ if(n<=1) return 1; return n*factorial(n-1); } ```
49,642,800
I have a DialogFragment in my Android app, and I need to set `android:configChanges="orientation|screenSize`, I want to load different layout for my DialogFragment in portrait or landscape, but now Android will not automatically do this for me, I think I need to update the layout in `onConfigurationChanged` , but I don't know how to do it, any sample code will be better, thank you!
2018/04/04
[ "https://Stackoverflow.com/questions/49642800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7290767/" ]
Your code will not compile as is. `s1` is not in main method and `reverse` method is accepting an `int` not `String`. Also, if you need to return an `int` from your method why not the reversed `int` which is the answer. Few edits to your code which will solve your issue. ``` public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Type the integer you'd like to be reversed:"); int num = s.nextInt(); System.out.println(reverse(num)); } public static int reverse(int num) { String strNum = String.valueOf(num); StringBuffer sb = new StringBuffer(); for(int i=strNum.length()-1;i>=0;i--) sb.append(strNum.charAt(i)); return Integer.parseInt(sb.toString()); } ```
``` import java.util.Scanner; public class Lab7 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Type the integer you'd like to be reversed:"); int num = s.nextInt(); String strNum = ""+num; reverse(strNum); } public static int reverse(String strNum) { String s1 =strNum; for(int i=s1.length()-1;i>=0;i--){ System.out.print(s1.charAt(i)); } return 0; } ``` }
48,829,263
I dont know how to attach onClick action with jquery to all the element from the list of attached files. That is my html file. ``` <p>Attachements</p> <div> <ul id="attach"> <li id="KjG344D">liu-kang.jpg<img src="/images/thrash.gif" id="delete_file"></li> <li id="3ujRCMB">kitana.jpg<img src="/images/thrash.gif" id="delete_file"></li> <li id="m3NSxbf">mk2.jpg<img src="/images/thrash.gif" id="delete_file"></li> </ul> </div> <script src="/modules/delete_file.js"></script> ``` Every single upload adds another 'li' to the list above with new generated 'id' for 'li' That's how my delete\_file.js script looks ``` $(document).ready(function() { $('#delete_file').on('click', function() { if (confirm("Are you sure you want to delete attachement ?") == true) { $.ajax({ url: '/modules/delete_file.php', type: "POST", dataType:'json', data: ({fid: this.parentElement.getAttribute("id")}), success: function(data){ alert("File was deleted"); } }); return true; } else { return false; } }); }); ``` And it works well but only for the first file from the list. When I click the second position from the list, or the third, nothing happens. I know that we can use function for multiple elements like: ``` $('.class1, .class2, .class3').click(some_function); ``` But the problem is that user attaches files, and I dont know how long the list will be. How can I use "delete\_file" action for all 'li' elements in such situation ?
2018/02/16
[ "https://Stackoverflow.com/questions/48829263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950348/" ]
All your links have id's an id has to be unique on a webpage so use classes instead. give each element a class e.g. `class="delete-file"` and then set your trigger onto the class name. ``` $('.delete-file').on('click', function() { //do delete }) ``` Also use `.on` or `.once` for attaching the event instead of `.click` See its documentation [here](http://api.jquery.com/on/) to readd the listener when you add elements on the fly use `.once` instead of `.on` or `.click`. then you do not need to worry about the already set listeners and can just re set the events
THank YoU VerRy mUch for Your answers. I solved the problem. And I have learned something new. Creating it as 'class' and using it in jquery made it WORK ! Thanks
70,811,647
I have two snippets of code that I want to put in the same line and center, but am unable to do Number 1: ``` <div class="a2a_kit a2a_kit_size_32 a2a_default_style"> <a class="a2a_button_facebook"></a> <a class="a2a_button_twitter"></a> <a class="a2a_button_whatsapp"></a> <a class="a2a_button_pinterest"></a> <a class="a2a_button_reddit"></a> <a class="a2a_button_line"></a> <a class="a2a_button_copy_link"></a> </div> <script async src="https://static.addtoany.com/menu/page.js"></script> ``` Number 2: ``` <span class="likebtn-wrapper" data-theme="drop" data-ef_voting="grow" data-rich_snippet="true"> </span> <script>( function (d, e, s) { if (d.getElementById("likebtn_wjs")) return; a = d.createElement(e); m = d.getElementsByTagName(e)[0]; a.async = 1; a.id = "likebtn_wjs"; a.src = s; m.parentNode.insertBefore(a, m) }) (document, "script", "//w.likebtn.com/js/w/widget.js"); </script> ```
2022/01/22
[ "https://Stackoverflow.com/questions/70811647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18001085/" ]
Waiting for the child works. However, your expectations are wrong. Apparently you think that computations in the child process after the fork are visible in the parent process. They are not. The child is a new copy of the parent program at the time of fork. At that time, the parent's `sum` is 0 and stays that way. There are several mechanisms to pass data from child to parent (the search term is *interprocess communication, IPC*). * exit() status * files * shared memory * pipes * signals * message queues * anything else I have missed
The issue here is the variable **sum** is not shared by the parent & child process, after fork() call the child will have its own copy of the variable sum. Use **shmget(),shmat()** from **POSIX** api. Or use **pthread** which will share the same memory space for the newly created thread. Update--- Added the shared memory to your code hopes this helps. ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/shm.h> int n; int i; pid_t pid; int time = 1000; int main(void) { int shmid; int *sum; printf("n: "); scanf("%d", &n); /*request the shared memory from the OS using the shmget()*/ shmid = shmget(IPC_PRIVATE, sizeof(int), 0777|IPC_CREAT); pid = fork(); if (pid < 0) { printf("Fork Failed"); exit(-1); } else if (pid == 0) { //child /* shmat() returns a char pointer which is typecast here to int and the address is stored in the int pointer. */ sum = (int *) shmat(shmid, 0, 0); for (i = 1; i <= n; i++) { *sum += i; } printf("Sum of 1 to %d: %d\n", n, *sum); // this is ok /* each process should "detach" itself from the shared memory after it is used */ shmdt(sum); } else { // parent wait(&time); sum = (int *) shmat(shmid, 0, 0); printf("Sum of 1 to %d: %d\n", n, *sum); // this always return 0; shmdt(sum); /*delete the cretaed shared memory*/ shmctl(shmid, IPC_RMID, 0); } return 0; } ``` Refer for more info- <https://man7.org/linux/man-pages/man2/shmget.2.html>
724,474
I was reading a book about Special Relativity. There is a chapter where it explains why magnetism is just an electrostatic force because of lenght contraction. The book, uses two reference systems $S$ and $S'$. In the first one, is "at rest", and sees the electrons drifting with velocity $v$ (for simplicity we will assume that our test-charge, $Q$, move also with velocity $v$). [![enter image description here](https://i.stack.imgur.com/NJPCl.png)](https://i.stack.imgur.com/NJPCl.png) [![enter image description here](https://i.stack.imgur.com/3uzl2.png)](https://i.stack.imgur.com/3uzl2.png) Then, $S'$ is the reference frame of the test-charge $Q$, hence it "sees" itself and electrons with $v = 0$ and the protons drifting to the left with velocity $-v$. The book states that the density of positive charges increases: $$ V = 2\pi r \ell \\ V' = 2\pi r \ell' \\ \ell' = \frac{\ell}{\gamma} \\ V' = \frac{2\pi r \ell}{ \gamma} \\ V' = \frac{V}{\gamma} \\ \rho\_0 = \frac{Q}{V} \\ \rho'\_+ = \frac{Q}{V'} = \frac{\gamma Q}{V} = \gamma \rho\_0 \\ $$ This makes perfect sense to me, because $Q$ is moving, hence its surroundings experience length contraction, concentrating more positive charges into the same amount of volume (assuming the wire is infinite). But, here comes the thing that does not make sense to me, the book also says that the electrons separation increases, because in the $S'$ frame they are no longer suffering from length contraction. But I don't quite see this, they shouldn't have more space between them, they have zero velocity (in the S' frame), hence $\gamma$ should be equal to one, hence no contraction or dilatation, no?
2022/08/23
[ "https://physics.stackexchange.com/questions/724474", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281431/" ]
It's simply the converse of length contraction. In $S$, the spacing between the electrons was contracted compared to its rest frame $S'$, so when you switch to $S'$, you have an effective length dilation of value $\gamma$. Mathematically, you obtain the following. Let $\lambda\_+,\lambda\_-$ be the respective linear charge densities of the nuclei and the electrons in $S$. From neutrality, you have $\lambda\_+ = -\lambda\_-$. In $S'$, they are transformed to: $$ \lambda\_- \to \lambda\_-' = \frac{\lambda\_-}{\gamma} \\ \lambda\_+ \to \lambda\_+' = \gamma\lambda\_+ $$ Note that this means that there still is a current. In $S$, it's $I = \lambda\_-v$, and in $S'$, it's $I'=-\lambda\_+'v = -\gamma I$. In particular for low velocities, you recover $I'=-I$ as expected. Btw, the remaining current means that you still have some magnetism in $S'$. In fact, the previous formula proves that the switch actually enhances the current, and therefore increases magnetism as well. Not only is magnetism in $S$ is not entirely described by electrostatics in $S'$, but it's rather the electrostatics that is present to compensate for the increase of magnetism. You'll need to switch to a reference frame $S''$ going at a different speed $u$ with respect to $S$ to have no current, and you can anticipate that for low $v$, it should be $v/2$. By some lucky algebra, it turns out that it is also the exact relativistic result. Let the corresponding factor be $\gamma\_u=(1-u^2/c^2)^{-1/2}$. In $S''$, the electrons are going at velocity: $$ v' = \frac{v-u}{1-uv/c^2} $$ with corresponding $\gamma' = (1-v'^2/c^2)^{-1/2}$. You get: $$ \lambda\_+''= \gamma\_u\lambda\_+ \\ \lambda\_-'' = \frac{\gamma'}{\gamma}\lambda\_- \\ \lambda\_-'' = \gamma\_u(1-uv/c^2)\lambda\_- $$ with the simplification coming from $\gamma' = \gamma\_u\gamma(1-uv/c^2)$. You then get: $$ I'' = -\lambda\_+'' u+\lambda\_-'' v'\\ =\gamma\_u(-u +(1-uv/c^2)v')\lambda\_+ $$ The equation $I''=0$ is equivalent to: $$ v-2u=0 $$ which you can solve for $u$ to obtain: $$ u = v/2 $$ @Brian Bi's answer is entirely satisfactory, it's just that I had started to write my answer, so might as well post it. Hope this helps.
Lorentz transformations are reversible. You can reason about the "old" frame by treating the "new" frame as if it's the old one, and then doing a boost in the other direction. If the separation between electrons in the "new" frame (where the electrons are stationary) is $d$, then in the "old" frame, which is moving with velocity $-v$ relative to the "new" one, that length appears to be contracted to $d/\gamma$. Based on this, it's clear that in the "new" frame the electrons are $\gamma$ further apart than they were in the "old" frame.
12,356,056
I have seen the other errors about this problem. I have done the exact same thing. When I try to render the menu I get this Fatal error: ``` Fatal error: Call to undefined method Knp\Menu\MenuItem::setCurrentUri() in ProjectBundle/Menu/Builder.php on line 23 ``` This is how my Builder looks: ``` <?php use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\HttpFoundation\Request; class Builder extends ContainerAware { private $factory; public function __construct(FactoryInterface $factory) { $this->factory = $factory; } public function createMenu(Request $request) { $menu = $this->factory->createItem('root'); $menu->setCurrentUri($request->getRequestUri()); $menu->addChild('Home', array('route' => '_home')); $menu->addChild('About', array('route' => '_about')); $menu->addChild('Bullshit', array('route' => '_bullshit')); return $menu; } } ``` I went through the issue tracker on Github, and it seems this issue has been fixed, but why do I have the same issue again? I mean, when I `var_dump($menu)`, it clearly says it's a `MenuItem` and seeing the Documentation of KnpMenu, there is definitely a `setCurrentUri()` method for my `$menu`.
2012/09/10
[ "https://Stackoverflow.com/questions/12356056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366455/" ]
It looks like the `MenuItem::setCurrentUri()` method was deprecated as of v1.1.0. See <https://github.com/KnpLabs/KnpMenu/issues/63> for more information. That issue has several links on how to set the current uri of the menu using `UrlVoter` instead.
I found the simplest solution. just add: ``` $menu->setCurrent(true); ``` It adds class 'current' to current menu. Method `setCurrentUri` has been deprecated and later removed from knpmenu.
12,596,098
I have these two tables: ``` desc students +-----------------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+---------+------+-----+---------+----------------+ | student_id | int(11) | NO | PRI | NULL | auto_increment | | student_ticket_number | int(11) | YES | | 0 | | +-----------------------+---------+------+-----+---------+----------------+ desc studentdates +-----------------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+---------+------+-----+---------+----------------+ | student_date_id | int(11) | NO | PRI | NULL | auto_increment | | student_id | int(11) | YES | | NULL | | | student_ticket_number | int(11) | YES | | 0 | | +-----------------------+---------+------+-----+---------+----------------+ ``` I would like to move the column `students.student_ticket_number` to `studentdates.student_ticket_number` where the field `student_id` match. So if the user John has `student_id` = 1 move his ticketnumber (for example 1234) from `students.student_ticket_number` to `studentdates.student_ticket_number WHERE student_id = '1'`. In the table `studentdates.student_id` there can be multiple identical records then I would like to use the lowest `studentdates.student_date_id` and skip the others. Tell me if this is unclear. I guess I need to do a subquery somehow but how?
2012/09/26
[ "https://Stackoverflow.com/questions/12596098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1398242/" ]
``` for(int j=0;j< GenresArray.count; j++) { NSString *value=[[genre componentsSeparatedByString: @","]objectAtIndex:j]; if([value isEqualToString:@"movies"]) { [genreMovies addObject:value]; } } ``` Thank you for your help guys ..Now i have my result:)
You can try to check if the string contains the substring you want . Like this: ``` NSString *typesString = [dic objectForKey:"genres_en"]; NSRange range = [typesString rangeOfString:@"horror"]; if(range.location != NSNotFound) { //it contains the substring "horror" } ``` Or , the better way would be to get the array of types. ``` NSArray *types = [[typesString componentsSeparatedByString:","]; ``` Now you can store this array for each entry and whenever you want to check if it belongs to a certain gender , just loop through the types array ( of each entry ) and compare the strings. Hope this helps. Cheers!
32,795,160
When I open web-forms page on a browser but i am getting this error ``` Object reference not set to an instance of an object ``` Kindly review the code snippet, what i am doing wrong ``` if (!IsPostBack) { if (string.IsNullOrEmpty(Session["LoginUser"].ToString()) == false && string.IsNullOrEmpty(Session["CustomerId"].ToString()) == false)//error { if (Session["LoginUser"].ToString() == "admin") { DDlUsers.Visible = true; fillusers(); } else if (Session["LoginUser"].ToString() != "admin" && Session["CustomerId"].ToString() == "True") { DDlUsers.Visible = false; //fillusers(); } else { DDlUsers.Visible = false; } FillProjectList(); Pnl_Link.Visible = false; Pnl_Status.Visible = false; } else { Response.Redirect("~/login.aspx"); } } ``` how to make if session is null it should redirect to login.aspx. without throwing run time exception.
2015/09/26
[ "https://Stackoverflow.com/questions/32795160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5370744/" ]
When you update your composer it will check the providers. Because you haven't installed `laravelcollective/html` yet he can't find it and throws an error: So first require your packeges, then add them to the config file. You can also work with `composer require laravelcollective/html`, it will add it to the json file automatically. Then it doesn't matter if you have added them before or not because the config file won't be checked.
Installation failed, reverting `./composer.json` to its original content. > > [ErrorException] > > copy(/home/zahid/.composer/cache/files/laravelcollective/html/20e9e29d83e23aba16dc4b8d93d0757e1541f076.zip): > failed to open stream: Permiss ion denied > > > Command: `composer require laravelcollective/html --prefer-source` then it work
38,081,807
The following for loop in Go isn't allowed, ``` for i := 0, j := 1; i < 10; i++, j++ {...} ``` What's the correct equivalent of the for-loop of two variables below? ``` for (int i = 0, j = 1; i < 10; i ++ , j ++) {...} ```
2016/06/28
[ "https://Stackoverflow.com/questions/38081807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363663/" ]
Although above Answer is accepted, and it fully satisfy the need. But I would like to contribute some further explanation to it. Golang Does not support many things which could be done in simple terms. For loop is a most common example of this. The beauty of Go's For loop is that it merges many modern style of looping into one keyword. Similarly Golang do with Multiple Variable declaration and assignment. According to above mentioned problem, We could solve multi-variable for loop with this simple tool which Golang provides us. If you want to look into further explanation, this question provide further details and way of [declaring multiple variables in one statement](https://stackoverflow.com/questions/21071507/can-you-declare-multiple-variables-at-once-in-go). Coming back to for loop, If we want to declare variable of same datatype we can declare them with this ``` var a,b,c string ``` but we use short hand in for loop so we can do this for initializing them with same value ``` i,j := 0,1 ``` **Different Datatypes and Different Values** and if we want to declare different type of variables and want to assign different values we can do this by separating variables names and after := different values by comma as well. for example ``` c,i,f,b := 'c',23423,21.3,false ``` **Usage of Assignment Operator** Later on, we can assign values to multiple variables with the same approach. ``` x,y := 10.3, 2 x,y = x+10, y+1 ``` **Mixing Struct and Normal types in single statement** Even we can use struct types or pointers the same way. Here is a function to iterate Linked list which is defined as a struct ``` func (this *MyLinkedList) Get(index int) int { for i,list := 0,this; list != nil; i,list = i+1,list.Next{ if(i==index){ return list.Val } } return -1 } ``` This list is defined as ``` type MyLinkedList struct { Val int Next *MyLinkedList } ``` **Answering to Original Problem** Coming to the origin Question, Simply it could be done ``` for i, j := 0, 1; i < 10; i, j = i+1, j+1 { fmt.Println("i,j",i,j) } ```
Suppose you want to loop using two different starting index, you can do this way. This is the example to check if string is palindrome or not. ``` name := "naman" for i<len(name) && j>=0{ if string(name[i]) == string(name[j]){ i++ j-- continue } return false } return true ``` This way you can have different stopping conditions and conditions will not bloat in one line.
2,918,464
I need to get a closed form from $$ \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 $$ Starting from the most outer summation, I got $$ \sum\_{k=1}^{j} 1 = j $$ But now I don't know how to proceed with: $$ \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} j $$ Could you guys please help me? Thanks in advance.
2018/09/16
[ "https://math.stackexchange.com/questions/2918464", "https://math.stackexchange.com", "https://math.stackexchange.com/users/585618/" ]
Thanks @Winther for pointing out the previous mistake \begin{equation} \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 \end{equation} We know that \begin{equation} \sum\_{k=1}^{j} 1 = j \end{equation} So \begin{equation} \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 = \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} j \end{equation} \begin{equation} \sum\_{j=i+1}^{n} j = \sum\_{j=1}^{n} j - \sum\_{j=1}^{i} j = \frac{n(n+1)}{2} - \frac{i(i+1)}{2} \end{equation} \begin{equation} \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 = \sum\_{i=1}^{n-1} ( \frac{n(n+1)}{2} - \frac{i(i+1)}{2}) = \frac{n(n+1)(n-1)}{2} - \frac{1}{2} \sum\_{i=1}^{n-1} i+i^2 \end{equation} But \begin{align} \sum\_{i=1}^{n-1} i &= \frac{(n-1)n}{2} \\ \sum\_{i=1}^{n-1} i^2 &= \frac{(n-1)n(2n-1)}{6} \end{align} So \begin{equation} \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 = \frac{n(n+1)(n-1)}{2} - \frac{1}{2} (\frac{(n-1)n}{2} + \frac{(n-1)n(2n-1)}{6}) \end{equation} Let's arrange \begin{equation} \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 = \frac{6n(n+1)(n-1) - 3n(n-1) - n(n-1)(2n-1)}{12} \end{equation} > > We arrive at the most compact form, > \begin{equation} > \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} 1 = > \frac{(n-1)n(6n + 6 - 3 - 2n + 1)}{12} > = > \frac{(n-1)n(n + 1)}{3} > \end{equation} > > >
Knowing that \begin{align} \sum\_{k=1}^{n} (1) &= n \\ \sum\_{k=1}^{n} k &= \frac{n \, (n+1)}{2} \\ \sum\_{k=1}^{n} k^2 &= \frac{n(n+1)(2n+1)}{6} \end{align} then \begin{align} S &= \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} \sum\_{k=1}^{j} (1) \\ &= \sum\_{i=1}^{n-1} \sum\_{j=i+1}^{n} j \\ &= \sum\_{i=1}^{n-1} \left(\sum\_{j=1}^{n} j - \sum\_{j=1}^{i} i \right) \\ &= \sum\_{i=1}^{n-1} \left(\binom{n}{2} - \frac{i(i+1)}{2}\right) \\ &= \binom{n}{2} \, \sum\_{i=1}^{n-1} (1) - \frac{1}{2} \, \sum\_{i=1}^{n-1} i^2 - \frac{1}{2} \, \sum\_{i=1}^{n-1} i \\ &= \binom{n}{2} \, (n-1) - \frac{n(n-1)}{4} - \frac{n(n-1)(2n-1)}{12} \\ &= \frac{(n-1)(n)(n+1)}{3} = 2 \, \binom{n+1}{3}. \end{align}
35,146,538
The [WeakMap polyfill](https://github.com/webcomponents/webcomponentsjs/blob/master/src/WeakMap/WeakMap.js) is throwing an error when trying to define property on inextensible object. Those are in the middle of a bunch of node, javascript code and libraries so I couldn't actually point out where causes the issue. There are many other libraries which also have their own polyfill. It's difficult to debug in which library causes the error. And, the errors are ONLY on IE10. To get rid of it, I added a checker before defining a property like (line 26 in the above file): ``` if (entry && entry[0] === key) { entry[1] = value; } else if (Object.isExtensible(key)) { defineProperty(key, this.name, { value: [ key, value ], writable: true }); } ``` My question is, Is it safe/right to fix it as in my code above? If not, how should I fix my problem?
2016/02/02
[ "https://Stackoverflow.com/questions/35146538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159297/" ]
As best I can tell that `weakMap` polyfill is ONLY designed to work with extensible objects as keys. It simply won't work with a non-extensible object. Your modification has made it so it doesn't throw an exception, but then the non-extensible item will not be in the `weakMap` either. So, your fix isn't really a fix. That particular polyfill would have to be rewritten to handle non-extensible keys. It would not be a simple fix as it would need a conceptually different approach. There are a number of other polyfills that take a different approach. I have not researched which ones might be better in this regard. I suspect it's a little bit of conundrum between actually being "weak" (e.g. allows garbage collection) vs. can handle a non-extensible object. The fundamental issue is that if you are going to be weak, then you can't store a reference to the object itself. So, you need to store a reference to some string representation of the object. Well, JS objects don't have a built-in guaranteed unique string representation. So, the usually fix is to coin one using some sort of counter and store it on the object as a property and then you store that string representation in your map. But, if the object isn't extensible, then you can't do that either. So, you're stuck storing the actual object reference in your map, but then it's not really "weak" any more. You can see how you're kind of stuck. I think this is one case where a polyfill just can't quite live up to the real thing. Different polyfills will have different tradeoffs in this regard. You picked one that is truly weak, but requires the objects to be extensible so a property can be added.
As in my question, I want a solution which does not have huge impact on other functionality or plugins, so here is my fix for this issue. The fix is based on the answer of @jfriend00 above and reference from other implementation in the internet. ``` var defineProperty = Object.defineProperty; var counter = Date.now() % 1e9; var FrozenStore = function() { this.a = []; }; var findFrozen = function(store, key){ return store.a.forEach(function(it){ if (it[0] === key) { return it; } }); }; var findIndexFrozen = function(store, key){ return store.a.forEach(function(it, id){ if (it[0] === key) { return id; } }); }; FrozenStore.prototype = { get: function(key){ var entry = findFrozen(this, key); if (entry) return entry[1]; }, has: function(key){ return !!findFrozen(this, key); }, set: function(key, value){ var entry = findFrozen(this, key); if (entry) entry[1] = value; else this.a.push([key, value]); }, "delete": function(key){ var index = findIndexFrozen(this, key); if (~index) this.a.splice(index, 1); return !!~index; } }; var WeakMap = function() { this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__"); }; var frozenStore = function(that){ return that._l || (that._l = new FrozenStore); }; WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) { entry[1] = value; } else { if (!Object.isExtensible(key)) { frozenStore(this).set(key, value); } else { defineProperty(key, this.name, { value: [ key, value ], writable: true }); } } return this; }, get: function(key) { var entry; if ((entry = key[this.name]) && entry[0] === key) { return entry[1]; } else if (!Object.isExtensible(key)) { frozenStore(this).get(key); } else { return undefined; } }, "delete": function(key) { var entry = key[this.name]; if (!entry || entry[0] !== key) return false; if (!Object.isExtensible(key)) frozenStore(this)['delete'](key); entry[0] = entry[1] = undefined; return true; }, has: function(key) { var entry = key[this.name]; if (!entry) return false; if(!Object.isExtensible(key)) return frozenStore(this).has(key); return entry[0] === key; } }; window.WeakMap = WeakMap; ``` This introduces the FrozenStore which will manage all non-extensible keys being added to WeakMap. I'm not sure whether it breaks the concept of WeakMap or not but it does rescue me from the issue.
880,141
I need to generate something that can be used as a unique handle for a user defined type (struct or class) in the [D programming language](http://digitalmars.com/d/1.0/index.html). Preferably this would be a compile time computable value. I want the handle to relate to the name of the type as well as change if the internal structure (data layout) of the type changes but remain the same for most other edits (including compiling the same type into a different app). This is not a security thing so it doesn't need to be hard to bypass or anything My current thought is to use a string with something like an MD5 hash of the type name and member types and names. Any thoughts
2009/05/18
[ "https://Stackoverflow.com/questions/880141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
The fully qualified name of a type should be unique. This is the same as typeid(T).toString. This is *not* the same as T.stringof -- T.stringof will erase any template instantiations and will not give the fully qualified name. The workaround is to use demangled(T.mangleof) at compiletime and typeid(T).toString at runtime.
You know, you can just hardcode a revision into the type, like "const REV = 173; ", then update it every time you change the layout, then mix that with the type name to produce your identifier. This is a bit of a hassle because it requires manual updates, but you could script it to be updated automatically on commit when svn diff recognizes a change in that class. And it's probably the easiest solution.
312,834
In the context of quantum mechanics one cannot measure the velocity of a particle by measuring its position at two quick instants of time and dividing by the time interval. That is, $$ v = \frac{x\_2 - x\_1}{t\_2 - t\_1} $$ does not hold as just after the first measurement the wavefunction of the particle "collapses". So, experimentally how exactly do we measure the veolcity (or say momentum) of a particle? One way that occurs to me is to measure the particle's de Broglie wavelength $\lambda$ and use $$p = \frac{h}{\lambda}$$ and $$v = \frac{p}{m}$$ to determine the particle's velocity. Is this the way it is done? Is there any other way?
2017/02/17
[ "https://physics.stackexchange.com/questions/312834", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/133131/" ]
For a cold atom experiment, experimentalists use time-of-flight (TOF) measurement to determine the momentum distribution of atoms in the optical trap. Suppose there are an ensemble of atoms trapped in the optical trap, when the optical trap is switched off, the atoms will "fly around" with their momentum. With detectors installed around the trap, one could obtain both the value and direction of atomic momenta, which could be gathered to contruct the momentum distribution. See [arXiv: 1002.2311](https://arxiv.org/abs/1002.2311)
In condensed matter physics community, one can use the [ARPES apparatus](https://en.wikipedia.org/wiki/Angle-resolved_photoemission_spectroscopy). [ARPES gives information](http://www.arpes.org.uk/Index.html) on the direction, speed and scattering process of valence electrons in the sample being studied (usually a solid). This means that information can be gained on both the energy and momentum of an electron, resulting in detailed information on band dispersion and Fermi surface.
10,404,208
I heard it is possible to write an Operating System, using the built in bootloader and a kernel that you write, for the PIC microcontroller. I also heard it has to be a RTOS. 1. Is this true? Can you actually make an operating system kernel (using C/C++) for PIC? 2. If yes to 1, are there any examples of this? 3. If yes to 1, would you need any type of software to create the kernel? 4. Is Microchip the only company that makes PIC microcontrollers? 5. Can the PIC microcontroller be programmed on a mac? Thanks!
2012/05/01
[ "https://Stackoverflow.com/questions/10404208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162346/" ]
1. Yes, you can write your own kernel (I have written 2 of my own). Yes you can write it in C for PIC. If you want pre-emptive scheduling, then you're going to have a real tough time avoiding assembly completely when writing the context switch. On the other hand, you can *easily* write a cooperative kernel purely in C (I have done this myself). (Note that creating an operating system is not a simple task... I'd get your feet wet in pure C first, then USE an OS or two, then try creating one.) 2. An excellent example of this is FreeRTOS. It has preexisting ports (i.e. MPLAB projects that run without any modification on the Explorer16 demo board) for PIC24F, PIC33F, and PIC32MX (as well as 20-some odd other official ports for other vendors' devices). PIC18F is supported but it's not pretty... 3. You only need MPLAB to create the kernel (free from Microchip). It can work interchangably with C and assembly. Depending on the processor, there are free versions of their C30 and C32 compilers to go with MPLAB. 4. PIC is a type of microcontroller, and is a trademark of Microchip. Many other companies make microcontrollers and call them something else (e.g. AVR, LPC, STM32). 5. Yes, the new version of MPLAB X is supported on Mac, Linux and Windows.
I second the vote for FreeRTOS; we use this all the time on PIC24 designs. The port works well and doesn't use a ton of memory. [Microchip supports many third party RTOSes.](http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1406&dDocName=en531543&page=wwwRTOS) Most have free demo projects that you can download, build in MPLAB, and program onto an Explorer16 board very easily. You can then experiment to your heart's content.
28,418,233
I have a django application with an angular front-end. When from the front-end I try to send a request for passwordReset, I get the following error: > > Reverse for 'password\_reset\_confirm' with arguments '()' and keyword > arguments '{u'uidb64': 'MTE', u'token': u'3z4-eadc7ab3866d7d9436cb'}' > not found. 0 pattern(s) tried: [] > > > Its a POST request going to `http://127.0.0.1:8080/rest-auth/password/reset/` Following is what my urls.py looks like: ``` from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^account/', include('allauth.urls')) ) ```
2015/02/09
[ "https://Stackoverflow.com/questions/28418233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131194/" ]
For those who are still struggling with this issue, I found that the reverse look up internal view looks for reverse lookup within the core project urls and not within any application. It could work within application with some tweak, but I am not sure. But it works creating the reset urls directly on core project urls.py ```py { path(r'password_reset/', PasswordResetView.as_view(template_name='password_reset_form.html'), name='password_reset'), path(r'password_reset_done/', PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path(r'password_reset_confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), name='password_reset_confirm'), path(r'password_reset_complete/', PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), } ```
Add this to your project url.py file ``` url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), url('', include('social.apps.django_app.urls', namespace='social')), ```
26,975,914
I have a list of packages and want to remove suffixes from specific combination of characters. Should I use regex or other mehotds such as replace ? All packages' endings are different because these are versions so I am not sure which to use and how. I think I should clear the remaining characters from `-0:` in string. What list is like: ``` ... 'znc-devel-0:1.4-1.el6.i686', 'znc-devel2-0:1.4-1.el6.x86_64' ... ``` What I want to have: ``` ...'znc-devel', 'znc-devel2'... ``` What should I do?
2014/11/17
[ "https://Stackoverflow.com/questions/26975914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4095134/" ]
`partition` on "-0" and take the left portion. ``` seq = ['znc-devel-0:1.4-1.el6.i686', 'znc-devel2-0:1.4-1.el6.x86_64'] print [item.partition("-0")[0] for item in seq] ``` Result: ``` ['znc-devel', 'znc-devel2'] ```
Through `re.sub` and list comprehension. ``` >>> L = ['znc-devel-0:1.4-1.el6.i686', 'znc-devel2-0:1.4-1.el6.x86_64'] >>> import re >>> [re.sub(r'-0:.*', r'', line) for line in L] ['znc-devel', 'znc-devel2'] ```
19,418
I need to edit my OpenOffice documents. Is there any version of LibreOffice for Android? Or Is there any ODT texteditor app for Android?
2012/02/13
[ "https://android.stackexchange.com/questions/19418", "https://android.stackexchange.com", "https://android.stackexchange.com/users/9897/" ]
[Zoho Writer](https://play.google.com/store/apps/details?id=com.zoho.writer) seems to support viewing & editing ODT files (only tested with a very simple document): > > ... > > > * Supports saving of documents in different formats like doc,docx,rtf,odt,txt,html and PDF > > > Though it seems to work awkwardly: * Can't directly open a file from disk, first step is importing the file. * Can't directly save file, must find a hidden "Export" button first. * Google Play reviewers have many strange bugs to report. After trying it for a few seconds I have noticed some strange redrawing issues.
[Collabora Office](https://play.google.com/store/apps/details?id=com.collabora.libreoffice), a LibreOffice derivative, works well on my tablet.
18,969,798
Essentially, I'm trying to find a good way to attach more views to a Router without creating a custom Router. **What's a good way to accomplish this?** Here is something sort of equivalent to what I'm trying to accomplish. Variable names have been changed and the example method I want to introduce is extremely simplified for the sake of this question. Router: ``` router = routers.SimpleRouter(trailing_slash=False) router.register(r'myobjects', MyObjectViewSet, base_name='myobjects') urlpatterns = router.urls ``` ViewSet ``` class MyObjectsViewSet(viewsets.ViewSet): """ Provides API Methods to manage MyObjects. """ def list(self, request): """ Returns a list of MyObjects. """ data = get_list_of_myobjects() return Response(data) def retrieve(self, request, pk): """ Returns a single MyObject. """ data = fetch_my_object(pk) return Response(data) def destroy(self, request, pk): """ Deletes a single MyObject. """ fetch_my_object_and_delete(pk) return Response() ``` One example of another method type I need to include. (There are many of these): ``` def get_locations(self, request): """ Returns a list of location objects somehow related to MyObject """ locations = calculate_something() return Response(locations) ``` The end-result is that the following URL would work correctly and be implemented 'cleanly'. ``` GET example.com/myobjects/123/locations ```
2013/09/23
[ "https://Stackoverflow.com/questions/18969798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/485900/" ]
The [answer given by mariodev](https://stackoverflow.com/a/18970651/3216056) above is correct, as long as you're only looking to make `GET` requests. If you want to `POST` to a function you're appending to a ViewSet, you need to use the `action` decorator: ``` from rest_framework.decorators import action, link from rest_framework.response import Response class MyObjectsViewSet(viewsets.ViewSet): # For GET Requests @link() def get_locations(self, request): """ Returns a list of location objects somehow related to MyObject """ locations = calculate_something() return Response(locations) # For POST Requests @action() def update_location(self, request, pk): """ Updates the object identified by the pk """ location = self.get_object() location.field = update_location_field() # your custom code location.save() # ...create a serializer and return with updated data... ``` Then you would `POST` to a URL formatted like: `/myobjects/123/update_location/` <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing> has more information if you're interested!
You can now do this with the list\_route and detail\_route decorators: <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing> For example: ``` from rest_framework.decorators import list_route from rest_framework.response import Response ... class MyObjectsViewSet(viewsets.ViewSet): ... @list_route() def locations(self, request): queryset = get_locations() serializer = LocationSerializer(queryset, many=True) return Response(serializer.data) ```
6,283,837
About pyQt4 I prefer to use the static method for the getSaveFilename in the QFileDialog so that the user sees the Windows/Mac native dialog. My problem is that if the user doesn't type the file extension the in the save file name (say when selecting an image type to save a file as), then I don't have a way of checking to see what type of file they wanted to save as. How can I create a dialog to save files with a filter, and how to know which filter the user chose? For example: ``` files_types = "GML (*.gml);;Pickle (*.pickle);;YAML (*.yml)" file = QtGui.QFileDialog.getSaveFileName(self, 'Save file', '', files_types) ``` With var file I'll have only the file's path, but I'm not sure whats the format that user chose. So, I wanna know how could I get the extension, or the files type chosen by user. Is there away to get the selectedFilter using this method? Thanks a lot!
2011/06/08
[ "https://Stackoverflow.com/questions/6283837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/771740/" ]
In PyQt5 just use: ``` files_types = "GML (*.gml);;Pickle (*.pickle);;YAML (*.yml)" options = QFileDialog.Options() filename, _ = QFileDialog.getSaveFileName( self, 'Save as... File', 'untitled.gml', filter=file_types,options=options) ```
Its not possible. The only way to do this, is creating a generical dialog, but by another hand you will lost the pretty native windows.
53,778,712
I have been trying to create a **custom** login feature in **ASP.NET Core 2.1**. However, it doesn't seem the work and I have no idea why. This is run in the controller: ``` var claims = new List<Claim> { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Role, loginResult.User.RoleName) }; ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal principal = new ClaimsPrincipal(identity); var timespanExpiry = new TimeSpan(0, 0, 30, 0, 0); await httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme , principal , new AuthenticationProperties { ExpiresUtc = new DateTimeOffset(timespanExpiry.Ticks, timespanExpiry) }); ``` This is what I have in my Startup.cs: ``` public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSingleton<IConfiguration>(Configuration); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //services services.AddSingleton<ITableStorageService, TableStorageService>(); services.AddAuthorization(options => { options.AddPolicy("ConfirmUser", policy => policy.Requirements.Add(new AuthorizationsRequirement(AuthorizationKeyConstants.AUTH_CONFIRM_USER))); options.AddPolicy("GetUser", policy => policy.Requirements.Add(new AuthorizationsRequirement(AuthorizationKeyConstants.AUTH_GET_USER))); options.AddPolicy("RemoveUser", policy => policy.Requirements.Add(new AuthorizationsRequirement(AuthorizationKeyConstants.AUTH_DELETE_USER))); options.AddPolicy("GetListUser", policy => policy.Requirements.Add(new AuthorizationsRequirement(AuthorizationKeyConstants.AUTH_GETLIST_USER))); }); services.AddAuthentication(options => { options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = new PathString("/User/Login"); options.AccessDeniedPath = new PathString("/error?unauth"); }); services.AddSingleton<IAuthorizationHandler, AuthorizationsHandler>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } ``` No errors are occurring, but when I use the code below in Razor or in my controller to check if the user is authenticated, it returns a false. I have checked other questions and answers as well, none of it helps and helped me out with this. ``` httpContextAccessor.HttpContext.User.Identity.IsAuthenticated ``` Is there another way to do this, or am I doing something wrong? **EDIT: I have included my whole `Startup.cs` but excluded some dependency injections and database related information on purpose.**
2018/12/14
[ "https://Stackoverflow.com/questions/53778712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5350903/" ]
I know this was asked a long time ago, but I recently encountered this same issue. So,here I am sharing my finding. ``` app.UseHttpsRedirection(); app.UseStaticFiles(); var cookiePolicyOptions = new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Strict, HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always, Secure = CookieSecurePolicy.None, }; app.UseCookiePolicy(cookiePolicyOptions); app.UseRouting(); app.UseAuthorization(); app.UseAuthentication(); ``` For some reason when I use the above code in startup.cs ,It always redirecting to `/login` But the below code is working fine. ``` app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); var cookiePolicyOptions = new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Strict, HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always, Secure = CookieSecurePolicy.None, }; app.UseCookiePolicy(cookiePolicyOptions); app.UseAuthentication(); app.UseAuthorization(); ``` It seems position of `UseRouting()` impacts cookie authentication, any comments on this will be appreciated.
Try one of the following process: 1. Clear browser cache. 2. Use a different browser.
192,852
Output Distinct Factor Cuboids ============================== Today's task is very simple: given a positive integer, output a representative of each cuboid formable by its factors. Explanations ------------ A cuboid's volume is the product of its three side lengths. For example, a cuboid of volume 4 whose side lengths are integers can have sides `[1, 1, 4]`, `[1, 2, 2]`, `[1, 4, 1]`, `[2, 1, 2]`, `[2, 2, 1]`, or `[4, 1, 1]`. However, some of these represent the same cuboid: e.g. `[1, 1, 4]` and `[4, 1, 1]` are the same cuboid rotated. There are only two distinct cuboids with volume 4 and integer sides: `[1, 1, 4]` and `[1, 2, 2]`. The output can be any representation of the first cuboid, and any representation of the second cuboid. Input ----- Your program must take a single positive integer \$1 \le n \le 2^{31}βˆ’1\$. Output ------ You will need to output all possible cuboids in a list or any other acceptable way. E.g. ``` Input Output 1 [[1, 1, 1]] 2 [[1, 1, 2]] 3 [[1, 1, 3]] 4 [[1, 1, 4], [1, 2, 2]] 8 [[1, 1, 8], [1, 2, 4], [2, 2, 2]] 12 [[1, 1, 12], [1, 2, 6], [1, 3, 4], [2, 2, 3]] 13 [[1, 1, 13]] 15 [[1, 1, 15], [1, 3, 5]] 18 [[1, 1, 18], [1, 2, 9], [1, 3, 6], [2, 3, 3]] 23 [[1, 1, 23]] 27 [[1, 1, 27], [1, 3, 9], [3, 3, 3]] 32 [[1, 1, 32], [1, 2, 16], [1, 4, 8], [2, 2, 8], [2, 4, 4]] 36 [[1, 1, 36], [1, 2, 18], [1, 3, 12],[1, 4, 9], [1, 6, 6], [2, 2, 9], [2, 3, 6], [3, 3, 4]] ``` Sub-lists don't need to be sorted, just as long as they are unique. Scoring ------- This is code golf, so shortest answer in bytes wins. Standard loopholes are forbidden. *[Here](https://tio.run/##VVDbSgQxDH3vVwREaHVZdlyfhHlS9NEPWAapvWhgTEsnA@vXj2lnL5iXkJOT5JzkX/5OtF@Wm/eZ88zwghMjOYZX6zgVeJ4/E/oJ3gKFYgVRytkpQA9IrJFkRhujfIgQkfxHbGOTPponBRKnWviHYQVkKcowFEtfQXcbOMI9dCd6DYwC3Qqp72F3ha/LtjbnQF6jac0SeC50bioV5dg/LVWwUfiTU2FADoVTGiuxE@YohvUF3OaS/OxYx43szcFyvxd7yjoX8mqiGhirgdit4kTveNgNcCepW9PDUMW3R1nyMMnh4PVogBLX0bbuaq2VZ1cXslG51Ce3rlHL8vgH "Python 3 – Try It Online") is a test case generator* Leaderboards ------------ Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ```js var QUESTION_ID=192852; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ```css body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ```
2019/09/15
[ "https://codegolf.stackexchange.com/questions/192852", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/78850/" ]
[JavaScript (V8)](https://v8.dev/), ~~61~~ 60 bytes =================================================== Prints the cuboids to STDOUT. ```javascript n=>{for(z=n;y=z;z--)for(;(x=n/y/z)<=y;y--)x%1||print(x,y,z)} ``` [Try it online!](https://tio.run/##JYxNCoMwGET3PUU2xYSOlST9EdLPXbe9QOlCBKldpGJFTNSzpxE3w8wbeJ9yKH9V17R9OuShpmCpmOpvxz1Z48gbn6Zi3YaPZDOXeXEjZ1yk417Oc9s1tucjHLxYgnlKKGickEMqSA15hsyhNNQVOl6X1@4YdfeyenPLqGAT2xTJgxJ2YFYYVvM1NxzLIsIf "JavaScript (V8) – Try It Online") ### Commented ```javascript n => { // n = input for( // outer loop: z = n; // start with z = n y = z; // set y to z; stop if we've reached 0 z-- // decrement z after each iteration ) // for( // inner loop: ; // no initialization code (x = n / y / z) // set x to n / y / z <= y; // stop if x > y y-- // decrement y after each iteration ) // x % 1 || // unless x is not an integer, print(x, y, z) // print the cuboid (x, y, z) } // ```
[Pyth](https://github.com/isaacg1/pyth), 11 bytes ================================================= ``` fqQ*FT.CSQ3 ``` [Try it online!](https://tio.run/##K6gsyfj/P60wUMstRM85OND4/39jMwA "Pyth – Try It Online") ``` SQ # range(1, Q+1) # Q = input .C 3 # combinations( , 3) f # filter(lambda T: vvv, ^^^) qQ # Q == *FT # fold(__operator_mul, T) ( = product of all elements) ```
34,448,539
* MySQL version: 5.6 * Storage engine: InnoDB The deadlock occurred when two tasks tried to `select` and then `insert` the same table. The procedure looks like: ``` Task_1 Task_2 ------ ------ Phase 1 | SELECT SELECT Phase 2 | INSERT INSERT SELECT count(id) from mytbl where name = 'someValue' and timestampdiff(hour, ts, now()) < 1; INSERT mytbl (id, name, ts) values ('newId', 'anotherValue', now()); ``` The deadlock log is as following (with some details truncated): ``` ------------------------ LATEST DETECTED DEADLOCK ------------------------ 151225 8:22:17 *** (1) TRANSACTION: TRANSACTION 0 746402, ACTIVE 0 sec, process no 4690, OS thread id 140411390486272 inserting mysql tables in use 1, locked 1 LOCK WAIT 1172 lock struct(s), heap size 112624, 32914 row lock(s) MySQL thread id 3909, query id 31751474 10.20.36.38 mydb update INSERT INTO mytbl -- truncated *** (1) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 0 page no 5044 n bits 88 index `PRIMARY` of table `MYDB`.`mytbl` trx id 0 746402 lock_mode X insert intention waiting Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0 0: len 8; hex 73757072656d756d; asc supremum;; *** (2) TRANSACTION: TRANSACTION 0 746449, ACTIVE 0 sec, process no 4690, OS thread id 140411389953792 inserting, thread declared inside InnoDB 500 mysql tables in use 1, locked 1 1172 lock struct(s), heap size 112624, 32914 row lock(s) MySQL thread id 3906, query id 31751477 10.20.36.38 mydb update INSERT INTO mytbl -- truncated *** (2) HOLDS THE LOCK(S): RECORD LOCKS space id 0 page no 5044 n bits 88 index `PRIMARY` of table `MYDB`.`MYTBL` trx id 0 746449 lock mode S Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0 0: len 8; hex 73757072656d756d; asc supremum;; *** (2) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 0 page no 5044 n bits 88 index `PRIMARY` of table `MYDB`.`MYTBL` trx id 0 746449 lock_mode X insert intention waiting Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0 0: len 8; hex 73757072656d756d; asc supremum;; *** WE ROLL BACK TRANSACTION (2) ``` --- Questions --------- 1. According to MySQL manual, the simple `SELECT` statement uses snapshot read which requires no *S lock*. The `INSERT` statement requires *X lock* on the single row to be inserted. Then why `Task_2` held an *S lock* and resulted in deadlock? --- Edit ---- The result of `SHOW CREATE TABLE` is as following: ``` | task_content | CREATE TABLE `mytbl` ( `id` bigint(20) NOT NULL, `ts` timestamp NULL DEFAULT NULL, `name` varchar(32) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | ```
2015/12/24
[ "https://Stackoverflow.com/questions/34448539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510918/" ]
> > where name = 'someValue' and timestampdiff(hour, ts, now()) < 1; > > > That is rather inefficient. Let's clean that up to speed things up, to decrease the likelihood of a deadlock. `timestampdiff(hour, ts, now()) < 1` hides any index with `ts`; let's rewrite it to ``` ts < NOW() - INTERVAL 1 HOUR ``` Yours truncated in unexpected ways; mine says "ts older than 1 hour ago", which I suspect you wanted. Now we can index `ts` to good effect. But let's carry it further by using a "composite" index: ``` INDEX(name, ts) ``` This will efficiently use both parts of the `WHERE` clause for locating the row(s). You say `COUNT(id)` -- this implies that you need to avoid `NULLs` in `id`. Perhaps that is not a concern, and you could say simply `COUNT(*)`. Those should make the `SELECT` faster. Now let's figure out why that `SELECT` and `INSERT` have anything to do with each other. Are they in the same transaction? Or do you have autocommit turned OFF, but forgot to say `COMMIT`? Please show us the entire transaction, plus `SHOW CREATE TABLE`.
Write your every query in **BEGIN** and **END** transaction. I hope it will not happened. More : [here](http://dev.mysql.com/doc/refman/5.7/en/commit.html)