_id
stringlengths
2
6
text
stringlengths
4
46k
title
stringclasses
1 value
d16201
You can use map by Series: df1 = df.groupby("b").mean().cumsum() print (df1) a b 1 2 2 5 df['a'] = df['b'].map(df1['a']) print (df) a b 0 2 1 1 2 1 2 5 2 3 5 2
d16202
Assign the id to a $scope $scope.id = message.data.id And use it as: <i class="fa fa-pencil fa-2x order-edit" aria-hidden="true" id="editOrder" ng-click='editOrder(id)'></i> UPDATE: Assigned a DOM Id to the li element in above and fetched the element as: var editOrder = document.getElementById("editOrder"); Now, binding the ng-click with the id. editOrder.bind('ng-click', { id: message.data.id}, function(event) { var data = event.data; alert(data.id); }); PS: The update works for the javascript click event, its not tested for ng-click. EDIT: Tested for 'ng-click', it doesnt work. You could look into this Fiddle and create a custom directive that suits the requirement.
d16203
We don't know what you're trying to achieve by overwriting the gtag function so we can't answer the specific question as to what "works" and what doesn't. What can be said: arguments is an Object and GTM expects an object from dataLayer.push, hence why this follows the intended design (whereas [first, second] is an Array and thus does not). Note that the push call in itself "works": However you won't be able to read that data via GTM which as explained above expects .push to pass Objects. If you want to use the dataLayer in a compeltely free way, you can use the GTM dataLayer helper: https://github.com/google/data-layer-helper This does support the array syntax via Meta commands: dataLayer.push(['abc.push', 4, 5, 6]); However GTM by default doesn't support reading this data (once again GTM expects an Object so it can extract values based on the object properties), so to read that data via GTM you would need to use the dataLayer helper within GTM tags and variables. A: So, at the end, this version of the code works fine for me, without linter errors: window.dataLayer = window.dataLayer || [] function gtag(..._args: unknown[]) { window.dataLayer.push(arguments) } gtag('js', new Date()) gtag('config', trackingCode)
d16204
This can be done via port forwarding on the router. For example: for external IP / port 1234 -> forward to internal IP (and possibly different port) of RPi 1 for external IP / port 1235 -> forward to internal IP of RPi 2 and so on.. I use port 1234 as an example for the webserver, because there could be problems when using port 80 on a home network. To access it you can use yourPublicIP:1234/index.html (or dynamic_domain:1234 )
d16205
This is because you are using in_group_of with no option. Replace your code with this: <div class="container-fluid text-center"> <table> <% @cities.in_groups_of(3,false) do |row_cities| %> <tr> <% row_cities.each_with_index do |city,index| %> <td> <h3><%= city.name %></h3> <p><%= city.country %></p> <%= link_to "See More", city_path(city) %> </td> <% end %> </tr> <% end %> </table> </div> More info here.
d16206
Here's a blog post that explains under what circumstances and why there are performance differences when using different column sizes (with tests and technical details): Advanced TSQL Tuning: Why Internals Knowledge Matters A: It does matter for the query optimiser when it will evaluate the best query path to perform your query. When more than one path will be available, it will calculate an I/O cost and other various parameters based on your query and from these, chose the one that will appears to him as the least costly. This is not an absolute calculation, it's only an approximation process. Therefore, it can easily be thrown off if the apparent mean size required to manipulate the records from one table in memory is much bigger then what will be really necessary and the optimiser might chose a less performing path based on what it thinks would have be necessary for the others paths. Having a realistic max size is also usefull to any other programmer that will come along looking at your code. If I have a variable that I want to display in a GUI, I might allocate much more space than neededd if I see that is backed by something like nvarchar(200) or nvarchar(2000) instead of nvarchar(20) if its size is never greater than that. A: Yes, the length of varchar affects estimation of the query, memory that will be allocated for internal operation (for example for sorting) and as consequence resources of CPU. You can reproduce it with the following simple example. 1.Create two tables: create table varLenTest1 ( a varchar(100) ) create table varLenTest2 ( a varchar(8000) ) 2. Fill both of them with some data: declare @i int set @i = 20000 while (@i > 0) begin insert into varLenTest1 (a) values (cast(NEWID() as varchar(36))) set @i = @i - 1 end 3. Execute the following queries with "include actual execution plan": select a from varLenTest1 order by a OPTION (MAXDOP 1) ; select a from varLenTest2 order by a OPTION (MAXDOP 1) ; If you inspect execution plans of these queries, you can see that estimated IO cost and estimated CPU cost is very different: A: Size matters Always use the smallest data size that will accommodate the largest possible value. If a column is going to store values between 1 and 5, use tinyint instead of int. This rule also applies to character columns. The smaller the data size, the less there is to read, so performance, over all, benefits. In addition, smaller size reduces network traffic. With newer technology, this tip seems less relevant, but don’t dismiss it out of hand. You’ll won’t regret being efficient from the get-go. For more info visit http://www.techrepublic.com/blog/10-things/10-plus-tips-for-getting-the-best-performance-out-of-your-sql-server-data-types/
d16207
A viable approach would be to clone the repositoy from the source server to a temporary location and from there push it to the destination server. You can clone a repository with JGit like this: Git.cloneRepository() .setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user", "password" ) ); .setURI( remoteRepoUrl ) .setDirectory( localDirectory ) .setCloneAllBranches( true ) .call(); To transfer the just cloned repositoy to the destination, you have to create a repository on the destination server first. Neither JGit nor Git support this step. GitHub offers a REST API that lets you create repositories. The developer pages also list the language bindings that are available for this API with Java among them. Once the (empty) repository is there, you can push from the temporary copy to the remote: Git git = Git.open( localDirectory ); git.push() .setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user", "password" ) ); .setRemote( newRemoteRepoUrl ) .setForce( true ) .setPushAll() .setPushTags() .call() More information about authentication can be found here Note that if the source repository contains tags, these have to be fetched into the temporary repository separately after cloning.
d16208
If you have the log-file open with full sharing-mode, others are still stopped from opening for exclusive access, or with deny-write. Seems the second program wants more access than would be compatible. Also, I guess you only want to append to the log, use mode "a" instead of "w". Last, do not call _unlock_file unless you called _lock_file on the same file previously. There is a way to do what you want though: Open your file without any access, and then use Opportunistic Locks. Raymond Chen's blog The Old New Thing also has a nice example: https://devblogs.microsoft.com/oldnewthing/20130415-00/?p=4663
d16209
Here is how to issue group claims out of B2C: 1. Define a new claim type in for groups in the Base policy file. This definition should be at the end of < ClaimsSchema > element (yes, the man who wrote about stringCollection was write!) <ClaimType Id="IdpUserGroups"> <DisplayName>Security groups</DisplayName> <DataType>stringCollection</DataType> <DefaultPartnerClaimTypes> <Protocol Name="OAuth2" PartnerClaimType="groups" /> <Protocol Name="OpenIdConnect" PartnerClaimType="groups" /> <Protocol Name="SAML2" PartnerClaimType="http://schemas.xmlsoap.org/claims/Group" /> </DefaultPartnerClaimTypes> </ClaimType> *Use this new defined claim in the < OutputClaims > in the extenstion policy in < ClaimsProvider > definition for ADFS <OutputClaims> <OutputClaim ClaimTypeReferenceId="socialIdpUserId" PartnerClaimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" /> <OutputClaim ClaimTypeReferenceId="IdpUserGroups" PartnerClaimType="http://schemas.xmlsoap.org/claims/Group" /> <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="SAML fmdadfs4.local"/> <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="SAML ADFS4 fmdadfs4.local" /> </OutputClaims> *Use the same claim in the < OutputClaims > dfinition in relyng party definition under < RelyngParty > elemnt in your SignIn policy file <OutputClaims> <OutputClaim ClaimTypeReferenceId="socialIdpUserId" /> <OutputClaim ClaimTypeReferenceId="IdpUserGroups" /> <OutputClaim ClaimTypeReferenceId="identityProvider" /> <OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="userPrincipalName" /> *Issue group claims from ADFS as it is shown here A: Looks like OP simply has the partnerclaimtype misspelled. Not certain because you may have mapped something non-standard, but I'm thinking you just need to change your PartnerClaimType from group to groups. <ClaimType Id="groups"> <DisplayName>Groups</DisplayName> <DataType>stringCollection</DataType> <DefaultPartnerClaimTypes> <Protocol Name="OpenIdConnect" PartnerClaimType="groups" /> </DefaultPartnerClaimTypes> <UserHelpText>List of group memberships</UserHelpText> </ClaimType> * *Once you define the ClaimType, you don't need to specify the PartnerClaimType anywhere else - unless you're overriding the value. *I'd also consider using the DefaultValue="" attribute so you can check your policy is properly executing the output claim. OutputClaim ClaimTypeReferenceId="groups" DefaultValue="no groups assigned
d16210
Maybe I misunderstood something...but don't get it why vs? isArray is just says you that you'll get an array throughout this resource and an array will be returned instantly for you to be able to iterate over it and then it will be populated by your data, so you can use it as an array after you just call a resource. quote from documentation: It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. params is just pre-bounded params for your POST request. You can read this article for better understanding
d16211
You could use this ES6 function: function checkIfWordContainsLetters(wordToCheck, letters){ return !letters.reduce((a, b) => a.replace(b,''), wordToCheck.toLowerCase()).length; } console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"])); console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"])); The idea is to go through each letter in the letters array, and remove one (not more!) occurrence of it in the given wordToCheck argument (well, not exactly in it, but taking a copy that lacks that one character). If after making these removals there are still characters left over, the return value is false -- true otherwise. Of course, if you use Internet Explorer, you won't have the necessary ES6 support. This is the ES5-compatible code: function checkIfWordContainsLetters(wordToCheck, letters){ return !letters.reduce(function (a, b) { return a.replace(b, ''); }, wordToCheck.toLowerCase()).length; } console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"])); console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"])); A: As long as it is not the best solution for long strings for which using some clever regex is definitely better, it works for short ones without whitespaces. function checkIfWordContainsLetters(word, letters){ word = word.toLowerCase().split(''); for(var i = 0; i < letters.length; i++) { var index = word.indexOf( letters[i].toLowerCase() ); if( index !== -1 ) { // if word contains that letter, remove it word.splice( index , 1 ); // if words length is 0, return true if( !word.length ) return true; } } return false; } checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]); // returns true checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]); // returns false
d16212
In Polars, column names are always stored as strings, and hence you have the alphanumeric sorting rather than numeric. There is no way around the strings, so I think the best you can do is to compute the column order you want, and select the columns: import polars as pl df = pl.DataFrame({"version": [9, 85, 87], "testsuite": ["scan1", "scan2", "scan3"], "status": ["ok"] * 3}) wide = df.pivot(index="testsuite", columns='version', values='status') cols = df["version"].cast(pl.Utf8).to_list() wide[["testsuite"] + cols] ┌───────────┬──────┬──────┬──────┐ │ testsuite ┆ 9 ┆ 85 ┆ 87 │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str │ ╞═══════════╪══════╪══════╪══════╡ │ scan1 ┆ ok ┆ null ┆ null │ ├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤ │ scan2 ┆ null ┆ ok ┆ null │ ├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤ │ scan3 ┆ null ┆ null ┆ ok │ └───────────┴──────┴──────┴──────┘
d16213
You need to use HAVING clause like below SELECT * from Customer Where ref in (select ref from Customer Group By ref having count(*) >= 4) SQL Demo A: If I understand correctly, you can use the Having clause in the query: SELECT Ref, LastName, FirstName from MyTable group by Ref, LastName, FirstName having count(*) >= 4 I have omitted ID, since this is possibly a primary key and probably not required here as the grouping wouldn't work. EDIT: Since the above query will not return your result...You can also use a join... SELECT * FROM Customer c INNER JOIN ( SELECT ref FROM Customer GROUP BY ref HAVING COUNT(*) >= 4 ) t ON c.ref = t.ref A: SELECT * from MyTable Group By ref HAVING COUNT(*) >= 4 A: SELECT Ref, LastName, FirstName from YourTable group by Ref, LastName, FirstName having count(*) >= 4 A: assuming records with the same Reference associate to the same customer then something meaningful can be got from : select ID , max(Ref) as the_Ref , count(Ref) as count_ref from Customer group by Ref having count(Ref) >= 4; If , however , Ref refers to something which occurs independently of the existence of customers ( maybe its used to refer to customer orders ) I'd recommend you consider normalising (http://en.wikipedia.org/wiki/Database_normalization) the data model a little more into two tables instead of one viz : Customer( ID , firstName , LastName ) Customer_Order ( Ref , Customer_ID) whats known as a foreign key relationship can then be set up between these two tables A: As a lover of INNER JOIN, I would prefer the following way. SELECT * FROM Customer C INNER JOIN ( SELECT Ref, LastName, FirstName, COUNT(1) AS NumberOfRef FROM Customer GROUP BY Ref, LastName, FirstName ) T ON T.Ref = C.Ref AND T.LastName = C.LastName AND T.FirstName = C.FirstName AND T.NumberOfRef >= 4 However, after I did it, I started to feel the table Customer to be a bit strange. Even though we normalize it, as @diarmuid suggested, what should we use as the primary key for Customer_Order? Customer(ID , FirstName, LastName ) Customer_Order (Ref, CustomerID)
d16214
I just needed to update to the latest geckoDriver. A: It might be useful to someone else, since I didn't immediately have success from just updating to the latest gecko driver (I was running an older version of selenium stand alone server, 3.6). I am using facebook/php-webdriver. After updating to Firefox 63, the combination of Selenium standalone server v3.8.1 and geckodriver 0.23 stopped the error occurring. A: I am Case I Update my Gecko Driver its Working Fine Now.Always Try New Gecko Driver . https://www.seleniumhq.org/download/.
d16215
It's useful to use an autorelease pool when you are allocating autoreleased objects in a loop, that will reduce the peak of memory consumption of the underlayer autorelease pool. More info on autorelease pool in https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html A: The autorelease pool in main fulfills your applications's responsibility to Cocoa that an autorelease pool always be available. This pool is drained at every cycle of the main event loop. Further, each NSThread you create must have its own autorelease pool. Beyond that, it is simply an issue of estimating how many autoreleased objects you are creating before the main autorelease pool drains. You may also use Instruments to look at the peak memory footprint as further evidence of where an autorelease pool may be used. A: The only time you need to manually manage NSAutoreleasePool objects is when you are running in a thread. If the thread doesn't use much memory then drain at the beginning and drain at the end. Otherwise drain every so many loop iterations. How many iterations between draining the pool depends on the amount of memory you are using in the pool. The more often you drain the more efficient your memory usage is. If you are doing this for something like a particle system with tens of thousands of particles, then you are better off not allocating & releasing memory all the time but instead allocate once and use a ring buffer or something similar.
d16216
You can use merge to return an observable that has two sources that emit independently into the same stream. In this case, you don't even need to use a subject: data$ = http.get(url_1).pipe( switchMap(response1 => { const call1 = of(response1); const call2 = response1.needsRefresh ? http.get(url_2) : EMPTY; return merge(call1, call2); }) )
d16217
someObj.ObservableReturninFunction().subscribe( (obj)=> { conosle.log(obj.message); }, (err)=>{ console.log(err.message); } }); when success; SpyOn(someObj,"ObservableReturninFunction").and.returnValue( Observable.of({message: "something"})); when erro: SpyOn(someObj,"ObservableReturninFunction").and.returnValue( Observable.throw({message: "some-error"})); A: I would create two mocks - one that throws an error: class ObserverThrowServiceStub { getData() { return Observable.throw(new Error('Test error')); } } and one that returns successfully. class ObserverSuccessServiceStub { getData() { return Observable.from(data); } } Then, instead of providing the same mock service to all tests, you provide the failing/successful mock service appropriately depending on the test in question (obviously you'll need to move your module configuration into a configurable method that you call from within each test rather than in the .beforeEach() code. There is a really nice article on testing Angular services using Observables here (which uses exactly this model): http://www.zackarychapple.guru/angular2/2016/11/25/angular2-testing-services.html A: You can use Jasmine Spy to spyOn your mock service class's method which returns an Observable. More detail is here: Jasmine - how to spyOn instance methods A: I would add a public error flag in the stub. Then I can create the stub once in beforeEach() and just update the error flag in each test case to decide which version of getData I want to use. class ObserverServiceStub { public error = false; getData() { if (this.error) { return Observable.throw(new Error('Test error')); } else { return Observable.from(data); } } }
d16218
I talked to AWS, still no fix and no time estimation. A: I sent this to AWS support. They're aware of the issue but have no ETA. Thanks for contacting AWS Premium Support. I understand that you would like to know whether Cognito team is aware of the issue posted here[1]. I checked with Cognito team on our end and YES, they are aware of this issue/bug. Good news is, we already have trouble ticket open with Cognito Team to fix the issue. However, I won't be able to provide an ETA on when this fix will go live as I don't have any visibility into their development/release plans. But, I would like to thank you for your valued contribution in bringing this issue to our attention, I do appreciate it. A: Cognito limits usernames to one user only. However, yes multiple user can share an email.
d16219
Looks like it's only available through BrainTree; confirmed by PayPal customer support.
d16220
It is mainly because of scaling and overflow issues. The documentation for filter2D does not mention(atleast i did not find) whether the overflowed values are clipped or scaled appropriately to the min-max range. This is more important in the case of directional filters, where the co-efficients are positive and negative and after the algebraic The function 'myfilter2D' presented on the link above does not scale to the min-max range which should be the case. If you could post the sample code then it would be easier to help. My suggestion would be to convert the matrices to float(with scaling) and perform algebraic operations because this tends to preserve the resulting values and values are not lost due to overflow or saturation. im2double()->"perform algebraic operations"->im2uchar() for displaying void im2uchar( Mat & src, Mat & dest){ double minVal, maxVal; minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities src.convertTo(dest, CV_8U, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal)); } void im2float( Mat & src, Mat & dest){ double minVal, maxVal; minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities src.convertTo(dest, CV_32F, 1.0/(maxVal - minVal), -minVal * 1.0/(maxVal - minVal)); }
d16221
Solution for this was that I switched from @JacksonXmlTextto @JacksonXmlProperty. I misunderstood how @JacksonXmlTextshould be used. @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JacksonXmlRootElement(localName="product") @JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders", "occasions", "categories" }) public class Product { @JsonProperty("sku") @JacksonXmlProperty(localName="sku") private String sku; @JsonProperty("image") @JacksonXmlProperty(localName="image") private String image; @JsonProperty("brand") @JacksonXmlProperty(localName="brand") private String brand; @JsonProperty("sizeCM") @JacksonXmlProperty(localName="sizeCM") private String sizeCM; @JsonProperty("colors") @JacksonXmlProperty(localName = "colors") @XmlElement(name="colors") private Colors colors; Allowed me to parse the xml without any problem.
d16222
Yes that is correct. Your client is responsible for creating an account and paying the developer fee. You could create the account, but then when your contract is over you would be getting support requests, be responsible for all future updates, and have to renew the account every year. It's better for your client to create the account. SEE EDIT Edit: Found a thread on this discussion - http://www.buzztouch.com/forum/thread.php?tid=10608297F86BD057C74C0F9. The post by MGoBlue on 10/10/11 at 09:04 PM is Apple's stance, which says not to do that. Don't mess with Apple, have your client create an account and invite you to it. There's also a note about this on Apple's Program Enrollment FAQ: I'm a contractor who develops apps for companies other than my own. How do I ensure my client's name is listed as the “Seller” on the App Store? If your client plans to distribute the apps you create for them on the App Store with their legal entity name as the “Seller”, they must enroll in the iOS Developer Program. They can add you as a member of their development team so you can access the resources you need to create the app. While they must be the one who submits the app for review, you can assist them if necessary.
d16223
That's a bug in Visual Studio. You can't do anything about it. It's just that the dudes at Microsoft didn't get Syntax Highligthing and Intellisense right in Razor views. Hopefully they will in some future version of Visual Studio. There's nothing wrong with the code you have shown. It works perfectly fine at runtime. Just the tools you are using aren't capable of realizing that.
d16224
In C++ there's no simple way to do this. This feature is available in higher-level languages like Python, Lisp, Ruby and Perl (usually with some variation of an eval function). However, even in these languages this practice is frowned upon, because it can result in very unreadable code. It's important you ask yourself (and perhaps tell us) why you want to do it? Or do you only want to know if it's possible? If so, it is, though in a hairy way. You can write a C++ source file (generate whatever you want into it, as long as it's valid C++), then compile it and link to your code. All of this can be done automatically, of course, as long as a compiler is available to you in runtime (and you just execute it with system). I know someone who did this for some heavy optimization once. It's not pretty, but can be made to work. A: You can create a function and parse whatever strings you like and create a data structure from it. This is known as a parse tree. Subsequently you can examine your parse tree and generate the necessary dynamic structures to perform the logic therin. The parse tree is subsequently converted into a runtime representation that is executed. All compilers do exactly this. They take your code and they produce machine code based on this. In your particular case you want a language to write code for itself. Normally this is done in the context of a code generator and it is part of a larger build process. If you write a program to parse your language (consider flex and bison for this operation) that generates code you can achieve the results you desire. A: Many scripting languages offer this sort of feature, going all the way back to eval in LISP - but C and C++ don't expose the compiler at runtime. There's nothing in the spec that stops you from creating and executing some arbitrary machine language, like so: char code[] = { 0x2f, 0x3c, 0x17, 0x43 }; // some machine code of some sort typedef void (FuncType*)(); // define a function pointer type FuncType func = (FuncType)code; // take the address of the code func(); // and jump to it! but most environments will crash if you try this, for security reasons. (Many viruses work by convincing ordinary programs to do something like this.) In a normal environment, one thing you could do is create a complete program as text, then invoke the compiler to compile it and invoke the resulting executable. If you want to run code in your own memory space, you could invoke the compiler to build you a DLL (or .so, depending on your platform) and then link in the DLL and jump into it. A: First, I wanted to say, that I never implemented something like that myself and I may be way off, however, did you try CodeDomProvider class in System.CodeDom.Compiler namespace? I have a feeling the classes in System.CodeDom can provide you with the functionality you are looking for. Of course, it will all be .NET code, not any other platform Go here for sample A: Yes, you just have to build a compiler (and possibly a linker) and you're there. Several languages such as Python can be embedded into C/C++ so that may be an option. A: It's kind of sort of possible, but not with just straight C/C++. You'll need some layer underneath such as LLVM. Check out c-repl and ccons A: One way that you could do this is with Boost Python. You wouldn't be using C++ at that point, but it's a good way of allowing the user to use a scripting language to interact with the existing program. I know it's not exactly what you want, but perhaps it might help. A: Sounds like you're trying to create "C++Script", which doesn't exist as far as I know. C++ is a compiled language. This means it always must be compiled to native bytecode before being executed. You could wrap the code as a function, run it through a compiler, then execute the resulting DLL dynamically, but you're not going to get access to anything a compiled DLL wouldn't normally get. You'd be better off trying to do this in Java, JavaScript, VBScript, or .NET, which are at one stage or another interpreted languages. Most of these languages either have an eval or execute function for just that, or can just be included as text. Of course executing blocks of code isn't the safest idea - it will leave you vulnerable to all kinds of data execution attacks. My recommendation would be to create a scripting language that serves the purposes of your application. This would give the user a limited set of instructions for security reasons, and allow you to interact with the existing program much more dynamically than a compiled external block. A: Not easily, because C++ is a compiled language. Several people have pointed round-about ways to make it work - either execute the compiler, or incorporate a compiler or interpreter into your program. If you want to go the interpreter route, you can save yourself a lot of work by using an existing open source project, such as Lua
d16225
If you are creating a DataFrame from a database, you can use read_sql: df = pd.read_sql('SELECT * FROM foo', con) Here con is a connection object, e.g. created using sqlite3 or mysqldb.
d16226
It's unclear to me whether you meant you want to convert this given 2D array to a 2D list, or wether you meant to just create a new list with these values as a one-liner. If you meant the former, you could stream the array and then stream each of its elements, and collect them: List<List<Integer>> currGridList = Arrays.stream(currGrid) .map(g -> Arrays.stream(g).boxed().collect(Collectors.toList())) .collect(Collectors.toList()); If you meant the latter, you could use List.of: List<List<Integer>> currGridList = List.of(List.of(1, 1), List.of(1, 2), List.of(2, 2));
d16227
You can open an incognito tab; it will have the requested behavior. I don't think you can clear session data, and simply clearing history does not prevent reopening.
d16228
Use css to set cursor of body as "Wait" when button is clicked. And when page is processed, set them to "Default". Wait cursor over entire html page A: Have you already checked with some tool (like fiddler) whether loading of the page is really done? If youre not using CSS for changing the cursor, the problem might be that some request is still running: this would then be the point for further investigation.
d16229
The answer from github at (https://github.com/python-pillow/Pillow/issues/4464) was to use profile.to_bytes(): img.save(OUT_IMG_PATH, icc_profile=profile.tobytes())
d16230
You should remove only the libraries you don't use in your project. Two weeks ago my ipa file was at almost 200 MB, then I deleted all the Swift libraries that was unnecessary for the project, and now I create smaller ipa files than the previous one (80 MB). So you need to check your application, see if you have unnecessary libraries and delete it, this way you will reduce the ipa size. A: I would suggest looking into the 'Linker', which you will find in your iOS build options within Visual Studio A brief overview: * *Don't Link - all assemblies left untouched (largest ipa size) *Link SDK assemblies only - reduces size of SDK (Xamarin.iOS) assemblies by removing everything that your application doesn't use *Link all assemblies - reduces size of all assemblies by removing everything that your application doesn't use (smallest ipasize) Note that 'link all assemblies' can cause issues as the linker can't always determine what is used and can therefore remove code from an assembly that is actually required (think web services, reflection, serialisation). In such cases you can set a manual mtouch argument to prevent a specific assembly (or assemblies) from having being touched by the linker as below: --linkskip=NameOfAssemblyToSkipWithoutFileExtension or --linkskip=NameOfFirstAssembly --linkskip=NameOfSecondAssembly A real use case I've come across where the above is necessary is when using Entity Framework with Xamarin.iOS, as the linker removes code which is then called using reflection which causes the app to crash. The full documentation for the Linker is available here: https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/linker?tabs=vsmac
d16231
Try this: function renderLink( val ){ return '<a href="javascript:void(0);" onclick="someMethod(); return false;">' + val + '</a>'; A: You can attach click event for example with dblclick listener: listeners: { dblclick : { fn: function() { var selectedRecord = Ext.getCmp('ObjectsGrid').getSelectionModel().getSelection()[0]; console.log(selectedRecord); }, element: 'body' } } All columns values can be seen by console.log(selectedRecord):
d16232
Fixed the first problem by doing this in the theme.inc if($vars['fields'][$field] == 'content') { $field_output = "<form action=\"download.php\" method=\"POST\"> <input type=\"submit\" name=\"download\" value=\"Download\"> <input type=\"hidden\" name=\"did\" value=\"$num+1\"> </form>"; } and download.php needs to have something like this <?php if(isset($_POST['id'])) { $table = 'tablename'; $download_id = $_POST['id']; $q="SELECT * FROM {$table} where id = $download_id"; $link = mysqli_connect(...); $res = mysqli_query($link,$q); if($res) { $row = mysqli_fetch_assoc($res); $id = $row['id']; $name = $row['name']; $status = $row['status']; $content = $row['content']; header("Content-type: required type"); header("Content-Disposition: attachment; filename=$name"); echo $content; exit; } else{ echo "Cannot download";} } ?> I am still unable to fix the second problem.
d16233
Coming in v1.63 are file links in notebooks, see release note: file links in notebooks. Markdown inside notebooks can now link to other files in the current workspace Links the start with / are resolved relative to the workspace root. Links that start with ./ or just start with a filename are resolved relative to the current notebook. [link text](./cat.gif) Bare http(s) links notebooks In addition, markdown text that looks like an http and https is now automatically turned into a link:
d16234
In your slot, you should be able to call the function sender(), which would return a pointer to the object that emitted the signal (if any did... remember, you can call slots just like a function as well). This is the quick, relatively easy, and sloppy way. However, it breaks encapsulation. A slightly better way would be to provide a numbering mechanism for the buttons, and use a QSignalMapper to map the individual buttons into one signal that contains an int for the button that was clicked. This is in C++ (which I'm more familiar with): QSignalMapper *mapper = new QSignalMapper( this ); connect( mapper, SIGNAL( mapped( int ) ), SLOT( MyFancyFunction( int ) ) ); // Do this for each button: mapper->connect( button1, SIGNAL( clicked() ), SLOT( map() ) ); mapper->setMapping( button1, FIRST_TOOL ) Then: void MyFancyFunction( int option ) { switch ( option ) { case FIRST_TOOL: // do whatever... } }
d16235
Finally after a lot of search on google(approx 3 days continuously) about R programming and concept and techniques to resolve my above issue, now i am able to give my answer itself. dates= c(classInstance$getAllDates(fromDate,toDate)); from here Case : 1 Solution for(i in 1 : dates$length) { #Fetching one by one date object using for each loop in R index = .jevalArray(dates)[[i]] # Holding an individual array into variable print(index$toString()) # Now printing using Java toString() method only. } Note** : but for "list" type this solution also got stuck. It worked for me when typeof was "S4" Case : 2 Solution I found a working solution for this as well arraysObject = .jnew("java/util/Arrays") #Just taken a reference of an object of java Arrays classes for (i in 1:length(indexes[[1]])){ print(arraysObject$toString(indexes[[1]][i])) #calling Arrays.toString() method of java into R programming } OR arraysObject = .jnew("java/util/Arrays") print(arraysObject$toString(indexes[[1]]))
d16236
I talked with Atlassian support and they helped me work through the issue. I had setup the remote agent as a windows service which was causing the problems. I removed the service and started the remote agent via the BambooAgent.bat script. Mine was located at %InstallDirectory%/bin/BambooAgent.bat
d16237
You cannot rely on page_source to get the current state of the page. The Python docs do not point it out but if you look at the Java docs of Selenium for getPageSource you'll see: If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page. What you can do is ask the browser to serialize the DOM. This will produce HTML that represents the DOM at the time you make the call: driver.execute_script("return document.documentElement.outerHTML") A: I had similar problem. I used time.sleep(5) after get.page_source so that the contents can be read. A: Are you aware that the page content loads/unloads as you scroll down? The page is unloading previous sections as you scroll down. For instance, scroll all the way down to the bottom of the page and start scrolling back up. You will see that it's loading previous sections. To prove this... when you first load the page, the first article title is, "The Short List: Weird Al, the Heartless Bastards, Chastity Belt, more". Scroll to the bottom of the page, pull the HTML source (manually), and search for that title. It's not there. So, I don't know what you are trying to do but if all you want to do is to load the last section you can navigate directly to the last section using the URL, http://www.citypaper.com/music/music-boxes/ The different sections are: Main article http://www.citypaper.com/music/music-features/ http://www.citypaper.com/music/listening-party/ http://www.citypaper.com/music/music-boxes/ Why are you wanting the HTML source of the page anyway? What are you trying to accomplish? One of the main points of using Selenium is so you can find HTML tags using locators so you don't have to parse source, etc.
d16238
It is working for me. Try this attribute: [Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")] Or you can use regular expression: [RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")] public int bmi_number { get; set; }
d16239
Actually, it looks like a bug in your libc implementation. File I/O streams are usually a libc abstraction over the file descriptor based binary I/O implemented by the OS kernel. So any strange behaviour shall be attributed to your specific libc quirks. Since you're apparently using Windows, that may be the source of your problems. What is the compiler you're using? There is no such problem with GCC 4.6.1 and glibc-2.13 on Ubuntu 11.10.
d16240
Documentation says: Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms. You may want to use $.keydown.
d16241
int n = arrInt.length; int temp = 0; for (int i = 0; i < n; i++) { for (int v = 1; v < (n - i); v++) { if (arrInt[v - 1] < arrInt[v]) { temp = arrInt[v - 1]; arrInt[v - 1] = arrInt[v]; arrInt[v] = temp; } } } Try this. Update - Replaced j with v A: The problem is the inner loop should be from 1 to n. Instead your inner loop stops early. Also you are testing i in the inner loop condition, but you should be testing v. Try this: //bubble sort for(int i=0;i<size;i++) { for(int v=1;v<size;v++) { if(arrInt[v-1]<arrInt[v]) { temp = arrInt[v-1]; arrInt[v-1]=arrInt[v]; arrInt[v]=temp; } } } A: Bubble Sort Method for Descending Order public static void BubbleSort( int[ ] arr){ int records=arr.length-1; boolean notSorted= true; // first pass while (notSorted) { notSorted= false; //set flag to false awaiting a possible swap for( int count=0; count < records; count++ ) { if ( arr[count] < arr[count+1] ) { // change to > for ascending sort arr[count]=arr[count]+arr[count+1]; arr[count+1]=arr[count]-arr[count+1]; arr[count]=arr[count]-arr[count+1]; notSorted= true; //Need to further check } } } } In this method when array is sorted then it does not check further. A: Usually I implement Bubble sort like this, for(int i=0;i<size-1;i++) { for(int v=0;v<(size-1-i);v++){ if(arrInt[v]<arrInt[v+1]) { temp = arrInt[v]; arrInt[v]=arrInt[v+1]; arrInt[v+1]=temp; } } } You know what is the problem is, in your code??? Look at the inner loop, you are initializing v but checking and changing i. Must be a copy paste error.. :P Hope it helped... A: Here you go: int x = 0; for(int i = 0; i < array.length; i++) for(int j = 0; j < array.length; j++) if(array[i] > array[j + 1]) x = array[j + 1]; array[j + 1]= array[i]; array[i] = x; x here is a temporary variable you only need for this operation. A: here's a complete running program for you. Hope that keeps you motivated package test; public class BubbleSort { private static int[] arr = new int[] { 1, 45, 65, 89, -98, 2, 75 }; public static void sortBubbleWay() { int size = arr.length-1; int temp = 0; // helps while swapping for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i; j++) { if (arr[j] < arr[j+1]) { /* For decreasing order use < */ temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } private static void showShortedArray() { for (int elt : arr) { System.out.println(elt); } } public static void main(String args[]) { sortBubbleWay(); showShortedArray(); } }//end of class
d16242
I don't think it is a good idea to push to the test server. Since shared repository is usually a bare repository. It would be best to keep the shared repository somewhere on a third server. Everyone can push to this server, and you can maintain several branches there if you wish. The test server pulls the changes before running the test. Or for a more complete test - it would clone the entire repository fresh each time before test. A: There are really plenty of approaches to this problem, you should consider read more about "Auto deployment", "GIT + deploy" etc. Personally I'm using special script to export all the files between specific tags in GIT repository and upload them directly on the server. A: Take a look on the git workflow(s) modal. https://www.atlassian.com/git/tutorials/comparing-workflows/ http://nvie.com/posts/a-successful-git-branching-model/ You simply have to figure out which workflow suits you the best and you can grab the most suitable one. If you choose to use nvie gitworkflow you can customize it to your own needs by modifing teh scripts
d16243
Looks like the generated entity misses the return type hints… probably a bug in Sonata Easy Extends bundle. You can add type hint by finding and modifying Application\Sonata\DashboardBundle\Entity\Dashboard
d16244
No, there is no workaround as such, unless you decide to write your own library. On the github page of ng-csv : https://github.com/asafdav/ng-csv It is clearly stated that Safari is not supported and only IE 10+ are supported.
d16245
tl;tr What was the reasoning to not implement private constants? This is a good question. Did they really consider this? I don't know. * *When searching through the PHP internals mailing list, i found nothing about this topic. Unless a internal's member speaks up, we'll never know. With regard to the history of the language - a bit 1:1 C method wrapping, some bits from Perl (regexp), some bits Java (oop) - it's possible that this idea popped up, while looking for new language features. I would relate the concept of a "private constant" to VisualBasic or Java. I doubt that VB has a big or any influence on PHP. VB allows the definition of "private constants" in "Modules" - it's the default access scope. Visual Basic doesn't allow constants in Interfaces and Namespaces (but PHP does). PHP might include some OOP concepts from Java, but there is one big difference: constants are variables in Java. Their access modifiers / visibility levels are: "public, private, final and static". A private constant declaration looks like this: "private static final String MYCONST = "My Constant"; It's OOP - end of story. PHP constant access feels more hackish compared to that - BUT it's more simple and you still have the workaround at hand. *The first comment in the PHP manual for Class Constants is: It may seem obvious, but class constants are always publicly visible. They cannot be made private or protected. I do not see it state that in the docs anywhere. Why is this obvious? "Why is a class constant public by default and not private?" Maybe, it's a missing language feature, because not all class members can be hidden properly. And he is right, when you come from Java or VB to PHP this question pops up. *Let's take a look at the PHP spec. The current state of implementation in PHP is: class constants are always public and static. So, again and again, thumbs up for Facebook for writing such detailed document: the author considered different visibility or access-control levels. Let's take a look at interface, class, constant and visibility: * *How does the concept "const" differ from "private static"? The static variable can be changed, the constant cannot be changed. You cannot assign the runtime value of a function to a const (const A = sprintf('foo %s', 'bar');), but to a private static var. *An interface might have constants - they cannot be overridden. *A class might have a constant - which might be overridden by a inheriting class/interface. *There is also an OOP pattern called "constant interface pattern" - it describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants. An interface is provided so you can describe a set of functions and then hide the final implementation of the functions in an implementing class. This allows you to change the implementation of the functions, without changing how you use it. Interfaces exist to expose an API. And by defining constants in an interface and implementing the interface by a class, the constants become part of the API. In fact, you are leaking implementations details into the API. That's why some consider this being an anti-pattern, among them Joshua Bloch (Java). Now, let's try to combine some concepts and see if they fit. Let's pretend we try to avoid the critique from above, then you need to introduce a syntax, which allows qualified access to the constant, but hides the constant in the API. You could come up with "Access control" via visibility levels: "public, private, protected, friend, foe". The goal is to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. It is all about hiding implementation details, right? What about "private constants" in "interfaces"? That would actually solve the critique from above, right? But the combination of interface with "private", doesn't make sense. The concepts are contrary. That's why interface do not allow "private" access/visibility-levels. And a "private" constant in an "interface" would be mutually exclusive, too. What about "private constants" in "classes"? class a { /*private*/ const k = 'Class private constant k from a'; } class b extends a { const k = 'Overridden private constant a::k with Class constant k from b'; const k_a = parent::k; // fatal error: self-referencing constant #const k_selfref = self::k . ' + ' . self::k_selfref; // fatal error: "static::" is not allowed in compile-time constants #const k_staticref = static::k; } // direct static access would no longer work, if private // you need an instance of the parent class or an inheriting class instance echo a::k; echo b::k; echo b::k_a; $obj_b = new b; echo $obj_b::k; echo $obj_b::k_a; Is there a benefit? * *The private constant in the class wouldn't be exposed in the API. This is good OOP. *The access to the parent constant from outside would be a class and/or inheritance access. echo a::k, which now works - could respond with "Fatal error: Trying to access a private constant without a class instance or inheritance.". *(This might still work solely at compile-time, if there is no run-time value assignment to a const. But i'm not sure about this one.) Are there caveats? * *We would lose direct static access to constants. *Requiring that an instance of a class is created, just to access constants, is a waste of resources. Direct static access saves resources and is simple. If we introduce private, that's lost and the access would be bound to the instance. *A "private const" is implicitly a "private static const". The access operator is still "::". A possible follow-up change would be the switch to implicitly non-static constants. That's a BC break. If you switch the default behavior to non-static, the access operator changes from "::" to "->". This establishes a proper OOP object access to constants, which is comparable to Java's concept of "constants as variables with access level". This would work a bit like this: http://3v4l.org/UgEEm. The access operator changes to static, when the constant is declared as "public static const", right? Is the benefit good enough to implement it? I don't know. It's up for discussion. I like both: the const static access, because it's dead simple and the concept of "constants as variables" and proper access levels. After that's implemented, in order to save resources and keep going fast, everyone starts to (re-)declare "public static const", to drop the instance requirement and violate OOP ;) And btw: i found an HHVM overflow, while experimenting with code of this answer. A: Why doesn't PHP permit private constants? In PHP constants are part of the interface and the interface is public, always (that's what an interface is for). See as well PHP Interfaces. I'm pretty sure this is the reason design-wise. Regarding the comment under your question that someone wants to reduce the visibility of constants to change them later, I'd say this sounds more like a variable than a constant which does not change it's value. It's constant.
d16246
Not exactly sure what you're trying to acheive, but something like this should at least resolve the postgres error you're seeing: LesleyGrade.where('STC_TERM_GPA IN (SELECT STC_TERM_GPA FROM (SELECT DISTINCT STC_TERM_GPA, TERM, last, first FROM lesley_grades order by first, term ASC) AS results )' ) There's a few levels there: The deepest level says "get me all rows which have a distinct / unique combination of the columns STC_TERM_GPA, TERM, last, and first The next layer says "Of those results, get rid of the other columns and just give me the STC_TERM_GPA column. The outer-most layer says "Give me all rows where the STC_TERM_GPA value is in the set of STC_TERM_GPA we just selected. EDIT: it sounds like you don't what a WHERE clause at all. You want something like: LesleyGrade.select('STC_TERM_GPA, TERM, last, first').group('STC_TERM_GPA').order('first, term ASC') That's untested. But to select multiple columns, but restrict to distinct values of one column, you'll want to use SQL's GROUP BY clause, which is available in Rails' ActiveRecord through the group method. BTW, select distinct STC_TERM_GPA, TERM, last, first from lesley_grades order by first, term ASC will give you results which are unique on the COMBINATION of STC_TERM_GPA, TERM, last, first, not on JUST STC_TERM_GPA. I've assumed that while you want all those columns, you only want DISTINCT on the STC_TERM_GPA.
d16247
Looking at the provided OPL examples (e.g. BasketballScheduling\acc.mod) I think that the 'then' part defining the constraint should have '==' rather than '='. It is not an assignment, but declaring that the two must be equal. A: using CP; tuple TimeSlot { key int day; key int slotNo; } {TimeSlot} TimeSlots = {<1,1>,<2,2>};; {int} mondays = {t.slotNo|t in TimeSlots:t.day==1}; int monMax = max(t in mondays) t; range monRange = 0..monMax; range allEmployees = 1..10; dvar int monStart[allEmployees] in monRange; //Start of monday shift dvar int monEnd[allEmployees] in monRange; //End of monday shift dvar int monAtWork[allEmployees] in 0..1; //Binary //minimize ... subject to{ forall(t in allEmployees) (monStart[t] > 0 && monEnd[t]>0) => monAtWork[t] == 1; //Get error here } works fine
d16248
I decided to answer my question, hope it can help someone else. For OAuth 2 I found this solution: http://code.google.com/p/gtm-oauth2/ There are sample projects for mac and iOS.
d16249
If you do not have an interop library, you can use dynamic to access it by ProgID: dynamic updateSearcher = Activator.CreateInstance(Type.GetTypeFromProgID("Microsoft.Update.Searcher")); var count = updateSearcher.GetTotalHistoryCount(); var history = updateSearcher.QueryHistory(0, count); for (int i = 0; i < count; ++i) Console.WriteLine(history[i].Title); The interface is listed as being present in WUAPI.idl on the MSDN page, so another option would be to compile it with midl and reference the generated tlb (Add Reference > COM). @HansPassant points out that the tlb is preregistered as "WUAPI 2.0 Type Library", which eliminates the need to manually compile the idl.
d16250
Window in Spark streaming is characterized by windowDuration and slideDuration (optional). So, it is a time window. But you can consider using Apache Flink. It supports both count windows and time windows. But in comparison to Spark, Flink has another streaming ideology. It process incoming events as they arrive (Spark processes events in micro-batches). As a result, Flink may have some restrictions. Give it a try if it suits your needs.
d16251
Monaco-vue, to my knowledge, simply enables you to easily render the Monaco Editor into your Vue app by way of a Vue component. Vue language support within the editor requires that you hook up the editor to a Language Server Protocol (LSP)-compliant service. I believe Vetur is an LSP implementation - though I have not yet attempted to connect my Monaco editor to it as of yet. The Vetur LSP project seems to have decent documentation: https://github.com/vuejs/vetur/tree/master/server For an overview of integrating LSP into a Monaco editor, see this: https://typefox.io/teaching-the-language-server-protocol-to-microsofts-monaco-editor ...and a link to a module that helps with this (also from Typefox): https://github.com/TypeFox/monaco-languageclient Beware that, as of my last visit to that project, it does not work with the very latest version of Monaco - though I haven't lost any features of note by staying back at version 14.xx. Also, I couldn't get Monaco Vue to work for me. It isn't hard to embed via the mounted lifecycle hook that renders the editor to the DOM on the mounted hook, like this: mounted: function () { this.editor = monaco.editor.create(document.getElementById('container'), { value: 'this is code', automaticLayout: true }) },
d16252
This is a very common problem when dealing with data that is loaded asynchronously. Here's how I would suggest debugging this to understand your problem: * *Remove the offending code so that you can observe what's happening. *Add console.log(quotes) in your component. You will see that it logs [] and then again with your array. *Next add console.log(quotes[quoteIndex]). Notice that it logs undefined and then an object. Consider that while the value is undefined, you cannot treat it like an object and attempt to access properties on it. *Add a check to make sure the value is an object before using it: // Nullsafe operator quotes[quoteIndex]?.quote // Or ternary quotes[quoteIndex] ? quotes[quoteIndex].quote : null Here is a simulated example: const async_quotes = [ { "id":0, "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.", "author": "Thomas Edison" }, { "id":1, "quote": "You can observe a lot just by watching.", "author": "Yogi Berra" } ] const {useState, useEffect} = React; const index = 1; const Example = () => { const [quotes, setQuotes] = useState([]); useEffect(() => { setTimeout(() => { setQuotes(async_quotes); }, 3000); }, []); console.log("quotes:", quotes); console.log("single quote:", quotes[index]); return <div>{quotes[index] ? quotes[index].quote : ''}</div> } ReactDOM.render(<Example />, document.getElementById('root')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
d16253
The property "createdAt" is not included in the optimistic reply. __typename: 'Comment', postedBy: ownProps.currentUser, content: commentContent, Should be: __typename: 'Comment', postedBy: ownProps.currentUser, createdAt: Date(), content: commentContent, A missing field in an optimistic reply will silently fail to return anything to any queries that call that data.
d16254
simply adding: allprojects { buildscript{ repositories{ maven { url "https://foo.com" } } } repositories { maven { url "https://foo.com" } } } is the solution
d16255
is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? The closest thing I can think of is std::stable_partition: std::vector<int> v; // ... auto it = std::stable_partition(v.begin(), v.end(), pick_the_good_elements); std::vector<int> w(std::make_move_iter(it), std::make_move_iter(v.end())); v.erase(it, v.end()); Now v will contain the "good" elements, and w will contain the "bad" elements. A: Could this be the worst named function in the STL? A bit of background information: in the standard library (or the original STL), there are three concepts, the containers, the iterators into those containers and algorithms that are applied to the iterators. Iterators serve as a cursor and accessor into the elements of a range but do not have a reference to the container (as mentioned before, there might not even be an underlying container). This separation has the nice feature that you can apply algorithms to ranges of elements that do not belong to a container (consider iterator adaptors like std::istream_iterator or std::ostream_iterator) or that, belonging to a container do not consider all elements (std::sort( v.begin(), v.begin()+v.size()/2 ) to short the first half of the container). The negative side is that, because the algorithm (and the iterator) don't really know of the container, they cannot really modify it, they can only modify the stored elements (which is what they can access). Mutating algorithms, like std::remove or std::remove_if work on this premise: they overwrite elements that don't match the condition effectively removing them from the container, but they do not modify the container, only the contained values, that is up to the caller in a second step of the erase-remove idiom: v.erase( std::remove_if( v.begin(), v.end(), pred ), v.end() ); Further more, for mutating algorithms (those that perform changes), like std::remove there is a non-mutating version named by adding copy to the name: std::remove_copy_if. None of the XXXcopyYYY algorithms are considered to change the input sequence (although they can if you use aliasing iterators). While this is really no excuse for the naming of std::remove_copy_if, I hope that it helps understanding what an algorithm does given its name: remove_if will modify contents of the range and yield a range for which all elements that match the predicate have been removed (the returned range is that formed by the first argument to the algorithm to the returned iterator). std::remove_copy_if does the same, but rather than modifying the underlying sequence, it creates a copy of the sequence in which those elements matching the predicate have been removed. That is, all *copy* algorithms are equivalent to copy and then apply the original algorithm (note that the equivalence is logical, std::remove_copy_if only requires an OutputIterator, which means that it could not possibly copy and then walk the copied range applying std::remove_if. The same line of reasoning can be applied to other mutating algorithms: reverse reverses the values (remember, iterators don't access the container) in the range, reverse_copy copies the elements in the range to separate range in the reverse order. If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? There is no such algorithm in the STL, but it could be easily implementable: template <typename FIterator, typename OIterator, typename Pred> FIterator splice_if( FIterator first, FIterator last, OIterator out, Pred p ) { FIterator result = first; for ( ; first != last; ++first ) { if ( p( *first ) ) { *result++ = *first; } else { *out++ = *first; } } return result; } A: If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? Not really. The idea is that the modifying algorithms are allowed to "move" (not in the C++ sense of the word) elements in a container around but cannot change the length of the container. So the remove algorithms could be called prepare_for_removal. By the way, C++11 provides std::copy_if, which allows you to copy selected elements from one container to another without playing funny logic games with remove_copy_if. A: You are right, that is what it does... std::remove_copy_if copies the vector, removing anything that matches the pred. std::remove_if ... removes on condition (or rather, shuffles things around). A: I agree that remove is not the best name for this family of functions. But as Luc said, there's a reason for it working the way it does, and the GoTW item that he mentions explains how it works. remove_if works exactly the same way as remove - which is what you would expect. You might also want to read this Wikibooks article.
d16256
You can use callback to get response from asynchronous functions. var http = require('http'); var stockPrice = 10; function GetStockPrice(ticker, callback){ var options = { host: 'dev.markitondemand.com', port: 80, path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker, method: 'GET' }; http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); res.setEncoding('utf8'); var stockPrice=''; res.on('data', function (chunk) { stockPrice = stockPrice + chunk; }); res.on('end', function(){ return callback(JSON.parse(stockPrice)); }); }); }; module.exports = GetStockPrice; And GetStockPrice('AMZN', function(data){ console.log(data); }); Pardon me, if there are any typos.
d16257
You didn't provide some details but do you want something like that; var query = from ts in db.TimeSheets join tsd in db.TimesheetDatas on ts.Guid equals tsd.TimesheetGuid where ts.StartDate > thisWeekStart && ts.StartDate < thisWeekEnd select tsd.hour
d16258
I removed the priority inside the tag and make it run by default instead, I just found out that the priority by default (alphabetical) is not based on the tag name of the feature file (@faturefile) that is being called But, it is based from the filename of the feature file (teststep.feature)
d16259
I am not familiar with react however with Angular you would have to run through the same process on the server as you would to run the app locally but with the server variables in place of the local variables. For example on angular I have to compile and run my front/back ends and ensure my database is also live for it to run at all otherwise nothing would work on the server . Check what configs need changing to process the change from local to dev Hopefully that is at least a little bit helpful, the below article should be useful to you. https://medium.com/@baphemot/understanding-react-deployment-5a717d4378fd
d16260
did you call DataTable dispose after setting Session Var? Because if you do this, solution is like this: System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();
d16261
You could have a look at hg-git GitHub plugin: adding the ability to push to and pull from a Git server repository from Mercurial. This means you can collaborate on Git based projects from Mercurial, or use a Git server as a collaboration point for a team with developers using both Git and Mercurial. Note: I haven't tested that tool with the latest versions of Mercurial. A: You add entries to the [paths] section of your local clone's .hg/hgrc file. Here's an example of a section that would go in the .hg/hgrc file: [paths] remote1 = http://path/to/remote1 remote2 = http://path/to/remote2 You can then use commands like hg push remote1 to send changesets to that repo. If you want that remote repo to update is working directory you'd need to put a changegroup hook in place at that remote location that does an update. That would look something like: [hooks] changegroup = hg update 2>&1 > /dev/null && path/to/script/restart-server.sh Not everyone is a big fan of having remote repos automatically update their working directories on push, and it's certainly not the default. A: if you want to add default path, you have to work with default in your ~project/.hg/hgrc file. As Follows: [paths] default = https://path/to/your/repo Good Luck. A: If you're on Unix and you have Git installed, you can use this bash function to readily add a path to the remotes without a text editor: add-hg-path() { git config -f $(hg root)/.hg/hgrc --add paths.$1 $2 awk '{$1=$1}1' $(hg root)/.hg/hgrc > /tmp/hgrc.tmp mv /tmp/hgrc.tmp $(hg root)/.hg/hgrc } Then invoke it with: $ add-hg-path remote1 https://path.to/remote1 If someone would like to build a Powershell equivalent, I'd like to include that as well. Other potentials improvements include error checking on the parameters and factoring out the call to $(hg root).
d16262
In order to get the quantity for order_items for a particular related order write the following code - >>> from django.db.models import Sum >>> order.order_items_set.aggregate(quantity=Sum('quantity')) It will return you a dictionary like - {'quantity': 3} Refer to here for more information about aggregations In order to show it in your Admin for Order model - class OrderAdmin(admin.ModelAdmin): list_display = ('id', 'user_id', 'status', 'created_at', 'get_quantity') class Meta: model = Order def get_quantity(self, obj): result = obj.order_items_set.aggregate(quantity=Sum('quantity')) return result.get('quantity',0) get_quantity.short_description = 'Quantity' admin.site.register(Order, OrderAdmin) Refer to here to know more about django-admin customizations.
d16263
Recommended ... different approach. Locate your stored procedure on your SSRS Reports SQL Server. Debug this stored procedure with SSMS. Once that is working, you will have no issue getting the data into SSRS.
d16264
Don't try and import the internal class. That's causing your compiler error // import com.example.Foo.Bar.Baz; import java.io.Serializable; public class Foo implements Serializable { public final Bar bar; public Foo(Bar bar) { this.bar = bar == null ? new Bar(Bar.Baz.ONE) : bar; } public static class Bar implements Serializable { public enum Baz { ONE } public final Baz baz; public Bar(Baz baz) { this.baz = baz; } } } A: in java7 and java8 compiling depended on order of imports. your code works in java >= 9. see https://bugs.openjdk.java.net/browse/JDK-8066856 and https://bugs.openjdk.java.net/browse/JDK-7101822 to make it compile in java7 and java8 just reorder the imports
d16265
The addGroup method has the wrong type hint: It should be: /** * Add groups * * @param \Blogger\BlogBundle\Entity\Group $groups * @return User */ public function addGroup(\Blogger\BlogBundle\Entity\Group $groups) { $this->groups[] = $groups; return $this; } Notice \Blogger\BlogBundle\Entity\Group instead of \Blogger\BlogBundle\Entity\groups.
d16266
As the error said that your loader can't handle this syntax, maybe it is old, and you need to update it, but as a temporary solution you can convert this syntax to ternary operator syntax and it should work. const initialState = selectedActivity ? selectedActivity : emptyActivity;
d16267
In Groovy you can set default values for optional closure parameters, like so: static at = { year=null, geo=null -> ... } I think that'll clear ya up. :) update Ok, I know you don't need it anymore, but I made this for my own use when I was learning Groovy, and I thought someone might find it helpful: * *{ -> ... } a closure with exactly zero parameters. Groovy will blow up if you call it with params. *{ ... } a closure with one optional parameter, named "it" *{ foo -> ... } a closure with one parameter named "foo" (foo can be any type) *{ foo, bar, baz -> ... } a closure with 3 parameters named "foo", "bar" and "baz" *{ String foo -> ... } You can specify the type of the parameters if you like
d16268
So, 3 weeks later, I finally found a way to fix this. I ended up completely uninstalling/deleting Python on my secondary machine and reinstalling everything (along with reinstalling all modules, and confirming via pip list) and now it works (no more SSL error). For what it's worth, and I can't be sure this is what was causing the issue in the first place, but previously, I was running Python 3.6.1 on the working machine and python 3.6.2 on the other, non-working machine. When I reinstalled everything, I reinstalled Python 3.6.1 (to match the working machine) and it worked on both.
d16269
Try this code: #dummy data with factors df <- data.frame(flight_time=c("11:42:00","19:37:06","18:11:17")) #add Seconds column df$Seconds <- sapply(as.character(df$flight_time), function(i) sum(as.numeric(unlist(strsplit(i,":"))) * c(60^2,60,1))) #result df # flight_time Seconds # 1 11:42:00 42120 # 2 19:37:06 70626 # 3 18:11:17 65477
d16270
Remove the min-height: 100%; from the .tbl-searchpanel label rule Stack snippet html, body { height: 100%; margin: 0; } .tbl-main { height: 100%; box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3); display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ display: -moz-box; /* OLD - Firefox 19- (doesn't work very well) */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: -webkit-flex; /* NEW - Chrome */ display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */ -webkit-box-direction: normal; -moz-box-direction: normal; -ms-flex-direction: column; -webkit-flex-direction: column; flex-direction: column; } .tbl-searchpanel { min-height: 15px; background: yellow; } .tbl-container { min-height: 50px; background-color: blue; -webkit-box-flex: 1; -moz-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; } .tbl-searchpanel input { display: none; visibility: hidden; } .tbl-searchpanel label { display: block; padding: 0.5em; text-align: center; border-bottom: 1px solid #CCC; color: #666; background-color: lightcoral; /* min-height: 100%; removed */ } .tbl-searchpanel label:hover { color: #000; } .tbl-searchpanel label::before { font-family: Consolas, monaco, monospace; font-weight: bold; font-size: 15px; content: "+"; vertical-align: central; display: inline-block; width: 20px; height: 20px; margin-right: 3px; background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%); } #expand { width: 100%; height: 250px; overflow: hidden; transition: height 0.5s; /*background: url(http://placekitten.com/g/600/300);*/ /*color: #FFF;*/ background-color: red; display: none; } #toggle:checked~#expand { display: block; } #toggle:checked~label::before { content: "-"; } <div class="tbl-main"> <div class="tbl-searchpanel"> <input id="toggle" type="checkbox" /> <label for="toggle"></label> <div id="expand"></div> </div> <div class="tbl-container"> </div> </div>
d16271
elem=driver.find_element_by_id("on_off_on") driver.execute_script("arguments[0].click();",elem) Try targeting the input id instead. A: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC elem=WebDriverWait(driver,5000).until(EC.visibility_of_element_located( (By.XPATH, "//input[@id='on_off_on']"))) driver.execute_script("arguments[0].scrollIntoView();",elem) element.click() Try using webdriver wait
d16272
Why would you need to copy and paste the entire function? Wouldn't you just use the same methods as in the SO thread you linked. ie just have a section of the code at the top specifying that x, y and z are equal to data df <- data.frame(x = c(1:5), y = c(4:8), z = c(5:1)) my_fxn <- function(x, y, z, data) { if(missing(data)){ x = x; y = y; z = z # unnecessary but just to be explicit } else { x = data$x y = data$y z = data$z } aaa <- x ^ 2 + 5 bbb <- (y * log(y) + 5) ^ 7 ccc <- z + aaa ddd <- mean(c(x, y, z)) eee <- aaa + bbb + ccc + ddd paste(eee, "my_fxn", eee, sep = "_") } my_fxn(df$x, df$y, df$z) [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" "240475836.750078_my_fxn_240475836.750078" "776392986.326892_my_fxn_776392986.326892" [5] "2219080769.50416_my_fxn_2219080769.50416" > my_fxn(x, y, z, data = df) [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" "240475836.750078_my_fxn_240475836.750078" "776392986.326892_my_fxn_776392986.326892" [5] "2219080769.50416_my_fxn_2219080769.50416" So on your update you are attempting to to assign aaa = as.numeric(data$aaa) bbb = as.numeric(data$bbb) ccc = as.character(data$ccc) Where data$aaa would be data$x and data$bbb would be data$y. The issue here is that there is no reason why the x column would be associated with aaa which is why in my previous answer I used x, y, z. in your case, the function will look for df$aaa which doesn't presently exist. In order to generalize this the way you want so that you do not need to know the column names and hard code them into the function, You might try my_fxn <- function (aaa, bbb, ccc, data) { if (!missing(data)) { aaa = as.numeric(data[,1]) bbb = as.numeric(data[,2]) ccc = as.character(data[,3]) } print(aaa[1]) } my_fxn(x, y, z, df) A: Easiest fix would be passing the column names as character to the function and modify the function so it gets the values from the dataframe columns. df <- data.frame(x = c(1:5), y = c(4:8), z = c(5:1)) my_fxn <- function(xx, yy, zz, data) { if(missing(data)){ x = xx; y = yy; z = zz } else { x <- data[[xx]] y <- data[[yy]] z <- data[[zz]] } aaa <- x ^ 2 + 5 bbb <- (y * log(y) + 5) ^ 7 ccc <- z + aaa ddd <- mean(c(x, y, z)) eee <- aaa + bbb + ccc + ddd paste(eee, "my_fxn", eee, sep = "_") } my_fxn("x", "y", "z", data = df) # [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" # [3] "240475836.750078_my_fxn_240475836.750078" "776392986.326892_my_fxn_776392986.326892" # [5] "2219080769.50416_my_fxn_2219080769.50416"
d16273
Try this $this->Form->create('User', array('type' => 'file', 'class' => 'classname', 'url'=>array('controller'=>'Users','action'=>'newUser') ) ); You don't need to create a separate array for the all options. Docs: Form Options A: <?php echo $this->Form->create('User', array('url' => array('controller' => 'Users','action' =>'newUser'),'class'=>'classname','enctype'=>'multipart/form-data')); ?>
d16274
The line str = str + 3; isn't legal C code. In C, you can't assign one array variable to another. (There's no fundamental reason why the language couldn't have made this work; it's just not supported.) That being said, the expression str + 3 is a perfectly legal expression that results in a pointer to the third (zero-indexed) element of the array. You could either print it by writing printf("%s\n", str + 3); or by writing char* midPtr = str + 3; printf("%s\n", midPtr); Either approach works. That first one is probably easier if you just need to do this once, and the second one is a bit easier if you plan on using that pointer more than once.
d16275
It looks like you want a list of lists. Try changing line 3 into d.append([X_test[i], y_test[i], y_pred[i]]) to append the three items as a list. A: You can only append one value. In this case, you want to append one list of 3 values. d.append([X_test[i], y_test[i], y_pred[i]]) If you wanted to append 3 separate values at once, use the same list as an argument to the extend method instead. >>> d = [] >>> d.extend([1,2,3]) >>> d [1, 2, 3] A: d = [] for i in range(len(X_test)): e = [] e.append(X_test[i]) e.append(y_test[i]) e.append(y_pred[i]) d.append(e) print(X_test[i]," ", y_test[i], " ", y_pred[i]) print(d) Output : 1.5 37731.0 40835.10590871474 10.3 122391.0 123079.39940819163 4.1 57081.0 65134.556260832906 3.9 63218.0 63265.36777220843 [ [1.5, 37731.0, 40835.10590871474], [10.3, 122391.0, 123079.39940819163], [4.1, 57081.0, 65134.556260832906], [3.9, 63218.0, 63265.36777220843] ] A: I think you are looking for something like this. X_test = ['1.5', '10.3', '4.1'] y_test = ['37731.0', '122391.0', '57081.0' ] y_pred = ['40835.10590871474','123079.39940819163','65134.556260832906'] d = list() for i in range(len(X_test)): if X_test[i] and y_test[i] and y_pred[i]: d.append([X_test[i], y_test[i], y_pred[i]]) for item in d: print(item)
d16276
You may consider using Pandas apply method, https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html Using this you can vectorize the operation
d16277
This is an alternative way to get size if (filesize($target_file) > 2097152) { echo "SizeError"; } But firstly I think there is an error UPLOAD_ERR_INI_SIZE at $_FILES['file']['error']. UPLOAD_ERR_INI_SIZE=1 You can increase it in php.ini. Add or modify this in your php.ini for example yo increase max_file_size = 25mb: upload_max_filesize = 25M After modifying php.ini your code should work too: if ( 0 < $_FILES['file']['error'] ) { echo 'Error'; } else if ($_FILES["file"]["size"] > 2097152) { echo "SizeError"; } To check your php.ini settings call: echo phpinfo(); You will see your settings, find upload_max_filesize it's 2mb as default value. Looks like this: A: check this condition first if ($_FILES["file"]["size"] > 2097152) then check others. You probably get the UPLOAD_ERR_INI_SIZE at $_FILES['file']['error'] which is qual to 1. You can increase it in php.ini. Change this in your php.ini: upload_max_filesize = 25M A: The reason you're getting "error" is because of this line: if ( 0 < $_FILES['file']['error'] ) If you read the documentation here: PHP: Upload Error Messages Explained, then you'll notice that there are several values that can be returned with $_FILES['file']['error']. It returns 0 when there are no errors. But it returns 1 if The uploaded file exceeds the upload_max_filesize directive in php.ini. And it returns 2 if: The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. In both cases 0 is smaller than 1 or 2. So your script is returning you "Error". Because the condition evaluates to true. You need to either change the condition, or check for the file size first. A: I was facing the same issue,and got the solution. Codeigniter allows you to upload the image of size less than 2mb.but if you want to upload the image of 5 mb than you should add this line in your .htaccess file. php_value upload_max_filesize 20M After adding this line in your .htaccess file,your code will work fine.
d16278
Try this code, it will work as your wish. On 1st Page store data into localStorage variable var page_content = document.getElementsByTagName("body")[0].innerHTML; console.log( page_content ); localStorage.setItem("page_content", page_content ); Retrieve on 2nd page document.getElementById("parent2").innerHTML = localStorage.getItem("page_content"); console.log( page_content ); Check console on 1st page for confirmation data storing successfully.
d16279
You can do something like below. I have done it in one of my project and it worked fine. String updateSet = " UserAnswer = ? ," + " UserAnswerType = ? "; new Update(Question.class) .set(updateSet, answerID, userAnswerType) .where(" QID = ? ", questionID) .execute(); Following similar pattern for any number of columns will work. In case if you have Boolean type fields in your table, this issue can help you. A: We Can achieve it like this way. StringBuilder data=new StringBuilder(); if (!TextUtils.isEmpty(name.getText().toString())) { data.append("Name = '"+name.getText().toString()+"',"); } if (!TextUtils.isEmpty(age.getText().toString())) { data.append("Age = '"+age.getText().toString()+"',"); } if (!TextUtils.isEmpty(empCode.getText().toString())) { data.append("EmployeeCode = '"+empCode.getText().toString()+"',"); } if (!TextUtils.isEmpty(mobNum.getText().toString())) { data.append("MobileNumber = '"+mobNum.getText().toString()+"',"); } if (!TextUtils.isEmpty(adress.getText().toString())) { data.append("address = '"+adress.getText().toString()+"'"); } String str=data.toString(); //-------------and update query like this----------------- new Update(EmpProfile.class).set(str).where("EmployeeCode = ?", empCode) .execute(); A: String x="sent = 1,file = "+n.getString("file"); new Update(Messages.class) .set(x) .where("id = ?", lid) .execute();
d16280
You are setting text to i tag and you want a text for span right so set text just after append span instead of after append i as below var body = placeWrapper .append('div') .attr('class', 'thm-listing__body'); body.append('span') .attr('class', 'thm-listing__location') .text(function (d) { return d.Address; }) .append('i') .attr('class', 'fa fa-map-marker'); Update Set icon before span text use prepend() as per below var body = placeWrapper .append('div') .attr('class', 'thm-listing__body'); body.append('span') .attr('class', 'thm-listing__location') .text(function (d) { return d.Address; }) .prepend('i') .attr('class', 'fa fa-map-marker');
d16281
If you're using mmap, your probably concerned about speed and efficiency. You basically have a few choices. * *Wrap all your reads and writes with htonl, htons, ntohl, ntohs functions. Calling htonl (host to network) order on Windows will convert the data from little endian to big endian. On other architectures it will be a noop. These conversions do have an overhead, but depending on your operations, they may or may not be significant. AFAIK, this is the approach used by SQLite *Your other option is to always write data in host format, and provide routines if users need to migrate their data across platforms. Databases usually read and write data in host format, but provide tools like bcp which will write to either ASCII or network byte order. *You can tag the header of your file with a byte order mark. When your program starts, it will compare it's byte order with that of the file, and provide any translation if needed. This is often good for simply data formats like UTF-16, but not for formats where you have a number of variable length types. Additionally, if you do things like provide length prefixes, or file offsets, you may have a mixture of 32 bit and 64 bit pointers. A 32 bit platform can't create a mmap view larger than 4GB, so it's unlikely that you would support file sizes larger than 4 GB. Programs like rrdtool take this approach, and support much larger file sizes on 64 bit platforms. This means your binary file wouldn't be compatible across platforms if you used the platform pointer size inside of your file. My recommendation is to ignore all byte order issues up front, and design the system to run fast on your platform. If/when you need to move your data to another platform, then choose the easiest/quickest/most appropriate method of doing so. If you start out by trying to create a platform independent data format, you will generally make mistakes, and have to go back and fix those mistakes later. This is especially problematic when 99% of the data is in the correct byte order, and 1% of it is wrong. This means fixing bugs in your data translation code will break existing clients on all platforms. You'll want to have a multi-platform test setup before writing code to support more than one platform. A: Yes. mmap maps raw file data to process address space. It does not know anything about what the raw data represents, let alone try to convert it for you. If you are mapping the same file on architectures with different endianness, you'll have to do any necessary conversion yourself. As a portable data format across computers, I'd consider something of higher abstraction level such as JSON or even XML that does not tie the data format to a particular implementation. But it really depends on your specific requirements.
d16282
When should we use Google Play's service Application Licensing? When you have an application that you fear will be pirated, and sold/modified without your permission. Is this a new mechanism against cracked apps on Android? This system itself has been cracked. Application Licensing uses the LVL library. AntiLVL can crack it. It's best to implement this in addition to your own authentication methods(Cntrl+F for "Guidelines for custom policies".
d16283
when using ${{ }} syntax that variable is being replace at the compile time. Read more here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#understand-variable-syntax A: The variables werent in scope! Its worth noting that "much to learn" also identified this :)
d16284
@luke-h I'm fairly certain it makes sense to piggyback https://bugzilla.mozilla.org/show_bug.cgi?id=1256756 I just did.
d16285
I disagree with your search depth being O(Wlog(W)). In the worst case, where every intermediate letter (except the last) matches the word, your recursion will have a branching factor of 2, and will explore 2^W paths. Take, as an example, an extremely large grid, filled entirely with As, and a sole B in the lower right corner, and a search word AAA...AB. You can see how that would explode exponentially (with respect to W). You are correct too, in that you'd ignore the smaller term, so overall I think the time complexity should be O(RC*2^W).
d16286
Apparently the phar:// stream wrapper will allow you to read the CSV file contents directly out of the gzipped TAR. $fh = fopen('phar://example.tar.gz/target_file.csv', 'r'); while( $row = fgetcsv($fh) ) { // code! } This should leverage PHP's stream goodness so that reading from the file doesn't require more than a few kilobytes actually reside in memory at a given time. That said, if you start just appending rows to an array in that loop you're going to have the same memory problems. Do something with the row, and then discard it.
d16287
foreach ($countries as $country) { foreach ($country as $k => $v) { echo $k . ': ' . $v . '<br>'; // nombre: Argentina ... } }
d16288
The Regular chrome browser is fetching the details of your bike(Something -- yamaha 125). It could be from past cookies or cache. However, once you are opening it with Automation, a clean session s opened. Try cleaning your cookies and cache on the browser(regular) and then try, both of them should appear same. Or you can use options in chrome to select the profile your regular chrome browser is using. See https://startingwithseleniumwebdriver.blogspot.com/2015/07/working-with-chrome-profile-with.html. Hope it Helps!
d16289
To count the values 1 for each row you can just use: mydf$newvar <- rowSums(mydf==1) If you want to see whether any of the values is 1 (as your intended outpur newvar implies): mydf$newvar <- +(rowSums(mydf==1)>0) A: Thank you Henrik! You are right. It was answered in the thread you mentioned. Here the answer again, because nothing is trivial for everyone :-) newvar<-as.numeric(apply(cbind(var1,var2,var3), 1, function(r) any(r == 1))) Elch von Oslo
d16290
You should consider using a templating language like Jinja2. Here is a simple example straight from the link above: >>> from jinja2 import Template >>> template = Template('Hello {{ name }}!') >>> template.render(name='John Doe') Generally, though you save templates in a file, and then load / process them: from jinja2 import Environment, PackageLoader # The env object below finds templates that are lcated in the `templates` # directory of your `yourapplication` package. env = Environment(loader=PackageLoader('yourapplication', 'templates')) template = env.get_template('mytemplate.html') print template.render(the='variables', go='here') As demonstrated above, templates let you put variables into the template. Placing text inside {{ }} makes it a template variable. When you render the template, pass in the variable value with a keyword argument. For instance, the template below has a name variable that we pass via template.render This is my {{name}}. template.render(name='Jaime') A: Also consider Python Bottle (SimpleTemplate Engine). It is worth noting that bottle.py supports mako, jinja2 and cheetah templates. The % indicates python code and the {{var}} are the substitution variables HTML: <ul> % for item in basket: <li>{{item}}</li> % end </ul> Python: with open('index.html', 'r') as htmlFile: return bottle.template(htmlFile.read(), basket=['item1', 'item2'])
d16291
You have to specify 'inplace=True' df.set_index('A', inplace=True) otherwise it doesn't persist. A: Consider this df val A 10001 5 10002 6 10003 3 You can filter the rows using df[df.index == '10001'] You get val A 10001 5
d16292
For scripts that do not open a cursor (like insert, update or exec ones) use the ExecSQL Method of TADOQuery. It returns a Integer representing the number of affected rows by your query. ADOQuery1.Close; ADOQuery1.SQL.Clear; ADOQuery1.SQL.Add('insert into Table1'); ADOQuery1.SQL.Add('select Field1 ,Field2 from Table2'); ADOQuery1.SQL.Add('where ArtNo= 1'); NumRows := ADOQuery1.ExecSQL; ShowMessageFmt('Affected rows on Table2: %d', [NumRows]);
d16293
Looks like there is a hard cap on results in three places that need to be updated for large domains: * *event.js - line 166 *metric.js - line 11 *metric.js - line 12 In addition, I was unable to find any query-string apis for the parameters. Ideally, we can leave the cap at 1000 (to avoid server bloat for people not tuning their queries correctly) and allow the consumer to define override behavior.
d16294
You can do a generic extension method to check if your object is null or not. Try: public static bool IsNullOrEmpty<T>(this IEnumerable<T> source) { return source?.Any() != true; } A: Another way to check for NullOrEmpty is to coerce Count() to an int?. Then we can compare the result of GetValueOrDefault to 0: if((model?.Count).GetValueOrDefault() == 0) return this; How it works: * *Because the ?. operator will return null if the left side is null, and Count returns an int, the result of (model?.Count) is a Nullable<int>. *The GetValueOrDefault method returns the value of Count if model is not null, otherwise it returns default(int) (which is 0). *This way if model is null, the condition returns 0
d16295
As above_c_level suggested the minimal solution is to change the primary key column name in the base class. The mistake what I made both the base class and the subclass had the "id" property which was overriden by the subclass. You can find below the working code sample. """Joined-table (table-per-subclass) inheritance example.""" from sqlalchemy import Column from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy import inspect from sqlalchemy import Integer from sqlalchemy import or_ from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm import with_polymorphic Base = declarative_base() class Resource(Base): __tablename__ = "resource" resource_id = Column(Integer, primary_key=True) # Permissions and other common columns. # Left out for simplicity type = Column(String(50)) __mapper_args__ = { "polymorphic_identity": "resource", "polymorphic_on": type, } class ChildResource(Resource): __tablename__ = "child_resource" id = Column(ForeignKey("resource.resource_id"), primary_key=True) name = Column(String(30)) parent_id = Column(ForeignKey('parent_resource.id'), nullable=False) parent = relationship('ParentResource', back_populates='children', foreign_keys=parent_id) __mapper_args__ = {"polymorphic_identity": "child_resource", "inherit_condition": id == Resource.resource_id} class ParentResource(Resource): __tablename__ = "parent_resource" id = Column(ForeignKey("resource.resource_id"), primary_key=True) name = Column(String(30)) children = relationship('ChildResource', back_populates='parent', foreign_keys='ChildResource.id') __mapper_args__ = {"polymorphic_identity": "parent_resource", "inherit_condition": id == Resource.resource_id} if __name__ == "__main__": engine = create_engine("sqlite://", echo=True) Base.metadata.create_all(engine) session = Session(engine) res_child = ChildResource( name="My child shared resource", ) res_parent = ParentResource( name="My parent shared resource" ) res_parent.children.append(res_child) session.add(res_child) session.add(res_parent) session.commit()
d16296
Look at System.Windows.Controls.DefinitionBase It's values (taken from sharedscope if used) are then used in grid.SetFinalSize
d16297
You can't. The PHP syntax parser is limited and does not allow it in current versions. The PHP devs extended the parser for upcoming releases of PHP. Here's a link to a blog talking about it A: You cant :) function find_student() {return array('name'=>123);} echo find_student()['name']; Result: Parse error: syntax error, unexpected '[', expecting ',' or ';' A: You can do something similiar using ArrayObject. function find_student() { //Generating the array.. $array = array("name" => "John", "age" => "23"); return new ArrayObject($array); } echo find_student()->name; // Equals to $student = find_student(); echo $student['name']; Downside is you cant use native array functions like array_merge() on that. But you can access you data as you would on array and like on an object.
d16298
There are two ways you can go about this: * *Add the Dlls to the VS project as a file, then set Build Action to None and Copy to output directory as Copy. This should ensure that any external dependencies of the referenced library are copied. *Add a command like xcopy "$(ProjectDir)lib\*.*" "$(OutDir)\" /y /e or xcopy "$(ProjectDir)lib\*.*" "$(TargetDir)" /y to the Build Events section in Project properties. This should copy the \lib directory from the project root to the output.
d16299
No, you cannot have more than one domain root. You can use mod_alias to configure other file system paths for example, you could have: Alias /working d:/working Alias /other e:/
d16300
So i managed to fix it! The issue was with the embedded SDK. If anyone struggles with the same probelm here are the steps i took: * *Download WinSCP. *Connect to the arduino using SSH in WinSCP (username root) *copy across the two embedded parse.com arduino files (make sure they are in the correct root folder *Download PuTTY and use this to open the arduino command line *call opkg install *.ipk to install the SDK files That seems to have sorted the problem, they weren't installed properly before