_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d12801
train
let leftAlignedColor if(element.isrespond == "left"){ leftAlignedColor = '#000' }else{ leftAlignedColor = null } <Grid.Column floated={ element.isrespond ? "right" : "left"}><p style={{color: `${leftAlignedColor}`}}> {result.message}</p></Grid.Column> its better to use a <span>,<p> inside a column as a good practice. Hope this is helpful! A: You should apply a conditional style. This will enable you even pass a specific class name that styles the component. let myStyle = element.isrespond ? {float:"right",color:"blue"} : {float:"left",color:"red"}; <Grid.Column style={myStyle}> {result.message}</Grid.Column> A: <Grid.Column floated={ element.isrespond ? "right" : "left"}><p style={{color: element.isrespond ? "blue" : "green",background:element.isrespond ? "yellow" : "cyan"}}> {result.message}</p></Grid.Column> I think this will work. change the required colors. I added botj for color and background. In the above one. its "green" for left and "blue" for right
unknown
d12802
train
You are using wrong method name for sending email in your controller: $this->blogs_model->send_mail($this->input->post('email')) Correct function name is sendEmail() $this->blogs_model->sendEmail($this->input->post('email')) A: Check your code: You should change function "send_mail" in your controller because in model you used "sendEmail". Change in to your controller : $this->blogs_model->sendEmail($this->input->post('email')) A: I think the problems in your code is this line smtp_host' => 'ssl://smtp.googlemail.com try instead: smtp_host' => 'http://smtp.gmail.com
unknown
d12803
train
Yes, those resources will be kept if you specify the [--retain-resources <value>], if you dont Cloudformation will delete all the resources in the stack name (including the nested stacks as well) you are providing given you have permissions to do. If any of the resources inside the cloudformation stack has retain policy set they won't be deleted. During deletion, AWS CloudFormation deletes the stack but does not delete the retained resources. From the same page aws cloudformation delete-stack You might wanna read this too How do I retain some of my resources when I delete an AWS CloudFormation stack? You can specify the retain policy as well in cloudformation template.
unknown
d12804
train
The reference String that you are passing while putting the argument args.putString("yog",god);should be the same while you are retriving it yog=getArguments().getString("yog");
unknown
d12805
train
What about use delete keyword? delete personList[personId]; A: Since you're already assigning the keys of your object to the personId you can just do: const Delete = (id: string): void => { const filteredPersonList: Record<string,PersonInfo> = {} for(let key in personList){ if(key !== id){ filteredPersonList[key] = personList[key] } } setPersonList(filteredPersonList) } A: Based on the context (i.e. updating React state) and your code sample, what you're actually trying to do is create a modified copy of the record without mutating the original. const deletePerson = (personId: string): void => { // first create a shallow copy of the old record. const newList = {...personList}; // now delete the entry from the new record delete newList[personId]; setPersonList(newList) } A: Eslint complains with @ehutchllew answer: 40:7 error for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array no-restricted-syntax 40:7 error The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype guard-for-in So using the suggested Object.{keys,values,entries}, it becomes: const Delete = (id: string): void => { const filteredPersonList: Record<string, PersonInfo> = {}; Object.keys(personList).forEach((key) => { if (key !== id) { filteredPersonList[key] = personList[key]; } }); setPersonList(filteredPersonList); };
unknown
d12806
train
Although this is off-topic but to answer your question, this is called re-targeting. You can do that using google adwords program - it works through the use of cookies. A: It's called remarketing in AdWords and there are various flavours of it on the platform. There are dedicated remarketing campaign type templates available when creating a new campaign in AdWords.
unknown
d12807
train
You can get the index of sodf==11 and then get the loc value -1 onwards. Here's how to do it. import pandas as pd sodf = pd.Series([9,10,10,9,10,11]) x = sodf[sodf == 11].index[0] print (sodf.loc[x-1:]) Output will be: 4 10 5 11 If you just want the value of the previous row, then you can also give print (sodf.loc[x-1]) The output will be just the value as this is a pd.Series with one column: 10 A: Try something like this: i = sodf[(sodf == 9)].index i = i.union(i-1) i = i[i>=0] sodf[i] Output 0 9 2 10 3 9 dtype: int64
unknown
d12808
train
As of the resolution of https://issues.apache.org/activemq/browse/SMXCOMP-711 and https://issues.apache.org/activemq/browse/SMXCOMP-712 (servicemix-cxf-bc-2010.01) it should be possible and easy to do. See http://fisheye6.atlassian.com/browse/servicemix/components/bindings/servicemix-cxf-bc/trunk/src/test/java/org/apache/servicemix/cxfbc/ws/security/CxfBcSecurityJAASTest.java?r=HEAD for an example. Specifically the testJAASPolicy method. As for the error relating to asserting the UsernameToken assertion, you may want to try putting the UsernameToken assertion inside of a SupportingToken or binding assertion depending on what you want to do with the token. It looks like you just want a username and password to be passed in the message without any other security such as a cryptographic binding of the token to the message or encryption so a supporting token will likely fit your needs. I also urge you to consider the following additional precautions when using a UsernameToken: * *Cryptographically bind the token to the message using a signature. *Use a nonce and created timestamp and cache the token on the server to prevent replay *Consider encrypting the token (before signing if you also sign) using XML enc *Using TLS either in lieu of or in addition to the above suggestions A: With david's and Freeman over at the servicemix-user mailing-list. I was able finally get the correct configuration to implement WS-Security Policy. Here's my final beans.xml for the my BC <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxfbc="http://servicemix.apache.org/cxfbc/1.0" xmlns:util="http://www.springframework.org/schema/util" xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:person="http://www.mycompany.com/ws-sec-proto" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://servicemix.apache.org/cxfbc/1.0 http://repo2.maven.org/maven2/org/apache/servicemix/servicemix-cxf-bc/2010.01/servicemix-cxf-bc-2010.01.xsd http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd http://cxf.apache.oarg/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" /> <import resource="classpath:META-INF/cxf/osgi/cxf-extension-osgi.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-policy.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-ws-security.xml" /> <bean id="myPasswordCallback" class="com.mycompany.ServerPasswordCallback" /> <cxfbc:consumer wsdl="classpath:wsdl/person.wsdl" targetService="person:PersonService" targetInterface="person:Person" properties="#properties" delegateToJaas="false" > <!-- not important for ws-security <cxfbc:inInterceptors> <bean class="com.mycompany.SaveSubjectInterceptor" /> <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /> </cxfbc:inInterceptors> --> </cxfbc:consumer> <util:map id="properties"> <entry> <key> <util:constant static-field="org.apache.cxf.ws.security.SecurityConstants.CALLBACK_HANDLER" /> </key> <ref bean="myPasswordCallback" /> </entry> </util:map> <httpj:engine-factory bus="cxf"> <httpj:engine port="9001"> <httpj:tlsServerParameters> <sec:keyManagers keyPassword="password"> <sec:keyStore type="JKS" password="password" resource="certs/cherry.jks" /> </sec:keyManagers> <sec:cipherSuitesFilter> <sec:include>.*_WITH_3DES_.*</sec:include> <sec:include>.*_WITH_DES_.*</sec:include> <sec:exclude>.*_WITH_NULL_.*</sec:exclude> <sec:exclude>.*_DH_anon_.*</sec:exclude> </sec:cipherSuitesFilter> <sec:clientAuthentication want="false" required="false" /> </httpj:tlsServerParameters> </httpj:engine> </httpj:engine-factory> <bean id="cxf" class="org.apache.cxf.bus.CXFBusImpl" /> <bean class="org.apache.servicemix.common.osgi.EndpointExporter" /> </beans> Full example can be found here but it may not be there after a while.
unknown
d12809
train
To send variables from flash to PHP: //Actionscript: loadVariables ("test.php?myVariable=" + myFlashVar , _root); //PHP can retrieve it using $myVar = $_GET['myVariable']; To send from PHP to flash, use exactly the same: //Actionscript: loadVariables ("test.php?" , _root); //PHP: echo "&myVariable=hello"; //Now in your flash movie, _root.myVariable will be equal to 'hello' I hope this is enough to get you started :)
unknown
d12810
train
a=int(input()) if u r keeping any integer values. A: That happens because you are using input. Use raw_input instead. raw_input is what you have to use with python 2. A: This problem does not occur in my pylance. It seems that there are some errors in your vscode's pylance. It doesn't recognize the input() method. You can try to update the pylance in the extension store or add the following code in settings.json: "python.analysis.diagnosticSeverityOverrides": { "reportUndefinedVariable": "none" }
unknown
d12811
train
Does pvc or pv create folders under the cloudshare? No. A Kubernetes PersistentVolume is just some storage somewhere, and a PersistentVolumeClaim is a way of referencing a PV (that may not immediately exist). Kubernetes does absolutely no management of any of the content in a persistent volume; it will not create directories on startup, copy content from the image into a volume, or anything else.
unknown
d12812
train
Your while loop's parentheses are kind of messed up, I changed it to this and it works, and is more readable: while ( ((height>=2) && (height<=13) && (width>=2) && (width<=21)) && ( (labMap[height - 1][width] && labMap[height - 2][width] ) || (labMap[height + 1][width] && labMap[height + 2][width] ) || (labMap[height][width - 1] && labMap[height][width - 2] ) || (labMap[height][width + 1] && labMap[height][width + 2] ))) {
unknown
d12813
train
The fundamental issue is that a mutable field can only be modified if the struct itself is mutable. As you noted, we need to use byref in the declaration of Age. We also need to make sure a is mutable and lastly we need to use the & operator when calling the function inside. The & is the way to call a function with a byref parameter. type [<Struct>] Age = { mutable n : int } let printInside a = printfn "Inside = %d" a.n let inside (a : Age byref) = a.n <- a.n + 1 a.n let mutable a = {n = 1} printInside a //a = 1 inside &a printInside a //a = 2 A: Now that I get the pattern, here is a simple example (just an int instead of a struct record) of how to mutate values passed into a function: let mutable a = 1 let mutate (a : byref<_>) = a <- a + 1 mutate &a a //a = 2
unknown
d12814
train
The closest thing I can think of is do.call: > lims <- c(10,20) > do.call(seq, as.list(lims)) [1] 10 11 12 13 14 15 16 17 18 19 20 But do note that there are some subtle differences in evaluation that may cause some function calls to be different than if you had called them directly rather than via do.call.
unknown
d12815
train
It looks like they have created their own, here take a look: https://github.com/sferik/rails_admin/blob/master/app/assets/javascripts/rails_admin/ra.filtering-multiselect.js It would be nice to pull it out and make a plugin, as a note it does look like it depends on jQuery, and jQueryUI.
unknown
d12816
train
You can add the following to your ggvis function ... %>% scale_ordinal("fill", range = c("red", "green", "yellow"))
unknown
d12817
train
oops.. someone beat me to it... When you read files as Dataurl on the clientside: reader.readAsDataUrl(...) the file is encoded in to a base64 string.. That's why if you save the data directly, it's not in the correct format. As the previous answer states, you base64_decode your data into the correct format. A: First, there isn't anything in $_POST["data"] because the index (data) is named by the key in the JSON key : value pair, not the JavaScript var. Secondly, you should change this: $Handle = fopen($FileName, 'w'); fwrite($Handle, $data); print "Data Written"; fclose($Handle); to this: file_put_contents($FileName, base64_decode($data));
unknown
d12818
train
You should try to look for TemplateEngine - it could allow to decrease code count and make it more clear. What Javascript Template Engines you recommend? A: You should run your code through a linting engine like JSLint or JSHint and you should familiarize yourself with good practice. Here's one way (of more than one possible solution) to optimize your code: function populate(myresults) { var table = $(document.createElement('table')); $(myresults).each(function (i) { var row = $(document.createElement('tr')), cell = $(document.createElement('td')).text(myresults[i].name); row.append(cell); table.append(row); }); $('#divId').append(table); } A: Maybe, creating a new DOM element more correct ? Like this: function populate(myresults) { var str= $('<table />)'; for(var i in myresults){ str.append($('<td />').text(myresults[i].name).appendTo($('<tr />'))); } $('#divId').empty().append(str); } A: You could do it this way: function populate(myResults) { var tab = $('<table />'); for(var i in myResults){ if (myResults.hasOwnProperty(i)) { var tr = $('<tr />'); tr.append($('<td /'>, {text: i.name})); tab.append(tr); } } $('#divId').append(tab); } Using a template engine as suggested by the others would be preferable as it's a better, more maintainable approach.
unknown
d12819
train
malloc reservers a particular amount of memory on the heap and gives back a pointer to this memory block (or NULL, if it was not able to allocate the desired memory block). Note, however, that malloc will not initialise the memory block in any way. It will not fill it with 0 or any other value; it will simply keep it's content as is. So the question is actually "what is the initial content of the heap when a program starts?". And the answer is: it depends on the operating system, which portion of memory it assigns to a program when executed, and the content of this memory block is very likely to be just "something undefined", not even random. This can be some recurring patterns of values, it can be zeros, it can be everything. When you look into different portions of a program's heap, you will probably see this "something undefined" content, regardless of whether you have used malloc before or not. You may see recurring patterns as in your case. Note, however, that "looking into" portions of the heap that have not been allocated before is actually undefined behaviour.
unknown
d12820
train
Change initView() to : private void initView() { View view = inflate(getContext(), R.layout.fragment_user_menu, null); addView(view); bindViewWithButterKnife(this, view); } I don't think you need to call the methods, the annotations already do the job to set the listeners, right ?
unknown
d12821
train
Here's your culprit. #content { overflow: hidden; } This is exactly the reason why you shouldn't use overflow hidden for clearing floats. Anchor links will cause overflowed elements to scroll in certain situations. Look into clearfix for clearing floats instead. Run this javascript in your console for a demonstration on the problem: document.getElementById("content").scrollTop = 0
unknown
d12822
train
They are completely different things: one declares a class property, and the other is the name of the class constructor. There is no such thing as "one or the other" here. I suggest re-reading all about classes and objects in your PHP book, or the manual. A: public $var is not a constructor, which __construct() is. I hope you meant something else. As stated in the manual, there's two kinds of constructors: class Bar { public function Bar() { // "old" style constructor } } class Foo { function __construct() { // new style constructor } } A: public $var; Declares a variable that will be accessible to the outside world. function __construct () { /* Do stuff */ } Defines the "magic" constructor method. This method will be invoked when a new instance is created (i.e. when you create a new object). This method is what accepts and handles any arguments that are passed when creating a new object. The key difference is that one defined a variable (property) and one defines a function (method).
unknown
d12823
train
We can use that. var myBoolean = { value: false } //get myBoolean.value; //set myBoolean.value = true; A: Several problems there: * *'false' is not false. *Variables are passed by value in JavaScript. Always. So there is no connection whatsoever between the boolVar in setToFalse and the isOpen you're passing into it. setToFalse(isOpen) is processed like this: * *The value of isOpen is determined *That value (completely disconnected from isOpen) is passed into setToFalse *JavaScript has some interesting handling around primitive types: If you try to use them like object types (var a = 42; a.toFixed(2); for instance), the value gets promoted to a temporary object, that object is used, and then the object is discarded. So if obj is false, obj.anything = "whatever" ends up being a no-op, because the object that temporarily exists ends up getting released as soon as the line finishes. You could do something like what you're doing by promoting isOpen to an object via new Boolean, but beware that it will then act like an object, not a boolean: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, false); } var isOpen = new Boolean(true); // An object setToFalse(isOpen); snippet.log('isOpen ' + isOpen); <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> That works because the value in isOpen is a reference to an object. So when that value is passed into setToFalse as boolVar, boolVar's value is a copy of that reference, and so refers to the same object. So that sorts out issue #2 above. Issue #3 is solved by creating an object explicitly, rather than relying on the implicit behavior. But, remember my warning above about how it will act like an object (because it is one), not like a boolean? Here's an example: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, false); } var isOpen = new Boolean(true); // An object setToFalse(isOpen); snippet.log('isOpen ' + isOpen); if (isOpen) { snippet.log("isOpen is truthy, what the...?!"); } else { snippet.log("isOpen is falsey"); } <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> We see: isOpen false isOpen is truthy, what the...?! ...because isOpen contains a non-null object reference, and non-null object references are always truthy. A: You are passing boolean primitive variable isObject. For primitive types it doesn't make sense to try to set toString method, because it's not needed (and used), since in ECMAScript spec there are already defined rules for to String conversion. If you really want to use modifyVar function like you are trying, you can work with Boolean object instead of primitive: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, 'false'); } var isOpen = new Boolean(true); setToFalse(isOpen); console.log('isOpen ' + isOpen); So the answer: use new Boolean(true) or Object(true). A: I am not sure but you are assigning false in single quote, value withing single/double quotes will be considered as string. Just use modifyVar(boolVar, false); and try.
unknown
d12824
train
I think GCC is correct in accepting the given example. This is because the static data member named constant is an ordinary data member variable(although it is still considered a templated entity). And since constant is an ordinary data member variable, dcl.constexpr#1.sentence-1 is applicable to it: The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. (emphasis mine) Thus, as the construct that you have provided after the class template is nothing but an out-of-class definition for the ordinary static data member constant, the given example is well-formed. template <typename T> constexpr Test<T> Test<T>::constant {42}; //this is an out-of-class definition for the ordinary static data member variable `constant` Note Note that dcl.constexpr#1.sentence-1 doesn't mention templated entity, but instead only mention "variable" and "variable template" and since constant is a variable(ordinary), the same should be applicable to constant.
unknown
d12825
train
Simply call RavenDB to load the object with the appropriate ID, make the changes to its contents and persist it again. No need to worry about any UpdateModel calls. It doesn't apply here. Be aware of one potential issue since you are including the id in the model. If I sent a PUT command to http://server/controller/pages-3 with that body what would happen? You should probably send me a bad request response or something similar depending on how you want your API to work. A: Is there any reason not to be explicit in your parameters? I would define an UpdateModel and take that as parameter instead of the dynamic. Then it also would be able to model validation. ASP.NET WebApi includes handling of converting from both JSON and XML as input to your controller methods. I'm guessing your combination of custom mediatypeformatter and use of dynamic would be unneccesary in this case, if there is not something I'm missing.
unknown
d12826
train
If I understand you correctly, you want to have 2 "columns" (variables) that contain obstacles but cannot both contain obstacles in the same "row" (bit) If this is the case the first observation I would make is that any time there is a blockage in the left column the possible options of the right column on both sides of that blockage are totally independent, in fact if my left column looks something like this: 000110000 Then really I just need to find all combinations of obstacles for R=3 and also for R=4 then the final answer will be the Cartesian product of filling those 2 gaps with the combinations. So first we can write some code to make all possible permutations of obstacles for a given R which we can do recursively, you indicated you wanted to move away from bitwise so I'll use tuple concatenation as it will likely be a little easier to manipulate for your actual task than bit operations. def obstacle_combos(R): """ yields all sequences of obstacles with size 'size' obstacle_patterns is a set of tuples representing different obstacles """ if R==0: # cannot fit any blocks of size 0 yield () return if R==1: # this ensures the loop below can always check combo[-1] without index error yield (0,) return for combo in obstacle_combos(R-1): yield combo + (0,) if combo[-1] == 0: # when the last element is empty we could instead put a block of 1s as well. yield combo[:-1] + (1,1) print(*obstacle_combos(5), sep="\n") The way this works is relatively straight forward, the base case of R=0 and R=1 are the trivial case, otherwise we check for R-1 and that combo with an extra 0 at the end is a valid obstacle combo for R, but also if the last element is 0 we can stick a 11 at the end as well so that becomes a conditional extra case. The next step would be to identify runs of consecutive 0s, this is also not particularly complicated we just iterate over the sequence and implement some logic when we switch from 0 to 1 or 1 to 0 etc: def find_gaps(obstacle_sequence): "yields (slice, size) for each range of concecutive 0s in the sequence" in_seq = False #whether we are currently in a run of 0s for i,elem in enumerate(obstacle_sequence): if not in_seq and elem == 0: in_seq = True start_idx = i elif in_seq and elem == 1: in_seq = False yield slice(start_idx, i), i-start_idx # after the loop if the last elements were 0s then yield the final sequence if in_seq: yield slice(start_idx, len(obstacle_sequence)), len(obstacle_sequence)-start_idx One thing here that is slightly unorthodox is that I am creating slice objects directly, this is what happens internally if you do x[a:b] it is the same as x[slice(a,b)], the goal here being that later we can use the values this function produces to do something like: Y = [0]*len(X) # some sequence of same size as X for idx_range, size in find_gaps(X): Y[idx_range] = generate_seq_of_length(size) to set ranges of Y (which will end up being our right_obstacles eventually) with minimal effort outside the find_gaps function. Now the tricky part, we want a function to take a left_obstacles sequence of 1s and 0s, find all the runs of 0s by calling find_gaps and at the same time find all the combinations of obstacles we could put in that section. Then go over all combinations (cartesian product) of the obstacles that can be laid out in each region. import itertools def place22blocks(left_obstacles): # start by making a sequence of the same size as left_obstacles right_obstacles = [0 for _ in left_obstacles] # then we will find all the gaps and setup the obstacle_combos for each one gap_ranges = [] seq_filling_iterators = [] for idx_range, size in find_gaps(left_obstacles): gap_ranges.append(idx_range) seq_filling_iterators.append(obstacle_combos(size)) # at this point each element of seq_filling_iterators is an iterator # that will give the different possibilities of obstacles for each region, # the final result of possible obstacles is the cartesian product of all of them for list_of_obstacles_per_gap in itertools.product(*seq_filling_iterators): # list_of_obstacles_per_gap is now a list of the sequences to fill in each gap, it is the "generate_seq_of_length(size)" in the previous example essentially. for idx_range, seq in zip(gap_ranges, list_of_obstacles_per_gap): right_obstacles[idx_range] = seq # since we are reusing the right_obstacles variable every loop we will need to make a copy for each valid obstacle list, will make it a tuple so it is immutable but you could also do list(right_obstacles) if you wanted. yield tuple(right_obstacles) print(*place22blocks((0,0,0,1,1,0,0,0)),sep="\n") This function I will admit is very complicated to fully wrap your head around for how short it is. gap_ranges is the list of ranges where we have space to put obstacles which is parallel to list_of_obstacles_per_gap that is the list of sequences, each element matching with the indices stored in gap_ranges which is why we zip them together. The way list_of_obstacles_per_gap is generated is a little harder to grasp though, the first thing is that product is like a nested loop: # example loop: for x in range(5): for y in ["a","b","c"]: for z in range(10): things = (x,y,z) # that would be equivalent to for things in itertools.product(range(5), ["a","b","c"], range(10)): pass so an example that might help would be to think about how the code would work if there were exactly 2 gaps to put obstacles: for obs_seq1 in obstacle_combos(3): for obs_seq2 in obstacle_combos(4): right_obstacles[0:3] = obs_seq1 right_obstacles[5:9] = obs_seq2 print(right_obstacles) so in the function above the outer loop is collapsing an arbitrary number of nested loops and the inner loop is performing all those sequence assignments. No idea if any of this will actually help you, I'm still not sure exactly what you are trying to accomplish but I had fun working through this, happy coding :) Also note if you wanted to implement this more efficient algorithm with bitwise operations that would be very doable as well: import itertools def obstacle_combos(R): """ yields all sequences of obstacles with size 'size' obstacle_patterns is a set of tuples representing different obstacles """ if R<=1: # cannot fit any blocks of size 0 yield 0 return for c in obstacle_combos(R-1): # shift the original combo so that we are inserting at the least significant bits, # is a little simpler than tracking how much to shift the 3 by. combo = c<<1 yield combo if combo&3 == 0: # when the last element is empty we could instead put a block of 1s as well. yield combo | 3 #print(*obstacle_combos(5), sep="\n") def find_gaps(obstacle_sequence, R): "yields (slice, size) for each range of consecutive 0s in the sequence, where slice is the bit position of the least significant bit that is 0" in_seq = False #whether we are currently in a run of 0s for i in range(R): elem = obstacle_sequence & (1<<i) if not in_seq and elem == 0: in_seq = True start_idx = i elif in_seq and elem > 0: in_seq = False yield start_idx, i-start_idx # after the loop if the last elements were 0s then yield the final sequence if in_seq: yield start_idx, R-start_idx def place22blocks(left_obstacles, R): # start by making a sequence of the same size as left_obstacles gap_ranges = [] seq_filling_iterators = [] for idx_range, size in find_gaps(left_obstacles, R): gap_ranges.append(idx_range) seq_filling_iterators.append(obstacle_combos(size)) for list_of_obstacles_per_gap in itertools.product(*seq_filling_iterators): yield sum(x<<i for i,x in zip(gap_ranges, list_of_obstacles_per_gap)) print("\n\n") print(*map("{:09b}".format, place22blocks(0b000110000, 9)),sep="\n")
unknown
d12827
train
Let say in your show,have a 'Next' button to trigger the next partial. In the 'Next' button, I can pass a param[:page1] and all the necessary param when click. In the 'Show', if there is param[:page1] ,then display _partial1.html.erb its goes all the same. A: So if I were you, I would put render all three partials in your show view, and use Javascript, and CSS to manage when each one was shown. If you drop each of those partials in a div, its easy to use JQuery's hide and show methods, linked to the click event of the "Go To Next Step" button. To do it this way you wouldn't have to touch your Controller at all.
unknown
d12828
train
Thanks to Joshua K. Object.keys(o) worked perfectly.
unknown
d12829
train
To get exactly 0 or 1 answers: dig +short gmail.com mx | sort -n | nawk '{print $2; exit}' | dig +short -f - You'll need a non-ancient dig that supports +short. As noted there may be more than one "primary" MX as the preferences need not be unique. If you want all the IP addresses of all of the lowest preference records then: dig +short oracle.com mx | sort -n | nawk -v pref=65536 '($1<=pref) {pref=$1; print $2}' | dig +short -f - | uniq This does not handle the case where there is no MX record and the A record accepts email, an uncommon but perfectly valid configuration. Sadly all the dig versions I've tested return 0 whether the domain exists or not (NXDOMAIN), and whether any MX records exist or not. You can catch a DNS time-out (rc=9) though. The related host command does return a non-zero rc with NXDOMAIN, but its behaviour is a little inconsistent, it's messy to script and the output harder to parse. A poor man's error-checking version (inspired by tripleee's comment) that might be slightly more robust depending on your host command is: DOMAIN=gmail.com if ! host -t any $DOMAIN >/dev/null 2>&1 ; then echo "no such domain" elif ! host -t mx $DOMAIN >/dev/null 2>&1; then echo "no MX records" else dig +short $DOMAIN mx | sort -n | nawk '{print $2; exit}' | dig +short -f - fi (Perversely, you may require an older version of host (bind-8.x) for the -t mx test to work, newer versions just return 0 instead.) This is just about the point people start backing away nervously asking why you're not using perl/python/$MFTL. If you really need to write a robust version in bash, check out the djbdns CLI tools and debugging tools which are rather easier to parse (though sadly don't set user exit codes either).
unknown
d12830
train
You can use ng-grid's layout plugin (ng-grid-layout.js). It should come with ngGrid located at: ng-grid/plugins/ng-grid-layout.js (UPDATED: now at https://github.com/angular-ui/ng-grid/blob/2.x/plugins/ng-grid-layout.js) You will have to include an additional script tag pointing to this js file in your main index.html file. And the order of including this versus ng-grid.js is important. You would have to set a watch on displayEditForm and then call the plugin's updateGridLayout() function. So it would be something like: var gridLayoutPlugin = new ngGridLayoutPlugin(); // include this plugin with your grid options $scope.gridOptions = { // your options and: plugins: [gridLayoutPlugin] }; // make sure grid redraws itself whenever // the variable that ng-class uses has changed: $scope.$watch('displayEditForm', function() { gridLayoutPlugin.updateGridLayout(); }); From my understanding, watches generally belong in the link function rather than the controller but it will work in either spot. You could also go a bit further and say: $scope.$watch('displayEditForm', function(newVal, oldVal) { if (newVal !== undefined && newVal !== oldVal) { gridLayoutPlugin.updateGridLayout(); } }); To make sure this only fires when the data switches from true/false. This would matter if your data is initially undefined and you waste time calling grid redraw before you give it an initial value.
unknown
d12831
train
I don't think you need require for this. Why not use the prop you pass and bake that into a string literal that you insert into the component (without require and outside of the return)? const mobilePath = `./../images/BG/${props.bgmobile}_Mobile.jpg`; const desktopPath = `./../images/BG/${props.bgdesktop}_Desktop.jpg`; return( <Heroes mobile={mobilePath} desktop={desktopPath} /> ) EDIT: the substring part could be added in either <Heroes> before passing the prop. Or by filtering the prop in <Hero> and passing that variable instead of the prop
unknown
d12832
train
I think you must use the javascript closures in order to achive it. Try it: var count = element(by.css('li')).count().then(function(c){ return function(){ return c } }); var value = count(); Your value should be in the "value" variable. PS: I don't have a protractor environment to test this code now A: Here's how I solved it. function getRow(index) { var count = $$('li').count(); var test = function(index, count) { // Ensure a parameter has been passed. if (index == undefined) { throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1); } // Ensure the parameter is within bounds if (index < 0 || index >= count) { throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1); } }); count.then(function(count) { test(index, count); } return $$('li').get(index); } I'm not sure why this works and my previous attempt didn't. Well, other than I abstracted the function and allowed myself to pass in the index in a clean manner.
unknown
d12833
train
There are two possible causes of seeing exactly 1e-7 on subtracting 2.0000001-2.0. One is that many systems round to a reasonable number of digits on output. The exact conversion to decimal of IEEE 64-bit binary 2.0000001-2.0 is 9.9999999836342112757847644388675689697265625E-8. Some systems round to a limited number of significant digits, and might print that as 1e-7. On the other hand, Java, for example, delivers by default enough digits to distinguish the original value from any other double, and prints 9.999999983634211E-8 The other possible cause is if the arithmetic is being done in decimal, in which case the real numbers 2.0000001, 2, and their difference are all exactly representable because they are all decimal fractions. You would need to calculate something like 1/3 to see rounding error.
unknown
d12834
train
How to Create and Use a CollectionView The following example shows you how to create a collection view and bind it to a ListBox In the same way you can use it with datagrid <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ListBox ItemsSource={Binding Customers} /> </Window> public class CustomerView { public CustomerView() { DataContext = new CustomerViewModel(); } } public class CustomerViewModel { private ICollectionView _customerView; public ICollectionView Customers { get { return _customerView; } } public CustomerViewModel() { IList<Customer> customers = GetCustomers(); _customerView = CollectionViewSource.GetDefaultView(customers); } } Filtering To filter a collection view you can define a callback method that determines if the item should be part of the view or not. That method should have the following signature: bool Filter(object item). Now set the delegate of that method to the Filter property of the CollectionView and you're done. ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers); _customerView.Filter = CustomerFilter private bool CustomerFilter(object item) { Customer customer = item as Customer; return customer.Name.Contains( _filterString ); } Refresh the filter If you change the filter criteria and you want to refresh the view, you have to call Refresh() on the collection view public string FilterString { get { return _filterString; } set { _filterString = value; NotifyPropertyChanged("FilterString"); _customerView.Refresh(); } }
unknown
d12835
train
I solved my own problem. Here is the typescript class I wrote to handle chunked audio in JavaScript. I am not a JavaScript expert and therefore there may be faults. EDIT: After running it in 15 minute lots several times, it failed a couple of times at about the 10 minute mark. Still needs some work. // mostly from https://gist.github.com/revolunet/e620e2c532b7144c62768a36b8b96da2 // Modified to play chunked audio for games import { setInterval } from "timers"; // const MaxScheduled = 10; const MaxQueueLength = 2000; const MinScheduledToStopDraining = 5; export class WebAudioStreamer { constructor() { this.isDraining = false; this.isWorking = false; this.audioStack = []; this.nextTime = 0; this.numberScheduled = 0; setInterval(() => { if (this.audioStack.length && !this.isWorking) { this.scheduleBuffers(this); } }, 0); } context: AudioContext; audioStack: AudioBuffer[]; nextTime: number; numberScheduled: number; isDraining: boolean; isWorking: boolean; pushOntoAudioStack(encodedBytes: number[]) { if (this.context == undefined) { this.context = new (window.AudioContext)(); } const encodedBuffer = new Uint8ClampedArray(encodedBytes).buffer; const streamer: WebAudioStreamer = this; if (this.audioStack.length > MaxQueueLength) { this.audioStack = []; } streamer.context.decodeAudioData(encodedBuffer, function (decodedBuffer) { streamer.audioStack.push(decodedBuffer); } ); } scheduleBuffers(streamer: WebAudioStreamer) { streamer.isWorking = true; if (streamer.context == undefined) { streamer.context = new (window.AudioContext)(); } if (streamer.isDraining && streamer.numberScheduled <= MinScheduledToStopDraining) { streamer.isDraining = false; } while (streamer.audioStack.length && !streamer.isDraining) { var buffer = streamer.audioStack.shift(); var source = streamer.context.createBufferSource(); source.buffer = buffer; source.connect(streamer.context.destination); if (streamer.nextTime == 0) streamer.nextTime = streamer.context.currentTime + 0.01; /// add 50ms latency to work well across systems - tune this if you like source.start(streamer.nextTime); streamer.nextTime += source.buffer.duration; // Make the next buffer wait the length of the last buffer before being played streamer.numberScheduled++; source.onended = function () { streamer.numberScheduled--; } if (streamer.numberScheduled == MaxScheduled) { streamer.isDraining = true; } }; streamer.isWorking = false; } }
unknown
d12836
train
In order to send emails on a daily basis, Celery provides a scheduler for recurring task named Celery beat: https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html Once you have Celery beat set up, create a task to send the emails based on user information. The task could look through all users and include only recipients that have a send email flag or a datetime information for sending the next email. If the user completes the required action, you would unset the send email flag or delete the datetime information and the recurring task would stop sending emails to this user.
unknown
d12837
train
* *Add permission <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> *Try this btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(false); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.disable(); } });
unknown
d12838
train
This isn't an answer to the question itself, which still stands, but an answer to the underlying issue, in case somebody arrives here by Google search with a similar issue. In my case it was indeed the case that accessibility settings were causing font to be bigger than it was designed to be, thus triggering the above scenario. While I still don't know how to center the text adequately in this case, in my case the issue could be circumvented by making sure allowFontScaling=false for relevant Views holding text.
unknown
d12839
train
Try to apply one-hot enconde to your labels before to train.. from sklearn.preprocessing import LabelEncoder mylabels= ["label1", "label2", "label2"..."n.label"] le = LabelEncoder() labels = le.fit_transform(mylabels) and then try to split your data: from sklearn.model_selection import train_test_split (x_train, x_test, y_train, y_test) = train_test_split(data, labels, test_size=0.25) now probably your labels will be encoded with numbers which is good to train a machine learning algorithm.
unknown
d12840
train
keys will give you those keys. sub max_gate_order { my ($gates_info) = @_; my $max_order; my @gates; for my $gate_type (keys %{ $gates_info->{order} }) { for my $gate_id (keys %{ $gates_info->{order}{$gate_type} }) { my $order = $gates_info->{order}{$gate_type}{$gate_id}; $max_order //= $order; if ($order >= $max_order) { if ($order > $max_order) { $max_order = $order; @gates = (); } push @gates, $gate_id; } } } return @gates; } my @gates = max_gate_order(\%gates_info); The above returns all the gates with the highest order. If you want both the gate type and the gate id, replace push @gates, $gate_id; with push @gates, [ $gate_type, $gate_id ]; or push @gates, [ $gate_type, $gate_id, $order ]; A: This is a longer, more redundant solution, more of an exercise really. But you might find it interesting to examine the structure of the hash iteration this way. (I know I do!) This could be useful if you only have the main hash name (%gates_info), and none of the keys under that. Which is what your question implies is the case. This pulls out all the key and value names as deep as the hash goes, in case any of those might be useful. (Note this does require knowing how many levels deep your hash is.) #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %gates_info=( 'order' => { 'nand' => { 'nand2_1' =>2, 'nand2_5' =>-1, 'nand2_4' =>2, 'nand2_6' =>-1, 'nand2_2' =>2, 'nand2_3' =>3 }, 'and' => { 'and2'=>1, 'and3'=>2, }, } ); print Dumper %gates_info; print "\n\n"; my @gate; my $hival; foreach my $gate (sort keys %gates_info) { foreach my $gatekey (sort keys %{$gates_info{$gate}}) { foreach my $deepkey (sort keys %{$gates_info{$gate}{$gatekey}}) { my $deepvalue = $gates_info{$gate}->{$gatekey}->{$deepkey}; push @gate, $deepvalue; @gate = sort @gate; $hival = $gate[@gate - 1]; print "Gate is $gate, gatekey is $gatekey, deepkey is $deepkey, deepvalue is $deepvalue\n"; } print "\nGatekey is $gatekey, highest value is $hival\n\n"; @gate = (); #empty gate array } } exit 0; The output of the code is: $VAR1 = 'order'; $VAR2 = { 'and' => { 'and2' => 1, 'and3' => 2 }, 'nand' => { 'nand2_3' => 3, 'nand2_6' => -1, 'nand2_4' => 2, 'nand2_5' => -1, 'nand2_2' => 2, 'nand2_1' => 2 } }; Gate is order, gatekey is and, deepkey is and2, deepvalue is 1 Gate is order, gatekey is and, deepkey is and3, deepvalue is 2 Gatekey is and, highest value is 2 Gate is order, gatekey is nand, deepkey is nand2_1, deepvalue is 2 Gate is order, gatekey is nand, deepkey is nand2_2, deepvalue is 2 Gate is order, gatekey is nand, deepkey is nand2_3, deepvalue is 3 Gate is order, gatekey is nand, deepkey is nand2_4, deepvalue is 2 Gate is order, gatekey is nand, deepkey is nand2_5, deepvalue is -1 Gate is order, gatekey is nand, deepkey is nand2_6, deepvalue is -1 Gatekey is nand, highest value is 3 A: sub max_gate_order { my %hash =(); foreach my $k (keys %{$gates_info{'order'}}) { my @arr = (sort {$a <=> $b} values %{$gates_info{'order'}->{$k}}); $hash{$k} = $arr[-1]; } return \%hash; }
unknown
d12841
train
Use arrayformula and you won't have to drag anything. Try: =arrayformula(transpose('Form responses 1'!A$1:BB$4))
unknown
d12842
train
You need to use the silent option of regsrv32 (/s): Syntax REGSVR32 [/U] [/S] [/N] /I:[CommandLine] DLL_Name Key /u Unregister Server. /s Silent, do not display dialogue boxes. /i Call DllInstall to register the DLL. (when used with /u, it calls dll uninstall.) /n Do not call DllRegisterServer, you must use this option with /i. CommandLine An optional command line for DllInstall /c Console output (old versions only).
unknown
d12843
train
That's not how to use helpers Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2] Fatal error: Call to a member function flash() on a non-object in login.ctp Whilst it's not in the question your login.ctp template looks something like this: <?php echo $session>flash(); # line 2 That's not how helpers are expected to be used in CakePHP 2.x: you can use [the helper] in your views by accessing an object named after the helper: <!-- make a link using the new helper --> <?php echo $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5'); ?> The code you're looking for is: # echo $session->flash(); # wrong echo $this->Session->flash(); # right Note also that Session needs to be in the controller $helpers array. In 1.2 and earlier versions of CakePHP helpers were expected to be variables, this changed but was still supported in 1.3. If your 1.3 CakePHP application has been using helpers in this way, it has been relying on backwards-compatibility with earlier versions. In 2.0 helpers are not variables, and only possible to access as a view class property. Be sure to read the migration guides - for more information on what has changed.
unknown
d12844
train
There're two ways (or more?). Rendering with PHP or JavaScript. With PHP at view For example, using foreach ($itemset1 as $item) probably what you want. <div> <header> <h3>Mylist</h3> </header> <ul> <?php foreach ( $itemset1 as $item ) { ?> <li><?php echo $item ?></li> <?php } ?> </ul> </div> With JavaScript In this case, I'm using AngularJS for rendering data. Assuming you have known what AngularJS is and have been prepared for that. <div> <header> <h3>Mylist</h3> </header> <ul> <li ng-repeat="item in itemset1">{{ item }}</li> </ul> </div> Of course, If you like, jQuery is also a good choice for you. But hate the jQuery append expression. And it's inconvenient. See that reference: PHP: foreach - Manaual AngularJS: API: ngRepeat A: Sure but now i have to write <div> <header> <h3>Mylist</h3> </header> <ul> <li ng-repeat="item in itemset1">{{ item }}</li> </ul> </div> <div> <header> <h3>Mylist</h3> </header> <ul> <li ng-repeat="item in itemset2">{{ item }}</li> </ul> </div> Any way that i can avoid writing twice all of this div,header,ul,li elements?
unknown
d12845
train
I'm not sure what you want exactly, but in singleton pattern I prefer make a main class like GameManager and set it as a singleton class by using this piece of code: static GameManager _instance; public static GameManager instance { get { if (!_instance) { _instance = FindObjectOfType<GameManager>(); } return _instance; } } Or the piece of code that you wrote, after that define variables according to other sub managers type and access to them by GameManagersingleton. For example: public BulletManager myBulletManager; and use it like this: GameManager.instance.myBulletManager.Fire();
unknown
d12846
train
Your constructor now returns another constructor function, not an object. Return an instance of that constructor instead: // module.exports = { let moduleExports = { Editor_Theme: function(data) { var _themeData = JSON.parse(data) var _titlebar_color = _themeData.titlebar_color var _background_color = _themeData.background_color const Func = function() {} Func.prototype = { getTitlebarColor: function() { return _titlebar_color }, getBackgroundColor: function() { return _background_color }, setTitlebarColor: function(titlebarColor) { _titlebar_color = titlebarColor || _titlebar_color } } Object.freeze(Func) Object.freeze(Func.prototype) return new Func() //Instantiate constructor } } // const editor_theme = require('./editor-theme.js') const editor_theme = moduleExports let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}') defaultTheme.setTitlebarColor('888888') console.log(defaultTheme.getTitlebarColor()) Or even better, just Object.create an object with a custom prototype: // module.exports = { let moduleExports = { Editor_Theme: function(data) { var _themeData = JSON.parse(data) var _titlebar_color = _themeData.titlebar_color var _background_color = _themeData.background_color const prototype = { getTitlebarColor: function() { return _titlebar_color }, getBackgroundColor: function() { return _background_color }, setTitlebarColor: function(titlebarColor) { _titlebar_color = titlebarColor || _titlebar_color } } Object.freeze(prototype) return Object.create(prototype) //Object with custom prototype } } // const editor_theme = require('./editor-theme.js') const editor_theme = moduleExports let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}') defaultTheme.setTitlebarColor('888888') console.log(defaultTheme.getTitlebarColor())
unknown
d12847
train
Move HTML outpout after to session_start function. <?php session_start(); ?> <!DOCTYPE html> A: You can't try to set a cookie (which is done in response headers) after you have started to make output to the page (which starts on your first line of code).
unknown
d12848
train
The usual approach is to start protractor in a debug mode and put browser.debugger() breakpoint before the problem block of code. See more information at Debugging Protractor Tests. On the other hand, you can catch the chromedriver service logs that look like: [2.389][INFO]: COMMAND FindElement { "sessionId": "b6707ee92a3261e1dc33a53514490663", "using": "css selector", "value": "input" } [2.389][INFO]: Waiting for pending navigations... [2.389][INFO]: Done waiting for pending navigations [2.398][INFO]: Waiting for pending navigations... [2.398][INFO]: Done waiting for pending navigations [2.398][INFO]: RESPONSE FindElement { "ELEMENT": "0.3367185448296368-1" } Might also give you a clue of what is happening. For this, you need to start chrome with --verbose and --log-path arguments: { browserName: "chrome", specs: [ "*.spec.js" ], chromeOptions: { args: [ "--verbose", "--log-path=/path/to/the/log/file" ] } } (not tested) For firefox, you can turn on and view logs by setting webdriver.log.driver and webdriver.log.file firefox profile settings. See also: * *Monitoring JSON wire protocol logs *How to change firefox profile
unknown
d12849
train
Create another overload, taking Action instead of Func<T>: public static class DummyClassName { public static void DummyTemplateFunc(DummyInterfaceName aaa1, Action action) { // you cannot assign result to variable, because it returns void action(); // I also changed method to return void, so you can't return anything // return something; // ofc you can make it return something instead } }
unknown
d12850
train
There are both "account" and "Account" types in state package, which seems weird. There is a meaningful difference between these two names in the language specification. From the Go Language Specification: An identifier may be exported to permit access to it from another package. An identifier is exported if both: * *the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and *the identifier is declared in the package block or it is a field name or method name. All other identifiers are not exported. So, taking a closer look at the go-ethereum codebase, here are my observations: * *type account in managed_state.go is an internal implementation detail, providing a type for the accounts field in the exported ManageState struct *type Account in state_object.go is an exported identifier I think the implementation choice make more sense when you look at the generated documentation. In particular, the Account type is front and center, detailing a data structure that's of interest to consumers of the package. When you look at the documentation for the ManageState struct, the unexported fields are purposely not documented. This is because they're internal details that don't impact the exported interface and could easily be changed without impacting users of the package. In regards to naming recommendations, see the Names section in Effective Go.
unknown
d12851
train
Please use a more recent D compiler. You can download the latest version of the reference D compiler from http://dlang.org/download.html, or you can compile and run a D program online on http://dpaste.dzfl.pl/. A: It works perfectly fine with a recent compiler. If you're using ideone.com to test this, then that's bound to be your problem. 2.042 is years old now, and it's highly likely that the functionality that you're trying to use was added since then. Looking at the documentation that came with the zip file for 2.042, the documentation for std.format has changed dramatically since then. So, I'd say that the problem is that you're using what is effectively an ancient compiler version. ideone.com hasn't updated their D compiler in years, making them a horrible site to test D code on, especially if it's functionality in the standard library that you're testing out rather than the language itself. If you want to try compiling D code online, I'd suggest that you try out dpaste. It actually has an up-to-date D compiler, because it's designed specifically for compiling D code examples online.
unknown
d12852
train
r = requests.get(url) pat = re.search(regex, r.text)
unknown
d12853
train
Re 1: Please dump value of 'verticaltext', with it you can create a static slider to see why there is an empty slide. Re 2: Please use $StartIndex option var options = { ..., $StartIndex: 0, //specify slide index to display at the beginning. ... };
unknown
d12854
train
Basically, you need any mode of determining that you have already stored the information of this user. DB, session, or even the auth()->user() object(this one depends on the use case) can store this data. Take an example of session: Broadcast::channel('chat', function ($user) { $ip = Request::ip(); $time = now(); if (auth()->check() && !session()->has('user_id')){ UserInfo::storeUser(); session()->put('user_id',$user->id); return [ 'id' => $user->id, 'ip' => $ip, 'name' => $user->name, 'joined' => $time ]; } }); and on logout: session()->forget('user_id') Bear in mind, this is a basic example without much context.
unknown
d12855
train
navLinkDayClick in FullCalendar v3.8 - navLinks: true, navLinkDayClick: function (date) { selectedDate = date.format("DD-MMM-YYYY"); selectedAmountEvent = amounts.find(item => item.paymentDate.format("DD-MMM-YYYY") === selectedDate); var $AmountData = $('<div/>'); $AmountData.append($('<p/>').html('<b>Payment Date: </b>' + selectedAmountEvent.paymentDate.format("DD-MMM-YYYY"))); if (selectedAmountEvent.totalAmount < 0) { $AmountData.append($('<p/>').html('<b style="color:red;">Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + '</b >')); } else { $AmountData.append($('<p/>').html('<b style="color:green;">Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + '</b >')); } $('#eventModal #AmountDetails').empty().html($AmountData); $('#eventModal').modal(); } amounts is an array holding the data.
unknown
d12856
train
I see that you have twitterTemplate bean configured, if you are able to use it in the application you won't need to do anything else. Use TwitterTemplate instead of Twitter. TwitterTemplate implements Twitter interface, so all methods are available. Examples: //1. Search Twitter SearchResults results = twitterTemplate.searchOperations().search("#WinterIsComing"); List<Tweet> tweets = results.getTweets(); int i =0; for (Tweet tweet : tweets) { System.out.println(tweet.getUser().getName() + " Tweeted : "+tweet.getText() + " from " + tweet.getUser().getLocation() + " @ " + tweet.getCreatedAt() + tweet.getUser().getLocation() ); } //2. Search Place by GeoLocation RestTemplate restTemplate = twitterTemplate.getRestTemplate(); GeoTemplate geoTemplate = new GeoTemplate(restTemplate, true, true); List<Place> place = geoTemplate.search(37.423021, -122.083739); for (Place p : place) { System.out.println(p.getName() + " " + p.getCountry() + " "+p.getId()); } //3. Get Twitter UserProfile TwitterProfile userProfile = twitterTemplate.userOperations().getUserProfile(); System.out.println(userProfile.getName()+" has " +userProfile.getFriendsCount() + " friends"); Using TwitterTemplate, users don't need to login. Hope this helps!
unknown
d12857
train
This looks like some sort of rounding issue, the result in D3 is deemed to be very slightly below the actual value shown - try using ROUND function in column D, e.g. =ROUND((C3-DATE(1970,1,1))*86400,0)
unknown
d12858
train
You must make your render windows to render offline like this: renderWindow->SetOffScreenRendering( 1 ); Then use a vtkWindowToImageFilter: vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter = vtkSmartPointer<vtkWindowToImageFilter>::New(); windowToImageFilter->SetInput(renderWindow); windowToImageFilter->Update(); This is called Offscreen Rendering in VTK. Here is a complete example A: You can render the image offscreen as mentioned by El Marce and then convert the image to OpenCV cv::Mat using unsigned char* Ptr = static_cast<unsigned char*>(windowToImageFilter->GetOutput()->GetScalarPointer(0, 0, 0)); cv::Mat RGBImage(dims[1], dims[0], CV_8UC3, Ptr);
unknown
d12859
train
You need to use guild.iconURL().
unknown
d12860
train
class Base: pass class Target(Base): def __init__(self, name: str): self.name = name def __repr__(self): return "{}({})".format(type(self).__name__, repr(self.name)) class Adapter(Target): def __new__(cls, adaptee: Base, name: str): if isinstance(adaptee, Target): return adaptee else: return super().__new__(cls) def __init__(self, adaptee: Base, name: str): super().__init__(name=name) self.adaptee = adaptee print(Adapter(Base(), "a")) # Adapter('a') print(Adapter(Target("b"), "c")) # Target('b')
unknown
d12861
train
in this link View Android Developer there is a section on implementing a custom view onDraw(Canvas canvas) is called whenever a view should render its content if you define to use this view in your layout xml or even in code you can specify the attributes android:layout_width= android:layout_height= and those attributes will be applied to the size that the view will use in your layout.xml <your.package.name.extendedviewclass android:layout_width="100dp" android:layout_height="100dp"/>
unknown
d12862
train
Consider an SQL solution using UNION queries to select each column for long format. If using Excel for PC, Excel can connect to the Jet/ACE SQL Engine (Windows .dll files) via ADO and run SQL queries on worksheets of current workbook. With this approach, you avoid any for looping, nested if/then logic, and other data manipulation needs for desired output. Below example assumes data resides in tab called DATA and an empty tab called RESULTS. Sub RunSQL() Dim conn As Object, rst As Object Dim strConnection As String, strSQL As String Dim i As Integer Set conn = CreateObject("ADODB.Connection") Set rst = CreateObject("ADODB.Recordset") ' CONNECTION STRINGS (TWO VERSIONS) ' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _ ' & "DBQ=C:\Path\To\Workbook.xlsm;" strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _ & "Data Source='C:\Path\To\Workbook.xlsm';" _ & "Extended Properties=""Excel 8.0;HDR=YES;"";" strSQL = " SELECT 'AUS' AS COUNTRY, AUS AS RETURNS, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'UK', UK AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'USA', USA AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'GERMANY', GERMANY AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'FRANCE', FRANCE AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'MEXICO', MEXICO AS Country, [DATE] FROM [DATA$];" ' OPEN CONNECTION & RECORDSET conn.Open strConnection rst.Open strSQL, conn ' COLUMN HEADERS For i = 1 To rst.Fields.Count Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name Next i ' DATA ROWS Worksheets("RESULTS").Range("A2").CopyFromRecordset rst rst.Close: conn.Close Set rst = Nothing: Set conn = Nothing End Sub Output COUNTRY RETURNS DATE AUS R1 1 AUS R2 2 UK R1 1 UK R2 2 USA R1 1 USA R2 2 GERMANY R1 1 GERMANY R2 2 FRANCE R1 1 FRANCE R2 2 MEXICO R1 1 MEXICO R2 2 A: Okay, I fixed it. Probably not the best code, but it works :). Sub replicate_dates() 'declare variables Dim i As Double Dim j As Double Dim reps As Integer Dim country As String Dim strfind As String Dim obs As Integer 'set strfind value strfind = "-DS Market" 'count the number of countries reps = Range("D1:AL1").Columns.Count 'count the number of observations per country obs = Range("C4:C5493").Rows.Count i = 0 'copy and paste country into panel format For k = 1 To reps 'set country name and clean string country = Replace(Range("D1").Cells(1, k), strfind, "") For j = i + 1 To obs + i 'copy and paste country values Range("AS5").Cells(i, 1) = country i = 1 + i Next j Next k End Sub Edit: Nvm, this fails to work outside a very specific case.
unknown
d12863
train
I think you are confusing “value type” with “immutable type”. You actually want your ResourceVector to be an immutable type. An immutable type is one that has no way to change its contents. Once constructed, an instance retains its value until it is garbage-collected. All operations such as addition return a new instance containing the result instead of modifying an existing instance. string is the most well-known immutable class. All operations like Substring and Replace return a new string and don’t modify the existing strings. Once your type is properly immutable, semantically it doesn’t matter so much anymore whether it is a value type or a reference type — but it matters to the performance. If you pass values around a lot, you should probably make it a reference type in order to avoid a lot of unnecessary copying.
unknown
d12864
train
[expr.post.incr]/1 ... The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. —end note ]... My reading of this is that the side effects of a++ and b++ must complete before the body of f is executed, and therefore within f it must be that a==1 and b==1. Your examples #2 and #3 are not possible with a conforming implementation. A call to g is indeterminately sequenced with a call to f, and thus can observe either pre-increment or post-increment values. A: f(a++, b++) + g(); Compiler can decide the order of execution of f() and g() in the above statement. These are only 2 possibilities not 3. Either f() will call first and modifies variables a and b OR g() will get call first.
unknown
d12865
train
I believe you're hitting https://github.com/docker/fig/issues/447 If you added VOLUME to the Dockerfile at one point, you keep getting the contents of that volume when you recreate. You should fig rm --force to clear out the old containers, after that it should start working and using the host volumes.
unknown
d12866
train
You should use a form. But how to make it pretty? With JavaScript you can have a kind of front-end for the form. Hide the form elements and have some JS that changes the form field values on interaction. Search for pretty forms jquery in Google. A: From what I understand is that you don't want to manually get the value of each element that has the class 'on'. You could use jQuery's each function looping through all the elements you need. Something like: ​var query = ""; $(".on")​​.each(function(i){ if(i === 0) { query+="?"+$(this).attr('id')+"="+$(this).text(); } else { query+="&"+$(this).attr('id')+"="+$(this).text(); } }); (see: http://jsfiddle.net/MkbrV/) Is this something you are looking for? A: You could use jQuery's serialize() method: $('form .on').serialize(); jsFiddle example
unknown
d12867
train
There is no such event in WinAPI, but you may track it yourself. wParam of all button down/up messages contains information of the state of all buttons at the time of event: MK_LBUTTON 0x0001 The left mouse button is down. MK_MBUTTON 0x0010 The middle mouse button is down. MK_RBUTTON 0x0002 The right mouse button is down. Thus, you need to keep the track of changes and define a threshold that will filter out all events that you like to consider as a "simultaneous click/release" A: You will need to write your own method of handling this. Record when the first button was clicked, when the other button is clicked see if the first button is still down and if the delay is less than whatever delta you've supplied. A: If GetAsyncKey(0x01) && GetAsyncKey(0x02){ DoEvent(); }
unknown
d12868
train
.getData() returns the ABI-encoded input you would have to send to the smart contract to invoke that method. If you want to actually call the smart contract, use .call() instead.
unknown
d12869
train
You can get the edge coordinates by using numpy library: xAxis, yAxis = np.nonzero(edges) In here xAxis and yAxis include all the x and y axis respectively belong to the edge which canny detected. You can also simply calculate the average of these coordinates which mean the center of detected edge coordinates: centerX = int(np.mean(xAxis)) centerY = int(np.mean(yAxis)) Here is the whole code: import numpy as np import cv2 as cv from matplotlib import pyplot as plt from numpy.core.defchararray import center img = cv.imread('/home/yns/Downloads/st.jpg',0) edges = cv.Canny(img,100,200) xAxis, yAxis = np.nonzero(edges) centerX = int(np.mean(xAxis)) centerY = int(np.mean(yAxis)) cv.circle(img,(centerX,centerY),5,(0,255,255),3) plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(edges,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.show()
unknown
d12870
train
use the below code.. and let me know the feedback. To show the text, handler is not needed. /** The m handler. */ private Handler mHandler; /** The hello btn. */ private Button helloBtn; /** The hello text. */ private TextView helloText; /** The msg hello. */ private final int MSG_HELLO = 2; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); helloBtn = (Button) findViewById(R.id.btn_hello); helloBtn.setOnClickListener(this); helloText = (TextView) findViewById(R.id.txt_hello); mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_HELLO: helloText.setText("hello world"); break; } } }; } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ public void onClick(View view) { if (view.getId() == R.id.btn_hello) { Message msg = new Message(); msg.what = MSG_HELLO; mHandler.sendMessage(msg); } } A: The class Message has a field "target" which is used to store the handler that you used to send message. When you call a Handler's sendMessage(msg) method, the reference of the handler will be stored in the message. When the Looper dispatch your message it'll call msg.target.dispatchMessage(msg), which means that your msg will be dispatched to the same handler that you used to send it. The method dispatchMessage(msg) will call handleMessage(msg) eventually. You can use a BroadcastReceiver to solve your problem. Register a BroadcastReceiver in the Activity that you want to update in the future, and send a Broadcast to it from the other part of you app.
unknown
d12871
train
One way to implement this is to calculate the total whenever input ng-changes: var sum = function(acc,cur){ return acc+cur; } $scope.modelChanged = function(section, input){ var inputsCount = section.sectionInputs.length; var totalInput = section.sectionInputs[inputsCount-1]; if(input === totalInput){ return; } var total = section.sectionInputs.slice(0, inputsCount - 1).map(function(input){ return $scope.model[input.model]; }).filter(angular.isDefined).reduce(sum, 0); $scope.model[totalInput.model] = total; }; Which can then be invoked on each input: <input ng-model="model[input.model]" ng-change="modelChanged(section, input)" type="number" /> Here's an updated plunker. A: Well, I have solved it with jQuery, maybe this answer doesn't fit you because it's inconsistent with your angular app, but I hope it can be helpful to someone else. $(document).on("change", "input", function() { $tr = $(this).parent().parent(); $tds = $tr.find("td"); var sum = 0; $.each($tds, function(index, td){ var valueInput = $(td).find("input").val(); if(index < 9 ){ sum += parseFloat((valueInput != "") ? valueInput : 0 ); } }); $tds.eq(9).find("input").val(sum); }); Here is the updated plunker
unknown
d12872
train
It is not possible to filter only the current page. If you have a look at the Row Management Pipeline Documentation you will see that Tabulator first filters data and then paginates the data that passes the filter. In order to do this you would need to filter data outside of the table and then paginate it.
unknown
d12873
train
Usually, PTZ functions are software implemented on the server running in the cam. Some older cameras used to ship with an activeX control. These functions can be accessed by getting or posting to a url relative to the camera. For Your camera, you should be able to post the controls on the following url: http://<ip>/pantiltcontrol.cgi Available controls: POST parameters PanSingleMoveDegree (default 5) TiltSingleMoveDegree (default 5) PanTiltSingleMove Values for PanTiltSingleMove (based on the web UI controls): Top 1 Top right 2 Right 5 Bottom right 8 Bottom 7 Bottom left 6 Left 3 Top left 0 Home (reset) 4 So a typical post example using curl to change the pan-tilt, should be similar to this: curl --user <username>:<password> --user-agent "user" --data "PanSingleMoveDegree=5&TiltSingleMoveDegree=5&PanTiltSingleMove=5" http://<ip>/pantiltcontrol.cgi For a quick test using your web browser, You should Be able to do the same thing using a get request for the following structured url: http://<username>:<password>@<ip>/pantiltcontrol.cgi?PanSingleMoveDegree=5&TiltSingleMoveDegree=5&PanTiltSingleMove=5 Now, Back to your question. All you need to control PTZ in C++, is to web query the mentioned urls. So this should be your searching point. Many Answers for this topic are already on stack overflow. This is the first result I got while googling "c++ http get post". How do you make a HTTP request with C++?
unknown
d12874
train
You might not have to compile to .class to achieve your goal, you can compile the xsl once per run and re-use the compiled instance for all transformations. To do so you create a Templates object, like: TransformerFactory factory = TransformerFactory.newInstance(); factory.setErrorListener(new ErrorListener( ... )); xslTemplate = factory.newTemplates(new StreamSource( ... )); and use the template to get a transformer to do the work: Transformer transformer = xslTemplate.newTransformer(); Depending on the XSL library you use your mileage may vary. A: You'll need a Template and a stylesheet cache: http://onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=9 Do be careful about thread safety, because Transformers aren't thread safe. Best to do your transformations in a ThreadLocal for isolation. A: Consider using Gregor/XSLT compiler
unknown
d12875
train
Here are the steps I took to get it to work. I started with a new cli application. npm install --save jquery jstree npm install --save-dev @types/jquery @types/jstree I then updated the angular.json file, if you are using an older version of angular-cli, makes changes to the angular-cli.json file. I added "../node_modules/jstree/dist/themes/default-dark/style.min.css" to the styles property array. I also added two items into the scripts property array: "../node_modules/jquery/dist/jquery.min.js", "../node_modules/jstree/dist/jstree.min.js" I then updated src/app/app.component.html to <div id="foo"> <ul> <li>Root node 1 <ul> <li>Child node 1</li> <li><a href="#">Child node 2</a></li> </ul> </li> </ul> </div> I also update src/app/app.component.ts to import { Component, OnInit } from '@angular/core'; declare var $: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(): void { $('#foo').jstree(); } } Hope this helps! A: @IamStalker, it seems that i know what the problem is. But can you present more code to show how you want to use it? As jstree depends on jQuery, you have to import it too. You may have to use scripts config. Here is the reference: https://github.com/angular/angular-cli/wiki/stories-global-scripts.
unknown
d12876
train
Assuming you meant the Spirit version ("as a one liner"), below is an adapted version that adds the check for number of elements. Should you want more control (and on the fly input checking, instead of 'in hindsight') then I recommend you look at another answer I wrote that shows three approaches to do this: * *Boost::Spirit::QI parser: index of parsed element . #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <boost/spirit/include/karma.hpp> namespace spirit = boost::spirit; namespace qi = boost::spirit::qi; namespace karma = boost::spirit::karma; int main() { std::cin.unsetf(std::ios::skipws); spirit::istream_iterator b(std::cin), e; std::vector<std::vector<int> > vectors; if (qi::phrase_parse(b, e, +qi::int_ % qi::eol >> qi::eoi, qi::blank, vectors)) { std::cerr << "Parse failed at '" << std::string(b,e) << "'\n"; return 255; } // check all rows have equal amount of elements: const auto number_of_elements = vectors.front().size(); for (auto& v : vectors) if (v.size() != number_of_elements) std::cerr << "Unexpected number of elements: " << v.size() << " (expected: " << number_of_elements << ")\n"; // print the data for verification std::cout << karma::format(karma::right_align(8)[karma::auto_] % ',' % '\n', vectors) << std::endl; return 0; } The karma bits are not necessary (they're just there to output the whole thing for demonstration). UPDATE To build in more active error checking, you could do: int num_elements = 0; bool ok = qi::phrase_parse(b, e, (+qi::int_) [ phx::ref(num_elements) = phx::size(qi::_1) ] >> *(qi::eol >> qi::repeat(phx::ref(num_elements)) [ qi::int_ ]) >> *qi::eol, qi::blank, vectors); Which uses qi::repeat to expect the num_elements number of elements on subsequent lines. You can just store that into a 1-dimensional array: #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <boost/spirit/include/karma.hpp> namespace qi = boost::spirit::qi; namespace phx = boost::phoenix; namespace karma = boost::spirit::karma; int main() { std::cin.unsetf(std::ios::skipws); boost::spirit::istream_iterator b(std::cin), e; //std::vector<std::vector<int> > vectors; std::vector<int> vectors; int num_elements = 0; bool ok = qi::phrase_parse(b, e, (+qi::int_) [ phx::ref(num_elements) = phx::size(qi::_1) ] >> *(qi::eol >> qi::repeat(phx::ref(num_elements)) [ qi::int_ ]) >> *qi::eol, qi::blank, vectors); std::cout << "Detected num_elements: " << num_elements << "\n"; if (!ok) { std::cerr << "Parse failed at '" << std::string(b,e) << "'\n"; return 255; } if (b!=e) std::cout << "Trailing unparsed: '" << std::string(b,e) << "'\n"; // print the data for verification std::cout << karma::format_delimited(karma::columns(num_elements)[+karma::int_], ' ', vectors) << std::endl; return 0; } Note the use of karma::columns(num_elements) to split the output into the correct number of columns per row.
unknown
d12877
train
In this particular case, it appears that I needed just one slight tweak when building the context. It's not so obvious but it kinda makes sense in the context of the problem encountered Context.newBuilder().engine(engine).allowAllAccess(true).build()
unknown
d12878
train
Solved On line 62 in the gist, I was hitting the wrong resource. The correct resource is https://graph.microsoft.com
unknown
d12879
train
Just use the JsonConvert.DeserializeType overload that accepts a type parameter instead of the generic one: public object GetData(Type t,Uri uri, HttpStatusCode expectedStatusCode) { .... return JsonConvert.DeserializeObject(responseString,t); } This is a case of the XY problem. You want to deserialize arbitrary types (problem X) and think that somehow, you need pass a generic type at runtime (problem Y), so when you get stuck ,you ask about Y.
unknown
d12880
train
I recommend keeping sequence mode off, like you did for the two pages, and lay out the entire sequence (in pairs) that way. You should then create your own next/previous buttons and use viewer.viewport.fitBounds to animate the viewer to each pair as needed. Here's an example of a system that does something like that (plus a lot more): https://iangilman.com/osd/test/demo/m2/ Press the "book" button at the top to see the "two-page" mode. The code for this is here: https://github.com/openseadragon/openseadragon/tree/master/test/demo/m2 Of course you don't need all of that code, but hopefully it can be a helpful reference.
unknown
d12881
train
At least these problems: Code is assigning = when it should compare ==. // if (randOne = 1) if (randOne == 1) The last if () { ... } else { ... } will cause one of the 2 blocks to execute. OP wants an if () { ... } else if () { ... } else { ... } tree. // Problem code if (randOne = 3) { randOne = *(symbols+2); } else { randOne = *(symbols+3); } Suggest if (randOne == 1) { randOne = *symbols; } else if (randOne == 2) { randOne = *(symbols+1); } else if (randOne == 3) { randOne = *(symbols+2); } else { randOne = *(symbols+3); } Also research switch. switch (randOne) { case 1: randOne = *symbols; break; case 2: randOne = *(symbols+1); break; case 3: randOne = *(symbols+2); break; default: randOne = *(symbols+3); break; } Or consider a coded solution: randOne = *(symbols+(randOne-1)); But code needs to return a pointer to a string not an int and has no need to pass in randOne as a parameter. const char * slotOne(const char *symbols[]) { int randOne = rand() % 4; return symbols[randOne]; } Calling code also needs to adjust to receive a const char *, not an int. // int one; // one = slotOne(x); const char *one = slotOne(symbols);
unknown
d12882
train
You didn't specify the version of actionscript in use, so I'll assume you're using as3. You could * *use cue points embedded in the flv (added when creating the flv) *if you're using the FLVPlayer component, use cue points created with actionscript *use a regular Timer If you don't have access to the creating-the-flv-part, the simplest (and the most inaccurate, but I would assume that displaying a button doesn't need to be millisecond-level-accurate) solution would be number three. If the user has no control over the playback (i.e. pause, rewind) and the video isn't being streamed over network, just start/stop a timer with the playback. If the user can pause and rewind the video, you'll have to also stop and adjust the timer every time the user does so. If the video is being streamed over network, you'll have to take any buffering pauses into account, too. A: You can add cuepoint and listen for them with: _Player.AddEventListener(MetadataEvent.CUE_POINT, PlayerCuePoint); function PlayerCuePoint(e:MetadataEvent):void { _Button.visible = true; } Or you could check the progress like this: const BUTTON_TIME:Number = 10; //Time in seconds _Player.AddEventListener(VideoEvent.PLAYHEAD_UPDATE, PlayerPlayheadUpdate); function PlayerPlayheadUpdate(e:VideoEvent):void { if(_Player.playheadTime >= BUTTON_TIME) _Button.visible = true; }
unknown
d12883
train
fundamentally, you're setting yourself up for some race conditions (what if the folder already existed, &c). A better way to do this is creating a fresh folder before you run this script, then run it inside there. So: dir="$(mktemp aws-sync-XXXXX)" pushd "$dir" # do stuff popd rm -rf "$dir" That will ensure you delete everything your temporary command created, and nothing more.
unknown
d12884
train
There is no permission as android.permission.RECORD_VIDEO See here Ideally you should be using these permission <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> Also manifest should have <uses-feature android:name="android.hardware.Camera"/>
unknown
d12885
train
After a few attempts with changing a variety of parameters, I managed to solve the issue by simply changing the graph type to GAUGE. Seems to wrk pretty well now.
unknown
d12886
train
This part is circumstancial, but you get the idea. Give the values to the ones that are/aren't checked. if($checkboxone == '1') { $types = array( 'typeone' ) } if($checkboxtwo == '1') { $types = array( 'typetwo' ) } if($checkboxtwo == '1' && $checkboxone == '1'){ $types = array( 'typeone', 'typetwo' ) } then plug that value into your WP_Query by some means like this. the documentation for it is here // The Query $the_query = new WP_Query( array( 'post_type' => $types ); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); //DO STUFF endwhile; // Reset Post Data wp_reset_postdata();
unknown
d12887
train
Define a function that first check if the column exists in the dataframe. If the column does not exist, simply add it. In the case it already exists then use coalesce as before. This can be done as follows: def coalesceColumn(df: DataFrame, column: String, default: String) = { Try(df(column)).toOption match { case Some(_) => df.withColumn(column, coalesce(col(column), lit(default))) case _ => df.withColumn(column, lit(default)) } } val df2 = coalesceColumn(df, "Seq_num", "0") Note that it's possible to use df.columns.contains(column) to do the column check but in that case nested columns are not supported.
unknown
d12888
train
use .executemany to insert array of records as mentioned here my_trans = [] my_trans.append('car', 200) my_trans.append('train', 300) my_trans.append('ship', 150) my_trans.append('train', 200) sql_insert_query = 'INSERT INTO my_transport (transport, fee) VALUES (%s, %s)' cursor = connection.cursor() result = cursor.executemany(sql_insert_query, my_trans)
unknown
d12889
train
The name of a property's backing field is a compiler implementation detail and can always change in the future, even if you figure out the pattern. I think you've already hit on the answer to your question: ignore all properties. Remember that a property is just one or two functions in disguise. A property will only have a compiler generated backing field when specifically requested by the source code. For example, in C#: public string Foo { get; set; } But the creator of a class need not use compiler generated properties like this. For example, a property might get a constant value, multiple properties might get/set different portions of a bit field, and so on. In these cases, you wouldn't expect to see a single backing field for each property. It's fine to ignore these properties. Your code won't miss any actual data. A: You can ignore all properties completely. If a property doesn't have a backing field, then it simply doesn't consume any memory. Also, unless you're willing to (try to) parse CIL, you won't be able to get such mapping. Consider this code: private DateTime today; public DateTime CurrentDay { get { return today; } } How do you expect to figure out that there is some relation between the today field and the CurrentDay property? EDIT: Regarding your more recent questions: If you have property that contains code like return 2.6;, then the value is not held anywhere, that constant is embedded directly in the code. Regarding string: string is handled by CLR in a special way. If you try to decompile its indexer, you'll notice that it's implemented by the CLR. For these few special types (string, array, int, …), you can't find their size by looking at their fields. For all other types, you can. A: To answer your other question:Under what circumstances do properties not have backing fields? public DateTime CurrentDay { get { return DateTime.Now; } } or property may use any other number of backing fields/classes public string FullName { get {return firstName + " " + lastName;} }
unknown
d12890
train
user120242's solution worked for me ! animate(frameElapsed, points, canvas) { console.log("test"); if(frameElapsed < points.length - 1) { requestAnimationFrame(() => { this.animate(frameElapsed + 1, points, canvas); }); } ... } Thank you for your help !
unknown
d12891
train
After a quick look, Keith-wood countdown works as follows (example code they provide that works with your code): newYear = new Date(); var newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1); $('#defaultCountdown').countdown({until: newYear}); If I understand your question right, then you simply need to change the code at line 2: newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1); Since this sets the newYear variable to the date you want to count down to. So to set the date as per your question you simply need to properly set the JS constructor for the new Date on that line: new Date(year, month, day, hours, minutes, seconds, milliseconds) Hence if you are counting down to a launch at 10AM on the 15th December 2014 then you will just set it to: new Date(2014, 12, 15, 10, 0, 0, 0) If you want to know more about the basic set-up, not just changing the dates you can find that here on keith-wood's website. Hope that helps!
unknown
d12892
train
It is because lambda function captures variable by reference instead of value. So the correct manner is def create_learning_rate(global_step, lr_config): base_lr = lr_config.get('base_lr', 0.1) decay_steps = lr_config.get('decay_steps', []) decay_rate = lr_config.get('decay_rate', 0.1) prev = -1 scale_rate = 1.0 cases = [] for decay_step in decay_steps: cases.append((tf.logical_and(global_step > prev, global_step <= decay_step), lambda v=scale_rate: v)) scale_rate *= decay_rate prev = decay_step cases.append((global_step > decay_step, lambda v=scale_rate: v)) learning_rate_scale = tf.case(cases, lambda: 0.0, exclusive=True) return learning_rate_scale * base_lr
unknown
d12893
train
Try using any of the below Auth methods. 1st $user = User::create([ 'name' => $request->name, 'username' => $request->username, 'email' => $request->email, 'password' => Hash::make($request->password), ]); // here we're authenticating newly created user Auth::login($user); 2nd // newly created user email & password can be passed in an attempt function. Auth::attempt(['email' => $email, 'password' => $password]) 3rd $user = User::create([ 'name' => $request->name, 'username' => $request->username, 'email' => $request->email, 'password' => Hash::make($request->password), ]); // we can use loginUsingId like this Auth::loginUsingId($user->id);
unknown
d12894
train
Format for hosts file is #<ip> <hostname that resolve to the ip> 192.168.1.25 xyz.com # or a list of names 192.168.1.25 xyz.com myapp.xyz.com You do not put any port numbers or path parts in it. This will obviously only work if you edit the hosts file on all the computers you are indending to access the site from and not necessarily on the host running the application itself. That being said, you should probably read on supported Spring Boot properties because starting an application server on a specific port should be as easy as adding application.properties file in java resources with the following line: server.port=80
unknown
d12895
train
It is my understanding that you want the following css to only apply to children of .my_class. If so, please change your css to this: .my-class .sidebar .nav { width: 95%; } .my-class .sidebar-nav{ left: -200px; } .my-class .sidebar-nav.active{ left: 0; } Note that if you have any sidebar or sidebar-nav outside your my-class they won't be getting the above styles. Check out Specificity on MDN. A: .my-class .sidebar .nav { width: 95%; } .my-class .sidebar-nav{ left: -200px; } .my-class .sidebar-nav.active{ left: 0; }
unknown
d12896
train
An array is a contiguous bit of memory, calling a function like this: foo( ref bAarr[0], bArr.Length ); It passes two things: * *The address of the 1st element of the array, and *The number of elements in the array Your 3rd-party library is almost certainly a C/C++ DLL exposing a function signature along the lines of int foo( unsigned char *p, int len ); An array reference like arr[n] is [roughly] the equivalent of the following pseudocode: * *let p be the address of arr *let offset be n multiplied by the size in octets of the array's underlying type *let pElement be p + offset, the address of element n of array arr. pElement, when dereferenced, gives you the value of arr[n]. A: @Nicholas explained how it happens but if you want to do the same thing in the c# check the bellow code: I don't recommend using it, just for satisfying curiosity: void Main() { byte[] bArr = new byte[100]; // fill the entire array without passing it to method FillEntireArray(ref bArr[0], bArr.Length); // read the entire array without passing it to method ReadEntireArray(ref bArr[0], bArr.Length); } public unsafe void FillEntireArray(ref byte pByte, int length) { fixed (byte* ptr = &pByte) { byte* p = ptr; for (int i = 0; i < length; i++) { // set a new value to pointer *p = ((byte)(i)); // move pointer to next item p++; } } } public unsafe void ReadEntireArray(ref byte pByte, int length) { fixed (byte* ptr = &pByte) { byte* p = ptr; for (int i = 0; i < length; i++) { // Print the value of *p: Console.WriteLine($"Value at address 0x{(int)p:X} is {p->ToString()}"); // move pointer to next item p++; } } } A: shorter form: public unsafe void FillArray(ref byte arr, int length) { fixed (byte* ptr = &arr) { for (byte i = 0; i<length; i++) { *(ptr + i) = i; } } }
unknown
d12897
train
Try using a logarithmic scale. plot(ratioxy,type='l',col='blue')
unknown
d12898
train
Arrays are 0-indexed instead of one. foreach (DeArtIzm izm in colRindas) { objectData[i, 0] = izm.ArtCode; objectData[i, 1] = izm.ArtName; objectData[i, 2] = izm.Price; objectData[i, 3] = izm.RefPrice; i++;//Place where I get that error } A: in C#, Arrays are Zero-based by default (i.e. The first element has the index 0). So you need to start with objectData[i, 0], and end with objectData[i, 3].
unknown
d12899
train
According to Javascript documentation, assigning values means reading and writing to memory that is already allocated. When you assign a variable, memory is allocated. When you change its value, reading and writing is done on the same memory location.
unknown
d12900
train
Some sample data would be helpful to help design the queries. In principal you would need to join the tables together to get the desired result. You would join the productID on tblOrders to the ProductID on tblProducts. This will net you the name of the product etc. This would be an INNER join, as every order has a product. You would then join to tblSpareParts, also using the productID so that you could return the status of the spare parts for that product. This might be a LEFT JOIN instead of an INNER, but it depends on if you maintain a value of 0 for spare parts (e.g. Every product has a corresponding spare parts record), or if you only maintain a spare parts record for items which have spare parts.
unknown