text
stringlengths
64
81.1k
meta
dict
Q: Creating "cylinder with bottom" node shape in TikZ/PGF How to create custom TikZ node "cylinder with bottom", where hidden line in cylinder bottom is shown using dashed line. Something like the following creation, except node center should be in the middle of cylinder (as if it was in the middle of the center of 3D cylinder), not in center of the side -- it looks imbalanced https://www.writelatex.com/1149537sksqzs#/2737083/ \documentclass[tikz]{standalone} \usepackage{tikz} \usetikzlibrary{shapes.geometric,calc} \begin{document} \begin{tikzpicture} \node[cylinder,draw=black,thick,aspect=0.7, minimum height=1.7cm,minimum width=1.5cm, shape border rotate=90, cylinder uses custom fill, cylinder body fill=red!30, cylinder end fill=red!10] (A) {A}; \draw[dashed] let \p1 = ($ (A.after bottom) - (A.before bottom) $), \n1 = {0.5*veclen(\x1,\y1)}, \p2 = ($ (A.bottom) - (A.after bottom)!.5!(A.before bottom) $), \n2 = {veclen(\x2,\y2)} in (A.before bottom) arc [start angle=0, end angle=180, x radius=\n1, y radius=\n2]; \end{tikzpicture} \end{document} A: As Tarass correctly guessed, it is a problem of line width, but it affects both to the arc radius and to the initial point (A.before bottom). This is a possible fix: \documentclass[tikz]{standalone} \usepackage{tikz} \usetikzlibrary{shapes.geometric,calc} \title{TikZ: cylinder with bottom - example} \begin{document} \begin{tikzpicture} \node[cylinder,draw=black,thick,aspect=0.7,minimum height=1.7cm,minimum width=1.5cm,shape border rotate=90,cylinder uses custom fill, cylinder body fill=red!30,cylinder end fill=red!10] (A) {A}; \draw[dashed] let \p1 = ($ (A.after bottom) - (A.before bottom) $), \n1 = {0.5*veclen(\x1,\y1)-\pgflinewidth}, \p2 = ($ (A.bottom) - (A.after bottom)!.5!(A.before bottom) $), \n2 = {veclen(\x2,\y2)-\pgflinewidth} in ([xshift=-\pgflinewidth] A.before bottom) arc [start angle=0, end angle=180, x radius=\n1, y radius=\n2]; \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: What does the "lock" instruction mean in x86 assembly? I saw some x86 assembly in Qt's source: q_atomic_increment: movl 4(%esp), %ecx lock incl (%ecx) mov $0,%eax setne %al ret .align 4,0x90 .type q_atomic_increment,@function .size q_atomic_increment,.-q_atomic_increment From Googling, I knew lock instruction will cause CPU to lock the bus, but I don't know when CPU frees the bus? About the whole above code, I don't understand how this code implements the Add? A: LOCK is not an instruction itself: it is an instruction prefix, which applies to the following instruction. That instruction must be something that does a read-modify-write on memory (INC, XCHG, CMPXCHG etc.) --- in this case it is the incl (%ecx) instruction which increments the long word at the address held in the ecx register. The LOCK prefix ensures that the CPU has exclusive ownership of the appropriate cache line for the duration of the operation, and provides certain additional ordering guarantees. This may be achieved by asserting a bus lock, but the CPU will avoid this where possible. If the bus is locked then it is only for the duration of the locked instruction. This code copies the address of the variable to be incremented off the stack into the ecx register, then it does lock incl (%ecx) to atomically increment that variable by 1. The next two instructions set the eax register (which holds the return value from the function) to 0 if the new value of the variable is 0, and 1 otherwise. The operation is an increment, not an add (hence the name). A: What you may be failing to understand is that the microcode required to increment a value requires that we read in the old value first. The Lock keyword forces the multiple micro instructions that are actually occuring to appear to operate atomically. If you had 2 threads each trying to increment the same variable, and they both read the same original value at the same time then they both increment to the same value, and they both write out the same value. Instead of having the variable incremented twice, which is the typical expectation, you end up incrementing the variable once. The lock keyword prevents this from happening. A: From google, I knew lock instruction will cause cpu lock the bus,but I don't know when cpu free the bus ? LOCK is an instruction prefix, hence it only applies to the following instruction, the source doesn't make it very clear here but the real instruction is LOCK INC. So the Bus is locked for the increment, then unlocked About the whole above code, I don't understand how these code implemented the Add? They don't implement an Add, they implement an increment, along with a return indication if the old value was 0. An addition would use LOCK XADD (however, windows InterlockedIncrement/Decrement are also implement with LOCK XADD).
{ "pile_set_name": "StackExchange" }
Q: Is there have analog for HtmlTableRow in .NET Core I'm porting app from .NET to .NET Core and can't find analog for HtmlTableRow class Error CS0246 The type or namespace name 'HtmlTableRow' could not be found (are you missing a using directive or an assembly reference?) A: This is part of WebForms, which is not part of .NET Standard, and will never be available on .NET Core. You can't easily port a WebForms application to .NET Core. You'd have to change it into an ASP.NET MVC application first, and that won't be trivial.
{ "pile_set_name": "StackExchange" }
Q: Difference between ionic and cordova plugin install When working with ionic, what is the difference between ionic plugin install ... and cordova plugin install Which one should be used? And why? Thx! A: There is a difference Ionic create some files in the project, such as ionic.project and package.json. Each time you add a plugin with Ionic using the command ionic plugin add ... , Ionic updates package.json. Ionic CLI uses package.json to manage Cordova app state in terms of platforms and plugins. package.json has two sections, cordovaPlatforms and cordovaPlugins that allows a ionic state restore to get the Cordova environment ready for build, run, etc... More explanations here : https://stackoverflow.com/a/30192417/3096087
{ "pile_set_name": "StackExchange" }
Q: Suddenly Springfox Swagger 3.0 is not working with spring webflux Application was working with Springfox Swagger 3.0 few days back. Suddenly it is stopped working. The Jar file which was created before a week is still working but now when we try to build a new Jar file, which is not working, even without any code/library changes. I have even referred the below URL but still facing issue. 404 error with swagger-ui and spring webflux Below given my configuration: POM file: <properties> <java.version>1.8</java.version> <springfox.version>3.0.0-SNAPSHOT</springfox.version> <spring.version>2.3.1.RELEASE</spring.version> </properties> <repositories> <repository> <id>spring-libs-milestone</id> <name>Spring Milestone Maven Repository</name> <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-spring-webflux</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency> </dependencies> Config Files: @Configuration @EnableSwagger2WebFlux public class SwaggerConfiguration implements WebFluxConfigurer { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .description("My Reactive API") .title("My Domain object API") .version("1.0.0") .build()) .enable(true) .select() .apis(RequestHandlerSelectors.basePackage("com.reactive.controller")) .paths(PathSelectors.any()) .build(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/swagger-ui.html**") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } } I am getting 404 error when I try to open the swagger page. http://localhost:8080/swagger-ui.html Can someone help me with this. Thanks in advance. A: The implementation has changed recently (see migrating from earlier snapshots for a brief update on this). Now the UI is avaiable under /swagger-ui/ endpoint (not /swagger-ui.html). You should also drop the @EnableSwagger2WebFlux annotation and addResourceHandlers() method, remove all springfox dependencies and add just one: <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>${springfox.version}</version> </dependency>
{ "pile_set_name": "StackExchange" }
Q: Transport-level vs message-level security I'm reading a book on WCF and author debates about pros of using message-level security over using transport-level security. Anyways, I can't find any logic in author's arguments One limitation of transport security is that it relies on every “step” and participant in the network path having consistently configured security. In other words, if a message must travel through an intermediary before reaching its destination, there is no way to ensure that transport security has been enabled for the step after the intermediary (unless that interme- diary is fully controlled by the original service provider). If that security is not faithfully reproduced, the data may be compromised downstream. Message security focuses on ensuring the integrity and privacy of individ- ual messages, without regard for the network. Through mechanisms such as encryption and signing via public and private keys, the message will be protected even if sent over an unprotected transport (such as plain HTTP). a) If that security is not faithfully reproduced, the data may be compromised downstream. True, but assuming two systems communicating use SSL and thus certificates, then the data they exchange can't be decrypted by intermediary, but instead it can only be altered, which the receiver will notice and thus reject the packet?! b) Anyways, as far as I understand the above quote, it is implying that if two systems establish a SSL connection, and if intermediary system S has SSL enabled and if S is also owned by a hacker, then S ( aka hacker ) won't be able to intercept SSL traffic travelling through it? But if S doesn't have SSL enabled, then hacker will be able to intercept SSL traffic? That doesn't make sense! c) Message security focuses on ensuring the integrity and privacy of individ- ual messages, without regard for the network. Through mechanisms such as encryption and signing via public and private keys, the message will be protected even if sent over an unprotected transport (such as plain HTTP). This doesn't make sense, since transport-level security also can use encryption and certificates, so why would using private/public keys at message-level be more secure than using them at transport-level? Namelly, if intermediary is able to intercept SSL traffic, why wouldn't it also be able to intercept messages secured via message-level private/public keys? thank you A: Consider the case of SSL interception. Generally, if you have an SSL encrypted connection to a server, you can trust that you "really are* connected to that server, and that the server's owners have identified themselves unambiguously to a mutually trusted third party, like Verisign, Entrust, or Thawte (by presenting credentials identifying their name, address, contact information, ability to do business, etc., and receiving a certificate countersigned by the third party's signature). Using SSL, this certificate is an assurance to the end user that traffic between the user's browser (client) and the server's SSL endpoint (which may not be the server itself, but some switch, router, or load-balancer where the SSL certificate is installed) is secure. Anyone intercepting that traffic gets gobbledygook and if they tamper with it in any way, then the traffic is rejected by the server. But SSL interception is becoming common in many companies. With SSL interception, you "ask" for an HTTPS connection to (for example) www.google.com, the company's switch/router/proxy hands you a valid certificate naming www.google.com as the endpoint (so your browser doesn't complain about a name mismatch), but instead of being countersigned by a mutually trusted third party, it is countersigned by their own certificate authority (operating somewhere in the company), which also happens to be trusted by your browser (since it's in your trusted root CA list which the company has control over). The company's proxy then establishes a separate SSL-encrypted connection to your target site (in this example, www.google.com), but the proxy/switch/router in the middle is now capable of logging all of your traffic. You still see a lock icon in your browser, since the traffic is encrypted up to your company's inner SSL endpoint using their own certificate, and the traffic is re-encrypted from that endpoint to your final destination using the destination's SSL certificate, but the man in the middle (the proxy/router/switch) can now log, redirect, or even tamper with all of your traffic. Message-level encryption would guarantee that the message remains encrypted, even during these intermediate "hops" where the traffic itself is decrypted. Load-balancing is another good example, because the SSL certificate is generally installed on the load balancer, which represents the SSL endpoint. The load balancer is then responsible for deciding which physical machine to send the now-decrypted traffic to for processing. Your messages may go through several "hops" like this before it finally reaches the service endpoint that can understand and process the message. A: I think I see what he's getting at. Say like this: Web client ---> Presentation web server ---> web service call to database In this case you're depending on the middle server encrypting the data again before it gets to the database. If the message was encrypted instead, only the back end would know how to read it, so the middle doesn't matter.
{ "pile_set_name": "StackExchange" }
Q: Getting undefined variable using isset Using the following code, I'm getting the error "Undefined Index: area" <select id="area" name="area" class="selectbox dropdownfilter" data-target-id="location"> <option value="">all areas</option> <?php asort($areas) ?> <?php foreach ($areas as $code =>$area) : ?> <option value="<?php echo $code ?>"<?php if(isset($_SESSION['area']) | isset($_POST['area'])) { if($_SESSION['area'] == $area | $_POST['area'] == $area) { echo ' selected'; } } ?> ><?php echo $area ?></option> <?php endforeach ?> </select> It's outputting the $area correctly, the error is coming in the 'selected' script. Bit lost as to what I'm doing wrong, or how else I could do it. I'm just trying to select the option if it's what was submitted in the search form. A: That condition: if(isset($_SESSION['area']) | isset($_POST['area'])) { => Returns true if $_SESSION['area'] is set OR $_POST['area'] is set So it is true if $_SESSION['area'] is not set but $_POST['area'] is set, for example. Then : if($_SESSION['area'] == $area | $_POST['area'] == $area) { => You are testing $_SESSION['area'] value. If it's not set (it's possible as seen before), you'll have an error notice. Here is what I'd do, only one condition : if ( (isset($_SESSION['area']) && $_SESSION['area'] == $area) || (isset($_POST['area']) && $_POST['area'] == $area) ) { If $_SESSION['area'] is not set, PHP won't bother to test if $_SESSION['area'] == $area because it doesn't need to (as the 1st condition is false anyway), it will try what is after the OR See http://php.net/manual/en/language.operators.logical.php And http://php.net/manual/en/language.operators.precedence.php
{ "pile_set_name": "StackExchange" }
Q: Create string from regular expression PHP I'm trying to create a string from a regular expression. I noticed that in Kohana framework's routing system you can set a route using something similar to a regular expression. Then you can create an url matching a route you've set. I'm trying to do something similar, but I can't find a clean way to do it. I've for example got the following regular expression: /^(?<application>\w+)\/(?<controller>\w+)\/(?<method>\w+)\/(?<parameters>\w+)\/?$/ Now I want to be able to say that "application" equals "a", "controller" equals "b", "method" equals "c" and "parameters" equals "d". Then I should get a string that replaces the parts with the values specified. I can't find a good way to do this though. I've basically thought of two ways: 1) replace the corresponding values in the regular expression with the specified values, or 2) create a custom "regex syntax" that you can easily be used to create string and convert it to a "proper" regular expression when needed. Kohana uses the latter, but both ways sound quite bad to me. How would you do this? Edit: I'll try to clarify it a bit. I for example pass the following string to the regular expression shown above using preg_match(): "myApplication/myController/myMethod/myParameters". This returns an array that has a couple of items, including 4 items with indexes "application", "controller", "method" and "parameters" with the corresponding values. Now I have to create the string "myApplication/myController/myMethod/myParameters" with the regular expression's pattern while I only have that array with the 4 items. How can I do this using PHP? A: It should be pretty straightforward given that preg_match has support for named capturing groups (which your regular expression is, of course, using; more here). An example from PHP documentation: <?php $str = 'foobar: 2008'; preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches); /* This also works in PHP 5.2.2 (PCRE 7.0) and later, however * the above form is recommended for backwards compatibility */ // preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches); print_r($matches); ?> The above example will output: Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 ) So in your case, you can use your $matches array, e.g. $matches['application']. Edit: Okay, I did not fully understand the question. An obvious problem with using regular expressions to generate strings is that a regular expression can match infinite strings. For example, /cat\s+rat/ matches all of: cat rat cat rat cat rat etc. But in your example, nothing is undefined. So your inclination to define a "safe" or singly-generatable language that is a subset of regular expressions is a good one, given a narrow use case. Then you could replace occurrences of /\(\?P?<(\w+)>\)/ with the value of the capturing group in there. But since PHP doesn’t really let you just use the value of the capturing group to access a variable during replacement in one step, you will likely have to do this in multiple steps… e.g. matching all occurrances of the above group, extracting the named groups, and then finally doing (in a loop over $matches as $match) a simple string substitution from '(?P<' . $match . '>)' and '(?<' . $match . '>)' to the value of $$match (though in a safer way than that).
{ "pile_set_name": "StackExchange" }
Q: Ruby PATH Aptana Setup/Error Watir-Webdriver Well, I'm slow... I can't figure out how to change the PATH for Ruby in Aptana (plugin Eclipse). The Apatana website doesn't offer any "how to". And various searches have ended up no where. Here's the error I'm getting. /home/cmcintyre/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- watir-webdriver (LoadError) from /home/cmcintyre/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require' from /home/cmcintyre/dev/bsro_rebrand_automation/test.rb:2:in `<main>' Any help is much appreciated. Version: Aptana 3 OS: Ubuntu 12.10 A: I did find that using RVM with Ubuntu 12.10 is not a good choice when working with Aptana. I deleted the RVM directory and installed using: sudo apt-get install ruby. I also re-installed Eclipse and added the Aptana plugin. Installed Eclipse using apt-get, although this is probably not necessary. Eclipse/Aptana found the appropriate Ruby directory. When installing with Curl, Ruby is installed with the local user (although there are instructions for installing globally). So when you use sudo commands to install gems it installs them to your root. Aptana is getting confused, naturally, because you are not pointing to the right Ruby installation. Worked perfectly. I'm newer to Linux and assumed that it would be the same as on my Mac/PC. This is definitely specific to Linux/Ubuntu though, because I used the same install procedure on my Mac with Curl and had no issues. UPDATE: As noted below you can also just update all your gems via RVM instead of using Rubygems. This is probably a more appropriate response to the question.
{ "pile_set_name": "StackExchange" }
Q: CSS List with column padding I have created an unordered list with three columns. The columns touch when going responsive and shrinking the resolution. What can I use to give somesort of padding between them? .li-3col { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; } A: Try using the column-gap property: .li-3col { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 40px; /* Chrome, Safari, Opera */ -moz-column-gap: 40px; /* Firefox */ column-gap: 40px; } You can learn more about the column-gap property here.
{ "pile_set_name": "StackExchange" }
Q: restangular save ignores changes to restangular object I'm trying to call save on a restangularized object, but the save method is completely ignoring any changes made to the object, it seems to have bound the original unmodified object. When I run this in the debugger I see that when my saveSkill method (see below) is entered right before I call save on it the skill object will reflect the changes I made to it's name and description fields. If I then do a "step into" I go into Restangular.save method. However, the 'this' variable within the restangular.save method has my old skill, with the name and description equal to whatever they were when loaded. It's ignoring the changes I made to my skill. The only way I could see this happening is if someone called bind on the save, though I can't why rectangular would do that? My only guess is it's due to my calling $object, but I can't find much in way of documentation to confirm this. I'm afraid I can't copy and paste, all my code examples are typed by hand so forgive any obvious syntax issues as typos. I don't know who much I need to describe so here is the shortened version, I can retype more if needed: state('skill.detail', { url: '/:id', data: {pageTitle: 'Skill Detail'}, tempalte: 'template.tpl.html' controller: 'SkillFormController', resolve: { isCreate: (function(){ return false;}, skill: function(SkillService, $stateParams){ return SkillService.get($stateParams.id, {"$expand": "people"}).$object; }, }); my SkillService looks like this: angular.module('project.skill').('SkillService', ['Restangular, function(Retangular) { var route="skills"; var SkillService= Restangular.all(route); SkillService.restangularize= function(element, parent) { var skill=Restangular.restangluarizeElement(parent, elment, route); return skill; }; return SkillService; }]; Inside of my template.tpl.html I have your standard text boxes bound to name and description, and a save button. The save button calls saveSkill(skill) of my SkillFormController which looks like this: $scope.saveSkill=function(skill) { skill.save().then(function returnedSkill) { toaster.pop('success', "YES!", returnedSkill.name + " saved."); ...(other irrelevant stuff) }; If it matters I have an addElementTransformer hook that runs a method calling skilll.addRestangularMethod() to add a getPeople method to all skill objects. I don't include the code since I doubt it's relevant, but if needed to I can elaborate on it. A: I got this to work, though I honestly still don't know entirely why it works I know the fix I used. First, as stated in comments restangular does bind all of it's methods to the original restangularizedObject. This usually works since it's simply aliasing the restangularied object, so long as you use that object your modifications will work. This can be an issue with Restangular.copy() vs angular.copy. Restangualar.copy() makes sure to restangularize the copied object properly, rebinding restangualr methods to the new copy objects. If you call only Angular.copy() instead of Restangualar.copy() you will get results like mine above. However, I was not doing any copy of the object (okay, I saved a master copy to revert to if cancel was hit, but that used Restangular.copy() and besides which wasn't being used in my simple save scenario). As far as I can tell my problem was using the .$object call on the restangular promise. I walked through restangular enough to see it was doing some extra logic restangularizing methods after a promise returns, but I didn't get to the point of following the $object's logic. However, replacing the $object call with a then() function that did nothing but save the returned result has fixed my issues. If someone can explain how I would love to update this question, but I can't justify using work time to try to further hunt down a fixed problem even if I really would like to understand the cause better.
{ "pile_set_name": "StackExchange" }
Q: Purchasing a house with parent-in-law's money, temporarily Say I am about to purchase a £200,000 house (moving house, rather than first-time buyer), and can get a mortgage for the £120,000 difference I need. But, my parents-in-law have offered to loan us the £120,000 at 0% interest instead; and we would pay them back the same amount each month that we would have paid for the mortgage. The catch, however, is that at some point in the future they are likely to need the money back, although the timescales are not yet known - in which case we would have to take out a mortgage on the house at that point for the remaining value of the loan, in order to pay them back in a lump sum. What are the legal issues and risks with this approach - how should we make sure everyone is fairly covered? Is there any tax implications? Is there an easier way to approach this? Would we be less likely to get a mortgage in the future because the money would be being used to pay off this loan? Is there anything else I need to know before agreeing to this? A: I would proceed with caution and a lot of it depends upon the character of all parties involved. If the opportunity came along to open a joint venture with these people would you do so? Because basically that is what you are doing. Is anyone over emotional and liable to fly off the handle about money despite the facts? Are you able to keep accurate records and record the details of each transaction? This would include backing up bank statements so if the facts were disputed they could be provided as evidence. Are you willing to make payments like clockwork? If there is one shred of doubt, pass on this generous offer. The money you save will not be worth it. However it could work and does for some people that I know. If you would want proceed I would draw up a draft agreement. You may want to include a provision that they could not call the loan until 2 years after purchase or some other period of time. You may ask that they give you 90 days notice. What happens if a payment is late? How will the payments be tracked? Every contingency you can think of should be covered as if you do not trust these people or yourself. The goal is that there are no assumptions that everything is discussed beforehand. Then go see a lawyer and you would pay for that lawyer. They can make the agreement all legal and the cost will certainly be less than a couple of months of interest. I would say a key component of all of this is when they can call the loan. If they won't agree to a couple of years limitation then it would be a pass for me.
{ "pile_set_name": "StackExchange" }
Q: Email says it is from nobody I have recently tried to use the php mail function to send out confirmation emails and I have been successful in doing so. However, when I added a few things to my script, something doesn't seem to work. The code below is the code that I got to work. Everything that I need for the email to contain appears. $to = 'Myemail'; $subject = 'Confirmation'; $message = 'This is a test'; $headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=iso-8859-1' . "\r\n" . 'Content-Transfer_Encoding: 7bit' . "\r\n\r\n" . 'From: fromemail'."\r\n" . 'Reply-To: replyemail' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); However, when I transfer the same headers to another script (Below), the mail delivers but there are a few issues. 1) My mail says that the mail is from nobody. 2) Instead of the headers appearing in the info area, it appears as text in the mail From: from email Reply-To: reply email X-Mailer: PHP/5.2.9 The script below is being included in another program i wrote, so i am wondering if that is the problem. I don't think its syntax because its the same headers I used above. I have attached a picture of the mail I get. http://imgur.com/weNkr Your help is greatly appreciated!!! <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <HEAD> </HEAD> <body> <?php $message = $_POST['message']; $subject = $_POST['subject']; if ($message != null) { include("connect.php"); $extract = mysql_query("SELECT * FROM `contact` ORDER BY `id`") or die("Error"); $counter = 0; while ($row = mysql_fetch_assoc($extract)) { $email[$counter] = $row['email']; $counter++; } for ($x = 0; $x < $counter; $x++) { $to = $email[$x]; $subject = $subject; $message = $message; $headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=iso-8859-1' . "\r\n" . 'Content-Transfer_Encoding: 7bit' . "\r\n\r\n" . 'From: fromemail' . "\r\n" . 'Reply-To: replyemail' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); echo "EMAIL WAS SENT TO: "; echo $email[$x]; echo "<BR>"; } } ?> </body> </html> A: Your problem is with this line: 'Content-Transfer_Encoding: 7bit' . "\r\n\r\n" . //---------------------------------^^^^^^^^^^^ // Two line breaks ends the header block // These remaining headers are seen as part of the message body 'From: fromemail'."\r\n" . 'Reply-To: replyemail' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); You have an extra line break here, which completes the headers portion of the message before the From and subsequent headers. Remove the extra \r\n.
{ "pile_set_name": "StackExchange" }
Q: Create a pager for views output How can I make a pager for views output to limit them at 10 entries? $view = views_get_view('myview', 'default'); $view->override_path = $_GET['q']; $view_output = $view->execute_display('page_1', array($tid)); A: Drupal Views module provides this functionality. You don't need to write the code for that. See the image below Here you can set item to display as want. It has many more options
{ "pile_set_name": "StackExchange" }
Q: Cloud AMPQ integration with iOS APP I am working on to integrate cloud AMPQ to my iOS app. With RabbitMQ client, unable to make successful communication with the server. I have checked below stack overflow link to make a communication with the server: stack overflow link The sample source shared in above link broken. Please suggest me possible solution. Thanks in advance A: You should use the official client library: https://github.com/rabbitmq/rabbitmq-objc-client (Swift + ObjC compatible) Basic Usage (extract from repo): Instantiate an RMQConnection: let delegate = RMQConnectionDelegateLogger() // implement RMQConnectionDelegate yourself to react to errors let conn = RMQConnection(uri: "amqp://guest:guest@localhost:5672", delegate: delegate) Connect: conn.start() Create a channel: let ch = conn.createChannel() Use the channel: let q = ch.queue("myqueue") q.subscribe({ m in print("Received: \(String(data: m.body, encoding: String.Encoding.utf8))") }) q.publish("foo".data(using: String.Encoding.utf8)) Close the connection when done: conn.close() Depending on the provider, you'll need to construct the connection URI manually. Heroku for example already presents it in it's dashboard. Here's the documentation on the supported parameters: https://www.rabbitmq.com/uri-spec.html and https://www.rabbitmq.com/uri-query-parameters.html Example URI on Heroku: amqp://xxxxxxx:[email protected]:10674/bbbbbbb Format: amqp_URI = "amqp://" [ username [ ":" password ] "@" ] host [ ":" port ] [ "/" vhost ] [ "?" query ]
{ "pile_set_name": "StackExchange" }
Q: Python: Merge two csv files and mark the unmatched both in master and using data I am a bit new to python so sorry if my question is irrelevant. I have two csv files similar to this that I want to match file 1 sa_name ABC DEF ACE ABCD BCD And file 2 rs_name ABCD CDE DEFG ABCDE ABE And I want my output file to be like this: output file sa_name, rs_name, merge ABC, ABCD, 3 ABC, ABCDE, 3 ACE, ,1 DEF, DEFG, 3 ABCD, ABCDE, 3 ABCD, ABCD, 3 BCD, ABCD, 3 BCD, ABCDE, 3 , CDE, 2 , ABE, 2 So the rule is that merge=3 if row in file1.csv is a substring of a row in file2, if the data is only in file1.csv then merge=1 and if the data is only in file2.csv then merge=2. I only know how to get those rows with merge=3 but don't know how to merge two csv files and keep those unmatched in the output file and also indicate whether they come from file 1 or file 2. Here comes my code: import csv with open('file2.csv', encoding='UTF-8', newline='') as RS: RS_reader = csv.reader(RS) rows = [row for row in RS_reader] print("RS data loaded...") with open('file2.csv', encoding='UTF-8', newline='') as SA: with open('RS_SA.csv', 'w', encoding='UTF-8') as RS_SA: SA_reader = csv.reader(SA) print("SA data loaded") RS_SA_writer = csv.writer(RS_SA) RS_SA_writer.writerow(next(SA_reader, None) + rows[0]) print("Header written to the ourput file...") d = 0 for line in SA_reader: match2 = line[0] for row in rows: match1 = row[0] if match2 in match1: new_row = [','.join(line+row)] SA_writer.writerow(new_row) d = d+1 print(d) print(new_row) Anyone knows how to proceed? Thanks a lot! Some updates: in my file1 I have 100 columns and 6 millions observations and file 2 I have 20 columns with 3,500 observations. Those are not relevant for my matching so I didn't add them here in the example files. A: Assuming you've read the two files into "sa_name" and "rs_name", this will give you a final_list which is a list of lists each one representing a row to write to a csv file. You can then sort by the first column if needed. This may need some validation depending on how big your file is etc sa_name = ['ABC','DEF','ACE','ABCD','BCD'] rs_name = ['ABCD','CDE','DEFG','ABCDE','ABE'] found_rs_name, final_list = [], [] for sa in sa_name: found = False for rs in rs_name: if sa in rs: final_list.append([sa,rs,3]) found_rs_name.append(rs) found = True if not found: final_list.append([sa,"",1]) for rs in rs_name: if rs not in found_rs_name: final_list.append(["",rs,2])
{ "pile_set_name": "StackExchange" }
Q: TextField doesn't take input after adding 2 decimal positive numbers configuration in whitelistingtextinputformatter keyboardType: TextInputType.number, inputFormatters: [ WhitelistingTextInputFormatter( RegExp("^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*\$")) ], ), I'm using this settings in my TextFormField and using this regex which I took from another SO post. Tests seem fine on regex101.com but I can't put any input on my form with this regexp. My goal with regex is get two decimal positive floating point numbers. Regex greater than zero with 2 decimal places A: You may use RegExp(r"^\s*\d*(?:\.\d{1,2})?\s*$") ^ ^ Or, if you want to keep the "at least one non-zero digit in string" requirement (as the regex you tried hints at that): RegExp(r"^(?=.*[1-9])\s*\d*(?:\.\d{1,2})?\s*$") The point here is that: You should use a raw string literal for regex escapes to work with a single backslash $ is an end of string anchor only if it is not escaped and is out of square brackets The lookahead must be placed after ^ for better performance. Pattern details ^ - start of string (?=.*[1-9]) - there must be a non-zero digit after any 0+ chars other than line break chars \s* - 0+ whitespaces \d* - 0+ digits (?:\.\d{1,2})? - an optional sequence of \. - a dot \d{1,2} - 1 or 2 digits \s* - 0+ whitespaces $ - end of string.
{ "pile_set_name": "StackExchange" }
Q: Hashing a string value to the interval [0; 1] I need to make hashing of pk values (e.g. 1289359, 345623p, etc.) to the interval [0; 1]. The mapping should be deterministic in order to get the same result every time I run the code (I don't want to use seed numbers). For example, the result of mapping 1289359 might be 0.35 (just an example). How can I do it? Any hint would be highly appreciated. It is preferable that the solution is given in Scala, but it might be also in Java. UPDATE: Sorry for not posting my code sample that I tried as a possible solution: String myString = "345623p"; double value = Double.parseDouble(myString); I don't know how to map it to the exact interval [0; 1]. A: Your requirements are vague, but I think this satisfies them. val r = scala.util.Random val pks = List("1289359", "345623p") val hashes = pks.map { pk => r.setSeed(pk.hashCode()) (pk, r.nextDouble()) } List((1289359,0.36724077736416283), (345623p,0.243112317891797)) Note that there are some unexpected results of this approach. If the keys are very close (e.g. differ by the last char) then the hashes will also be very close, due to how scala's Random.nextDouble works. List((1234560,0.40817931760409776), (1234561,0.4084480629207127), (1234562,0.4083584960496689), (1234563,0.41077718899804194))
{ "pile_set_name": "StackExchange" }
Q: Python 3.7: Utility of Dataclasses and SimpleNameSpace Python 3.7 provides new dataclasses which have predefined special functions. From an overview point, dataclasses and SimpleNameSpace both provide nice data encapsulating facility. @dataclass class MyData: name:str age: int data_1 = MyData(name = 'JohnDoe' , age = 23) data_2 = SimpleNameSpace(name = 'JohnDoe' , age = 23) A lot of times I use SimpleNameSpace just to wrap data and move it around. I even subclass it to add special functions: from types import SimpleNameSpace class NewSimpleNameSpace(SimpleNameSpace): def __hash__(self): return some_hashing_func(self.__dict__) For my question: How does someone choose between SimpleNameSpace and dataclasses? Why were they necessary, when the same effect can be achieved with extending the SimpleNameSpace? What all other use cases dataclasses cater to? A: Dataclasses is much more like namedtuple and the popular attrs package than SimpleNamespace (which isn't even mentioned in the PEP). They serve two different intended purposes. Dataclasses Structured Typed (by default, but optional) Writes most of the boilerplate for basic dunder methods (__init__, __hash__, __eq__, and many more) Provide easy mechanism for default values for attributes Can easily add __slots__ and methods SimpleNamespace "Grab bag" data structure Used where you need more than a dictionary but less than a class Not intended to be use things like __slots__ From the SimpleNamespace documentation: SimpleNamespace may be useful as a replacement for class NS: pass. However, for a structured record type use namedtuple() instead. Since @dataclass is supposed to replace a lot of the use cases of namedtuple, named records/structs should be done with @dataclass, not SimpleNamespace. You may also want to look at this PyCon talk by Raymond Hettinger, where he goes into the backstory of @dataclass and it's use. A: The short answer is that this is all covered by PEP 557. Taking your questions slightly out of order... Why? To leverage PEP 526 to provide a simple way to define such classes. To support static type checkers. How to pick when to use them? The PEP is quite clear that they are not a replacement and expect the other solutions to have their own place. Like any other design decision, you'll therefore need to decide exactly what features you care about. If that includes the following, you definitely don't want dataclasses. Where is it not appropriate to use Data Classes? API compatibility with tuples or dicts is required. Type validation beyond that provided by PEPs 484 and 526 is required, or value validation or conversion is required. That said, the same is true for SimpleNameSpace, so what else can we look at to decide? Let's take a closer look at the extra features provided by dataclasses... The existing definition of SimpleNameSpace is as follows: A simple object subclass that provides attribute access to its namespace, as well as a meaningful repr. The python docs then go on to say that it provides a simple __init__, __repr__ and __eq__ implementation. Comparing this to PEP 557, dataclasses also give you options for: ordering - comparing the class as if it were a tuple of its fields, in order. immutability - where assigning to fields will generate an exception control of the hashing - though this isn't recommended. Clearly, then, you should use dataclasses if you care about ordering or immutability (or need the niche hashing control). Other use cases? None that I can see, though you could argue that the initial "why?" covers other use cases.
{ "pile_set_name": "StackExchange" }
Q: Can you use the parameters in a Knockout custom validator inside the message? I have made a custom validator much like the one that can be found here. The intent of my validator is to be generic enough that it can be used in other places. This particular one validates the filetype extensions passed into it, and returns true if the observable is of a valid filetype. I would like to pass a custom error message that includes these file types to alert the user of what extensions are acceptable. IE ko.validation.rules['validateFileTypeExtensions'] = { validator: function (fileName, validExtensions) { var isValidExtension = false; var extension = fileName.split('.').pop(); validExtensions.forEach(function(validExtension){ if(extension == validExtension) isValidExtension = true; }); return isValidExtension; }, // At this point message does not have access to the validExtensions // that were passed into the validator. Is there a way to get them here? message: 'Please chose a file with an acceptable extension ({0}).' }; ko.validation.registerExtenders(); //the valid file extensions are passed into the validator. var myCustomObj = ko.observable().extend({ validateFileTypeExtensions: ['xls', 'xlsx'] }); As you can see, the 'message' does not have access to the validExtensions variable. Is there some way that I'm just not aware of to access that value within the validator? A: The value will be inserted in place of the {0} part of your message string. If you wanted more control over how the message was formatted, make message a function where you return your formatted message. e.g., ko.validation.rules.myValidator = { validator: function (...) { ... }, message: function (params, observable) { return 'invalid, was expecting ' + params + ' but got ' + observable(); } }; If you want to completely override the message from the extender, rather than passing in your normal parameters in the extender, pass in a validator configuration with your params and the modified message. var obs = ko.observable().extend({ myValidator: { params: 123, message: 'oops' } });
{ "pile_set_name": "StackExchange" }
Q: cannot restore view pager fragment state i have a view pager with 3 fragments. i use retrofit rest api to populate each of my fragments for the first time. What i would like to achieve is when the user swipes back either in first or third fragment(those 2 fragment are being being destroyed by the view pager) to restore the data(saved in an array list) and not make a rest api call again. What i have done is to save the array list of downloaded data in onSaveInstanceState() and successfully retrieve it when the user swipes back to one of the 2 above fragments only FOR THE 1 FIRST TIME. The problem is when i navigate back to either one of the 2 fragments the specific bundle key where the array list was saved contains null value. CompletedSurveysFragment(the third fragment): public class CompletedSurveysFragment extends Fragment implements SAMVCView { private static final String debugTag = CompletedSurveysFragment.class.getSimpleName(); private View view; private RecyclerView completedSurveysRcV; private SAMVCPresenterImpl SAMVCpresenterImpl; private SurveysRcvAdapter surveysRcvAdapter; private List<SurveyData> data; public CompletedSurveysFragment() {} public static CompletedSurveysFragment newInstance() { return new CompletedSurveysFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.e(debugTag, "onCreateView"); if ( view == null ) view = inflater.inflate(R.layout.fragment_completedsurveys, container, false); completedSurveysRcV = (RecyclerView) view.findViewById(R.id.completedSurveysRcV); return view; } // TODO: 21/6/2016 configure Limit and offset values @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.e(debugTag, "onActivityCreated " + savedInstanceState); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); completedSurveysRcV.setHasFixedSize(true); completedSurveysRcV.setLayoutManager(linearLayoutManager); completedSurveysRcV.addItemDecoration(new DividerItemDecoration(ContextCompat.getDrawable(getActivity(), R.drawable.divider))); if (savedInstanceState == null) { SAMVCpresenterImpl = new SAMVCPresenterImpl(this); SAMVCpresenterImpl.getSurveysBasedOnSpecificFirmId(new AllSurveysBody(getResources().getString(R.string.list_surveys), LoginActivity.getSessionPrefs(getActivity()).getInt(getResources().getString(R.string.firm_id), 0), getResources().getString(R.string.completed), 8, 0)); surveysRcvAdapter = new SurveysRcvAdapter(null, completedSurveysRcV); completedSurveysRcV.setAdapter(surveysRcvAdapter); } else { //Log.e(debugTag, savedInstanceState.+""); if (savedInstanceState.getParcelableArrayList("data") != null) { Log.e(debugTag, "here "+ savedInstanceState); surveysRcvAdapter = new SurveysRcvAdapter(savedInstanceState.<SurveyData>getParcelableArrayList("data"), completedSurveysRcV); completedSurveysRcV.setAdapter(surveysRcvAdapter); surveysRcvAdapter.notifyDataSetChanged(); } //Log.e(debugTag, getArguments().getParcelableArrayList("data")+""); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) this.data); Log.e(debugTag, "CompletedFragment onSaveInstanceState "+ outState); } @Override public void onSuccessSurveysFetched(List<SurveyData> data) { this.data = data; surveysRcvAdapter = new SurveysRcvAdapter(data, completedSurveysRcV); completedSurveysRcV.setAdapter(surveysRcvAdapter); surveysRcvAdapter.notifyDataSetChanged(); } @Override public void onFailure() { } } View pager adapter: public class SurveysPagerAdapter extends FragmentStatePagerAdapter { private static final String debugTag = SurveysPagerAdapter.class.getSimpleName(); private List<SurveyData> data; String[] tabText; public SurveysPagerAdapter(FragmentManager fragmentManager, String[] tabText) { super(fragmentManager); this.tabText = tabText; } @Override public Fragment getItem(int position) { Log.e("SurveysPagerAdapter", position+""); switch (position) { case 0: return CompletedSurveysFragment.newInstance(); case 1: return OngoingSurveysFragment.newInstance(); case 2: return PendingSurveysFragment.newInstance(); default: return null; } } @Override public CharSequence getPageTitle(int position) { return tabText[position]; } @Override public int getCount() { return 3; } } A: Your issue is that you're always returning a new instance of your fragment. Instead of calling CompletedSurveysFragment.newInstance(); (and your other Fragments) every time user swipes, create an array of fragments and retrieve it this way: ... Fragment [] pages = new Fragment[getCount()]; ... @Override public Fragment getItem(int position) { Log.e("SurveysPagerAdapter", position+""); switch (position) { case 0: if(pages[position] == null) pages[position] = CompletedSurveysFragment.newInstance(); return pages[position]; ... } Then, you can fetch and cache your data in onCreate() and retrieve it later in onResume() in your respective fragments.
{ "pile_set_name": "StackExchange" }
Q: Simple Option Menu (C) I am trying to make a simple option menu that is executed within a do- while loop. The menu has 5 different options. I am currently trying to test the the get initial option but when I choose the case 'b' the function does not even execute and the option menu reappears again #include "mathprogram.h" int main (void) { char menu_option,initials; int difficulty; printf(" EDUCATIONAL MATH PROGRAM!!!\n"); printf("------------------------------------------\n\n"); do{ printf("Main Menu\n"); printf("a. Learn about how to use program.\n"); printf("b. Enter your initials (3 individual letters).\n"); printf("c. Difficulty Selection.\n"); printf("d. Start a new sequence of problems.\n"); printf("e. Save and quit.\n"); printf(" Please enter an option from the main menu: "); scanf("%c",&menu_option); switch(menu_option){ case 'a': //Learn_to_use(); break; case 'b': initials=get_intials(); break; case'c': printf("case c"); //difficulty = get_difficulty(); break; case'd': break; case'e': break; default: printf("invalid input"); break; } }while(menu_option !='e'); } get initials function: #include "mathprogram.h" char get_intials(void){ char initails; printf("Please Enter Initials: "); scanf("%c",&initails); return initails; } A: scanf("%c", &var); leaves the newline in the buffer or stream. Try to change it to scanf(" %c", &var); and it should work as expected (Note the space before the %; this consumes the whitespace so that the next scanf call should work). However, the initials as defined in your program consist of only one character, not three. I'll leave that up to you to design, that is a different question.
{ "pile_set_name": "StackExchange" }
Q: How to add seconds to date elements I have a date array. I want to add 20 seconds to each of the elements in the array. I tried for(int i=0i<20;i++) { date1[i]=date1[i].gettime()+20; } This gives a long int value. But what i need is time format result.My question is it possible to add seconds using built in functions or manual function should be written for the same. A: That is because Date.getTime() returns number of milliseconds since January 1, 1970, 00:00:00 GMT. So you are resetting the value in your array with Long. To convert it back to Date you need to construct new Date object like this. for(int i = 0; i < 20; i++) { date1[i] = new Date(date1[i].gettime() + TimeUnit.SECONDS.toMillis(20)); } or set the time back like this: for(int i = 0; i < 20; i++) { date1[i].setTime(date1[i].gettime() + TimeUnit.SECONDS.toMillis(20)); } But I would strongly advice you to use Joda Time instead of Java Date API
{ "pile_set_name": "StackExchange" }
Q: Crosstab / pivot query in Oracle's PL/SQL - iBatis - Extjs and JasperReport I tried to create a pivot table created from a table in Oracle 10g. here is the table structure: CREATE TABLE KOMUNIKA.STOCK_AREA ( PRODUCT_CODE VARCHAR2(20 BYTE) NOT NULL, PRODUCT_NAME VARCHAR2(50 BYTE), AREA_CODE VARCHAR2(20 BYTE), AREA_NAME VARCHAR2(50 BYTE), QUANTITY NUMBER(20,2) ) and i need those data displayed as : Name US Europe Asia SthAm Aust Africa Rest Total C 2601 156 86 437 27 279 22 708 1,715 C 2605 926 704 7,508 1,947 982 782 1,704 14,553 Total 56,941 72,891 118,574 55,868 46,758 19,813 60,246 431,091 then i will grab the result using iBatis framework, then display it in a ExtJs Grid, it is really big favour from me, if anyone have same problem as me and want to share it. i also already find some resource to start: http://www.sqlsnippets.com/en/topic-12200.html but if any of you have already find a simpler solution, you will save my weekend :(, thank you all A: You can do the pivot in SQL itself, using CASE expressions and GROUP BY, as long as the number of columns you want in the result is fixed (you can't write sql that would return a variable number of columns. Let's say your areas look like this: AREA_CODE AREA_NAME --------- --------- 101 US 102 Europe 103 Asia 104 South America 105 Australia 106 Africa 107 ... 108 ... You can write a query that return the results you have above as: SELECT PRODUCT_NAME , SUM(CASE WHEN AREA_CODE = 101 THEN QUANTITY ELSE 0 END) US , SUM(CASE WHEN AREA_CODE = 102 THEN QUANTITY ELSE 0 END) Europe , SUM(CASE WHEN AREA_CODE = 103 THEN QUANTITY ELSE 0 END) Asia , SUM(CASE WHEN AREA_CODE = 104 THEN QUANTITY ELSE 0 END) SthAm , SUM(CASE WHEN AREA_CODE = 105 THEN QUANTITY ELSE 0 END) Aust , SUM(CASE WHEN AREA_CODE = 106 THEN QUANTITY ELSE 0 END) Africa , SUM(CASE WHEN AREA_CODE NOT IN (101, 102, 103, 104, 105, 106) THEN QUANTITY ELSE 0 END) Rest , SUM(QUANTITY) Total FROM KOMUNIKA.STOCK_AREA GROUP BY PRODUCT_NAME;
{ "pile_set_name": "StackExchange" }
Q: How do I add more than 2 sprites into an animation in pygame? #Importing the pygame functions import pygame import sys import os from pygame.locals import * #Allows for the editing of a window pygame.init() #Sets screen size window = pygame.display.set_mode((800,600),0,32) #Names the window pygame.display.set_caption("TEST") #Types of colors (red,green,blue) black = (0,0,0) blue = (0,0,255) green = (0,255,0) yellow = (255,255,0) red = (255,0,0) purple = (255,0,255) lightblue = (0,255,255) white = (255,255,255) pink = (255,125,125) clock = pygame.time.Clock() L1="bolt_strike_0001.PNG" L1=pygame.image.load(L1).convert_alpha() L2="bolt_strike_0002.PNG" L2=pygame.image.load(L2).convert_alpha() L3="bolt_strike_0003.PNG" L3=pygame.image.load(L3).convert_alpha() L4="bolt_strike_0004.PNG" L4=pygame.image.load(L4).convert_alpha() lightingCurrentImage = 1 #Loop gameLoop = True while gameLoop: for event in pygame.event.get(): if event.type == pygame.QUIT: gameLoop=False #Allows the user to exit the loop/game window.fill(black) #used to fill the creen with the certian color variables if (lightingCurrentImage==1): window.blit(L1, (0,0)) if (lightingCurrentImage==2): window.blit(L2, (0,0)) if (lightingCurrentImage==3): window.blit(L3, (0,0)) if (lightingCurrentImage==4): window.blit(L4, (0,0)) if (lightingCurrentImage==2): lightingCurrentImage=1 if (lightingCurrentImage==3): lightingCurrentImage=2 if (lightingCurrentImage==4): lightingCurrentImage=3 else: lightingCurrentImage+=3; pygame.display.flip() #must flip the image o the color is visable clock.tick(5) pygame.quit() #quit the pygame interface exit(0) I'm having problems stitching together 10 images of a lightning bolt animation in pygame. What I have at the moment works but its not what I want it to look like. What happens when I run this is the lightning bolt creates the animation sequence once then disappears and never restarts the sequence again. If I set lightingCurrentImage+=3 to lightingCurrentImage+=2 it appears and stays on the screen but doesn't ever disappear. Please help me to see what the problem is if you can. Thanks! (I want the lightning bolt to begin and go all the way through the animation then disappear. Then begin again and repeat). A: First create list of images then you can use it this way: bold_imgs = [] bold_imgs.append( pygame.image.load("bolt_strike_0001.PNG").convert_alpha() ) bold_imgs.append( pygame.image.load("bolt_strike_0002.PNG").convert_alpha() ) bold_imgs.append( pygame.image.load("bolt_strike_0003.PNG").convert_alpha() ) bold_imgs.append( pygame.image.load("bolt_strike_0004.PNG").convert_alpha() ) lightingCurrentImage = 0 while True: # here ... your code with events window.fill(black) window.blit( bold_imgs[ lightingCurrentImage ], (0,0)) lightingCurrentImage += 1 if lightingCurrentImage = len( bold_imgs ): lightingCurrentImage = 0 pygame.display.flip() clock.tick(5) You can use tick(25) to get faster but smoother animation. Human eye needs at least 25 images per second to see it as smooth animation.
{ "pile_set_name": "StackExchange" }
Q: How to assume an AWS role from another AWS role? I have two AWS account - lets say A and B. In account B, I have a role defined that allow access to another role from account A. Lets call it Role-B { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::********:role/RoleA" }, "Action": "sts:AssumeRole" }] } In account A, I have defined a role that allows the root user to assume role. Lets call it Role-A { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::********:root" }, "Action": "sts:AssumeRole" }] } Role A has the following policy attached to it { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Resource": "arn:aws:iam::****:role/RoleB", "Effect": "Allow" }] } As a user in account A, I assumed the Role-A. Now using this temporary credential, I want to assume the Role-B and access the resource owned by account B. I have the below code client = boto3.client('sts') firewall_role_object = client.assume_role( RoleArn=INTERMEDIARY_IAM_ROLE_ARN, RoleSessionName=str("default"), DurationSeconds=3600) firewall_credentials = firewall_role_object['Credentials'] firewall_client = boto3.client( 'sts', aws_access_key_id=firewall_credentials['AccessKeyId'], aws_secret_access_key=firewall_credentials['SecretAccessKey'], aws_session_token=firewall_credentials['SessionToken'], ) optimizely_role_object = firewall_client.assume_role( RoleArn=CUSTOMER_IAM_ROLE_ARN, RoleSessionName=str("default"), DurationSeconds=3600) print(optimizely_role_object['Credentials']) This code works for the set of roles I got from my client but is not working for the roles I defined between two of the AWS account I have access to. A: Finally got this working. The above configuration is correct. There was a spelling mistake in the policy. I will keep this question here for it may help someone who want to achieve double hop authentication using roles.
{ "pile_set_name": "StackExchange" }
Q: Method in Java interface that returns class or subclass type I have an interface: public interface Displayable { public Class <Screen> classToDisplay(); } and some classes: public class Screen { } public class ScreenSubclass extends Screen { } public class Cue implements Displayable { @Override displayClass() { return ScreenSubclass.class; } } I'm getting an IDE error telling me they are incompatible types. What return value would be needed for 'classToDisplay()' to return a class or subclass type of Screen? A: Just figured it out. Use the ? wildcard along with 'extends'... Change the return type for 'displayClass' to: public Class<? extends Screen> displayClass();
{ "pile_set_name": "StackExchange" }
Q: Sum of dependent normal random variables Let ${\bf X} =(X_1,\ldots,X_n)'$ be a vector of random variables that may be dependent and let ${\bf a}=(a_1,\ldots,a_n)'$ and ${\bf b}=(b_1,\ldots,b_n)'$ be nonrandom vectors with $a_i \neq 0$ and $b_i \neq 0$ for $i=1,\ldots,n$. Assume $ {\bf a' \bf X} =\sum_{i=1}^n a_i X_i \sim N(0,\sigma_a^2)$ and $ {\bf b' \bf X} =\sum_{i=1}^n b_i X_i \sim N(0,\sigma_b^2)$ be normal random variables. Is $ {(\bf a' + \bf b') \bf X}$ also a normal random variable? A: Not always--otherwise every sum of normal random variables would be normal, and this ain't so. Canonical (counter)example: Assume that $\xi$ is standard normal and that $\eta=\sigma\xi$, where $\sigma=\pm1$ is symmetric Bernoulli and independent of $\xi$. Then $\eta$ is standard normal but $\xi+\eta$ is not normal since $P(\xi+\eta=0)=P(\sigma=-1)=\frac12$ while $P(\zeta=0)$ is $0$ or $1$ for every normal random variable $\zeta$. (This argument proves that the vector $(\xi,\eta)$ is not normal.) Variant of the same: $X=(\xi,\xi,\sigma\xi,\sigma\xi)$, $a=(1,1,1,-1)$, $b=(1,-1,1,1)$.
{ "pile_set_name": "StackExchange" }
Q: Derivation, composition, constructors, interfaces and TDD When developing TDD your objects 'grow' as code evolves . First they include only some functionalities, and later you add new ones. You can basically do it with composition and/or inheritance. At the same time, you almost always use interfaces (for test, and for production code) to ensure low coupling, dependency inversion, dependency injection and mocking. How do you MANAGE this? I mean, for example: you have created a class, and now it must include a new attribute (for example, a Person now can have an e-mail). What to do? Modify the class, adding the new attribute: Then you must ADD new constructors. But if you modify existing constructors then you must refactor all TEST involved, not only production code. You could try to keep all constructors as you add new attributes, but at the end mostly become unusefull, obsolete (only exist because of TESTS), with a complex logic of 'constructor calling another constructors' (or use some kind of 'factory') Derive the class: This is more compilant to OCP. But if you make a real TDD, with small steps, if you always derive, starting from a very simple class, you would end with a terribly complex and somehow unneccesary inheritance. And besides, it's supposed you always must test only PUBLIC exposed members. So, again, as base classes become protected, must refactor tests to access the public ones. Compose: Composing has no problem with constructors, but is not always a good solution. As for our current example. And a similar thing happens, in some way, with interfaces. So, as code grows, constructors an interfaces must evolve. And I have three precepts in mind: You should avoid refactor tests. The production code must not keep 'code only intended for testing' (i.e. constructors) ISP states to use specific interfaces. As code grows many of them become unnecesary, as they are only used for testing (i.e. mocking) classes that, in many cases, should be protected or private. So, as I said... how can i manage all this while developing TDD? I know it's a question for a long answer, so, if you could refer to some good article, or resource A: Changing your tests is OK What you're describing (Person now has an Email) is a change in the specs. Unit Tests are supposed to be your specs, so it's only normal that you have to change them when introducing new data. This kind of test fragility is a trade off for quality, a necessary evil. Don't overengineer By trying to apply OCP, inheritance and composition just to add one field, you're only making things more complicated for yourself. As you pointed out, it results in production code monstrosities just for the sake of testing, and you also have to modify the tests anyway. OCP might be good if you're adding a new behavior in a family of existing behaviors, but it's not the case here. Make changes more manageable There are tactics to make your tests more resistant to small changes, but they are mainly implemented at the test level, not in production code. Besides, opportunities for this are easily spottable if you frequently look for duplication in your tests, during the Refactor step of the TDD cycle for instance. One of them is to encapsulate your "system under test" creation in a Factory Method and call it instead of the normal constructor in each of your tests. Make most of its parameters optional with a default value. This will allow you to make changes (e.g. add the Email field) in one place and all the tests will benefit from it. This doesn't save you from modifying the test suite, but you do it just in one place.
{ "pile_set_name": "StackExchange" }
Q: Proving $n!n^s=o(n^n)$ I want to prove that for any $s\geq0$, and $n\to\infty$, $n!n^s=o(n^n)$ or $$\lim_\limits{n\to\infty}\frac{n!n^s}{n^n}=0.$$ As a hint, the inequality $$\sum\limits_{k=1}^{n}\log k\leq n\log\frac{n+1}2$$ is given. I thought that instead of proving $\lim_\limits{n\to\infty}n!n^{s-n}=0$, one could also show $\lim_\limits{n\to\infty}\log\left(n!n^{s-n}\right)=-\infty$. This would be equivalent to $\lim_\limits{n\to\infty}\log\left(n!\right)+\log\left(n^{s-n}\right)=-\infty$. Using the given inequality, it would be sufficient to prove $$\lim_\limits{n\to\infty}n\log\frac{n+1}2+\log\left(n^{s-n}\right)=-\infty\Leftrightarrow\lim_\limits{n\to\infty}n\log\frac{n+1}{2n}+s\log n=-\infty\\\Leftrightarrow\lim_\limits{n\to\infty}n\log\frac12+s\log n=-\infty.$$ What should I do now? A: The series $$\sum_\limits{n=1}^\infty\frac{n!n^s}{n^n}$$ is convergent by the ratio test (easy exercise). Therefore $$\lim_\limits{n\to\infty}\frac{n!n^s}{n^n}=0.$$
{ "pile_set_name": "StackExchange" }
Q: PHP Xpath simple search I'm trying to add two conditions to a search on my XML. Consider this XML: <?xml version="1.0"?> <votes> <vote> <url>http://www.mydoamin.com</url> <ip>xxx.xxx.xxx.xxx</ip> </vote> </votes> Then I use: $xml->xpath("(//votes/vote/[url='Admin' and ip='Group']"); But that give an invalid expression error: For a single condition this works: $xml->xpath("(//votes/vote/ip[contains(text(), '$ip')])"); Logic would suggest an AND would worK: $xml->xpath("(//votes/vote/ip[contains(text(), '$ip')]) & (//votes/vote/url[contains(text(), '$ip')])"); But this fails - Warning: SimpleXMLElement::xpath(): Invalid expression What am I doing wrong? A. A: Remove / between vote and [. XPath should look like //votes/vote[url='Admin' and ip='Group']
{ "pile_set_name": "StackExchange" }
Q: Java hashset vs Arrays.sort I am trying to solve the below 'codility' exercise: A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. Your goal is to find that missing element. Write a function: class Solution { public int solution(int[] A); } that, given a zero-indexed array A, returns the value of the missing element. For example, given array A such that: A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5 the function should return 4, as it is the missing element. Assume that: N is an integer within the range [0..100,000]; the elements of A are all distinct; each element of array A is an integer within the range [1..(N + 1)]. Complexity: expected worst-case time complexity is O(N); expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified. I came up with two solutions: 1) Gives 100%/100% class Solution { public int solution(int[] A) { int previous = 0; if (A.length != 0) { Arrays.sort(A); for (int i : A) { if (++previous != i) { return previous; } } } return ++previous; } } 2) Gives an error WRONG ANSWER, got 65536 expected 100001 class SolutionHS { public int solution(int[] A) { int previous = 0; HashSet<Integer> hs = new HashSet<>(); if (A.length != 0) { for (int a : A) { hs.add(a); } for (Integer i : hs) { if (++previous != i) { return previous; } } } return ++previous; } } My question is: Shouldn't both approaches (using hashset and Arrays.sort) work the same way? If not can you tell me what the difference is? A: HashSet is not sorted, so when you iterate over the elements of the Set, you don't get them in an ascending order, as your code expects. If you used a TreeSet instead of HashSet, your code would work. The HashSet solution will give the correct answer if you change the second loop to : for (int i = 0; i <= A.length; i++) { if (!hs.contains(i)) { return i; } } This loop explicitly checks whether each integer in the relevant range appears in the HashSet and returns the first (and only one) which doesn't. Anyway, both your implementations don't meet the O(n) running time and O(1) space requirements. In order you meet the required running time and space, you should calculate the sum of the elements of the array and subtract that sum from (A.length+1)*A.length/2.
{ "pile_set_name": "StackExchange" }
Q: Using ScheduledExecutorService, How to Start a Thread without waiting for other thread to complete at fixed interval? I want to run a task at every particular interval of time regardless of completion of previous thread. And I've used ScheduledExecutorService with the schedule time at every one second. But the problem is, in my Runnable, If I make thread to sleep for 5 seconds, My ScheduledExecuterService also getting executed in every 5 seconds while it supposed to run each thread at 1 second. It seems like it ScheduledExecuterService is waiting for previous thread to completion. But I want, The task to be triggered at every 1 second no matter what if job inside the task waits for longer time. Here's is my code. public class MyTask implements Runnable { public void run() { System.out.println("hi there at: "+ new java.util.Date()); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } And here's my ScheduledExecutorService Code. public class JavaScheduledExecutorServiceExample { public static void main(String[] args) { ScheduledExecutorService execService = Executors.newScheduledThreadPool(5); execService.scheduleAtFixedRate(new MyTask(), 0, 1000, TimeUnit.MILLISECONDS); } } Correct me If I'm doing something wrong. And If I'm wrong, is there any alternative to achieve the same? Providing Any best practices could be more helpful :) A: "If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute." The behavior you are seeing is consistent with the javadocs I believe this will perform the way you specified: public class JavaScheduledExecutorServiceExample { private static ScheduledExecutorService execService = null; private static int timesAsleep = 0; public static class MyTask implements Runnable { public void run() { System.out.println("hi there at: "+ new java.util.Date()); // schedule again execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS); try { int i = timesAsleep; timesAsleep++; System.out.println("asleep " + i + "----------------------"); Thread.sleep(5000); System.out.println("awoke " + i + "----------------------"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { execService = Executors.newScheduledThreadPool(5); execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS); } } Notice the use schedule() instead of scheduleAtFixedRate() on the ScheduledExecutorService instance. It also schedules the next task as soon as it starts the new task.
{ "pile_set_name": "StackExchange" }
Q: Соединить две окружности. В чём ошибка? Пытаюсь повторить полигон, тот что изображен зеленой линией на рисунке ниже. Пользовался этими советами: Совет первый Совет второй Оба дают результат с некоторым смещением вдоль окружностей. Помогите, пожалуйста, в чем моя ошибка. Jsfiddle проект Писал на JS, но подойдёт любое другое решение. Даже без кода, в чистой теории, в чем неверен мой подход. // A: Поскольку нужны только внешние касательные (могут быть ещё внутренние), то подход может быть не слишком сложным: Пусть центр большей окружности CR, меньшей cr. Вектор разности d, его длина и нормализованный вектор: d = cr - CR dlen = length(d) ud = d / dlen Общие касательные к окружностям разного радиуса пересекаются где-то в точке OP. Касательная вместе с радиусами к точкам касания образует два подобных прямоугольных треугольника (поскольку радиус перпендикулярен касательной). Из подобия следует Coeff = R / (R - r) OP = CR + d * Coeff Синус и косинус угла A этого треугольника ca = R / (dlen * Coeff) sa = Sqrt(1-ca*ca) Точки касания большой окружности могут быть получена поворотом вектора ud*R на A и -A P.x = CR.x + ca * R * ud.x + sa * R * ud.y P.y = CR.y - sa * R * ud.x + ca * R * ud.y Q.x = CR.x + ca * R * ud.x - sa * R * ud.y Q.y = CR.y + sa * R * ud.x + ca * R * ud.y Аналогично для малой окружности с использованием её центра и радиуса. Тест: fiddle: (подправил последовательность точек и знаки углов) let c1 = this.state.circles[0]; let c2 = this.state.circles[1]; let l = getVectorLen(c1,c2); let v = {x: c2.x-c1.x, y: c2.y-c1.y}; let uv = {x: v.x / l, y: v.y / l}; let ca = (c2.r - c1.r) / l; let sa = Math.sqrt(1 - ca*ca); let ps = [ c1.x - ca * c1.r * uv.x - sa * c1.r * uv.y, c1.y + sa * c1.r * uv.x - ca * c1.r * uv.y, c1.x - ca * c1.r * uv.x + sa * c1.r * uv.y, c1.y - sa * c1.r * uv.x - ca * c1.r * uv.y, c2.x - ca * c2.r * uv.x + sa * c2.r * uv.y, c2.y - sa * c2.r * uv.x - ca * c2.r * uv.y, c2.x - ca * c2.r * uv.x - sa * c2.r * uv.y, c2.y + sa * c2.r * uv.x - ca * c2.r * uv.y ];
{ "pile_set_name": "StackExchange" }
Q: Email hacking/masking prevention Can someone please explain to me how its possible that someone hacks a server and uses its email to send emails from a address thats not listed on the server and how to prevent it. When I look at the mail queue there are emails there from and to yahoo.com accounts, how does this happen and how can I prevent this. Running centos 6, interworx and qmail if that helps. A: This is the nature of how email works, unfortunately. There is nothing preventing you or I from sending an email from any address we choose, this is by design. What we can tell though is the IP address the email originated from in the mail headers, and this will give us an idea of where the original message came from. In the old internet, most mail servers were run as open relays. This means that to send an email from yahoo.com to google.com, you could use any open relay you found on the internet. If the IP got banned, its okay because it isn't your IP, and you could just change relays. Now, with most modern mail servers, this isn't really an option. SMTP servers will only relay a message if you are authenticated, preventing random internet users from abusing your services. The server would accept unauthenticated mail only for users on that particular mail server. Due to this change, spammers now need to completely compromise mail servers in order to abuse them. If an attacker compromises your server, there isn't much you can do to stop them from sending emails short of blocking outbound port 25 on the firewall. If you need to run a legitimate mail server, then this becomes a problem as you would be denying legit email from being sent. Also, I would check your IP against any blacklists. It may have ended up on some lists and you would then need to submit a delist request, including how you resolved the issue.
{ "pile_set_name": "StackExchange" }
Q: Create an event for tab pages in C# I am developing an application in C# Windows Forms, and I would like to create an event handler/event handlers based on whether or not a particular tab page of a tab control is selected. So for example, if I have three tab pages: tabPage1, tabPage2, tabPage3, which belong to tabControl1, I need the code to either: Have three separate event handlers for each tab page Have one event handler and inside of the event handler there is code which can determine the tab page that is currently selected (e.g. a case statement of some sort) I have looked at several examples thus far, but none seem to do what I need. How can I create this event/ these events? A: May be something like this: Make use of TabControl.Selected private void tabControl1_Selected(Object sender, TabControlEventArgs e) { if(e.TabPage == tabPage1) DoSomethingInRelationOfTab1(); else if(e.TabPage == tabPage2) DoSomethingInRelationOfTab2(); .... .... }
{ "pile_set_name": "StackExchange" }
Q: double click on mvc 4 web grid I am preparing a mvc 4 application and I am pretty new to it. I would like to implement a functionality like by double clicking a row of mvc 4 webgrid I should call an action method in ajax. But unfortunately I could not find how to implement double click on mvc 4 web grid. Can you please help me on that? A: You could use the .dblclick() event in jQuery. For example: <script type="text/javascript"> $(function() { $('table td').dblclick(function() { $.ajax({ url: '@Url.Action("SomeAction", "SomeController")', type: 'POST', success: function(result) { // do something with the result from your AJAX call } }); }); }); </script> Obviously there are lots of improvements that could be done to this code. For example you could use HTML5 data-* attributes on your grid to specify the url to the controller action that needs to be invoked and then externalize this script in a separate javascript file. You might also need to adjust the jQuery selector to match your WebGrid element.
{ "pile_set_name": "StackExchange" }
Q: OpenMesh: remove_property : is not a member of Decimater::DecimaterT I'm trying to use the decimater algorithm in OpenMesh. I followed the basic setup presented in this link: http://openmesh.org/Documentation/OpenMesh-2.0-Documentation/decimater_docu.html but I get the following error which is comes from the modquadrict.hh(part of the library). error C2039: 'remove_property' : is not a member of 'OpenMesh::Decimater::DecimaterT<MeshT>' main.cpp #include "MyMesh.h" #include <conio.h> #include <iostream> int main() { MyMesh mesh; decimater deci (mesh); HModQuadric hModQuad; if(!OpenMesh::IO::read_mesh(mesh, "models/monkey.obj")); { std::cout<<"Cannot read mesh"; } deci.add(hModQuad); std::cout << deci.module( hM).name() << std::endl; getch(); return 0; } MyMesh.h #pragma once // OpenMesh #pragma warning(push) #pragma warning(disable: 4267) #include <OpenMesh/Core/IO/MeshIO.hh> #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh> #include <OpenMesh/Tools/Decimater/ModQuadricT.hh> #include <OpenMesh/Tools/Decimater/DecimaterT.hh> #pragma warning(pop) //Additional mesh parameters struct MeshTraits : public OpenMesh::DefaultTraits { VertexAttributes(OpenMesh::Attributes::Normal); FaceAttributes(OpenMesh::Attributes::Normal); }; typedef OpenMesh::TriMesh_ArrayKernelT<MeshTraits> MyMesh; // Decimater type typedef OpenMesh::Decimater::DecimaterT< MyMesh > decimater; // Decimation Module Handle type typedef OpenMesh::Decimater::ModQuadricT< decimater >::Handle HModQuadric; A: The problem was with this line. typedef OpenMesh::Decimater::ModQuadricT< decimater >::Handle HModQuadric; it should be like this: typedef OpenMesh::Decimater::ModQuadricT< MyMesh >::Handle HModQuadric; I was referring the documentation from version 2.0 while working on version 3.0 With recent versions, the templating depend on the mesh and not the decimater.
{ "pile_set_name": "StackExchange" }
Q: Best way to reorganize array of objects I need reorganize and array of linked objects by id to only one tree object. The depth level is unknown, so that I think that it should be done recursively. What is the most efficient way? I have the next array of objects: const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 } ] I want restructure for have a only one object like a tree: const treeObj = { "id": 1, "children": [ { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] } ] } Each object has other many properties. A: You can use a recursive mapping function over all the children. const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 } ]; const res = arrObj[0];//assuming the first element is the root res.children = res.children.map(function getChildren(obj){ const child = arrObj.find(x => x.id === obj.id); if(child?.children) child.children = child.children.map(getChildren); return child || obj; }); console.log(res);
{ "pile_set_name": "StackExchange" }
Q: how to read cookies in jquery? I am creating a cookie with a key and value of an object using carhartl’s jQuery cookie plugin,In one of my method I call create cookie and right after that I call get cookie;but the read method doesn't work: makeCookie methode: function makeCookie(name,value){ $.cookie(name,value); } readCookie method: function readCookie(name){ $.parseJSON($.cookie(name)); } and calling these 2 methods: makeCookie('chatPopups',popUps); var all=readCookie('chatPopups'); alert(all); popUps is a global javascript object; The error I get is : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data can anybody help me? A: Solved the problem,changed makeCookie method to this: function makeCookie(name,value){ $.cookie(name,$.param(value),{ path: '/' }); } and readCookie method to this: function readCookie(name){ var readCookie=$.cookie(name); readCookie = readCookie.split('&'); if(readCookie.length != 0){ for (i=0; i<readCookie.length; i++) { readCookie[i] = readCookie[i].split('='); popUps[readCookie[i][0]] = readCookie[i][1]; } } }
{ "pile_set_name": "StackExchange" }
Q: Synchronized statement, unclear java doc example Currently I am trying to understand synchronized in Java getting to this java doc example under synchronized statements the example with the class MsLunch and the two instance variables c1 and c2. It states: Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. To me this sounds like c1 and c2 are not allowed to be used together. That is the reason why both statements which are incrementing c1 and c2 have to be synchronized. But why do they say in the next sentence that there is no reson to prevent an update of c1 from being interleaved with an update of c2. This sentences makes absolutely no sense to me. First they say they are not used together and now it is ok to increment c1 while at the same time c2 is being incremented. Can someone please elaborate this paragraph to me. Bear in mind that I am no native English speaker and there could be in fact a language problem in understanding this issue. A: c1 and c2 are two completely independant counters. A thread should be able to increament c1 while another thread increments c2. If you simply synchronized the inc1() and inc2() method, you would prevent thread 1 to increment c1 while thread 2 is incrementing c2 (and vice-versa). This would have a negative impact on performance. So you use two separate locks to synchronize each incrementation. If the value of c2 for example depended on the value of c1, then you would have to use a single lock to avoid race conditions.
{ "pile_set_name": "StackExchange" }
Q: Looking for up-to-date F# PowerPack Is there someone who working on F# Power Pack ? Seriously - last update is Dec10 for old F# Core. So I've got own rebuild for some parts (Linq2sql) for .net4 and new core and I think there is someone else who got the same and someone who is working on it - where can I find it ? Or F# PP is dead ? Also I can see only lesser compiler fixes. I like this work but it's not official tree. OK, just kidding, the question is still being about F# Power Pack. A: According to a comment in this blog post, updating the F# PowerPack isn't a high priority just yet.
{ "pile_set_name": "StackExchange" }
Q: Unity Sprite Editor: Can You Preview A Background Image While Setting Pivot? I've Googled around a lot, and I checked the Unity Asset store but I cannot seem to find what I think is a common problem (or perhaps I'm doing it wrong). The issue is when I use the Sprite Editor I cannot see a reference image which is useful for setting the sprite pivot. When I open the Sprite Editor on a given image file, I cannot seem to add a background reference image: I want to be able to see a background image (of a specific character for example) that I can position and then use that to set the pivot. Do you know of any way to do this? Asset Store references are acceptable. I found one for Animation pivot setting but not for static images. Any and all suggestions welcome (if you have a workflow suggestion that mitigates this issue, feel free to suggest :) ) A: I found a free option that works well enough: http://gnupart.tistory.com/entry/Unity3D-Custom-Sprite-Pivot-Editor-in-SceneView
{ "pile_set_name": "StackExchange" }
Q: Trouble updating a UIImageView selected from iphone photo library I'm using the code below to retrieve an image from the iphone photo library. self.selectedImageView.image is an image view located on top of the view of the current view controller. Everything in xcode seems linked correctly; the image view is wired and so fourth. Problem: After selecting an image I can see that this method is called but the new image does not update. The image view is completely blank. Question: Is their some sort of refreshing that needs to take place after reassigning a new image to an image view? - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSLog(@"image selected"); [picker dismissViewControllerAnimated:YES completion:NULL]; UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; self.selectedImageView.image = chosenImage; } A: Try using the key UIImagePickerControllerOriginalImage instead. The key your currently using, UIImagePickerControllerEditedImage, is for accessing images that the user has edited. -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ // Get the image first then dismiss the controller. UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; [self dismissViewControllerAnimated:YES completion:nil]; self.selectedImageView.image = chosenImage; }
{ "pile_set_name": "StackExchange" }
Q: How can I export content-type and content from one site to another? I got handed over a drupal 7 site with two branches, one is now in production and other is dev. I am working on dev and had to create new content types and made changes existing content types. In the meantime other users made some changes to content-type and content. Administration want to merge content types and retain the latest content. What is the workflow to do this kind of stuff. In the past I only had to clone whole site so I used rsync to sync file and export/import db. This looks like way more complicated than I anticipated as both sites have same content types but with some degree of variation in field names and types. From my current Drupal knowledge it seems like a very complex task. Where should I start and which approach/technique should I use? I went through other answers and found that the Node export module can export the node but how can I export the content and map the fields from one content type to another ? A: Node Export Looks like you are already familiar with the Node export module, allows users to export nodes and then import it into another Drupal installation. Bundle copy The Bundle copy module has support for export/import of: Node types. Taxonomy. User. Field API fields. Field groups.
{ "pile_set_name": "StackExchange" }
Q: I want a shadow on the floor for all my objects in SWIFT / Scenekit I'm working on an ARKit project in swift. In SWIFT I add objects to the scene. What I want to do with those objects is show a shadow beneath them to make them more realistic. I tried some things and those all didn't work. I'll explain that here. Please understand that I'm still new to swift. I'm creating objects programmatically in SWIFT. I thought I could do it by creating a invisible plane underneath all the objects and place a light above the scene. I learned that I can cast a shadow on an invisible plane in the Scene editor from Xcode by unchecking the "write to color" values red, green, blue and alpha. I placed a spot light above it and it worked. Now I want to do this programatically. In swift I created the light's and the plane as shown below. I don't use a spot anymore because the scene is so large. That's why I create a really large plane. I added those to light's ambient and directional. Ambient so it doesn't look black on the side and directional so the shadow is shown. This doesn't. The objects look weirdly lit and there are no shadows. let worldGroundPlaneGeometry = SCNPlane(width: 1000, height: 1000) worldGroundPlaneGeometry.firstMaterial?.colorBufferWriteMask = SCNColorMask(rawValue: 0) let worldGroundPlane = SCNNode() worldGroundPlane.geometry = worldGroundPlaneGeometry worldGroundPlane.position = worldPosition worldGroundPlane.castsShadow = true worldGroundPlane.eulerAngles = SCNVector3(Float.pi / 2, 0, 0) self.addChildNode(worldGroundPlane) // Create a ambient light let ambientLight = SCNNode() ambientLight.light = SCNLight() ambientLight.light?.color = UIColor.white ambientLight.light?.type = SCNLight.LightType.ambient ambientLight.position = SCNVector3(x: 0,y: 5,z: 0) // Create a directional light node with shadow let directionalNode = SCNNode() directionalNode.light = SCNLight() directionalNode.light?.type = SCNLight.LightType.directional directionalNode.light?.color = UIColor.white directionalNode.light?.castsShadow = true directionalNode.light?.automaticallyAdjustsShadowProjection = true directionalNode.light?.shadowSampleCount = 64 directionalNode.light?.shadowMode = .deferred directionalNode.light?.shadowMapSize = CGSize(width: 2048, height: 2048) directionalNode.light?.shadowColor = UIColor.black.withAlphaComponent(0.75) directionalNode.position = SCNVector3(x: 0,y: 5,z: 0) // Add the lights to the container self.addChildNode(ambientLight) self.addChildNode(directionalNode) It needs to look like this in the whole scene: P.S. The object and shadow look the same if I render it on my phone inside the app. I Hope you can help me find a solution to achieve the goal described above. I hope you can help me! Thanks EDIT: The solution provided below is not the solution. Now my scene looks like this with still no shadow: the code: let worldGroundPlaneGeometry = SCNPlane(width: 1000, height: 1000) let worldGroundPlane = SCNNode() worldGroundPlane.geometry?.firstMaterial?.lightingModel = .constant worldGroundPlane.geometry?.firstMaterial?.writesToDepthBuffer = true worldGroundPlane.geometry?.firstMaterial?.colorBufferWriteMask = [] worldGroundPlane.geometry = worldGroundPlaneGeometry worldGroundPlane.position = worldPosition worldGroundPlane.castsShadow = true worldGroundPlane.eulerAngles = SCNVector3(Float.pi / 2, 0, 0) self.addChildNode(worldGroundPlane) // Create a ambient light let ambientLight = SCNNode() ambientLight.light = SCNLight() ambientLight.light?.shadowMode = .deferred ambientLight.light?.color = UIColor.white ambientLight.light?.type = SCNLight.LightType.ambient ambientLight.position = SCNVector3(x: 0,y: 5,z: 0) // Create a directional light node with shadow let directionalNode = SCNNode() directionalNode.light = SCNLight() directionalNode.light?.type = SCNLight.LightType.directional directionalNode.light?.color = UIColor.white directionalNode.light?.castsShadow = true directionalNode.light?.automaticallyAdjustsShadowProjection = true directionalNode.light?.shadowSampleCount = 64 directionalNode.light?.shadowMode = .deferred directionalNode.light?.shadowMapSize = CGSize(width: 2048, height: 2048) directionalNode.light?.shadowColor = UIColor.black.withAlphaComponent(0.75) directionalNode.position = SCNVector3(x: 0,y: 5,z: 0) // Add the lights to the container self.addChildNode(ambientLight) self.addChildNode(directionalNode) A: I was playing around with your lighting setup and found the ambient light gave it a very washed out look... & the shadow seemed too unnaturally dark. Anwway I tweaked your light setup configuration to the following. I got rid of the ambient light all together, and I added a constraint on the object node (timber box) is this case. I also controlled the lighting intensity with just one directional light. let directionalNode = SCNNode() let constraint = SCNLookAtConstraint(target:node) directionalNode.light = SCNLight() directionalNode.light?.type = .directional directionalNode.light?.color = UIColor.white directionalNode.light?.castsShadow = true directionalNode.light?.intensity = 2000 directionalNode.light?.shadowRadius = 16 directionalNode.light?.shadowMode = .deferred directionalNode.eulerAngles = SCNVector3(Float.pi/2,0,0) directionalNode.light?.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) directionalNode.position = SCNVector3((node?.position.x)! + 10,(node?.position.y)! + 30,(node?.position.z)!+30) directionalNode.constraints = [constraint] // Add the lights to the container self.sceneView.scene.rootNode.addChildNode(directionalNode)
{ "pile_set_name": "StackExchange" }
Q: Haskell if then else with "two statements" How can I do this: if n > 0 then putStrLn "Hello" putStrLn "Anything" I want to have "two statements" in one condition but I keep getting compilation errors I tried using semi-colon with no luck A: then can only take one value.... But you are in luck, because do smashes multiple IO() values into one.... if n > 0 then do putStrLn "Hello" putStrLn "Anything" else return () Remember, in Haskell, you need an else also (and return () creates the trivial IO() that does nothing). A: Your example wouldn't make sense in Haskell. Every expression needs to have a value, which is why you always need to have an else, even if it is just return (). Because it needs to be a single expression, you can't just do putStrLn "Hello" putStrLn "Anything" since those are two expressions of type IO (), which means it is a computatinon with some external effects, and that there is no result. You have two computations that need to run in a sequence, which can be done using the >> combinator putStrLn "Hello" >> putStrLn "Anything" There is also an alternative syntax using the do block. do putStrLn "Hello" putStrLn "Anything" The important thing to note here is that this will compile to the same >> code as the example above. The do block can be thought of just as syntactic sugar (there is more to it, but for simplicity you can think of it that way.) Putting this all together leaves us with if n > 0 then putStrLn "Hello" >> putStrLn "Anything" else return () or using the do block if n > 0 then do putStrLn "Hello" putStrLn "Anything" else return () Because this pattern is quite common, there is a when combinator (in Control.Monad), which does precisely this when (n > 0) do putStrLn "Hello" putStrLn "Anything" or just simply when (n > 0) (putStrLn "Hello" >> putStrLn "Anything")
{ "pile_set_name": "StackExchange" }
Q: How to set previous value when cancelling a drop-down list with Angular Directive? I have an angular directive that you add to any 'select' element to give it a cool modal pop up and add a custom message (which I omitted from this example). I'm trying, in the directive, to make it so when the user clicks cancel the value goes back to what it was, otherwise it appears that it has changed. I can this normally in jquery without this weird modal setup I have Here's a working plnkr with info - http://plnkr.co/edit/JRi5AsarX9AztCWLx1QR?p=preview Angular Directive: angular.module('plunker', ['ui.bootstrap']).directive('ngConfirmClick', ['$modal', function($modal) { return { restrict: 'A', scope:{ ngConfirmClick:"&", item:"=" }, link: function(scope, element, attrs) { if(element.context.tagName == 'SELECT'){ $("select").change(function() { var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.ok = function() { $modalInstance.close(); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var message = attrs.ngConfirmMessage || "Are you sure ?"; var modalHtml = '<div class="modal-header" id="confirm-box"><h4 id="title-color" class="modal-title"><i class="fa fa-exclamation"></i> Please Confirm</h4></div><div class="modal-body">' + message + '</div>'; modalHtml += '<div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>'; var modalInstance = $modal.open({ template: modalHtml, controller: ModalInstanceCtrl }); modalInstance.result.then(function() { scope.ngConfirmClick({item:scope.item}); }, function() { }); }); } } } } ]); HTML <div ng-controller="ModalDemoCtrl"> <b>This is the list I'm looping through:</b> <h3>{{peoples}}</h3> When I cancel I want to return to the value Sam or whatever value was selected at the time of cancel. <select ng-confirm-click="sendPost()" ng-model="selectedPerson" class="form-control-dropdown" ng-options="people as people for people in peoples"></select> </div> controller: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCtrl = function ($scope, $modal, $log) { $scope.selectedPerson = 'Sam'; $scope.peoples = ['Sam', 'Randy', 'Joe'] ; $scope.sendPost = function(){ console.log('this makes a POST call normally'); }; }; I have tried a lot to get this working, some methods more hacky than other. My problem is I for some reason can't figure out, once I'm inside the $modalinstance to pass the original value A: Please check the updated plunker. I did a small change. I have added ngModel in scope variable and just maintaining the oldValue in the variable from scope.ngModel
{ "pile_set_name": "StackExchange" }
Q: Get MySQL Path Columns of Subpages Into Hierarchical Array And Output To Tiered I have a MySQL table with content for a custom CMS I've built. There are a number of columns, but the ones dealing with the paths are: path (full path to the page, e.g. /category/page1/ ) parentpath (path up to that particular page, e.g. /category/ ) childpath (path following the parentpath, e.g. page1/ ) I've written a function that gets all subpages of a particular page into an array, and another that outputs them into li elements. function get_subpages($path) { $GetSubpages=mysql_query("SELECT * FROM content WHERE parentpath='$path'"); while ( $SubpageLoop = mysql_fetch_assoc($GetSubpages) ) { $Subpages[] = $SubpageLoop; } unset($GetSubpages); return $Subpages; } and function list_subpages($path) { $Subpages=get_subpages($path); if ($Subpages) { $Output=""; foreach($Subpages as $Subpage) { $Output .= '<li><a href="'.$Subpage[path].'">'.$Subpage[title].'</a></li>'; } } return $Output; } However, I would like to have the functions operate so that the array produced is hierarchical, corresponding to the page structure, along with the HTML list that is produced. I've been experimenting with the DISTINCT operator in the SQL query, and then creating a secondary loop to then get the subpages of each result, but without much luck mysql_query("SELECT DISTINCT parentpath FROM content WHERE parentpath LIKE '$path%' ORDER BY path ASC"); I also started playing with a preg_match to catch any items with a slash in the middle of them and then run another query using one of the array results, but haven't been able to figure out exactly how to get that to work the way I want. preg_match ( "/^(.*)\/(.*)\//", $ParentLevel, $Matches ); I'm just having a really hard time piecing it together. Can anyone help me out? A: Figured it out: function has_immediate_children($path) { $path=sanitize($path); $GetImmediateChildren=mysql_query("SELECT path FROM content WHERE parentpath='$path' ORDER BY path ASC"); if ( mysql_num_rows($GetImmediateChildren)>0) { return true; } else { return false; } } function get_immediate_children($path) { $path=sanitize($path); $GetImmediateChildren=mysql_query("SELECT * FROM content WHERE parentpath='$path' ORDER BY path ASC"); while ( $ImmediateChildrenLoop = mysql_fetch_assoc($GetImmediateChildren) ) { $ImmediateChildren[]=$ImmediateChildrenLoop; } return $ImmediateChildren; } function get_all_subpages($path) { $path=sanitize($path); $ImmediateChildren=get_immediate_children($path); echo '<ul>'; foreach ($ImmediateChildren as $ImmediateChild) { echo '<li><a href="'.$ImmediateChild[path].'">'.$ImmediateChild[title].'</a></li>'; if ( has_immediate_children($ImmediateChild[path]) ) { get_all_subpages($ImmediateChild[path]); } } echo '</ul>'; }
{ "pile_set_name": "StackExchange" }
Q: Manually Start Ubuntu One Daemon I would like to be able to manually start and stop the Ubuntu One Daemon. However, I need to know: What is the name of the ubuntu one daemon ? Can I use update-rc.d (ubuntu one daemon) disable & to manually start it? Any help will be greatly appreciated. Updated Remove It From Auto Starting When System Boots . i did it with update-rc.d bluetooth disable A: Ubuntuone is autostarted from /etc/xdg/autostart/ubuntuone-launch.desktop not from upstart. gnome-session-properties OR StartUp Appication Preference on session-indicator doesnot let you enable/disable the autostart application in /etc/xdg/autostart as most of them contain NoDisplay=true. What you can do is either: Comment the line NoDisplay=true as #NoDisplay=true and disable it from the above mentioned guis. OR do: mv /etc/xdg/autostart/ubuntuone-launch.desktop /etc/xdg/autostart/ubuntuone-launch.desktop.disabled How do I add/remove the "hidden" startup applications?
{ "pile_set_name": "StackExchange" }
Q: Download a zip archive and extract one file from it I wrote a function that downloads a file https://www.ohjelmointiputka.net/tiedostot/junar.zip if it not already downloaded, unzips it and returns the content of junar1.in found in this zip. I have PEP8 complaints about the length of lines that I would like to fix. Is there a way to make the code more readable? My code : import os.path import urllib.request import shutil import zipfile def download_and_return_content(): if not os.path.isfile('/tmp/junar.zip'): url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip' with urllib.request.urlopen(url) as response, open('junar.zip', 'wb') as out: data = response.read() # a `bytes` object out.write(data) shutil.move('junar.zip','/tmp') with zipfile.ZipFile('/tmp/junar.zip', 'r') as zip_ref: zip_ref.extractall('/tmp/') with open('/tmp/junar1.in') as f: return f.read() A: Let's start refactoring/optimizations: urllib should be replaced with requests library which is the de facto standard for making HTTP requests in Python and has reach and flexible interface. instead of moving from intermediate location (shutil.move('junar.zip','/tmp')) we can just save the downloaded zip file to a destination path with open('/tmp/junar.zip', 'wb') as out decompose the initial function into 2 separate routines: one for downloading zipfile from specified location/url and the other - for reading a specified (passed as an argument) zipfile's member/inner file reading from zipfile.ZipFile.open directly to avoid intermediate extraction. Otherwise zipfile contents should be extracted at once, then - just reading a regular files being extracted (with adjusting the "reading" function) From theory to practice: import os.path import requests import zipfile import warnings def download_zipfile(url): if not os.path.isfile('/tmp/junar.zip'): with open('/tmp/junar.zip', 'wb') as out: out.write(requests.get(url).content) def read_zipfile_item(filename): with zipfile.ZipFile('/tmp/junar.zip') as zip_file: with zip_file.open(filename) as f: return f.read().decode('utf8') # Testing url = 'https://www.ohjelmointiputka.net/tiedostot/junar.zip' download_zipfile(url=url) print(read_zipfile_item('junar1.in')) The actual output (until the input url is accessible): 10 6 1 4 10 7 2 3 9 5 8
{ "pile_set_name": "StackExchange" }
Q: jQuery clone with radio I have trouble to $_POST radio and radio selection if i use jquery clone method. Below code i have Gender selection. If user can click on add-more link clone gender and append to same form. HTML <form action="test.php" method="post"> <div id="one"> <input type="radio" name="gender" value="1" />Male<br /> <input type="radio" name="gender" value="2" />Female<br /> </div> <div id="appendBefore"></div> <a href="#" onclick="addMore();">Add More</a> </form> jQuery <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> function addMore(){ var copy_ = $("#one").clone(); copy_.insertBefore('#appendBefore'); } </script> PHP print_r($_POST); Q - 1. Radio not checked properly. Q - 2. Radio not posted properly in php. Thanks. A: The issue is here: <input type="radio" name="gender" value="1" />Male<br /> <input type="radio" name="gender" value="2" />Female<br /> You can only check one radio with in a same group (having the same name). In your case when you clone and append the radio's, the new group is also having the same name, that's why you can only select one from all the radio's. To resolve this, you have to make the radio's name different for each group. Maintain a counter like thing with the name and every thing will be fine. Ex: <p> Block 1 </p> <input type="radio" name="gender1" value="1" />Male<br /> <input type="radio" name="gender1" value="2" />Female<br /> <p> Block 2 </p> <input type="radio" name="gender2" value="1" />Male<br /> <input type="radio" name="gender2" value="2" />Female<br /> JSFiddle with proposed solution
{ "pile_set_name": "StackExchange" }
Q: Angular2 Testing: Service returning function instead of object array I want to write some tests for my service written in Angular 2.1.0: @Injectable() export class MyService { api_base_url = 'http://' + environment.apiHost + ':5000/api/'; constructor(private http: Http) { } getMyObjs(query): Observable<MyObj[]> { let params = new URLSearchParams(); if (query != null && query.length > 0) params.set('q', query); return this.http.get(this.api_base_url + 'entries/' + pipelineId, {search: params}) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response) { let body = res.json(); return body.entries || {}; } private handleError(error: any) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } } And here is the test so far: describe('Service: Entry', () => { beforeEach(async(() => { TestBed.configureTestingModule({ providers: [ BaseRequestOptions, MockBackend, MyService, { provide: Http, useFactory: (backend: MockBackend, options: BaseRequestOptions) => { return new Http(backend, options); }, deps: [MockBackend, BaseRequestOptions] } ] }); })); it('should return myobjs', inject([MockBackend, MyService], (backend: MockBackend, service: MyService) => { const my_body = JSON.stringify([ { "timestamp": "2016.01.01T12:55:00Z", "level": 0, } ]); const baseResponse = new Response(new ResponseOptions({body: my_body, status: 200})) backend.connections.subscribe((connection: MockConnection) => { return connection.mockRespond(baseResponse); }); service.getMyObjs(null).subscribe((obs: MyObj[]) => { console.log(obs); expect(obs.length).toBe(1); }); })); }); This test fails saying Expected 0 to be 1.. The console.log shows LOG: function obs() { ... }. I do not undestand why this is a function and not an array of objects. I'm runnign the tests with ng test command. A: In the mocked HTTP response you return object structure that is different from what extractData() is expecting. I suppose it should look like this: // ... stuff ... it('should return myobjs', ...) => { const my_body = JSON.stringify({ entries: [{ "timestamp": "2016.01.01T12:55:00Z", "level": 0, }] });
{ "pile_set_name": "StackExchange" }
Q: AngularJS select change trigger I am trying to do a script that will copy the value of one select tag model to another and then trigger its ng-change function using a checkbox. What happens is when you click the checkbox, it does copy the value but the trigger does not work anymore. Seems like there is a conflict between setting a model's value and doing the trigger because either one of them fails. Here is my code: <!DOCTYPE html> <html ng-app="myApp"> <head> <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> </head> <body ng-controller="myCtrl"> <select ng-model="first.selection" id="first" ng-change="changeOver('dean')"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <br /> <input type="checkbox" ng-model="same" id="same" ng-change="sameAsAbove(first, second)"> Same as above <br /> <select ng-model="second.selection" id="second" ng-change="changeOver('armada')"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <!-- <span id="clickMe">Click Me!</span> --> <script type="text/javascript"> app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $timeout){ $scope.first = {}; $scope.second = {}; $scope.sameAsAbove = function(primary, receiver){ receiver['selection'] = primary['selection']; $timeout(function() { angular.element(document.getElementById('second')).triggerHandler('change'); }, 100); }; $scope.changeOver = function(value){ alert(value); } }); $("#clickMe").click(function(){ // alert("czxvzx"); // $("#same").trigger("click"); $("#changes").change(); }); </script> </body> </html> Here is the plunkr url: http://plnkr.co/edit/zErS4DaTgR79SBLbtGOy?p=preview A: In DOM body you should change this line like this. <select ng-model="second.selection" id="second" ng-change="same=second.selection"> and use watch to change the checkbox value $scope.$watch("same", function(newValue, oldValue){ $scope.changeOver('armada'); //or do anything }); plunker demo link
{ "pile_set_name": "StackExchange" }
Q: Golang: Issues replacing newlines in a string from a text file I've been trying to have a File be read, which will then put the read material into a string. Then the string will get split by line into multiple strings: absPath, _ := filepath.Abs("../Go/input.txt") data, err := ioutil.ReadFile(absPath) if err != nil { panic(err) } input := string(data) The input.txt is read as: a strong little bird with a very big heart went to school one day and forgot his food at home However, re = regexp.MustCompile("\\n") input = re.ReplaceAllString(input, " ") turns the text into a mangled mess of: homeot his food atand I'm not sure how replacing newlines can mess up so badly to the point where the text inverts itself A: I guess that you are running the code using Windows. Observe that if you print out the length of the resulting string, it will show something over 100 characters. The reason is that Windows uses not only newlines (\n) but also carriage returns (\r) - so a newline in Windows is actually \r\n, not \n. To properly filter them out of your string, use: re = regexp.MustCompile(`\r?\n`) input = re.ReplaceAllString(input, " ") The backticks will make sure that you don't need to quote the backslashes in the regular expression. I used the question mark for the carriage return to make sure that your code works on other platforms as well. A: I do not think that you need to use regex for such an easy task. This can be achieved with just absPath, _ := filepath.Abs("../Go/input.txt") data, _ := ioutil.ReadFile(absPath) input := string(data) strings.Replace(input, "\n","",-1) example of removing \n
{ "pile_set_name": "StackExchange" }
Q: Should I provide login functionality in mobile version? I am working on a mobile version of the new website for my company, if users visit my website on a mobile device/tablet, they will be asked whether the visitor wants to go to the mobile version or the normal version. But on the normal version I have login functionality, so users can visit their data and so on. Should I "translate" that functionality to mobile as well? Do visitors login a lot on mobile devices, or is it a waste of time? A: The simple answer would be "yes, do it". But I think this is not an easy choice to make if you're asking that here. So I think it depends a lot of the kind of service you are providing. For example, the facebook's app would be useless without login feature while I don't really mind if I can't connect to my smashing magazine account on mobile. You should take a look at the website's stats. What are the most visited pages ? Without login in, are the users going to miss the main features ?
{ "pile_set_name": "StackExchange" }
Q: combineReducers is overwriting state instead of setting up different states I'm trying to learn Redux. I have this action which fetches data: export const FETCH_SUCCESS = "FETCH_SUCCESS"; import axios from "axios"; export const fetchData = () => { return async dispatch => { try { const result = await axios( `url` ); dispatch({ type: FETCH_SUCCESS, payload: { result } }); } catch (error) { console.log(error); } }; }; And this reducer: import { FETCH_SUCCESS } from "../actions/mainCategories"; const initialState = { mainCategories: [] }; const mainCategoriesReducer = (state = initialState, action) => { switch (action.type) { case FETCH_SUCCESS: return { data: action.payload.result.data }; default: return state; } }; export default mainCategoriesReducer; I use this twice, one for the mainCategories and the exact same code for my subcategories but in different files, so that I can combine it in App.js like this: import mainCategoriesReducer from "./store/reducers/mainCategories"; import subCategoriesReducer from "./store/reducers/subCategories"; const rootReducer = combineReducers({ mainCategories: mainCategoriesReducer, subCategories: subCategoriesReducer, }); const store = createStore(rootReducer, applyMiddleware(ReduxThunk)); I wrap the Provider with the stored store around my App: <Provider store={store}> <App /> </Provider> In the components I use it like this: import { fetchData } from "../store/actions/mainCategories"; const mainCategories = useSelector(state => state.mainCategories); useEffect(() => { dispatch(fetchData()); }, [dispatch]); And the same for the subCategories but with the corresponding imports and states (state.subCategories) Everything is working as expected. When the App loads, it fetches my mainCategories. I can navigate to my subcategories but when I go back, the mainCategories are overwritten by the subCategories. It seems like the combineReducers merges / overwrites instead of creating the different states. What am I doing wrong? Thank you A: You need different type names to make this work. When you combine reducers, it's important that the app knows how to route your actions to the correct store. If you want to call them both FETCH_SUCCESS, I think that's fine, but add the path in front of the definition: in your main categories actions file: export const FETCH_SUCCESS = "mainCategories/FETCH_SUCCESS"; and in your subcategories actions file: export const FETCH_SUCCESS = "subCategories/FETCH_SUCCESS"; That should work, but you may also need to rename the FETCH_SUCCESS variables if it's still not working.
{ "pile_set_name": "StackExchange" }
Q: Get iOS ID not FCM Id in Ionic 2 with Phonegap Push Plugin I'm developing app in Ionic 2. I installed phonegap push plugin https://github.com/phonegap/phonegap-plugin-push to get notifications and get device ID. When I'm in Android App the device ID of return is a GCM ID, but when I'm in iOS he return FCM Id, and I don't need that, I want get Push Plugin register: This is example of my issue: FCM Registration Token: cqs2H3ED5u8:APA91bEVQGi0SfbC1Yau1xN_PJB0SOmB50PgHMNG2zCqw4bzWfLruXfqKoIT7DeJnz5K37CqQLIs9F-CXfwurC-UhZjfLNUvnEfCZDpIleW_6xGZYZKokNcIPouGHdvdSnVMhHu6mITh Push Plugin register success: <5c27c9a8 87e28030 735f8bc7 e27ab8de e6d6538f c9759e70 26c306a6 fa0ac2cc> How to configure push plugin init to make this change? A: I open issue on Phonegap project. https://github.com/phonegap/phonegap-plugin-push/issues/1982 The answer was “Yes, when you remove the GoogleService-Info.plist from iOS it uses APNS but as long as you keep delivering google-service.json it uses FCM. Actually, Android won't work without the google-service.json file” If you want use APNS on iOS platform you have to remove GoogleService-info.plist (is optional on iOS and necessary on Android)
{ "pile_set_name": "StackExchange" }
Q: How to get the primary route, if it doesn't exist and we are being sent to 404 page So basically I am trying to debug my routes, because they are not working as intended, but when using the profiler, I can see the URI string, which is basically the second part of URL in the browser address bar and CLASS/METHOD which are always of the 404 page that I am being redirected to. So how can I get the primary routes Class, Method and arguments/parameters that were attempted to run before being sent to 404? E.g. $route['en/catalog/(.+)/(.+)'] = "ccatalog/index/$1/$2"; something's gone wrong and I get redirected to the 404, but I want to see which class (most likely "ccatalog" here), which method (hopefully "index") and arguments ($1, $2). Thank you in advance to anyone who could help me with my problem! A: Actually, this was done really easy: $this->uri->rsegment(1);
{ "pile_set_name": "StackExchange" }
Q: why the height of the out div is affected by vertical-align in chrome, I thought the height of .wrap should be 24px. it is 25px when the vertial-align is set to middle. can someone explain why? answer in this article body { line-height: 1.5; } .wrap { font-size:16px; /* 16*1.5= 24 */ } .btn { font-size: 14px; padding: 4px; line-height: 1; box-sizing: border-box; border: 1px solid blue; vertical-align: middle; } <div class="wrap"> <button class="btn"> OK </button> </div> A: As It is explained Here Aligns the middle of the element with the baseline plus half the x-height of the parent. The line-height of your .wrap element is by default 1.5 that inherits from the body, the vertical align property will render depending on your line-height, so if the line height is bigger than your wrapper element, you will see the effect. to fix it just put line-height in your .wrap class, you can play with it to see how the line-height affects the vertical alignment. body { line-height: 1.5; } .wrap { line-height:1; background:red; } .btn { font-size: 14px; padding: 4px; line-height: 1; box-sizing: border-box; border: 1px solid blue; vertical-align: middle; } <div class="wrap"> <button class="btn"> OK </button> </div>
{ "pile_set_name": "StackExchange" }
Q: Плавающий блок с position:fixed На пальцах объяснить трудно, вот пикча, того что я хочу сделать: Зеленые блоки это блоки с position:fixed; Красные полоски - границы экрана; Желтые блоки - это области в которых из которых не могут выйти зеленые блоки. Если листать выше или ниже, то зеленые блоки остаются на крайней границе желтых; Каким способом лучше сделать? A: Рабочий пример html <div id="railway_lines"> <div class="rails"> <div class="truck"></div> </div> <div class="rails"> <div class="truck"></div> </div> </div> css div#railway_lines { background-color: #55c1ff; height: 1200px; position: relative; } div.rails, div.truck { width: 80px; } div.rails { background-color: #ffee33; height: 800px; position: absolute; top: 100px; } div.rails:first-child { left: 0; } div.rails:not(:first-child) { right: 0; } div.truck { background-color: #00ff00; position: fixed; height: 120px; top: 100px; } javascript var truck = $(".truck"), rails = $(".rails"), css_top_onmove = $(rails[0]).css('top'), css_top_onhold = $(rails).height() - $(truck).height(), css_left = $(rails[0]).css('left'), css_right = $(rails[1]).css('right'); $(window).scroll(function () { var pos_top = $(window).scrollTop(); if (pos_top > css_top_onhold) { $(truck).css({ 'position': 'absolute', 'top': css_top_onhold + 'px' }); $(truck[0]).css('left', css_left); $(truck[1]).css('right', css_right); } else { $(truck).css({ 'position': 'fixed', 'top': css_top_onmove, 'left': '', 'right': '' }); } });
{ "pile_set_name": "StackExchange" }
Q: How do cursors work in Python's DB-API? I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor. Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb): connection = psycopg2.connect(host='otherhost', etc) And then one creates a cursor: cursor = connection.cursor() And then one can issue queries and commands: cursor.execute("SELECT * FROM etc") Now where is the result of the query, I wonder? is it on the server? or a little on my client and a little on my server? And then, if we need to access some results, we fetch 'em: rows = cursor.fetchone() or rows = cursor.fetchmany() Now lets say, I do not retrieve all the rows, and decide to execute another query, what will happen to the previous results? Is their an overhead. Also, should I create a cursor for every form of command and continuously reuse it for those same commands somehow; I head psycopg2 can somehow optimize commands that are executed many times but with different values, how and is it worth it? Thx A: ya, i know it's months old :P DB-API's cursor appears to be closely modeled after SQL cursors. AFA resource(rows) management is concerned, DB-API does not specify whether the client must retrieve all the rows or DECLARE an actual SQL cursor. As long as the fetchXXX interfaces do what they're supposed to, DB-API is happy. AFA psycopg2 cursors are concerned(as you may well know), "unnamed DB-API cursors" will fetch the entire result set--AFAIK buffered in memory by libpq. "named DB-API cursors"(a psycopg2 concept that may not be portable), will request the rows on demand(fetchXXX methods). As cited by "unbeknown", executemany can be used to optimize multiple runs of the same command. However, it doesn't accommodate for the need of prepared statements; when repeat executions of a statement with different parameter sets is not directly sequential, executemany() will perform just as well as execute(). DB-API does "provide" driver authors with the ability to cache executed statements, but its implementation(what's the scope/lifetime of the statement?) is undefined, so it's impossible to set expectations across DB-API implementations. If you are loading lots of data into PostgreSQL, I would strongly recommend trying to find a way to use COPY.
{ "pile_set_name": "StackExchange" }
Q: Pass method calls to object I am trying to create a custom swipe gesture recognizer to set allowed angles and distances. So far it works really well but needs a lot of code in the view controller. So my question is wether it is possible to somehow pass a method call like: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event in the view controller to my gesture recogniser object so that I don't have to write something like this - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.swipeGestureRecognizer touchesBegan:touches withEvent:event]; } into my view controller. I think the build in UIGestureRecognizer does this somehow but I could not figure out how it works. I really would appreciate your help. [EDIT] Generic example: I have an object A which creates an object B. A has a method c that gets called sometimes. What I want to achieve is that a method d of B gets called when c in A gets called. So to somehow forward or pass this method call. Specific example: The following method gets called in my view controller every time there is a touch on the screen: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event but I actually want my GestureRecognizer object to process this information so I have the same method in my GestureRecognizer object and I want this method to get called every time the counterpart in the view controller gets called. A: Sub class UIGestureRecognizer and create a class called CustomGestureRecognizer. Its .m file will look like this @implementation CustomGestureRecognizer - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // do your code here } @end Some where in the subclass you have to change the state of the recognizer to UIGestureRecognizerStateRecognized when the current gesture is registered, else change to UIGestureRecognizerStateFailed . Now in the view controller where you want to use this recognizer do : CustomGestureRecognizer * recognizer = [[CustomGestureRecognizer alloc] initWithTarget:self action:@selector(handleChange:)]; recognizer.delegate = self; [self.view addGestureRecognizer:recognizer]; Detailed explanation is given here Apple doc, under subclassing.
{ "pile_set_name": "StackExchange" }
Q: Infima and Inequalities This is a question about "taking the inf" that is done everywhere in analysis. I give one example here to make my question more concrete. In the proof that the Lebesgue outer measure of intervals is equal to the length of the interval $[a,b]$, we take any cover of intervals $\{I_n\}$ and show that $$\sum_{n=1}^\infty |I_n| \geq b-a,$$ as in equations 1-8 here. Then, we "take the infinum of this set of numbers" and obtain that $$m^*([a,b]) \geq b-a.$$ Why is it that we can take the infinum and the inequality still holds? Can we always do this? In the first inequality, we had that for any cover the inequality holds. But the infinum is not referring to a specific cover, it is rather the largest lower bound of all these numbers. Why is it not possible that this largest lower bound is less than $b-a$? How can this be made more explicit? Perhaps by stating that for every $\epsilon >0$, there exists a specific cover $\{I'_n\}$ such that $$m^*([a,b]) + \epsilon \geq \sum_{n=1}^\infty |I_n'| $$ and hence because the first inequality holds for any cover and we can take $\epsilon$ to be arbitrarily small, $$m^*([a,b]) \geq b-a.$$ Is that "how infimums work" in this context? A: Your question is this: if we have a set $A$ and a number $\alpha$ such that $(\forall a\in A):a\geqslant\alpha$, then $\inf A\geqslant\alpha$. This is true, because we are assuming that $\alpha$ is a lower bound of $A$ and, by definition, $\inf A$ is the greatest lower bound of $A$.
{ "pile_set_name": "StackExchange" }
Q: Python df.loc not working for variables I am fairly new to Python, especially pandas. I have a dataframe called KeyRow which is from a bigger df: KeyRow=df.loc[df['Order'] == UniqueOrderName[i]] Then I make a nested loop for i in range (0,len(PersonNum)): print(KeyRow.loc[KeyRow['Aisle'] == '6', 'FixedPill']) So it appears to only work when a constant is placed, whereas if I use PersonNum[0] instead of '6',even though both values are equivalent, it appears not to work. When I use PersonNum[i] this is the output I am getting: Series([], Name: FixedPill, dtype: object) Whereas if I use 'x' I get a desired result: 15 5 Name: FixedPill, dtype: object Thanks for all the help in advance. A: It's a little unclear what your are trying to accomplish with this questions. If you are looking to filter a DataFrame, then I would suggest to never do this in an iterative manner. You should take full advantage of the slicing capabilities of .loc. Consider the example: df = pd.DataFrame([[1,2,3], [4,5,6], [1,2,3], [2,5,6], [1,2,3], [4,5,6], [1,2,3], [4,5,6]], columns=["A", "B", "C"]) df.head() A B C 0 1 2 3 1 4 5 6 2 1 2 3 3 2 5 6 4 1 2 3 Suppose you have a list of PersonNum that you want to use to locate the a particular field where your list is PersonNum = [1, 2]. You can slice the DataFrame in one step by performing: df.loc[df["A"].isin(PersonNum), "B"] Which will return a pandas Series and df.loc[df["A"].isin(PersonNum), "B"].to_frame() which returns a new DataFrame. Utilizing the .loc is significantly faster than an iterative approach.
{ "pile_set_name": "StackExchange" }
Q: Describe or link to a simple method of solving set theory questions I have a series of set theory questions to answer and the method I have is to draw out venn diagrams one by one and work them out visually. I have been unsuccessful in my search for 3 set arithmetic questions. Is there a simpler general method or a link to a simpler general method of solving them? Example below: $A \cap C \cap B^\prime \cup A \cap B \cap C^\prime \subseteq (A \cup B \cup C)^\prime$ $(A \cup B)^\prime \cup C \cap B^\prime \subseteq C \cup A^\prime \cup B^\prime$ Please describe, or link to, a general method able to quickly decide if expressions such as these are true. A: First, you need to be much more careful with your parentheses, and add them when needed to avoid ambiguities. For example, your Venn diagrams should tell you that $A \cap (B \cup C)$ is not the same thing as $(A \cap B) \cup C$ Indeed, if we look at left hand side of your second expression ... is it $((A \cup B)' \cup C) \cap B'$, or is that $(A \cup B)' \cup (C \cap B')$? Anyway, once you have used parentheses to disambiguate, you can use some algebraic methods, which you can find online (look for 'Boolean algebra' or 'algebra of sets') To give an example, if we interpret the abov expression as the latter, we ca do the following: $(A \cup B)' \cup (C \cap B') =$ (DeMorgan) $(A' \cap B') \cup (C \cap B') =$ (Distribution) $(A' \cup C) \cap B' = $ (Commutation) $(C \cup A') \cap B'$ And since in general $A \cap B \subseteq A \cup B$, we can now say that: $(C \cup A') \cap B' \subseteq C \cup A' \cup B'$
{ "pile_set_name": "StackExchange" }
Q: Finding kernel and image of a linear transformation, given eigenvalues and eigenvectors? Problem: Consider the linear transformation $T : \mathbb{R}^3 \rightarrow \mathbb{R}^3$ with eigenvalues $-1, 0$ and $1$ and the corresponding eigenvectors $v_1, v_2, v_3$. Determine $\text{ker}(T)$ and $\text{Im}(T)$. Attempt at solution: In general we have $D = P^{-1} A P$, where $D$ is a diagonal matrix with the eigenvalues, $P$ is the matrix with columns the corresponding eigenvectors, and $A$ is the matrixrepresentation of $T$ with respect to some basis. Hence $A = PDP^{-1}$. Now the kernel of $T$ is the nullspace of the matrix $A$, while the image of $T$ is the columnspace of $A$. I'm not sure how to solve this problem, because we are not given any specific eigenvectors. So how could we ever find $P^{-1}$? Since $0$ is an eigenvalue of $T$, $A$ is singular. But what does that say about the nullspace and columnspace of $A$? Any help would be appreciated. A: Here's a possible strategy: Note that the dimension of $\operatorname{im}(T)$ equals the rank of $A$ and hence the rank of $D$ since conjugate matices have same rank. What is the rank of $D$? Hence, what is the dimension of $\operatorname{im}(T)$? Given the eigenvectors corresponding to the distinct non-zero eigenvalues, what are obvious independent elements of $\operatorname{im}(T)$? Further, how are the dimensions of $\operatorname{im}(T)$ and $\operatorname{ker}(T)$ related? Hence, given that $0$ is an eigenvalue, what is $\operatorname{ker}(T)$?
{ "pile_set_name": "StackExchange" }
Q: ERROR: Error installing jekyll: ERROR: Failed to build gem native extension My system has: ruby 2.0.0p451 (2014-02-24) [x64-mingw32] gem -version 2.2.2 devKit : DevKit-mingw64-64-4.7.2-20130224-1432-sfx.exe When I try to run gem install jekyll, I get this error: D:\devKit>gem install jekyll Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... ERROR: Error installing jekyll: ERROR: Failed to build gem native extension. "D:/Program Files (x86)/Ruby200-x64/bin/ruby.exe" extconf.rb D:/Program Files (x86)/Ruby200-x64/bin/ruby.exe: invalid switch in RUBYOPT: -F ( RuntimeError) extconf failed, exit code 1 Gem files will remain installed in D:/Program Files (x86)/Ruby200-x64/lib/ruby/g ems/2.0.0/gems/fast-stemmer-1.0.2 for inspection. Results logged to D:/Program Files (x86)/Ruby200-x64/lib/ruby/gems/2.0.0/extensi ons/x64-mingw32/2.0.0/fast-stemmer-1.0.2/gem_make.out A: I got this error while installing Jekyll on Linux (Mint 17, which is based on Ubuntu 14.04). I eventually found the solution here. I needed both the ruby-dev package and nodejs (the latter due to a bug in Jekyll). sudo apt-get install ruby ruby-dev make sudo gem install jekyll --no-rdoc --no-ri sudo apt-get install nodejs A: I ran into this problem too. Running the following installed Jekyll for me: $ \curl -L https://get.rvm.io | bash -s stable --rails --autolibs=enabled $ sudo gem install jekyll This installs RVM, updates Rails and installs Jekyll. BTW - Most of the posts I've found indicate it's a problem with Xcode not having the developer tools installed. I have a newer MacBook Pro on which this stuff was installed by default, so attempting to install the Xcode dev tools did nothing for me (unlike the above, which did everything I needed).
{ "pile_set_name": "StackExchange" }
Q: Join table on Count I have two tables in Access, one containing IDs (not unique) and some Name and one containing IDs (not unique) and Location. I would like to return a third table that contains only the IDs of the elements that appear more than 1 time in either Names or Location. Table 1 ID Name 1 Max 1 Bob 2 Jack Table 2 ID Location 1 A 2 B Basically in this setup it should return only ID 1 because 1 appears twice in Table 1 : ID 1 I have tried to do a JOIN on the tables and then apply a COUNT but nothing came out. Thanks in advance! A: Here is one method that I think will work in MS Access: (select id from table1 group by id having count(*) > 1 ) union -- note: NOT union all (select id from table2 group by id having count(*) > 1 ); MS Access does not allow union/union all in the from clause. Nor does it support full outer join. Note that the union will remove duplicates.
{ "pile_set_name": "StackExchange" }
Q: ggplot : Multi variable (multiple continuous variable) plotting A data that is deduced from a larger data using dplyr, shows me information regarding the total sales of the four quarters for the years 2013 and 2014. Quarter X2013 X2014 Total.Result 1 Qtr 1 77282.13 66421.10 143703.2 2 Qtr 2 69174.64 76480.13 145654.8 3 Qtr 3 65238.47 79081.74 144320.2 4 Qtr 4 65429.73 109738.82 175168.5 I wish to plot a bargraph for the following using ggplot by comparing the two years on the bars and for such bar-groups for the each of the quarters like shown below. (output from MS Excel) The ggplot statement that I used is as shown below (I may be wrong) ggplot(qtr2, aes(x=as.factor(Quarter),fill=c(X2013,X2014))) + geom_bar(position="dodge") and I get an error Error: Aesthetics must either be length one, or the same length as the dataProblems:as.factor(Quarter) A: You need to bring your data into the long format for ggplot: require(ggplot2) require(reshape2) df <- read.table(header = TRUE, text = 'R Quarter X2013 X2014 Total.Result 1 Qtr 1 77282.13 66421.10 143703.2 2 Qtr 2 69174.64 76480.13 145654.8 3 Qtr 3 65238.47 79081.74 144320.2 4 Qtr 4 65429.73 109738.82 175168.5') df$R <- NULL head(df) # bring to long data (1) dfm <- melt(df, id.vars = c('Quarter', 'Total.Result')) dfm ggplot(dfm, aes(x = factor(Quarter), y = value, fill = variable) ) + geom_bar(stat="identity", position = 'dodge') Regarding the Total Result column / bars: I don't know where this data should come from (missing?) - There is only one column, but two bars? And the values do not fit. If you tell me how to generate these, it should be no problem to plot.
{ "pile_set_name": "StackExchange" }
Q: JS url encoding when trying to encode the URL http://www.example.com/events/tours/example-tour/?utm_source=example&utm_medium=banner it gives me back the following: http%3A%2F%2Fwww.example.com%2Fevents%2Ftours%2Fexample-tour%2F%3Futm_source%3Dexample%26utm_medium%3Dbanner%20 which does not represent a valid url, since it can not be called in browsers and leads to a google search (Chrome, you know?) How can I encode the URL probably using JS only? A: the right way in javascript to encode a url properly is encodeURIComponent(); which gives you http%3A%2F%2Fwww.example.com%2Fevents%2Ftours%2Fexample-tour%2F%3Futm_source%3Dexample%26utm_medium%3Dbanner then decodeURIComponent(); at the other side to decode the url again to make it valid. encodeURIComponent is not a valid url because you encodeit to pass is as a GET variable. like http://www.site.com/index.php?url=http%3A%2F%2Fwww.example.com%2Fevents%2Ftours%2Fexample-tour%2F%3Futm_source%3Dexample%26utm_medium%3Dbanner
{ "pile_set_name": "StackExchange" }
Q: Why is Android Studio generating duplicate gradle dependency automatically? I am using Android Studio 2.3.3 on Windows 10. I already have these in my dependencies: compile 'com.android.support:recyclerview-v7:25.4.0' compile 'com.android.support:cardview-v7:25.4.0' compile 'com.android.support:customtabs:25.4.0' compile 'com.android.support:appcompat-v7:25.4.0' compile 'com.android.support:design:25.4.0' compile 'com.android.support:multidex:1.0.1' compile 'com.android.support:support-v4:25.4.0' compile 'com.android.support.constraint:constraint-layout:1.0.2' But these lines are always auto generated in gradle file: dependencies { compile 'com.android.support:support-v4:25.+' } dependencies { compile 'com.android.support.constraint:constraint-layout:+' } dependencies { compile 'com.android.support.constraint:constraint-layout:+' } Gradle Version: 3.3 Android Plugin Version: 2.3.3 How do it stop Android Studio from generating these unnecessary dependencies and why is it doing so? A: For those who are also facing this. I have found out that whenever we create an Activity using the Activity creation wizard with New -> Activity this line: dependencies { compile 'com.android.support.constraint:constraint-layout:+' } is added automatically to build.gradle file. And dependencies { compile 'com.android.support:support-v4:25.+' } is added automatically whenever we create a Fragment using New -> Fragment Even if dependencies are already added. I have not found any solution to prevent it so for now I am removing those manually after the Activity/Fragment are created.
{ "pile_set_name": "StackExchange" }
Q: Sorting out 2 UIalertview's button clicks I have 2 alerts on the same page. Problem is that the clickedButtonAtIndex is answering both alerts and not just the second one. How do I separate them? UIAlertView *passwordAlert = [[UIAlertView alloc] initWithTitle:@"Phone Number" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK",nil), nil]; UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Please Enter correct phone no." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Try Again", nil]; - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex { On the first one you enter a phone number and hit ok. If it validates, great. However if it does not the second alert shows. Now when they hit "Try Again" the clickedButtonAtIndex runs on the first and second alert. I need it to only run on the second. A: What you have to do is give different tag to both alert view and then access by tags as:- UIAlertView *passwordAlert = [[UIAlertView alloc] initWithTitle:@"Phone Number" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK",nil), nil]; passwordAlert.tag=1; UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Please Enter correct phone no." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Try Again", nil]; alert.tag=2; - (void)alertView:(UIAlertView *)alert didDismissWithButtonIndex:(NSInteger)buttonIndex { if(alert.tag==1) { if (buttonIndex==0) { } else if (buttonIndex==1) { } } if(alert.tag==2) { if (buttonIndex==0) { } else if (buttonIndex==1) { } }
{ "pile_set_name": "StackExchange" }
Q: Any way to check for un-handled errors in a Go program? Consider the following: package main import ( "errors" "fmt" ) func foo() error { return errors.New("Danger!") } func main() { foo(); fmt.Println("I don't have a care in the world!") } It would be nice if there was an easy way to see that possible errors from foo() are not being handled. Does Go have a built-in way to check programs/source files for errors that nothing has been done with? A: Go does not have a built-in way to do that, but there's a third-party tool by Kamil Kisiel that does. Just go get github.com/kisielk/errcheck then run bin/errcheck your/import/path from your $GOPATH and it will spit out a list of calls with ignored errors. (I just tried it on a project and, hrm, perhaps I'm not as 100% reliable about it as I thought.) If you like it, you might also like go vet's checks, and the lint package used within Google for style checks. A: You can use errcheck: $ errcheck github.com/your/package It will let you know when you are ignoring returned errors. I would argue that this should mostly be rare if you are using a decent editor (that shows you function signatures).
{ "pile_set_name": "StackExchange" }
Q: Add a button at the last cell of UITableView I currently have 2 UITableView to filter out 2 category, my category is cat and dog, 1st UITableView that handles cat and 2nd UITableView that handles dog. What i want is to have cat and dog into one UITableview, so the in the UITableView, the first part will be the cats, and the second part is the dog. what i want to do is to put a button above the dog part where it will be used as a separator for two category. this is the illustration: the 2 cells in the top is the cat and the one cell in the bottom is a dog there should be a button in the middle of the two category as a seperator. A: Try this code. @interface ViewController () <UITableViewDelegate, UITableViewDataSource> { NSArray *arrCat; NSArray *arrDog; } - (void)viewDidLoad { [super viewDidLoad]; arrCat = @[@"Cat 1", @"Cat 2", @"Cat 3", @"Cat 4", @"Cat 5"]; arrDog = @[@"Dog 1", @"Dog 2", @"Dog3 ", @"Dog4 ", @"Dog 5"]; } I have Programatically create Header, You can also create it by creating xib. Add UITableView delegate and DataSource like this. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (section == 0) { return arrCat.count; } return arrDog.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"TableViewCell"; TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil] objectAtIndex:0]; } if (indexPath.section == 0) { cell.lblCategory.text = arrCat[indexPath.row]; } else { cell.lblCategory.text = arrDog[indexPath.row]; } return cell; } -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 60)]; view.backgroundColor = [UIColor greenColor]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = view.frame; button.titleLabel.textAlignment = NSTextAlignmentCenter; button.titleLabel.textColor = [UIColor blackColor]; [view addSubview:button]; if (section == 0) { [button setTitle:@"CAT" forState:UIControlStateNormal]; } else { [button setTitle:@"DOG" forState:UIControlStateNormal]; } return view; } -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 60.0; }
{ "pile_set_name": "StackExchange" }
Q: Running Build-Heap Algorithm on given numbers I don't fully understand this build-heap function. Lets assume we have array 3, 4, 5, 13, 16, 32. It seems like we swap the parent when it is less than the current A[j] but which number does the loop start with? Maybe somebody can go through 2-3 loops and show how the array changes after 1st loop, 2nd loop, 3rd loop. Much appreciated. Oh, also, what would be the runtime? for i=2 to n j = i while (j>1) and A[parent(j)]<A[j] do swap A(parent(j)] and A[j] j = parent(j) A: It appears you're building a max-heap, where every element is greater than or equal to its child elements (if any). With that understanding, let's trace the action. First, the parent node of $A[j]$ will be $A[j/2]$ (integer division: discard any remainder) so we'll have $$\begin{array}{r|cccccccc} j & 1 & 2 & 3 & 4 & 5 & 6 & 7 & \dotsc\\ parent(j) & \_ & 1 & 1 & 2 & 2 & 3 & 3 & \dotsc \end{array}$$ To keep things simple, we'll let the initial array be $[3,4,5,13]$: Insert at $i=2$. $A[parent(2)]=A[1]=3 < 4=A[2]$ so we swap $A[1]$ and $A[2]$, giving us the array $$ [4,3,5,13] $$ Insert at $i=3$. $A[parent(3)]=A[1]=4 < 5=A[3]$ so we swap $A[1]$ and $A[3]$, giving us the array $$ [5,3,4,13] $$ Insert at $i=4$. $A[parent(4)]=A[2]=3 < 13=A[4]$ so we swap $A[2]$ and $A[3]$, giving us the array $$ [5,13,4,3] $$ and now $j=parent(4)=2>1$ so we see if we need another swap. $A[parent(2)]=A[1]=5 < 13=A[2]$ so we swap $A[1]$ and $A[2]$, giving us the array $$ [13,5,4,3] $$ and we're done, the array is now a max-heap. The runtime of this algorithm is no worse than a multiple of $n\log n$ since none of the elements are further than $\log_2n$ from the root at $i=1$ so you'll need at most $\log n$ swaps for each of the $n$ elements. This, by the way, is not as good as possible: there's different algorithm that builds a heap in no more than a multiple of $n$ time.
{ "pile_set_name": "StackExchange" }
Q: How does Leia Organa know carbon freezing causes hibernation sickness? In the Star Wars universe, there exists a carbon freezing process that has been used before to transport frozen gas over long distances. In Cloud City, the carbon freezing process is used for the first time to encase a living person in suspended hibernation. When Leia rescues Han Solo from his carbonite prison, Leia comments on the onset of hibernation sickness that Han is experiencing: Leia: "Just relax for a moment. You're free of the carbonite. Shh. You have hibernation sickness." Han: "I can't see." Leia: "Your eyesight will return in time." However, earlier, Lando Calrissian comments on how carbon freezing has never (to his knowledge) been used on humans before: "Lord Vader, we only use this facility for carbon freezing. If you put him in there it might kill him." How does Leia know that Han is experiencing hibernation sickness from being frozen in carbonite, if Han is the first person in history to go through that process? Even if hibernation sickness is not exclusive to carbon freezing, how does Leia know that it is specifically what Han is experiencing? A: I think I found a pretty good quote to answer my own question. Immediately after freezing Han Solo in carbonite, Darth Vader remarks to Lando: Vader: "Well, Calrissian? Did he survive?" Lando: "Yes, he's alive...and in perfect hibernation." If we can assume that Leia is within earshot of this conversation (which she most likely would be, as she is still at this point in the same room as far as I can remember), we now know that Leia knows that Han Solo is now in a form of hibernation. Since Leia already knows about the effects of hibernation sickness, it makes perfect sense that she would "put two and two together" by the time that she un-freezes Han and figure out that Han would, to the best of her knowledge, be experiencing a form of hibernation sickness. As an interesting side note, Leia might already possess a limited knowledge of some effects of carbon freezing (in the Legends Canon, anyway) as the Alderaanian Medical Association has done at least limited research on it. A: This is never sufficiently explained in Disney Canon. Carbonite Freezing of people has been done before, but there's no evidence that Leia would have known about the results or effects. However, in Legends Canon, this can be handwaved pretty easily. Leia explains that Han is suffering from Hibernation Sickness, but does not specify that it is specific to, or only caused by being frozen in carbonite. In fact, Hibernation Sickness is caused by being in suspended animation. Wookieepedia mentions a few methods of being put into suspended animation, such as sleeper ships and Sith techniques. In Legends canon, since this is not a new concept or affliction, it's entirely possible/likely that she simply knew what sort of effects being in suspended animation would cause. A: We don't know for sure, but it's apparent that some time has passed between the end of Empire Strikes Back, when Han was frozen, and the beginning of RotJ, when he is rescued. Boba Fett delivers Han to Jabba, Jabba has time to make him into a decoration in his palace. Leia and company also had to plan the rescue operation, which obviously began at least some time before RotJ starts, because Lando is already working as a guard in Jabba's palace at the start of the movie. I think it's safe to assume that just like every other aspect of the rescue was planned, they also had to have some idea of what shape Han would be in after being unfrozen and that Leia did some studying up on carbonite freezing during that time to answer that question.
{ "pile_set_name": "StackExchange" }
Q: how to create private key + CSR signed by a custom CA I am trying to generate a private key + certificate ... certificate need to be signed by CA. I generate a CA with openssl, key: openssl genrsa -aes256 -passout pass:xxxx -out ca.pass.key 4096 openssl rsa -passin pass:xxxx -in ca.pass.key -out ca.key cert: openssl req -new -x509 -days 3650 -key ca.key -out ca.pem Now generate client key + cert with keytool ... keytool -genkey -alias clientkey -keystore clientkeystore.p12 -keyalg RSA -storetype PKCS12 -validity 3650 Is possible to add sign with CA with Keytool ? A: After generating the key: Use keytool -certreq to generate a file containing the CSR. Use openssl x509 -signkey to sign the CSR and generate an X.509 certificate. Use keytool -importcert to import the signed X.509 certificate; it will be automatically associated with the internally generated private key. You might want to try tools such as Portecle or Keystore Explorer for Java keystore management. See other examples: https://www.digicert.com/csr-creation-java.htm https://knowledge.digicert.com/generalinformation/INFO227.html https://www.ibm.com/support/knowledgecenter/en/HW94A/com.ibm.acc.8731.doc/creating_a_java_keystore_mobile_interface.html https://docs.oracle.com/cd/E19509-01/820-3503/ggezu/index.html https://www.entrustdatacard.com/knowledgebase/how-do-i-generate-a-2048-bit-csr-using-java-keytool
{ "pile_set_name": "StackExchange" }
Q: iPhone Core Data Lightweight Migration Cocoa error 134130: Can't find model for source store Folks, Lightweight migration is failing for me 100% of the time on this line: [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error] with the error: Error: Error Domain=NSCocoaErrorDomain Code=134130 UserInfo=0x4fbff20 "Operation could not be completed. (Cocoa error 134130.)" "Can't find model for source store"; Here is my managed object context, model, and persistent store: - (NSManagedObjectContext *) managedObjectContext { if (managedObjectContext != nil) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator: coordinator]; } return managedObjectContext; } - (NSManagedObjectModel *)managedObjectModel { if (managedObjectModel != nil) { return managedObjectModel; } managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; return managedObjectModel; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator != nil) { return persistentStoreCoordinator; } NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Locations.sqlite"]]; NSError *error; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]]; // Allow inferred migration from the original version of the application. NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { NSLog(@"Error: %@",error); NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return persistentStoreCoordinator; } I have two versions of my model in my project: a version 4 and a version 5. If I set my version 4 as default, it works fine. If I select "Design -> Data Model -> Add Model Version" (as described by this post), make a change, Design -> Data Model -> Set Current Version, build and run, it will fail with the aforementioned "Can't find model for source store" error. Set model back to version 4, no problems, addPersistentStoreWithType. Alternatively, if I add model version and make no changes, simply go from version 4 to 5 without adding any new fields, no problems. If I then try to go from 5 to 6, the aforementioned error. This code is failing on both Simulator and Phone. I read several prescriptions calling for deleting and reinstalling the app, which does work for both Simulator and Phone, but I am afraid that when I release this to real users it will break my installed base since they won't be able to delete and reinstall - App Store will auto-upgrade them. This code worked in releases past with no changes on my part - hence my ability to make it all the way up to version 4. I recently upgraded to XCode 3.2.3 building for iOS4, which may have something to do with this. Is anyone else having this issue all of a sudden now like I am? Has anyone managed to work past it? Thanks. PS - For Googlers who stumble on this page, here are all the relevant pages you might consider reading, below. Unfortunately none of these solved my issue. Implementation of "Automatic Lightweight Migration" for Core Data (iPhone) http://iphonedevelopment.blogspot.com/2009/09/core-data-migration-problems.html https://stackoverflow.com/questions/2925918/iphone-core-data-lightweight-migration-error-reason-cant-find-model-for-sour iPhone Core Data "Automatic Lightweight Migration" http://www.iphonedevsdk.com/forum/iphone-sdk-development/38545-coredata-migration-issues.html UPDATE While this is not a real fix, it does avoid the scenario of a crashing client: simply delete the database file: if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { // Delete file if ([[NSFileManager defaultManager] fileExistsAtPath:storeUrl.path]) { if (![[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { // Handle the error. NSLog(@"Error: %@",error); NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } UPDATE 2 Here is what happens when I inspect VersionInfo.plist: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>NSManagedObjectModel_CurrentVersionName</key> <string>Profile 5</string> <key>NSManagedObjectModel_VersionHashes</key> <dict> <key>Profile</key> <dict> <key>Profile</key> <data> ZIICGgMBreuldkPXgXUhJwKamgwJzESM5FRTOUskomw= </data> </dict> <key>Profile 2</key> <dict> <key>Profile</key> <data> tEB7HrETWOSUuoeDonJKLXzsxixv8ALHOoASQDUIZMA= </data> </dict> <key>Profile 3</key> <dict> <key>Profile</key> <data> qyXOJyKkfQ8hdt9gcdFs7SxKmZ1JYrsXvKbtFQTTna8= </data> </dict> <key>Profile 4</key> <dict> <key>Profile</key> <data> lyWDJJ0kGcs/pUOModd3Q1ymDvdRiNXui4NCpLxDFSw= </data> </dict> <key>Profile 5</key> <dict> <key>Profile</key> <data> V4PyRK1ezj3xK1QFRCTVzGOqyJhEb7FRMzglrTsP0cI= </data> </dict> </dict> </dict> </plist> Here is the code that I wrote to inspect my model (note I had to go out and add a base64 encoder, since that is what is in the VersionInfo.plist file) if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { NSDictionary *storeMeta = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:nil URL:storeUrl error:&error]; NSLog(@"%@",storeMeta); id someObj = [[storeMeta objectForKey:@"NSStoreModelVersionHashes"] objectForKey:@"Profile"]; NSLog(@"%@",someObj); NSLog(@"%@",[NSString base64StringFromData:someObj length:[someObj length]]); And here is the debug output: { NSPersistenceFrameworkVersion = 310; NSStoreModelVersionHashes = { Profile = <97258324 9d2419cb 3fa5438c a1d77743 5ca60ef7 5188d5ee 8b8342a4 bc43152c>; SerializedMessage = <4530863c d943479a edfb4dfb 5059c28d d6137dc4 d1153d36 ed52be49 11074f13>; }; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( ); NSStoreType = SQLite; NSStoreUUID = "823FD306-696F-4A0F-8311-2792825DC66E"; "_NSAutoVacuumLevel" = 2; } <97258324 9d2419cb 3fa5438c a1d77743 5ca60ef7 5188d5ee 8b8342a4 bc43152c> lyWDJJ0kGcs/pUOModd3Q1ymDvdRiNXui4NCpLxDFSw= As you can see, that last line that starts with 'ly' matches Profile 4 in VersionInfo.plist...hence I see no reason why it should be failing. Any other ideas? A: I read several prescriptions calling for deleting and reinstalling the app, which does work for both Simulator and Phone, but I am afraid that when I release this to real users it will break my installed base since they won't be able to delete and reinstall. This is a problem caused by Xcode not removing old momc files from simulator/dev-device when a the model file is changed e.g. changing the name. The old file remains which causes confusion. This is something you only see during development because it is an artifact of the way that Xcode manipulates the app bundle without completely reinstalling it every time as must happen with a release version. You can confirm this logging the return of: [[NSBundle mainBundle] URLsForResourcesWithExtension:@"momc"subdirectory:nil]; ... which should show you all the compiled model files in the app bundle It is bad practice to rely on migration during development because it is very common for migration to fail if you are making changes to the model and store. You should only use migration after all the code is nailed down. I would also recommend regenerating your store from scratch every time you run. It is to easy to build up garbage in the store by changing up the model. A: I've read over your updated question. It's getting quite messy with model versions. You should try and audit the version of the model that the existing store is actually asking for, and try to list all available models in the app bundle at runtime. I look in my apps' model directory NSString *modelDirectoryPath = [[NSBundle mainBundle] pathForResource:@"MyModel" ofType:@"momd"]; I'm not sure if developers normally do this, but I keep my model versions with different names.. so I have in there: VersionInfo.plist MyModel.mom MyModel2.mom The version hashes listed in the VersionInfo.plist should help you troubleshoot. Look for the version hash required by the existing persistent store, and see if you can locate it in the version hashes listed in VersionInfo.plist. Actually, I can't see a way to write some code that will ask the persistent store what it's entity version hashes are. The NSPersistentStoreCoordinator or the NSMigrationManger seem to be doing that privately. i.e. they check the persistent store entity versions against the model that the store is loaded with. Had another quick look, and it's available in the store meta data. Nice and easy! NSError *error; NSURL *storeURL = [NSURL fileURLWithPath:[[self class] storePath]]; NSDictionary *storeMeta = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:nil URL:storeURL error:&error]; And looking in storeMeta I get a key with <CFString 0x7328050 [0x2724380]>{contents = "NSStoreModelVersionHashes"} = <CFBasicHash 0x7328340 [0x2724380]>{type = immutable dict, count = 5, entries => 0 : <CFString 0x7328110 [0x2724380]>{contents = "MyEntityNameOne"} = <CFData 0x73281b0 [0x2724380]>{length = 32, capacity = 32, bytes = 0x143325cf121239ce156af2e2a1aad7d9 ... 976977fdf29fc013} 1 : <CFString 0x7328130 [0x2724380]>{contents = "MyEntityNameTwo"} = <CFData 0x7328200 [0x2724380]>{length = 32, capacity = 32, bytes = 0x0ca6ecf1283d12bd3ca82af39b6b9f5d ... 149dd39a591e0c4d} ... } Should be easy to iterate over that NSStoreModelVersionHashes dictionary and log the version hashes your store requires. Manually match that back to the ones available in VersionInfo.plist and see what's missing. Perhaps there's not one single model that contains all the required versions of the entities in your existing persistent store. That might happen due to (accidental?) edits on the model before or after setting up a new model version? A: I had esilver's exact problem and found this question via Google. However, the fix that worked for me wasn't anywhere else on SO (that I know), so here goes: If there are multiple copies of your *.mom files (compiled object models) in your bundle, Core Data may become confused when attempting to migrate on your behalf. Our problem was that each individual model file (Data.xcdatamodel, Data_V1.xcdatamodel, Data_V2.xcdatamodel, etc.) was not only inside the xcdatamodeld/ directory (which was included as something to compile in the build process), but also each file was also included in the "Compile Sources" list. What this meant is that the resulting bundle had two sets of *.mom files: one inside xcdatamodeld/ and one at the top level. I think Core Data became very, very confused, and led to this error. Removing each xcdatamodel file from the "compile sources" and leaving the xcdatamodeld directory solved the problem for us (e.g. got auto-versioning up and running again). Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: How Can I replace a cursor in sql server 2008 In the last years I have put lot of effort in c# and left sql server a bit . My sql skills could be better. I know cursors are slow etc... I have put together a noddy example that I seem to encounter quite a bit at work. I need to migrate data from one flat table "Customer" into many tables "CustomerAddress" "CustomerPhone" etc.. If you were assigned this task how would you do it without using cursors? Cursor to convert BEGIN TRANSACTION DECLARE @CustomerID int, @Name nvarchar(50), @Surname nvarchar(50), @DateOfBirth datetime, @Address nvarchar(200), @City nvarchar(50), @County nvarchar(50), @Country nvarchar(50), @HomePhone nvarchar(20) DECLARE OldCustomerCursor CURSOR FAST_FORWARD FOR SELECT CustomerID,Name,Surname,DateOfBirth,Address,City,County,Country,HomePhone FROM OldCustomer OPEN OldCustomerCursor FETCH NEXT FROM OldCustomerCursor INTO @CustomerID, @Name , @Surname , @DateOfBirth , @Address , @City , @County , @Country , @HomePhone WHILE @@FETCH_STATUS = 0 BEGIN INSERT [dbo].[Customer] ([CustomerID], [Name], [Surname], [DateOfBirth]) VALUES(@CustomerID,@Name,@Surname,@DateOfBirth) INSERT [CustomerAddress]([AddressID],[CustomerID],[Country],[Address],[City],[County]) VALUES(@Count,@CustomerID,@County,@Address,@City,@Country) INSERT [dbo].[CustomerTelephone]([TelephoneID],[CustomerID],[Number]) VALUES(@Count,@CustomerID, @HomePhone) FETCH NEXT FROM OldCustomerCursor INTO @CustomerID, @Name , @Surname , @DateOfBirth , @Address , @City , @County , @Country , @HomePhone END CLOSE OldCustomerCursor DEALLOCATE OldCustomerCursor SELECT * FROM Customer SELECT * FROM CustomerAddress SELECT * FROM CustomerTelephone ROLLBACK TRANSACTION Thanks for any suggestions how to replace a cursor A: I don't see any reason to use cursors you can try it like this SELECT CustomerID,Name,Surname,DateOfBirth,Address,City,County,Country,HomePhone FROM OldCustomer INSERT [dbo].[Customer] ([CustomerID], [Name], [Surname], [DateOfBirth]) SELCT CustomerID,Name,Surname,DateOfBirth FROM OldCustomer INSERT [CustomerAddress]([AddressID],[CustomerID],[Country],[Address],[City],[County]) SELECT Count,CustomerID,County,Address,City,Country FROM OldCustomer INSERT [dbo].[CustomerTelephone]([TelephoneID],[CustomerID],[Number]) SELECT Count,CustomerID, HomePhone FROM OldCustomer
{ "pile_set_name": "StackExchange" }
Q: Elixir + Absinthe + Ecto + Dataloader – filter by multiple fields Using Elixir/Absinthe/Ecto/Dataloader, how do you query/filter a source by multiple fields? Example: Let's say you would want to filter a schema (and dataloader source) named User by two fields, one named is_admin (only true values) and one group_id that can be any value in a list, e.g [1, 5, 9] How would this look using Dataloader ? This is from the schema definition: alias App.Data # ... object :app do field :users, list_of(:user) do resolve fn app, _args, %{context: %{loader: loader}} -> params = [is_admin: true, group_id: [1,2,3]] loader |> Data.load_many(:users, params) |> on_load(fn loader -> {:ok, Data.get_many(loader, :user, params)} end) end end end and this is the data source module: defmodule App.Data do alias App.User def data do Dataloader.Ecto.new(Repo, run_batch: &run_batch/5) end def load_many(loader, :users, [is_admin: is_admin, group_id: ids]) do Dataloader.load(loader, __MODULE__, {:many, {User, is_admin: is_admin}}, group_id: ids) end def get_many(loader, :users, [is_admin: is_admin, group_id: ids]) do Dataloader.load(loader, __MODULE__, {:many, {User, is_admin: is_admin}}, group_id: ids) end def run_batch(queryable, query, col, inputs, repo_opts) do Dataloader.Ecto.run_batch(Repo, queryable, query, col, inputs, repo_opts) end end A: So to answer my own question, the solution that worked was to leverage the &query/2 of Dataloader so the resolver in GQL resolver would basically look like this: loader |> Data.load({:many, User, group_ids: ids}, is_admin: true) |> on_load(fn loader -> loader |> Data.get({:many, User, group_ids: ids}, is_admin: true) # ... end) ... and the query/2 method in the App.Data module would look like this: defp query(User, %{group_ids: ids}) do from u in User, where: u.group_id in ^ids end This is explained here: https://hexdocs.pm/lazyloader/Dataloader.Ecto.html#module-filtering-ordering
{ "pile_set_name": "StackExchange" }
Q: Term for "find, remove and return an element" in a set? Title says it mostly. I want to add a simple extension method to the base Dictionary class in C#. At first I was going to name it Pop(TKey key), kind of like the Stack method, but it accepts a key to use for lookup. Then I was going to do Take(TKey key), but it coincides with the LINQ method of the same name...and although C# 3.0 lets you do it, I don't like it. So, what do you think, just stick with Pop or is there a better term for "find and remove an element"? (I feel kind of embarrassed to ask this question, it seems like such a trivial matter... but I like to use standards and I don't have wide experience with many languages/environments.) EDIT: Sorry, should have explained more.... In this instance I can't use the term Remove since it's already defined by the class that I'm extending with a new method. EDIT 2: Okay, here's what I have so far, inspired by the wisdom of the crowd as it were: public static TValue Extract<TKey, TValue> ( this Dictionary<TKey, TValue> dict, TKey key ) { TValue value = dict[key]; dict.Remove(key); return value; } public static bool TryExtract<TKey, TValue> ( this Dictionary<TKey, TValue> dict, TKey key, out TValue value ) { if( !dict.TryGetValue(key, out value) ) { return false; } dict.Remove(key); return true; } A: I reckon Extract, like when archaeologists Find a mummy in the ground, Remove it and then Return it to a museum :)
{ "pile_set_name": "StackExchange" }
Q: PHP group certain results from foreach on array into another array I have an array that looks something like this: $array = array( [0] => FILE-F01-E1-S01.pdf [1] => FILE-F01-E1-S02.pdf [2] => FILE-F01-E1-S03.pdf [3] => FILE-F01-E1-S04.pdf [4] => FILE-F01-E1-S05.pdf [5] => FILE-F02-E1-S01.pdf [6] => FILE-F02-E1-S02.pdf [7] => FILE-F02-E1-S03.pdf ); Basically, I need to look at the first file and then get all the other files that have the same beginning ('FILE-F01-E1', for example) and put them into an array. I don't need to do anything with the other ones at this point. I've been trying to use a foreach loop finding the previous value to do this, but am not having any luck. Like this: $previousFile = null; foreach($array as $file) { if(substr_replace($previousFile, "", -8) == substr_replace($file, "", -8)) { $secondArray[] = $file; } $previousFile = $file; } So then $secondArray would look like this: Array ( [0] => FILE-F01-E1-S01.pdf [1] => FILE-F01-E1-S02.pdf [2] => FILE-F01-E1-S03.pdf [3] => FILE-F01-E1-S04.pdf [4] => FILE-F01-E1-S05.pdf) As my result. Thank you! A: Are you sure this will be the naming format? That is crucial information to have to construct a regexp or something to check for being a substring of the following strings. If we can assume this and that the "base" name is always at index 0 then you could do something like. <?php $myArr = [ 'FILE-F01-E1-S01.pdf', 'FILE-F01-E1-S02.pdf', 'FILE-F01-E1-S03.pdf', 'FILE-F01-E1-S04.pdf', 'FILE-F01-E1-S05.pdf', 'FILE-F02-E1-S01.pdf', 'FILE-F02-E1-S02.pdf', 'FILE-F02-E1-S03.pdf' ]; $baseName = ''; $allSimilarNames = []; foreach($myArr as $index => &$name) { if($index == 0) { $baseName = substr($name, 0, strrpos($name, '-')); $allSimilarNames[] = $name; } else { if(strpos($name, $baseName) === 0) { $allSimilarNames[] = $name; } } } var_dump($allSimilarNames); This will Check at index one to get the base name to compare against Loop all items in the array and match all items, no matter where in the array they are, that are similar according to your naming convention So if you next time have an array that is $myArr = [ 'FILE-F02-E1-S01.pdf', 'FILE-F01-E1-S01.pdf', 'FILE-F01-E1-S02.pdf', 'FILE-F01-E1-S03.pdf', 'FILE-F01-E1-S04.pdf', 'FILE-F01-E1-S05.pdf', 'FILE-F02-E1-S02.pdf', 'FILE-F02-E1-S03.pdf' ]; this will return all the items that match FILE-F02-E1*. You could also make a small function of it for easier use and not have to rely on the element at index 0 having to be the "base" name. <?php function findMatches($baseName, &$names) { $matches = []; $baseName = substr($baseName, 0, strrpos($baseName, '-')); foreach($names as &$name) { if(strpos($name, $baseName) === 0) { $matches[] = $name; } } return $matches; } $myArr = [ 'FILE-F01-E1-S01.pdf', 'FILE-F01-E1-S02.pdf', 'FILE-F01-E1-S03.pdf', 'FILE-F01-E1-S04.pdf', 'FILE-F01-E1-S05.pdf', 'FILE-F02-E1-S01.pdf', 'FILE-F02-E1-S02.pdf', 'FILE-F02-E1-S03.pdf' ]; $allSimilarNames = findMatches('FILE-F01-E1-S01.pdf', $myArr); var_dump($allSimilarNames);
{ "pile_set_name": "StackExchange" }
Q: How to call generic method with stronger constraint? namespace Test { #region Not my code public interface IAdditional { } public interface ISome { ISomeOther<T> GetSomeother<T>() where T : class; } public interface ISomeOther<T> where T : class { void DoFoo(T obj); } public class AnotherClass<T> where T : class { } public static class StaticClass { public static void DoBar<T>(AnotherClass<T> anotherClass, T obj) where T : class, IAdditional { } } #endregion #region MyCode public class SomeOtherImp<T> : ISomeOther<T> where T : class, IAdditional //Have to add IAdditional constraint to call StaticClass.DoBar { private AnotherClass<T> _anotherClass; public void DoFoo(T obj) { StaticClass.DoBar<T>(_anotherClass, obj); //I do need to call StaticClass.DoBar here.... } } public class ISomeImp : ISome { public ISomeOther<T> GetSomeother<T>() where T : class { return new SomeOtherImp<T>(); //Can't do this no IAdditional constraint on T } } #endregion } I was forced to add IAdditional to SomeOtherImp to be able to call StaticClass.DoBar. And now I can't implement ISome with SomeOtherImp<T>. A: Do you mean that you want to be able to call the Get method? If you can edit the interface ISome, try this: public interface ISome { T Get<T>() where T:class, ISomeInterface } ...otherwise you're going to have to use reflection: public class Foo : ISome { public T Get<T>() where T:class { if (!typeof(ISomeInterface).IsAssignableFrom(typeof(T))) throw new Exception(); return (T)typeof(SomeStaticClass).GetMethod("Create").MakeGenericMethod(new [] {typeof(T)}).Invoke(); } }
{ "pile_set_name": "StackExchange" }
Q: MDQueryGetResultAtIndex and UnsafeRawPointer in Swift 3 I'm having trouble exploring the results of a Spotlight search in Swift 3 using MDQuery. I expect MDQueryGetResultAtIndex to yield an MDItem, and in C/Objective-C, that assumption works, and I can call MDItemCopyAttribute on it to explore the item. Here, for example, I successfully get the pathname of a found item: MDItemRef item = (MDItemRef)MDQueryGetResultAtIndex(q,i); CFStringRef path = MDItemCopyAttribute(item,kMDItemPath); But in Swift 3, MDQueryGetResultAtIndex returns an UnsafeRawPointer! (it's a pointer-to-void in C). To get past that, I've tried, for example: if let item = MDQueryGetResultAtIndex(q, 0) { let ptr = item.bindMemory(to: MDItem.self, capacity: 1) let path = MDItemCopyAttribute(ptr.pointee, kMDItemPath) } but that crashes, and logging shows that ptr.pointee is an NSAtom. It is quite evident that my personal UnsafeRawPointer mojo is not working (and to be frank I've always found this confusing). How would I transform this UnsafeRawPointer into something I can successfully call MDItemCopyAttribute on? Alternatives I can get over this hump by putting my Objective-C code into an Objective-C helper object and calling it from Swift; but I'd like to write a pure Swift solution. Similarly, I could probably rewrite my code to use the higher-level NSMetadataQuery, and I may well do so; but my original Objective-C code using the lower-level MDQueryRef works fine, so now I'm curious how to turn it directly into Swift. Complete code for those who would like to try this at home: let s = "kMDItemDisplayName == \"test\"" // you probably have one somewhere let q = MDQueryCreate(nil, s as CFString, nil, nil) MDQueryExecute(q, CFOptionFlags(kMDQuerySynchronous.rawValue)) let ct = MDQueryGetResultCount(q) if ct > 0 { if let item = MDQueryGetResultAtIndex(q, 0) { // ... } } A: The problem in your code if let item = MDQueryGetResultAtIndex(q, 0) { let ptr = item.bindMemory(to: MDItem.self, capacity: 1) let path = MDItemCopyAttribute(ptr.pointee, kMDItemPath) } is that the UnsafeRawPointer is interpreted as a pointer to an MDItem reference and then dereferenced in ptr.pointee, but the raw pointer is the MDItem reference, so it is dereferenced once too often. The "shortest" method to convert the raw pointer to an MDItem reference is unsafeBitCast: let item = unsafeBitCast(rawPtr, to: MDItem.self) which is the direct analogue of an (Objective-)C cast. You can also use the Unmanaged methods to convert the raw pointer to an unmanaged reference and from there to a managed reference (compare How to cast self to UnsafeMutablePointer<Void> type in swift): let item = Unmanaged<MDItem>.fromOpaque(rawPtr).takeUnretainedValue() This looks a bit more complicated but perhaps expresses the intention more clearly. The latter approach works also with (+1) retained references (using takeRetainedValue()). Self-contained example: import CoreServices let queryString = "kMDItemContentType = com.apple.application-bundle" if let query = MDQueryCreate(kCFAllocatorDefault, queryString as CFString, nil, nil) { MDQueryExecute(query, CFOptionFlags(kMDQuerySynchronous.rawValue)) for i in 0..<MDQueryGetResultCount(query) { if let rawPtr = MDQueryGetResultAtIndex(query, i) { let item = Unmanaged<MDItem>.fromOpaque(rawPtr).takeUnretainedValue() if let path = MDItemCopyAttribute(item, kMDItemPath) as? String { print(path) } } } }
{ "pile_set_name": "StackExchange" }
Q: How to create dynamic substring with awk Let say i have file like below. ABC_DEF_G-1_P-249_8.CSV I want to cut to be like this below. ABC_DEF_G-1_P-249_ I use this awk command to do that like below. ls -lrt | grep -i .CSV | tail -1 | awk -F ' ' '{print $8}' | cut -c 1-18 Question is, if the number 1, is growing, how to make the substring is dynamic example like below... ABC_DEF_G-1_P-249_ .... ABC_DEF_G-10_P-249_ ABC_DEF_G-11_P-249_ ... ABC_DEF_G-1000_P-249_ A: To display the file names of all .CSV without everything after the last underscore, you can do this: for fname in *.CSV; do echo "${fname%_*}_"; done This removes the last underscore and evertyhing that follows it (${fname%_*}), and then appends an underscore again. You can assign that, for example, to another variable. For an example file list of ABC_DEF_G-1_P-249_9.CSV ABC_DEF_G-10_P-249_8.CSV ABC_DEF_G-1000_P-249_4.CSV ABC_DEF_G-11_P-249_7.CSV ABC_DEF_G-11_P-249_7.txt this results in $ for fname in *.CSV; do echo "${fname%_*}_"; done ABC_DEF_G-1_P-249_ ABC_DEF_G-10_P-249_ ABC_DEF_G-1000_P-249_ ABC_DEF_G-11_P-249_ A: You can do this with just ls and grep ls -1rt | grep -oP ".*(?=_\d{1,}\.CSV)" If you are concerned about the output of ls -1, as mentioned in the comments you can use find as well find -type f -printf "%f\n" | grep -oP ".*(?=_\d{1,}\.CSV)" Outputs: ABC_DEF_G-1_P-249 ABC_DEF_G-1000_P-249_ This assumes you want everything except the _number.CSV, if it needs to be case insensitive then you can the -i flag to the grep. The \d{1,} allows for the number between _ and .CSV to grow from one to many digits. Also doing it this way you don't have to worry about if the number 1 in your example increases: ABC_DEF_G-1_P-249
{ "pile_set_name": "StackExchange" }
Q: Really logging the POST request body (instead of "-") with nginx I'm trying to log POST body, and add $request_body to the log_format in http clause, but the access_log command just prints "-" as the body after I send POST request using: curl -d name=xxxx myip/my_location My log_format (in http clause): log_format client '$remote_addr - $remote_user $request_time $upstream_response_time ' '[$time_local] "$request" $status $body_bytes_sent $request_body "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; My location definition(in server clause): location = /c.gif { empty_gif; access_log logs/uaa_access.log client; } How can I print the actual POST data from curl? A: Nginx doesn't parse the client request body unless it really needs to, so it usually does not fill the $request_body variable. The exceptions are when: it sends the request to a proxy, or a fastcgi server. So you really need to either add the proxy_pass or fastcgi_pass directives to your block. The easiest way is to send it to Nginx itself as a proxied server, for example with this configuration: location = /c.gif { access_log logs/uaa_access.log client; # add the proper port or IP address if Nginx is not on 127.0.0.1:80 proxy_pass http://127.0.0.1/post_gif; } location = /post_gif { # turn off logging here to avoid double logging access_log off; empty_gif; } If you only expect to receive some key-pair values, it might be a good idea to limit the request body size: client_max_body_size 1k; client_body_buffer_size 1k; client_body_in_single_buffer on; I also received "405 Not Allowed" errors when testing using empty_gif; and curl (it was ok from the browser), I switched it to return 200; to properly test with curl.
{ "pile_set_name": "StackExchange" }
Q: Axios returns promise pending i want this function to return either true or false, instead I get /** * Sends request to the backend to check if jwt is valid * @returns {boolean} */ const isAuthenticated = () => { const token = localStorage.getItem('jwt'); if(!token) return false; const config = {headers : {'x-auth-token' : token}}; const response = axios.get('http://localhost:8000/user' , config) .then(res => res.status === 200 ? true : false) .catch(err => false); return response; } export default isAuthenticated; I tried separating them and using async/await : const isAuthenticated = async () => { const response = await makeRequest(); return response; } const makeRequest = async () => { const token = localStorage.getItem('jwt'); const config = {headers : {'x-auth-token' : token}}; const response = await axios.get('http://localhost:8000/user' , config) .then(res => res.status === 200 ? true : false) .catch(err => false); return response; } And still the same.. After some suggestions : const isAuthenticated = () => { const response = makeRequest(); return response; } const makeRequest = async () => { try { const token = localStorage.getItem('jwt'); const config = {headers : {'x-auth-token' : token}}; const response = await axios.get('http://localhost:8000/user', config); if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' } console.log('success stuff'); return true; } return false; } catch (err) { console.error(err) return false; } } export default isAuthenticated; A: First of all if. If you are using the default promise then & catch, then the success action should be handled within the 'then' function. axios.get('http://localhost:8000/user', config) .then(res => console.log('succesfull stuff to be done here') .catch(err => console.error(err)); // promise if you want to use the async/await syntactic sugar, which I personally like it's const makeRequest = async () => { try { const token = localStorage.getItem('jwt'); const config = {headers : {'x-auth-token' : token}}; const response = await axios.get('http://localhost:8000/user', config); if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' } console.log('success stuff'); return true; } return false; } catch (err) { console.error(err) return false; } }
{ "pile_set_name": "StackExchange" }
Q: How to say "I look" as in "I look stupid" in French? How do you say "I look" as in "I look pretty/stupid/etc"? Do you use ressemble? Also, out of topic: how do you say "you seem adjective", and how do you express "pretty" as in "That's pretty dumb"? A: "To look" + adjective in French can be said a couple different ways. "Avoir l'air______", e.g. "J'ai l'air ridicule." "Paraître______" e.g. "Elle paraît fatiguée." "Sembler______" e.g. "Ça semble intéressant !" "pretty" can be said a few different ways as well, depending on the context. "Plutôt" "Assez" are the most commonly used. For your examples, you could say: "J'ai l'air plutôt ridicule." "Elle paraît assez fatiguée." "Ça semble plutôt/assez intéressant !"
{ "pile_set_name": "StackExchange" }
Q: How to replace nested functions with class call I need to replace a nested function with a class call. Here is the original code. import numpy as np from variables_3 import vars def kinetics(y,t,b1,b2): v = vars(*y) def dydt(v): return [ (b1 * v.n) + (b2 * v.c1), (b1 * v.n) - (v.c1), (b1 * v.n) - (v.c2) ] dydt=dydt(v) return dydt In this code, variables3.py contains: class vars: def __init__(self, *args): (self.n, self.c1, self.c2)= args I would like my final code to look something like this: import numpy as np from variables_3 import vars from equations_3 import eqns def kinetics(y,t,b1,b2): v = vars(*y) dydt=eqns.dydt(v) return dydt What could the file equations_3.py possibly look like to do this? I have tried: from variables_3 import vars class eqns: def dydt(b1,b2,v): return [ (b1 * v.n) + (b2 * v.c1), (b1 * v.n) - (v.c1), (b1 * v.n) - (v.c2)] But that code does not work. Thanks in advance! A: When passing dydt=eqns.dydt(v) in def kinetics(y,t,b1,b2):, make sure to pass b1 and b2 in your function call. Your dydt() function call should look like this: dydt=eqns.dydt(b1, b2, v)
{ "pile_set_name": "StackExchange" }
Q: HTML5 video loading time I am trying to calculate the measure time of html 5 video. I use javascript to listen to html5 video event loadstart and canplaythrough using: media.addEventListener('loadstart'getStartTime(){ startTime = new Date().getTime();}, false) and similar for endTime with event set as canplaythrough to listen. However I could not get any data. Can someone please guide me how to measure video load time using javascript. Thank you for your response, but the solution is I believe using jQuery. however, i was wondering if it is possible from javascript. I have attached a copy of my codes: function loadVideo(){ var timeNow = Date.now(), timeStartLoad, timeFinishLoad; myVideos = new Array(); myVideos[0] = "trailer.mp4"; myVideos[1] = "trailer.ogg"; myVideos[2] = "trailer.m4v"; var videoId = document.getElementById('idForVideo'); var video = document.createElement('video'); for(var i=0; i } however i get undefined for both timestartLoad adn timeFinishLoad. my html body has onload method link to this function. A: Your code has some (copy & paste) syntax problems. var timeInit = Date.now(), timeLoad, timeCanPlay; $("movie").addEventListener('loadstart', function(){ timeLoad = Date.now(); $("t1").innerHTML = "load: " + (timeLoad - timeInit) + " msecs"; }); $("movie").addEventListener('canplaythrough', function(){ timeCanPlay = Date.now(); $("t2").innerHTML = "canplay: " + (timeCanPlay - timeLoad) + " msecs"; }); $("movie").src = "http://ia600208.us.archive.org/12/items/FarSpeak1935/FarSpeak1935_512kb.mp4"; $("movie").play(); Try out: http://jsfiddle.net/noiv/98xZP/:
{ "pile_set_name": "StackExchange" }
Q: How to get the OSM file to generate width of the streets? I'm attempting to load osm data into a database and i've used both osm2p0 and osm2pgrouting and kept realizing I wasnt seeing anything that referenced the width of the streets. This is important for me as I am writing a program to perform search and rescue where the size of the street is important as it can limit which vehicles can use which roads. So I started looking in the osm.xml file and I havent see anything that references width of streets. http://wiki.openstreetmap.org/wiki/Key:width. It says the key should be width. The key width describes the actual width of a way or other feature. Am I missing something or is width not actually provided within the OSM. A: Well, if you look at the OSM tags in use, you will discover the width=* tag, that can be used for highways, too. There are also some more tags that indicate the width of a road/way: maxwidth, lanes. All of this tags are optional and you don't should expect an global coverage... I guess most important criteria (as present for every road) is the road classification itself. But you need to take the country specific defaults into account, which is tricky and will take a lot of research. You might want to use TrafficMining to create a custom routing profile that takes the road width into account to move your HGV vehicles. Maybe the Humaniterian OSM Team has already some experience on such technologies to assist desaster and emergency response.
{ "pile_set_name": "StackExchange" }
Q: Renaming items in export menu in highcharts Can someone please suggest if there is anyway we can rename the items in the export menu in highcharts. Currently it has entries like: Download PNG image Download JPEG image ... I want to remove word "image". Moreover want to control the complete styling. A: There are lots of options for this. Some can be done in Javascript, and I'm sure more can be done in CSS. Here is a JSFiddle example showing the desired text changes and some style changes. You can read the details on this in the API under lang and navigation. The text is changed with: lang: { printChart: 'Print chart', downloadPNG: 'Download PNG', downloadJPEG: 'Download JPEG', downloadPDF: 'Download PDF', downloadSVG: 'Download SVG', contextButtonTitle: 'Context menu' } And the style of the button and menu with: navigation: { menuStyle: { border: '1px solid #A0A0A0', background: '#FFFFFF', padding: '5px 0' }, menuItemStyle: { padding: '0 10px', background: null, color: '#303030', fontSize: '11px' }, menuItemHoverStyle: { background: '#4572A5', color: '#FFFFFF' }, buttonOptions: { symbolFill: '#E0E0E0', symbolSize: 14, symbolStroke: '#666', symbolStrokeWidth: 3, symbolX: 12.5, symbolY: 10.5, align: 'right', buttonSpacing: 3, height: 22, // text: null, theme: { fill: 'white', // capture hover stroke: 'none' }, verticalAlign: 'top', width: 24 } } You can get the default values from the source code, almost at the very top. Some of the defaults use variables that you won't have though, so you may need to change them. And as mentioned, CSS may get you the extra distance.
{ "pile_set_name": "StackExchange" }
Q: Q about [42000] and passed by reference I have two errors in my php script, the only weard thing is this is the exact code as my other scripts. thats the reason that i can't find the solutions. Can you help me to find the solution? Strict Standards: Only variables should be passed by reference in /home/joshua/domains/*********/public_html/panel/settings.php on line 130 Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert = NULL, lastname = 'Hiwat', password = '$2a$13$nAJT6kLx8N5Hd0G8zQ4yheEOad' at line 1' in /home/joshua/domains/*********/public_html/panel/settings.php:216 Stack trace: #0 /home/joshua/domains/********/public_html/panel/settings.php(216): PDOStatement->execute() #1 {main} thrown in /home/joshua/domains/tubecreators.com/public_html/panel/settings.php on line 216 And here my code... <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { $errors = Array(); if(isset($_POST['name'])) { if(trim($_POST['name']) != '') { if(strlen(trim($_POST['name'])) < 2) { $errors[] = 'De voornaam is te kort (2).'; } }else{ $errors[] = 'De voornaam is leeg gelaten.'; } }else{ $errors[] = 'Er is geen voornaam meegestuurd.'; } if(isset($_POST['password'])) { if(trim($_POST['password']) != '' && strlen(trim($_POST['password'])) < 6) { $errors[] = 'Het wachtwoord moet minimum 6 karakters bevatten. Kies zorgvuldig een veilig wachtwoord met (hoofd)letters, cijfers en eventueel symbolen. Indien je je wachtwoord verliest kan je contact opnemen met de ICT manager.'; } }else{ $errors[] = 'Er is geen wachtwoord meegestuurd.'; } if(isset($_POST['passwordrepeat'])) { if(trim($_POST['passwordrepeat']) != trim($_POST['password'])) { $errors[] = 'De opgegeven wachtwoorden zijn niet hetzelfde.'; } }else{ $errors[] = 'Er is geen herhaald wachtwoord meegestuurd.'; } if(isset($_POST['lastname'])) { if(trim($_POST['lastname']) != '') { if(strlen(trim($_POST['lastname'])) < 2) { $errors[] = 'De achternaam is te kort (2).'; } }else{ $errors[] = 'De achternaam is leeg gelaten.'; } }else{ $errors[] = 'Er is geen achternaam meegestuurd.'; } if(isset($_POST['birth'])) { if(trim($_POST['birth']) != '') { if(strlen(trim($_POST['birth'])) < 2) { $errors[] = 'De de geboortedatum is ongeldig (2).'; } }else{ $errors[] = 'De geboortedatum is leeg gelaten.'; } }else{ $errors[] = 'Er is geen geboortedatum meegestuurd.'; } if(isset($_POST['city'])) { if(trim($_POST['city']) != '') { if(strlen(trim($_POST['city'])) < 1) { $errors[] = 'De stadsnaam is te kort (2).'; } }else{ $errors[] = 'De stadsnaam is leeg gelaten.'; } }else{ $errors[] = 'Er is geen stadsnaam meegestuurd.'; } if(isset($_POST['mail'])) { if(trim($_POST['mail']) != '') { if(filter_var(trim($_POST['mail']), FILTER_VALIDATE_EMAIL)) { $checkexist = $dbh->prepare('SELECT COUNT(id) FROM users WHERE mail = :mail AND NOT id = :id'); $checkexist->bindParam(':mail', trim($_POST['mail']), PDO::PARAM_STR); $checkexist->bindParam(':id', $user['id'], PDO::PARAM_INT); $checkexist->execute(); if($checkexist->fetchColumn() > 0) { $errors[] = 'Er is al een account met dit mailadres.'; } }else{ $errors[] = 'De e-mail is ongeldig.'; } }else{ $errors[] = 'De e-mail is leeg gelaten.'; } }else{ $errors[] = 'Er is geen e-mail meegestuurd.'; } if(isset($_POST['youtube'])) { if(trim($_POST['youtube']) != '') { if(strlen(trim($_POST['youtube'])) < 6) { $errors[] = 'De Youtube gebruikersnaam is te kort (6).'; } }else{ $errors[] = 'De Youtube gebruikersnaam is leeg gelaten.'; } }else{ $errors[] = 'Er is geen Youtube gebruikersnaam meegestuurd.'; } if(isset($_POST['about'])) { if(trim($_POST['about']) != '') { if(strlen(trim($_POST['about'])) < 20) { $errors[] = 'Het stukje over jezelf is te kort (2).'; } }else{ $errors[] = 'Het stukje over jezelf is leeg gelaten.'; } }else{ $errors[] = 'Er is geen stukje over jezelf meegestuurd.'; } if(isset($_POST['category'])) { if(trim($_POST['category']) != '') { if(strlen(trim($_POST['category'])) < 1) { $errors[] = 'De Youtube categorie is te kort (2).'; } }else{ $errors[] = 'De Youtube categorie is leeg gelaten.'; } }else{ $errors[] = 'Er is geen Youtube categorie meegestuurd.'; } if(count($errors) == 0) { $name = trim($_POST['name']); $password = trim($_POST['password']); if($password != '') { $bcrypt = new Bcrypt($config['security']['passwordsafety']); $passwordHashed = $bcrypt->hash($password); } $lastname = trim($_POST['lastname']); $birth = trim($_POST['birth']); $city = trim($_POST['city']); $mail = trim($_POST['mail']); $youtube = trim($_POST['youtube']); $about = trim($_POST['about']); $category = trim($_POST['category']); $update = $dbh->prepare('UPDATE users SET name = :name, insert = :insert, lastname = :lastname, ' . (($password != '') ? 'password = :password, ' : '') . 'birth = :birth, country = :country, city = :city, mail = :mail, facebook = :facebook, twitter = :twitter, google = :google, instagram = :instagram, youtube = :youtube, pinterest = :pinterest, about = :about, category = :category WHERE id = :id'); $update->bindParam(':name', $name, PDO::PARAM_STR); $update->bindParam(':insert', $insert, PDO::PARAM_STR); $update->bindParam(':lastname', $lastname, PDO::PARAM_STR); if($password != '') { $update->bindParam(':password', $passwordHashed, PDO::PARAM_STR); } $update->bindParam(':birth', $birth, PDO::PARAM_STR); $update->bindParam(':country', $country, PDO::PARAM_STR); $update->bindParam(':city', $city, PDO::PARAM_STR); $update->bindParam(':mail', $mail, PDO::PARAM_STR); $update->bindParam(':facebook', $facebook, PDO::PARAM_STR); $update->bindParam(':twitter', $twitter, PDO::PARAM_STR); $update->bindParam(':google', $google, PDO::PARAM_STR); $update->bindParam(':instagram', $instagram, PDO::PARAM_STR); $update->bindParam(':youtube', $youtube, PDO::PARAM_STR); $update->bindParam(':pinterest', $pinterest, PDO::PARAM_STR); $update->bindParam(':about', $about, PDO::PARAM_STR); $update->bindParam(':category', $category, PDO::PARAM_STR); $update->bindParam(':id', $user['id'], PDO::PARAM_INT); $update->execute(); addlog('Account gewijzigd', $user['id']); echo '<font color="gree">De gebruiker is succesvol gewijzigd.</font><meta http-equiv="refresh" content="1;url=http://panel.tubecreators.com/instellingen">'; $edited = true; }else{ echo '<font color="red">Er ging wat mis. De volgende dingen gingen fout:<ul><li>' . join('</li><li>', $errors) . '</li></ul>De gebruiker is nniet gewijzigd.</font>'; } } if(!isset($edited)) { ?> A: insert is a reserved MySQL keyword. You need to quote it in backticks like `insert`. You should get used to doing this for all table and column names. Only variables should be passed by reference means exactly what it says. It is expecting a reference, therefore a variable must be passed to it. I can update this once you point me to line 130 of panel/settings.php. My assumption is the error is generated by bind_param which requires a reference. The one line of code I see that would certainly generate this warning is: $checkexist->bindParam(':mail', trim($_POST['mail']), PDO::PARAM_STR); Here you are passing a return value instead of a variable. You could do this: $trimMail = trim($_POST['mail']) $checkexist->bindParam(':mail', $trimMail, PDO::PARAM_STR);
{ "pile_set_name": "StackExchange" }
Q: Can't connect to web socket react-native-meteor iOS I'm using react-native-meteor, and am having trouble connecting to the web socket with iOS only. My application works just fine when running on the android simulator, but just doesn't work in iOS simulator or device. This is my code: Meteor.connect('ws://app.mysite.com/websocket'); And the logs: [info][tid:main][RCTBatchedBridge.m:72] Initializing <RCTBatchedBridge: 0x7fe23b23d4c0> (parent: <RCTBridge: 0x7fe239d65090>, executor: RCTJSCExecutor) [warn][tid:main][RCTEventEmitter.m:54] Sending `websocketFailed` with no listeners registered. Disconnected from DDP server. Any idea why I can't connect on iOS only? I have already disabled App Transport Security, and downloaded a non-https webpage, so I know that's not the problem A: Well I figured it out. I think I had incorrectly configured the app transport security exception. To fix it, I connected to the secure web socket like this (note the extra s): Meteor.connect('wss://app.mysite.com/websocket');
{ "pile_set_name": "StackExchange" }
Q: JQuery Autocomplete trouble I'm trying to recreate JQUery autocomplete example from its website: http://jqueryui.com/autocomplete/#multiple-remote The only thing I change is I changes the source property from : source: function( request, response ) { $.getJSON( "search.php", { term: extractLast( request.term ) }, response ); }, To: source: function (request, response) { $.ajax({ type: "POST", url: "/UIClientsWebService.asmx/SearchCRMUsers", data: "{term:'" + extractLast(request.term) + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { $("#commentBody").autocomplete("option", "source", result.d); } }, response); }, Now the problem is autocomplete just work for first ',' . When I choose my first item, then when I want to search and choose second item, nothing happen. There is no error in my firebug. I can see search method call but source does not change and also nothing shown as my autocomplete items. I can see my search term change correctly but actually no search happen. A: try add the option multiple: true to your script $(document).ready(function() { src = '/UIClientsWebService.asmx/SearchCRMUsers'; $("#yourSelector").autocomplete({ source: function(request, response) { $.ajax({ url: src, dataType: "json", data: "{term:'" + extractLast(request.term) + "'}", success: function(data) { response(data); } }); }, min_length: 3, delay: 300, multipleSeparator:",", multiple: true, }); });
{ "pile_set_name": "StackExchange" }
Q: Can I display a message in MySQL? I have a question related to SQL. Can I display a custom message in MySQL phpMyAdmin, something like this: SELECT * FROM table_name PRINT 'The message that I want to write!'; I tried to do it with PRINT syntax, because I found something like that, but it doesn't work. Do you have some ideas? A: Put the text in the SELECT statement SELECT *, 'PRINT' FROM foo; If you're wanting to print a long message, and want a different column name, simply use an alias by using AS. SELECT *, 'The message i want to print' AS msg FROM foo;
{ "pile_set_name": "StackExchange" }
Q: Rails nested form, attributes not getting passed So I have a Conversation model, which has_many messages. I'm trying to create a new message when I create a conversation. Here's my ConversationsController: class ConversationsController < ApplicationController before_filter :authenticate_user! def new recipient = User.find(params[:user]) @conversation = Conversation.new(from: current_user, to: recipient) @conversation.messages.build(from: current_user, to: recipient) end def create @conversation = Conversation.create(params[:conversation]) redirect_to @conversation end end And here's my form (conversations/new.html.erb): <%= form_for @conversation do |f| %> <%= f.fields_for :messages do |g| %> <%= g.label :subject %> <%= g.text_field :subject %> <%= g.label :content %> <%= g.text_field :content %> <% end %> <%= f.submit "Send" %> <% end %> The problem: when I submit the form, the conversation's message gets saved, but the to and from fields that I specified as parameters in build are not saved (they are nil). However, the subject and content fields filled out in this form are saved just fine. I've done a little bit of digging... if I do a puts on @conversation.messages in the new action, or in the new.html.erb, the message seems to have to and from. It's only when the message reaches the create action do those fields disappear. A: UPDATED: class ConversationsController < ApplicationController before_filter :authenticate_user! def new recipient = User.find(params[:user]) @conversation = Conversation.new(to: recipient) @conversation.messages.build end def create @conversation = current_user.conversations.build(params[:conversation]) # Set all the attributes for conversation and messages which # should not be left up to the user. @conversation.to = current_user @conversation.messages.each do |message| message.to = @conversation.to message.from = @conversation.from end redirect_to @conversation end end <%= form_for @conversation do |f| %> <%= f.hidden_field :recipient %> <%= f.fields_for :messages do |g| %> <%= g.label :subject %> <%= g.text_field :subject %> <%= g.label :content %> <%= g.text_field :content %> <% end %> <%= f.submit "Send" %> <% end %> You may still want to validate the recipient in your Conversation model.
{ "pile_set_name": "StackExchange" }
Q: Count Based on 2 date Ranges for 2 different columns Having an issue writing a report. I am trying to count on the number of enquiries Issued and passed, they both have a datetime field The problem im having is the results are coming back incorrect. Running this code gives me 126 for passed SELECT COUNT(*) AS Passed FROM BPS.dbo.tbl_Profile AS p Inner Join BPS.dbo.tbl_Profile_Mortgage AS pm ON p.Id = pm.FK_ProfileId WHERE p.CaseTypeId IN (1,2,9,15) AND CONVERT(DATE,pm.DatePassed,103) BETWEEN @Start AND @End When i run the issued query I get 223 SELECT COUNT(*) AS Issued FROM BPS.dbo.tbl_Profile AS p Inner Join BPS.dbo.tbl_Profile_Mortgage AS pm ON p.Id = pm.FK_ProfileId WHERE p.CaseTypeId IN (1,2,9,15) AND CONVERT(DATE,pm.DateAppIssued,103) BETWEEN @Start AND @End These figures are correct so i put it in one query like so. SELECT COUNT(pm.DateAppIssued) AS Issued,COUNT(pm.DatePassed) AS Passed FROM BPS.dbo.tbl_Profile AS p Inner Join BPS.dbo.tbl_Profile_Mortgage AS pm ON p.Id = pm.FK_ProfileId WHERE p.CaseTypeId IN (1,2,9,15) AND (CONVERT(DATE,pm.DateAppIssued,103) BETWEEN @Start AND @End OR CONVERT(DATE,pm.DatePassed,103) BETWEEN @Start AND @End) This gives me Issued 265 and passed 185 I have tried many different variation but still cant get the correct figures I hope i have explained this well enough, any help would be much appreciated. Rusty A: Because you have the both the conditions in the where clause with an or condition, you are seeing a different result. Use them in the aggregation itself. SELECT COUNT(case when CONVERT(DATE,pm.DateAppIssued,103) BETWEEN @Start AND @End then 1 end) AS Issued, COUNT(case when CONVERT(DATE,pm.DatePassed,103) BETWEEN @Start AND @End then 1 end) AS Passed FROM BPS.dbo.tbl_Profile AS p Inner Join BPS.dbo.tbl_Profile_Mortgage AS pm ON p.Id = pm.FK_ProfileId WHERE p.CaseTypeId IN (1,2,9,15)
{ "pile_set_name": "StackExchange" }
Q: how to change code this into recursion Java? public long weightedSum(int[] a, int[] b, int n) { long value = 0; long sum = 0; for (int i = 0; i < a.length; i++) { value = a[i] * b[i]; sum = sum + value; } return sum; } takes two 1D integer arrays and an integer n as parameters and returns the sum of products of the first n elements of the two arrays. For example, given the following two 1D arrays: int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {6, 7, 8, 9, 10}; the first 4 elements of arr1 and arr2, that is,1 * 6 + 2 * 7 + 3 * 8 + 4 * 9 = 80 as the result. A: public static long weightedSum(int[] a, int[] b, int n) { if (n == 0) return 0; else return a[n - 1] * b[n - 1] + weightedSum(a, b, n - 1); } Output : int[] arr1 = { 1, 2, 3, 4, 5 }; int[] arr2 = { 6, 7, 8, 9, 10 }; System.out.println(weightedSum(arr1, arr2, 1)); // output : 6 System.out.println(weightedSum(arr1, arr2, 2)); // output : 20 System.out.println(weightedSum(arr1, arr2, 3)); // output : 44 System.out.println(weightedSum(arr1, arr2, 4)); // output : 80 System.out.println(weightedSum(arr1, arr2, 5)); // output : 130
{ "pile_set_name": "StackExchange" }