text
stringlengths
70
452k
dataset
stringclasses
2 values
Why doesn't <numeric> require/allow std::, but <cmath> does? Why, at least in my code, does <numeric> NOT require or ALLOW std::? I'm following along with a YouTube SDL2 tutorial, and IntelliSense has squiggled all my trig functions. In the process of experimenting, I removed all the std:: and it worked and compiled fine. I decided to add #include <cmath> as well and commented out #include <numeric>, and now all the math functions again have squiggles. I reinserted the std:: and the squiggles disappeared. I did some Google research and it seems to me that <numeric> is part of the standard library and thus should require std::. #include "screen.h" #include <numeric> //#include <cmath> void line(Screen& screen, float x1, float y1, float x2, float y2) { float dx = x2 - x1; float dy = y2 - y1; float length = float (sqrt(dx * dx + dy * dy)); float angle = float (atan2(dy, dx)); for (float i = 0; i < length; i++) { screen.pixel( x1 + float (cos(angle) * i), y1 + float (sin(angle) * i) ); } } int main(int argv, char** args) { Screen screen; for (int i = 0; i < 100; i++) { screen.pixel(rand() % 640, rand() % 480); } line(screen, 0, 0, 300, 300); while (true) { screen.show(); screen.input(); } return 0; } OK, once again, the code is NOT mine, it's a YouTube tutorial, thus it's his code, and this code compiled using <numeric> only for math functions such as sin(), cos(), atan2() and sqrt(). My one modification was to include <cmath>. Here's my reproducible example: //#include "screen.h" #include <numeric> #include <iostream> //#include <cmath> void line( float x1, float y1, float x2, float y2) { float dx = x2 - x1; float dy = y2 - y1; float length = float (sqrt(dx * dx + dy * dy)); float angle = float (atan2(dy, dx)); for (float i = 0; i < length; i++) { float tempx1 = x1 + float(cos(angle) * i); float tempy1 = y1 + float(sin(angle) * i); std::cout << i << " " << x1 << " " << y1 << std::endl; } } int main(int argv, char** args) { line(2, 2, 20, 20); return 0; } iirc <cxxxx> guarantee names under std namespace, while <xxxx.h> guarantee names under global space. your title seems mismatch the question body. (and c++ is case sensitive, don't type STD:: it'd not work) The <numeric> and <cmath> headers have nothing to do with each other. What does "screen.h" declares and what are you using from <numeric>? Please, provide a minimal reproducible example. Generally speaking, STL includes can bring stuff that isn't promised by the standart. Your code, as shown, is not using any functions from <numeric>. If you were to use any of those function, you would find that use of std is required, since the functions ARE in namespace std. Not only is nothing from <numeric> shown, but they're pulling in stuff like rand() without including the appropriate headers. It's like opposite day for includes. And rand() is used incorrectly to boot. If I try to compile your "reproducible example" in GCC, it fails as expected. If I take out #include <numeric> and put in #include <cmath>--the header that actually has the functions you're using--it works both with and without the std:: prefix in GCC and MSVC. I haven't downvoted this question, but I suspect the people who have did so because there's a bunch of (apparently?) irrelevant code in here and the snippets that ostensibly demonstrate the issue do not do so for them. It does appear that MSVC pulls in a bunch of mathematical functions just from including <iostream>. In both the std namespace and the global namespace. A bit surprising of it. The C++ header <cmath> declares exactly the same Standard C math functions also declared in the C header <math.h>, with functions like pow(), ceil(), sqrt(), tan(), and constants like M_PI. The C++ header <numeric> is completely different: Components for performing numeric operations. Includes support for complex number types, random number generation, numeric (n-at-a-time) arrays, generalized numeric algorithms, and mathematical special functions. If you happen to have some header named numeric.h on your workstation ... it's completely unrelated to either of the above headers. For example: Directory of c:\Ruby30-x64\include\ruby-3.0.0\ruby\internal\intern 07/09/2021 07:38 PM 1,941 numeric.h If you want to use the Standard C library math functions sqrt() or cos() (callable from either C or C++), then you need to #include either <cmath> or <math.h>. None of the functions in <math.h> are in the C++ namespace std, hence they don't need to be qualified with std::xxx. The #include is what ever came with MSVS 22 community // numeric standard header // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception Q: Between the comments and my reply, do you understand distinction between cmath, math.h, numeric and numeric.h? If not, exactly what don't you understand? Q: Did we address your original question? If not, exactly what is (are) your remaining question(s)? While really appreciate you expounding on the distinction between cmath,math.h and numeric, that was not really my question. My original question was why numeric didn't require a std::, not which include was more appropriate. @MichealDouble • what functions out of <numeric> are you using? @Micheal Double- I updated my reply (and corrected a misstatement), Look at the headers themselves (e.g. in "notepad"). Hopefully my update addresses your remaining questions. I'm not sure what the correct term for the cxxxxx headers is but I don't think it's "alias", since they're not 100% identical to the C version. "and constants like M_PI" - Neither standard C nor C++ requires M_PI to be defined in math.h/cmath.
common-pile/stackexchange_filtered
Excel VBA - Using range variable to dynamically set range a set # of cells I currently have my code looking down a column in a specific worksheet for a certain value in a cell. If it finds that value in a cell, it uses that cell as the anchor location for the rest of the subroutine. Here is the relevant code. With DailyWS Set DailyTable = .Range("C7:Q21") Set Week = .Range("F4") End With 'DailyWS Set rngY = BackupWS.Range("B1:B10000").Find(Replace(Week.Value, " Week", ""), lookat:=xlPart) If rngY Is Nothing Then Set rngY = BackupWS.Range("B1").Offset(LastRow, 0) End If With BackupWS Set BackupTable = rngY.Offset(0, 2) End With 'BackupWS I need to take the information in the DailyTable range and copy it to the BackupTable range. As it's currently coded, it only copies one cell because rngY only returns one cell [for other parts of the subroutine I still need rngY to be this one cell]. So I need is for it to copy DailyTable starting at the rngY cell. For example, if rngY returns as C1, then I would need to set BackupTable to range C1:Q15 then perform the .Offset(LastRow, 0) to that. I'm unsure how to successfully manipulate this to do that. If you need clarification, please ask. from your request: if rngY returns as C1, then I would need to set BackupTable to range C1:Q15 then perform the .Offset(LastRow, 0) to that. change: If rngY Is Nothing Then Set rngY = BackupWS.Range("B1").Offset(LastRow, 0) End If With BackupWS Set BackupTable = rngY.Offset(0, 2) End With 'BackupWS to: With BackupWS Set rngY = .Range("B1:B10000").Find(Replace(Week.Value, " Week", ""), lookat:=xlPart) If rngY Is Nothing Then Set rngY = .Range("B1").Offset(LastRow, 0) Set BackupTable = .Range(rngY, .Range("Q15")).Offset(LastRow, 0) End With 'BackupWS but you may want to add more details to your actual goal Perfect! I was able to make the adjustments need to the change you made to get it to work exactly how I wanted. Thanks!
common-pile/stackexchange_filtered
Civireport vs Views What is the best practice between CiviReport and Views ? (Except the fact than Views enables to order the columns, which CiviReport does not) Why and when should we use one rather than the other ? A basic difference is that CiviReport is CMS-independent whereas Views is a Drupal module so those running WordPress or Joomla don't have that choice. (Yes, OP knows that ... some readers might not!) In part, it depends on who is setting up the reports/views: For end-users, using the configuration tabs to adjust the output is easier than adding fields and filters via the Views UI. But the simplicity has limitations - you can't determine the order of fields in a report, you can only select the fields that have made available by the report author etc. For site-builders, Views offer more configurability without code. For developers, custom reports can make it easier for end-users to tweak their own reports and code-level data manipulation allows more complex presentation of data. Thank you Aidan, you clearly confirm my feeling : there is no general answer ; it depends upon different factors involving the type of report and the end-user understandability (BTW, I am not a developper).
common-pile/stackexchange_filtered
sw directory reference On this page I noticed a reference to the /sw directory. I would like more info on this directory. For example, is /sw a Mac only convention or is it used on other systems? /sw is used by the Fink project. Admittedly it does not conform to the Filesystem Hierarchy Standard.
common-pile/stackexchange_filtered
Maven : unable to find java.lang issue on OS X I getting the below issue when I tried mvn clean install obviously it is unable to find the run time jar but what I need to do ? the error log : [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] Failure executing javac, but could not parse the error: [parsing started /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java/com/ericsson/research/ag/ra/common/cthserverclient/IHttpClient.java] [parsing completed 42ms] [parsing started /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java/com/ericsson/research/ag/ra/common/cthserverclient/CTHWebSessionException.java] [parsing completed 1ms] [parsing started /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java/com/ericsson/research/ag/ra/common/cthserverclient/CTHServerSession.java] [parsing completed 14ms] [search path for source files: /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java,] [search path for class files: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/rt.jar,/Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/target/classes,/Users/olgunkaya/.m2/repository/json/json-simple/1.1/json-simple-1.1.jar,.] Fatal Error: Unable to find package java.lang in classpath or bootclasspath [INFO] 1error [INFO] ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.696s [INFO] Finished at: Mon Jun 11 07:54:00 EEST 2012 [INFO] Final Memory: 5M/81M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3:compile > (default-compile) on project ag.ra.common: Compilation failure [ERROR] Failure executing javac, but could not parse the error: [ERROR] [parsing started /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java/com/ericsson/research/ag/ra/common/cthserverclient/IHttpClient.java] [ERROR] [parsing completed 42ms] [ERROR] [parsing started /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java/com/ericsson/research/ag/ra/common/cthserverclient/CTHWebSessionException.java] [ERROR] [parsing completed 1ms] [ERROR] [parsing started /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java/com/ericsson/research/ag/ra/common/cthserverclient/CTHServerSession.java] [ERROR] [parsing completed 14ms] [ERROR] [search path for source files: /Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/src/main/java,] [ERROR] [search path for class files: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/rt.jar,/Users/olgunkaya/workspace/CM2H/remoteaccess/osgi/ag.ra.common/target/classes,/Users/olgunkaya/.m2/repository/json/json-simple/1.1/json-simple-1.1.jar,.] [ERROR] Fatal Error: Unable to find package java.lang in classpath or bootclasspath is ur java installed properly? if yes is it at same location where this command is trying to search(i.e. "System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/rt.jar") ? mac os x lion comes with its own java installed on. The problem is; as I know oraclhe hasn't been provided a java for MAC. Apple is using own java for it. And in that java no rt.jar is provided. I think it is something different name. But I am not sure. I think I found the issue. Apple has changed the rt.jar to classes.jar which is located in. /System/Library/Frameworks/JavaVM.framework/Versions/<your_java_version>/Classes/classes.jar I need to modify my pom.xml to show it the path to classes.jar. Edit : In a multi-mudule project. Creating soft links to classes jar in the lib directory is much better. sudo ln -s ../../Classes/classes.jar ./rt.jar Well sudo because writing in the result of /usr/libexec/java_homecommand ,which is your java home directory, requires administrator priviligies. When I tried this to fix a similar problem I had, the above command needed to be run from $JAVA_HOME/lib in order for Maven to find it. it is actually depends on which java version are you using. once I had this issue, Oracle had not implemented Java for OS X. Nowadays I don't think one need to do this operation (unless (s)he is not using java 1.6 or lower)
common-pile/stackexchange_filtered
Create standalone executable c++ embed Lua dymamic library link? (eclipse,ubuntu) I create a c++ program and embedding Lua script. I use dynamic link to Lua library (not install Lua). In Lua file embedding i just print a message "Hello Lua". so how to i make standalone executable c++ embed Lua library and i can run it on other machine(ubuntu)? Structure c++ project is: HelloLua (project) includes: (static library) data helloLua.lua include lua: (lua.h,lua.hpp...) lib lua x86:liblua52.a,liblua52.0 main main.cpp and this is command build make mkdir -p bin/x86 Compiling main/main.cpp ... done Linking bin/x86/MyNguyen ... done. > Target: MyNguyen (Arch: x86) > Settings: g++ -pipe -m32 -O3 -Wall -fmessage-length=0 -D_REENTRANT -D_PASSTHRU_0404 -DX86_BUILD -DLINUX -LDFLAGS -DSOFTWARE_VERSION="'1.0.0'" > Libraries: -lm -Wl,--no-as-needed -ldl -llua52 > strip bin/x86/MyNguyen ... done. **** Build Finished **** The source code of lua is widely available. You can compile lua as part of your project, or use the dynamic libraries. In both cases you'll need some C++ initialization code.
common-pile/stackexchange_filtered
How can I modify the internal swarm load balancer IP address? I have a docker swarm in a cluster of machines and my use case is deploying several standalone containers that need to be connected which have static IP configurations, so I created an overlay to connect all the nodes of the swarm. I don't use/want to use anything related to docker SERVICES nor its replication in my docker swarm, it's not a real word scenario it's a test one. The problem is when I deploy a container to a certain host a the swarm load balancer is created with a certain IP address which is random and I need it to be static because I can't change the configurations of the containers I want to deploy. I already searched how can I remove this load balancer, because as far as I'm concerned it's only used for external traffic coming into the swarm services/containers and they are not useful for my use case. A solution would be deploy a dummy container and check which IP was assigned to the swarm load balancers in each node and then adjust the configuration files of the containers I want to deploy, but this approach does not scale well and it's a workaround of the actual problem. My problems started when randomly my containers couldn't start giving docker: Error response from daemon: attaching to network failed, make sure your network options are correct and check manager logs: context deadline exceeded. where I could not identify it's reason to happen and then inferred it was because these load balancers where using the same IP adress I wanted to use in my containers. My question is how can I statically define the IP of these load balancers or remove them completely for every node? Thank you for your time. Docker Swarm Architecture Here is the output of docker inspect network <my-overlay-network> "Name": "my-network", "Id": "mo8rcf8ozr05qrnuqh64wamhs", "Created": "2020-11-16T01:59:20.100290182Z", "Scope": "swarm", "Driver": "overlay", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "<IP_ADDRESS>/24", "Gateway": "<IP_ADDRESS>" } ] }, "Internal": false, "Attachable": true, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "95b8e9c3ab5f9870987c4077ce264b96a810dad573a7fa2de485dd6f4b50f307": { "Name": "unruffled_haslett", "EndpointID": "422d83efd66ae36dd10ab0b1eb1a70763ccef6789352b06b8eb3ec8bca48410f", "MacAddress": "02:42:0a:00:01:0c", "IPv4Address": "<IP_ADDRESS>/24", "IPv6Address": "" }, "lb-my-network": { "Name": "my-network-endpoint", "EndpointID": "192ffaa13b7d7cfd36c4751f87c3d08dc65e66e97c0a134dfa302f55f77dcef3", "MacAddress": "02:42:0a:00:01:08", "IPv4Address": "<IP_ADDRESS>/24", "IPv6Address": "" } ` The question is why are using swarm when you have standalone containers? and when you say you want to set a static IP to a container, then what do you do when a swarm SERVICE is replicated and creates more than one container? I am just trying to say that maybe using docker swarm is the problem. Finally, I would say that the host machine needs to forward each static ip address you have to a nodeport of each service and then this becomes an iptables problem not a docker swarm one. Thank you for your response, I don't want to use anything related to services or replicate them in swarm. My objective here is I have a cluster of machines and I need to setup up a test to run a couple hundreds of containers and then I have a module that inject latency inside the docker swarm. It only works on docker swarm. I don't have any published ports or anything related to exterior communication. That's why I used it, among other reasons. I understand that you don't want to replicate but services created by swarm work under the assumption that you can. Also when deploying a new image to a service using swarm (and depending on ur configuration) then the service might have two containers online for a brief period. For all above reasons setting static IPs is a bad idea and im not sure is even possible. To point you to a different direction, you said that you don't have any published port so I assume that the services in the swarm communicate with each other, in which case why dont you use the service_name as an hostname instead of setting static IPs Thank you for your help, while reading all documentation on docker swarm and it's architecture I came up with a way to avoid my problem, which was I had 100+ containers running across a swarm cluster of 16 machines. In these machines the static configuration accidently collided with the internal load ballancer IP. My solution was to use a wider subnet mask which allowed me to avoid collisions. Althouth not the ideal solution will work great. Thank you for your time! I just use a wider subnet mask of /16 instead of /24. Which allowed me to have more IP addresses and thus avoiding collisions with the Internal load balancers.
common-pile/stackexchange_filtered
How I Can Delete Custom Post Type URL i create a Custom Post and i don't want them has a URL. There is a URL like that = site.com/custom-slug/and-id-or-title and i don't want this, how i can do that? Thank you already! If I correctly understand the question you're asking, you don't want your CPT to be directly available on the front-end. If so, then just set 'public' => false when you register the post_type. Remember that various other args to register_post_type() default to the value of public (e.g., show_ui), show when you set 'public' => false you often times need to explicitly set those args to true, e.g. $args = array ( // don't show this CPT on the front-end 'public' => false, // but do allow it to be managed on the back-end 'show_ui' => true, // other register_post_type() args ) ; register_post_type ('my_cpt', $args) ; That's the thing i search. Thank you. I try this 'public' => false, but like that i lost this in admin panel but when i add this: 'show_ui' => true, i can see that on admin panel and there is not a URL. Sparrow Hawk is correct, as "public' affects several other args options. So, while his solution will work, if you want to avoid having to make some other add'l changes because everything else is working, just set the arg you want to false, which is this one: 'publicly_queryable' => false, Add this line to the register_post_type function creating your custom post type and you won't have to make any other changes to the code. ALSO. Be sure to flush your permalinks after you make this change or you won't see any evidence of the change. (to flush them, go to settings / permalinks and hit save) This is what you are looking for: /** * Remove the slug from custom post type permalinks. */ function wpex_remove_cpt_slug( $post_link, $post, $leavename ) { if ( ! in_array( $post->post_type, array( 'YOUR_POST_TYPE_NAME' ) ) || 'publish' != $post->post_status ) { return $post_link; } $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'wpex_remove_cpt_slug', 10, 3 ); /** * Some hackery to have WordPress match postname to any of our public post types * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts * Typically core only accounts for posts and pages where the slug is /post-name/ */ function wpex_parse_request_tricksy( $query ) { // Only noop the main query if ( ! $query->is_main_query() ) { return; } // Only noop our very specific rewrite rule match if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'YOUR_POST_TYPE_NAME', 'page' ) ); } } add_action( 'pre_get_posts', 'wpex_parse_request_tricksy' ); Change "YOUR_POST_TYPE_NAME" with your post type name.
common-pile/stackexchange_filtered
AngularJS hide any parent div using ng-click in a child element I already know about ng-if and ng-show methods of showing/hiding DOM elements. In this case, however, I have about 100 div elements, each with multiple child span elements, and whenever a span is clicked, I want the parent div to hide. Example: <div>Display text <span ng-click="hideThisDiv(this)">Option1</span> <span ng-click="hideThisDiv(this)">Option2</span> <span ng-click="hideThisDiv(this)">Option3</span> </div> In the function, I want to be able to do something like: $scope.hideThisDiv = function(element){ element.$parent.$id.visible = false; } Using console.log(element.$parent) in this function shows, however, that there isn't a simple way to access a "visible" property of this div element. At least, not that I can see so far. This seems like a simple concept, I'm just lacking the proper syntax or access method. Try below code it works var app = angular.module('myApp', []); app.controller('MainCtrl', function ($scope) { $scope.hideParent = function (event) { var pEle = event.currentTarget.parentElement; pEle.style.visibility = "hidden"; } }); <!DOCTYPE html> <html ng-app="myApp"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-controller="MainCtrl"> <div> This is parent div click below to hide <br /> <span ng-click="hideParent($event)">Click here to hide</span> <br /> <span ng-click="hideParent($event)">or Here</span><br /> <span ng-click="hideParent($event)">or Here</span> </div> </body> </html> Interesting idea. No result, though, not even an error message. I modified the code, now it hide the parent element If you prefer to do this with jquery then use the jqLite approach with angular.element like this: $scope.hideThisDiv = function(el) { angular.element(el.target).parent().addClass('hidden'); }; Then pass in the event like this: <span ng-click="hideThisDiv($event)">Option1</span> The add this to your css .hidden { display:none } Solution: The better approach is to create a custom directive and hide the parent element using jqLite. var app = angular.module('app', []); app.directive('hideParentOnClick', function () { return { link: function (scope, element) { element.on('click', function () { element.parent().css({display: 'none'}); }); } } }); And in your HTML: <div> Display text <span hide-parent-on-click>Option1</span> <span hide-parent-on-click>Option2</span> <span hide-parent-on-click>Option3</span> </div> Plunker Example Advantages: You can combine this directive with the aforementioned ng-click because the last one is not utilized in this method and can be freely used for any other purpose. Directives are intended for DOM manipulations, not controllers. Read more here. Better overall modularity.
common-pile/stackexchange_filtered
How do I pre-cache images for quick viewing with javascript? I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map. <img src="pic.jpg" usemap="#picmap" /> <map id="picmap" name="picmap"><area shape="rect" coords ="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" /> </map> <p id="desc"></p> Where in the header I defined these functions: <script type="text/javascript"> function mouse_off(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic.jpg"; } function mouse_on_write(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic2.jpg"; </script> It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). How can I make the image switching more seamless without reduction in picture quality? On second thought I realize that I could also just have both images displayed, at a small and a large scale, and on mouse over they would switch places; How would I do this? Would this reduce lag? By the way, you're probably not going to want to inflict a 2.5 MB image on your users anyway. What are the dimensions of the space you're trying to fill? You don't need to create any page elements, it can all be preloaded using JavaScript: tempImg = new Image() tempImg.src="pic2.jpg" EDIT: If you have a lot of images, you can use the poor-man's multi-preloader: preloads = "red.gif,green.gif,blue.gif".split(",") var tempImg = [] for(var x=0;x<preloads.length;x++) { tempImg[x] = new Image() tempImg[x].src = preloads[x] } This method doesn't work for me. I need to preload because I am showing a message to users right before reloading the page--an edge case, I know. However, this works if I put it in the DOM: <img src="/images/icons/icon.png" style="visibility:hidden; height:0px; width:0px;" />. Forcing height and width to nothing keeps it from damaging the view no matter where it is, while visibility:hidden makes the browser load the image. Quick tip: Avoid at all costs to use a classic for loop. Use the forEach array helper function instead. Doing this with sprites is a good solution, because you don't have to wait to load the new image. Sprites work by combining the two images into one, and changing the background offset on mouseover. You can even do with with CSS instead, for much faster results. There's a good tutorial on this here. Sprites don't get enough love. Nicely played. Seems like overkill for just 2 images. Diodeus' solution seems simpler. But it depends on whether javascript is available I guess. not useful if you have +500 imgs, js is better for precaching next X pics @davefrassoni I don't know where you got that criteria from, but it wasn't the OP. That aside, don't follow 11-year-old advice on these matters. Use a service worker or something. As of Javascript 1.6 this can be accomplished without any named variables: imageList.forEach( function(path) { new Image().src=path } ); You can also put both images in same file and offset it up and down. If it should affect element you are crossing over with mouse it could look like a { background-image: url(back.png); background-repeat: no-repeat; background-attachment:fixed; background-position: 0 0; } a:hover { background-image: url(back.png); background-repeat: no-repeat; background-attachment:fixed; background-position: 0 20px; } This way it can work without javascript. If I understand your case correctly you still need javascript, but you can "preload" image this way nevertheless. Clever solution from Diodeus. However, unless there's a good reason NOT TO, you should really consider using sprites. It's a bit of work to get them setup, but the net efficiency is really worth it. This approach is the number one rule in Steve Souder's High Performance Web Sites. "Rule 1 - Make Fewer HTTP Requests" Good luck and have fun. - D. While I agree, due to the nature of the questioner it is seems something like sprites could be a bit too challenging. What you want todo is preload the images behind the scenes. Then, when moused over, the browser will already have that image in its cache and will switch it over very fast. function preloadImage(imagePath) { var img = document.createElement('IMG'); img.src = imagePath; } preloadImage('BigImage'); I've noticed that 'preloading' into .src to this day doesn't work consistently across all browsers - IE7 still can't figure out how to cache / use preloaded images - you can clearly see there's a server request made every time you mouse over. What I do is load in all images via standard HTML placement and just toggle style.display on and off. Here's how I do it, in pure JavaScript: var myImgs = ['path/to/img1.jpg', 'path/to/img2.gif']; function preload(imgs) { var img; for (var i = 0, len = imgs.length; i < len; ++i) { img = new Image(); img.src = imgs[i]; } } preload(myImgs); That said, ALassek's suggestion of using CSS sprites is an excellent one, if you have scope to do it. The advantages of sprites are many: fewer HTTP requests, smaller download size (usually), works without JavaScript enabled. Use display: none;, then have the Javascript change it to display: inline when you want to display it. This has the added advantage of being able to put the image exactly where you want in the page's source, rather than having to add it with Javascript later. http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/ When we first launched the lab, we released a jQuery plugin that automatically preloads all images referenced in CSS files. We've found the script to be incredibly helpful in developing snappy applications where images are always ready when we need them. This post describes a significant update to the script which will make it even easier to integrate in existing projects. Dead link. I couldn't find a replacement (mostly because I'm lazy)
common-pile/stackexchange_filtered
can't delete an element from a hashmap I created a hashmap to store object Person, the key is a String (Person's email address). I am trying to delete an entry in the hashmap using the key but not sure why it won't delete it. What went wrong? My code and the output are included. any help is appreciated! import java.util.HashMap; import java.util.Map; public class TestHashMap { private Map <String, Person> personDB = new HashMap<String, Person>(); // added main to test the code public static void main(String[] args) { TestHashMap org = new TestHashMap() ; // add data to personDB org.add(new Person("A", "Smith","1234567890","ASmith@atest.com")); org.add(new Person("B", "Smith","1234567890", "BSmith@atest.com")); org.add(new Person("C", "Walsh","1234567890","CWalsh@atest.com")); org.add(new Person("D", "Glatt","1234567890","DGlatt@atest.com")); org.add(new Person("E", "Cheong", "1234567890","ACheong@atest.com")); org.add(new Person("F", "Walsh","0123456789","FWalsh@sg.com")); // remove an element from personDB org.display("testing ......before remove"); // display all elements in personDB org.remove("ACheong@atest.com"); org.display("after.................."); } public void add(Person p) { String key = p.getEmail(); personDB.put(key, p); } public void remove(String mail) { Object obj = personDB.remove(personDB.get(mail)); System.out.println(obj + " deleted!"); } } My output: testing ......before<EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS>null deleted! after.................. <EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS> Object obj = personDB.remove(personDB.get(mail)); should be Object obj = personDB.remove(mail); The parameter to remove is the key, not the element. Person is the key, not<EMAIL_ADDRESS>This should work: Person p = new Person("E", "Cheong", "1234567890","ACheong@atest.com"); org.remove(p); Person is not the key. org is his own class. If you look at the add method, it uses p.getEmail() as the key.
common-pile/stackexchange_filtered
How can I submit a job form Zeppelin as a specific user? I am running Zeppelin on my cluster with user accounts set up, and I can log in to Zeppelin with my credentials, but all jobs submitted by all users show as being submitted by the user 'zeppelin'. Is there a way to have Zeppelin submit jobs to the cluster from a specific user, instead of the 'zeppelin' user? Running a Zeppelin interpreter process as the user logged in to the Zeppelin frontend is called user impersonation. The steps to enable user impersonation are documented in the user manual: https://zeppelin.apache.org/docs/0.7.2/manual/userimpersonation.html In a nutshell, you have to Enable authentication in conf/shiro.ini Enable password-less ssh Configure the interpreter to impersonate the user
common-pile/stackexchange_filtered
Archiving a huge database(oracle) without impacting processes that inserts records to it We have an audit database (oracle) that holds monitor information of all activities performed by services (about 100) deployed on application servers. As you may imagine the audit database is really huge because of the volume of requests the services process. And the only write transaction that occurs on this database is services writing audit information in real-time. As the audit database started growing (more than a million records per day), querying required data (for example select all errors occurred with service A for requests between start date and end date) quickly became nearly impossible. To address this, some "smart kids" decided to device a batch job that will copy data from the database over to another database (say, audit_archives) and delete records so that only 2 days worth of audit data is retained in audit database. This initially looked neat but whenever the "batch" process runs, the audit process that inserts data to audit database starts to become very slow - and sometimes the "batch" process also fails due to database contention. What is a better way to design this scenario to perform above mentioned archival in most efficient way so that there is least impact to the audit process and the batch? I Easy way. delete old records partially the best with FORALL statement copy data partially the best with FORALL add partitioning based on day of the week II Queues delete old records partially the best with FORALL statement fill audit_archives with trigger on audit, in trigger use queue to avoid long dml
common-pile/stackexchange_filtered
Compute percentile and max value per variable Bash Gurus, I need to compute the max and percentile numbers for each item in the list, using awk aa 1 ab 3 aa 4 ac 5 aa 3 ad 2 ab 4 ac 2 ae 2 ac 5 Expected output Item 90th percentile max value aa 3.8 4 ab 3.9 4 ac 5 5 ad 2 2 ae 2 2 Am able to get the sum and max using the below, but not the percentile. awk '{ item[$1]++; count[$1]+=$2; max[$1]=$2; percentile[$1,.9]=$2 } END{ for (var in item) print var,count[var],max[var],percentile[var] } ' Please suggest. What are you expecting percentile[$1,.9]=$2 to do? What method do you use to calculate the percentile ? Linear Interpolation ? Nearest Rank ? Have you implemented a function to do so in bash ? @jas they are 1, 3, and 4. Ups, I was blind :-(, thanks, @dood! @TomFenech - hoping to get to 90th percentile. @EdMorton Aren't you aware of percentiles? @PradeepBS yes I am. Are you looking for help to figure out how to calculate percentiles or how to implement that calculation in awk? If the former then you are doing the right thing by just stating you want percentiles and leaving it up to others to do everything else from there, but if the latter then showing your algorithm would go a long way to encouraging awk experts to help you implement it in awk otherwise the number of people who'll want to help you will be limited and you may end up with something that produces the output you want but is far from a good solution. Percentile calculation from Statistics for Dummies 2nd ed. :). In Gnu awk: $ cat mnp.awk BEGIN { PROCINFO["sorted_in"]="@ind_num_asc" # for order in output if(p=="") # if p not defined it's median p=0.5 else p=p/100 # if 90th percentile: p=0.9 } { v[$1][NR]=$2 # values stored per keyword. NR for unique if($2>m[$1]) # find max val m[$1]=$2 } END { for(i in v) { # for all keywords n=asort(v[i]) # sort values, n is count prc=p*n; # percentile figuration if(prc==int(prc)) w=(v[i][prc]+v[i][prc+1])/2 else w=v[i][int(prc)+1] print i, m[i], w # print keyword, max and nth value } } Run it: $ awk -p=90 -f mnp.awk data.txt aa 4 4 ab 4 4 ac 5 5 ad 2 2 ae 2 2 TODO: if the data file was sorted, this could be streamlined and not all data would need to be stored to memory. This is not the expected output OP posted. @dood Yeah. I wish OP would've given the definition of percentile he would've wanted. Quoting Wikipedia's page on percentile: There is no standard definition of percentile, however all definitions yield similar results when the number of observations is very large. The definition I used came from Statistics for Dummies 2nd ed. datamash is a lovely tool, although it doesn't support the percantile part. $ datamash -W --sort --group=1 max 2 min 2 < INPUT aa 4 1 ab 4 3 ac 5 2 ad 2 2 ae 2 2 It supports the following operations File operations: transpose, reverse Numeric Grouping operations: sum, min, max, absmin, absmax Textual/Numeric Grouping operations: count, first, last, rand unique, collapse, countunique Statistical Grouping operations: mean, median, q1, q3, iqr, mode, antimode pstdev, sstdev, pvar, svar, mad, madraw pskew, sskew, pkurt, skurt, dpo, jarque Here is an elegant solution I found floating around the internet for finding the max value: { max[$1] = !($1 in max) ? $2 : ($2 > max[$1]) ? $2 : max[$1] } END { for (i in max) print i, max[i] } Output: ab 4 ac 5 ad 2 ae 2 aa 4 You'd just do max[$1] = ( ($1 in max) && (max[$1] > $2) ? max[$1] : $2 ) to avoid negative (!) and repeating (setting it to $2 in multiple locations) syntax.
common-pile/stackexchange_filtered
Plot confusion matrix using tensorflow on CNN classification I'm trying to plot a confusion matrix to analyse my train and test and I'm having difficulties to print/plot the matrix. I'm using convolutional neural networks with Tensorflow for classification, and I have 3 labels to classify. That's how I'm trying to print it: true_class = tf.argmax(y, 1) predicted_class = tf.argmax(prediction, 1) confusion = tf.confusion_matrix(true_class, predicted_class, 3) print(confusion) But the print returns me the following result: Tensor("confusion_matrix/SparseTensorDenseAdd:0", shape=(3, 3), dtype=int32) Then I searched for people with the same problem and I tried doing this: true_class = tf.argmax(y, 1) predicted_class = tf.argmax(prediction, 1) confusion = tf.confusion_matrix(true_class, predicted_class, 3) print('Confusion Matrix: \n\n', tf.Tensor.eval(confusion,feed_dict=None, session=sess)) And it gives me the following error: tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float [[{{node Placeholder}}]] My code: def convolutional_neural_network(x): number = calc() weights = {'W_conv1': tf.Variable(tf.random_normal([3, 3, 3, 1, 32])), 'W_conv2': tf.Variable(tf.random_normal([3, 3, 3, 32, 64])), 'W_fc': tf.Variable(tf.random_normal([number, 1024])), 'out': tf.Variable(tf.random_normal([1024, n_classes]))} biases = {'b_conv1': tf.Variable(tf.random_normal([32])), 'b_conv2': tf.Variable(tf.random_normal([64])), 'b_fc': tf.Variable(tf.random_normal([1024])), 'out': tf.Variable(tf.random_normal([n_classes]))} x = tf.reshape(x, shape=[-1, IMG_SIZE_PX, IMG_SIZE_PX, SLICE_COUNT, 1]) conv1 = tf.nn.relu(conv3d(x, weights['W_conv1']) + biases['b_conv1']) conv1 = maxpool3d(conv1) conv2 = tf.nn.relu(conv3d(conv1, weights['W_conv2']) + biases['b_conv2']) conv2 = maxpool3d(conv2) fc = tf.reshape(conv2, [-1, number]) fc = tf.nn.relu(tf.matmul(fc, weights['W_fc']) + biases['b_fc']) fc = tf.nn.dropout(fc, keep_rate) output = tf.matmul(fc, weights['out']) + biases['out'] return output def train_neural_network(x): much_data = np.load('muchdata-50-50-30-pre.npy', allow_pickle=True) train_data = much_data[400:410] validation_data = much_data[390:399] prediction = convolutional_neural_network(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2( logits=prediction, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 1 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(hm_epochs): epoch_loss = 0 for data in train_data: X = data[0] Y = data[1] _, c = sess.run([optimizer, cost], feed_dict={x: X, y: Y}) epoch_loss += c print('Epoch', epoch + 1, '/', hm_epochs, '. Loss:', epoch_loss) true_class = tf.argmax(y, 1) predicted_class = tf.argmax(prediction, 1) confusion = tf.confusion_matrix(true_class, predicted_class, 3) print('Confusion Matrix: \n\n', tf.Tensor.eval(confusion,feed_dict=None, session=sess)) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) saver = tf.train.Saver() saver.save(sess, '../api/modelo') print('Accuracy:', accuracy.eval( {x: [i[0] for i in validation_data], y: [i[1] for i in validation_data]})) If anyone can help me figure out what's happening, I'll be very grateful! I'm new to this topic and I'm really struggling. Thank you so much! You need to feed values to the placeholders in feed_dict. Can you try replacing the following line of your code, print('Confusion Matrix: \n\n', tf.Tensor.eval(confusion,feed_dict=None, session=sess)) with the following, where your_X and your_Y are your test input and labels which we need to plot the confusion matrix on. print(sess.run(confusion, feed_dict={x:your_X, y:your_Y})) Hi! Thank you so much, you were really helpful! I just needed to adjust some things and it worked! :)
common-pile/stackexchange_filtered
Permalinks causing wp-json to 405 I have 3 sites I am working with and only the main domain is having this disruption. We have a staging site with no issues, and another subdomain with no issues as well. The main domain when updating certain plugins is coming back with a 405 rest_forbidden error. Our staging site has all the same plugins, same install version of Wordpress and same Theme, accept no issues. Our other site has the same theme and some same plugins as well but no errors as well. The fix (but its not a perfect fix). On the primary domain when I set the permalinks to plain the wp-json error goes away completely. I have to switch it back for seo purposes which returns the issue. Things I have done to attempt to resolve this. Remove all htaccess code and replace with install htaccess code Removed all plugins accept the primary fault plugin (no success) Checked for any code that may be custom in the functions.php (no success). Thank you for your help just to clarify, do you mean all pages/URLs give a 405 rest forbidden error? Or do you mean just all REST API endpoints say 405 forbidden? HTAccess has nothing to do with this. How do main and staging site differ in server setup?
common-pile/stackexchange_filtered
How to change values of ListView elements in Codebehind I'm trying to create a table with Listview and one of the fields I'm using is supposed to show a hyperlink to a more detailed view of the data shown, how I want to do that is by using FindControl on the ID of that item and then changing the value into a hyperlink of the detailed view page with a querystring attached, the problem is that I have no idea how to re-insert that data back into the listview field, which looks something like this: <ItemTemplate> <td> <asp:Label ID="ViewLinkLabel" runat="server" Text='[insert Link Here]' /> </td> </ItemTemplate> Please bear in mind that I'm still an amateur in ASP.net, and if any of this seems too convoluted when there's a much easier to do this that I don't know about. Thank you I dont have enough reputation to leave comments or edit posts but the code sample in Richard Harrison's post has some problems: protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e) { try { HyperLink ViewLinkLabel = (HyperLink)e.Item.FindControl("ViewLinkLabel"); ViewLinkLabel.NavigateUrl = "http://www.example.com/"; } catch { } } Ideally you should also check if ViewLinkLabel is null before you use it. Also this is presuming that the ViewLinkLabel control is a HyperLink but in the question this is actually a Label control. Change the label to a hyperlink and Use the OnItemDataBound event on the listview to modify the element: something like. protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e) { try { HyperLink ViewLinkLabel = (HyperLink)e.Item.FindControl("ViewLinkLabel"); lnkEvent.NavigateUrl += "http://required.url; } catch { } } ListView.ItemDataBound Event for more details Yeah you have made a few mistakes here. First off if you were going to do this you would want to use an <asp:Hyperlink> instead of an <asp:Label>. Also instead of trying to find the control in the code behind and set its value you would probably use a databinding statement in the markup. This would look like this: <ItemTemplate> <td> <asp:HyperLink ID="ViewLinkLabel" runat="server" Text="More details" NavigateUrl='<%# string.Format("~/DetailPage.aspx?ID={0}", Eval("RecordID")) %>' /> </td> </ItemTemplate> The pattern that you are referring to is called master / detail. This means you have a master list which lets you drill down into details. There are a bunch of tutorials which explain various ways to set this up on the official asp.net website: http://www.asp.net/learn/data-access/#master They were written before asp.net 3.5 came out so they don't cover the listview control but they will explain to you how to set up master / detail and also how the databinding syntax works. If you went through the first 25 tutorials in that data access series then you would have a pretty solid understanding of how a lot of the asp.net features work. The data access technology it uses is a bit out of date but it is an easy one to get started with.
common-pile/stackexchange_filtered
Is there a particular function to retrieve then delete random array element? I know I can do this in a couple of steps, but was wondering if there is a function which can achieve this. I want to array#sample, then remove the element which was retrieved. How about this: array.delete_at(rand(array.length)) This is essentially two steps (rand(array.length) and array.delete_at(idx)). OP did ask for only one method, but probably one of the simplest ways to perform this kind of operation in Ruby. I know this is ten years old, but just gotta say how much I love it when I find elegant solutions to my problems. Cheers! Another inefficient one, but super obvious what's going on: array.shuffle.pop What would be nice would be a destructive version of the sample method on Array itself, something like: class Array def sample! delete_at rand length end end Bottom line: something like your second example (although in the language in which the interpreter is implemented) should be part of the core Array implementation. I would probably call it something like delete_sample! or something, though, as I find it a bit more obvious what it does. :-) It needs to be array.shuffle!.pop If you go for this option, and you want to remove the item from original array you better do array.shuffle!.pop, or else your array will remain as it was. Doing shuffle without bang (!) will just give you another array to pop from. Linuxios's has it perfect. Here is another example: array = %w[A B C] item_deleted = array.delete_at(1) Here it is in irb: 1.9.2p0 :043 > array = %w[A B C] => ["A", "B", "C"] 1.9.2p0 :044 > item_deleted = array.delete_at(1) => "B" 1.9.2p0 :045 > array => ["A", "C"] 1.9.2p0 :047 > item_deleted => "B" An alternative to the rand(array.length) approach already mentioned, could be this one element = array.delete array.sample Eksample: >> array = (1..10).to_a >> element = array.delete array.sample >> array # => [1, 2, 4, 5, 6, 7, 8, 9, 10] >> element # => 3 This is also a set of two operations, but at least you won't have to move away from the array itself. This one may be less efficient than the others (delete requires a search) but it's obvious at a glance what it's doing. This is true, but I think it's a bit more readable than using rand, as there already is a way to find a random element in an array. Also, we don't have to drag in the length of the array, which is something we really shouldn't need to care about. :-) This approach runs into problems when you have duplicates in an array because delete removes all by equality. For instance in this example, if sample gets the "a". ["a","a","b"].delete sample ==> deleted: "a", remaining: ["b"] If you need to sample a number of items and the remove those from the original array: array = (1..10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] grab = array.sample(4) => [2, 6, 10, 5] grab.each{ |a| array.delete a } => [2, 6, 10, 5] array => [1, 3, 4, 7, 8, 9] This only works if your original array is full of unique values, otherwise you'd be deleting all '2's
common-pile/stackexchange_filtered
Can we prove that the object is not tilted from photo(s)? This is an image of Al-Masjid an-Nabawi. Can we from this image, or from combination of images available online say with a certain degree of confidence (prove?) that this red circled minaret is vertical, not tilted as it is claimed? (Original bigger version is at commons.wikimedia) I asked a question at Islam SE: Al-Masjid an-Nabawi tilted minaret?. So far it looks like there is no written evidence of that claim. (Not sure what tags to use, feel free to edit/suggest) Maybe a related post: Calculate camera tilt angle from 2D image Note: I can't go there and retake shots, experiment, etc. Is it still possible to best guess if it is tilted based on available photos online? As this is a forensics question rather than about photography itself, and since it's about a popular claim that you're skeptical of, maybe try [skeptics.se]? @mattdm Ah, good point! Do you think I should close/delete this post? To me it's kind of borderline on topicality, so up to you. If you want to know how to make a picture that makes the minaret appear either straight or tilted, this is definitely the place. In the age of Photoshop, can anyone prove anything based on photos? I believe it's just a bad/distorted picture. After correcting the pincushion lens distortion and camera angle (roll/tilt), it appears to me that the tower is straight. The horizontal lines I added reference to things that should be straight/level, and what I corrected for. The vertical lines are perpendicular to reference the straightness/verticality of the tower. (this was a quick correction using photoshop's lens correction filter and could probably be refined) The answer is maybe. It depends on whether the photos have required reference points to make the determination. If the required points exist on the photograph, yes. Verticality (plumb) is established as the line between the zenith (point overhead) and the nadir (centre of the planet). Any eccentricity from that is considered "tilted." The horizon is perpendicular to this imaginary line which can be established as the line joining the vanishing points (where receding parallel lines viewed in perspective appear to converge.) Any eccentricity from a line perpendicular to the horizon (level) is considered "tilted." Any photograph used to define perpendicularity must have at least one dependable reference line (plumb and/or level) to use for linear construction and comparison. You will need at least two of these photographic images taken from different orthogonal positions (90° with respect to the tower) to answer your question definitively. Additionally, it is handy for the camera axis to be "true." That is to be dead level with the subject centred horizontally and vertically in the viewfinder since, in effect, you are using the camera as a surveying (disambiguation) instrument. Quite apart from the photographic evidence that may or may not exist, I'd tend to believe the popular claim. Any equipped and motivated land surveyor with a couple of hours off could provide the answer to a fraction of a degree. No, not from one picture. It could be tilted towards the camera (or away from it), and there is no way to see it in the shot. The question asked "or from a combination of images" Theoretically, you might be able to determine the tilt angle. However, more information besides the photos is necessary. You would need to know the exact coordinates of the camera and several other objects in the image (several points along the buildings in the foreground). The next problem is that lenses are not perfectly rectilinear, straight lines will not necessarily appear straight. If you knew exactly which lens was used, you might be able to compensate. It would be much easier for someone at the location to perform a simple experiment. Place a large shallow pan of water on the ground. Photograph the minaret and the reflection in the water in the same image. Gravity will level the water exactly to create a perfectly horizontal mirror. Put the minaret exactly in the center of the photo so you don't have to deal with lens rectilinear issues. From the image, you should be able to calculate any tilt of the minaret using geometry. Thank you, great suggestion with a "pan of water". Unfortunately, I can't go there and retake the shots, see edit. I found a few images online with reflections in puddles of water. In one of the three, it looks slightly tilted, in two it does not. Water has surface tension, so a very thin layer might not be level. Sorry, I can't conclude anything, need thicker puddle, with higher resolution image, with minaret in center for better analysis. If your camera has a normal, rectilinear lens, then the 2D image on its sensor will be a perspective projection of the 3D scene. If you photograph a building from an arbitrary view point, then true right angles in the scene will not necessarily appear as true right angles in the photo, and lines that appear to make right angles in the photo are not necessarily at right angles to each other in the scene. @SolomonSlow - 1) If you know the exact 3D coordinates of the camera and several reference points in the picture, you can compensate for the perspective distortion (this is implied in my first paragraph). 2) The water reflection isn't affected by perspective distortion and if you put the minaret in the center, it isn't affected by barrel or pincushion distortion either. I failed to say that my comment was made in reference to the black lines that you drew over top of the photograph. I thought that maybe you meant to imply that the angles between those black lines said something about the true angles between the sides of the minaret and other elements of the architecture. I didn't pay attention to the part about IF you knew "exact coordinates of the camera," etc. I also didn't read the part about the reflection in the water. That would have been a good trick if only the photographer had thought to place a pan of water in the foreground to reflect the tower. @SolomonSlow - the image is from the other guys answer not mine. Most normal camera lenses are rectilinear. That means that straight lines in the 3D scene should show up as straight lines in the photo. If you photograph a scene with a rectilinear lens, then what you get is a perspective projection of the scene onto the image plane. Lines that are truly parallel to each other in the scene will not necessarily appear as parallel lines in the photo, but what they will do is, they will all appear to intersect at a single point (a.k.a., a "vanishing point") If you could extend all of the "vertical" lines in the picture to their vanishing point,* and if the "verticals" of the minaret converged on a different vanishing point from the other vertical lines, then that would prove that the real-life "vertical" lines of the minaret were not parallel to the other vertical lines in the scene (i.e., it would prove that the minaret was tilted.) * This could be hard to do because, depending on the viewpoint of the camera, the vanishing point could be far outside of the frame---like, miles outside of the frame. I hear that Microsoft has made 3D models of buildings just from using the huge corpus of photos available on the net so it is definitely possible. If you want to do that with 2 photos, just takes two pictures along two roughly orthogonal axes (for instance one from the North and one from the West), and if the minaret is vertical on both then it is vertical. Now, the question is how you determine that the minaret is vertical on a specific picture. Several ways: Take the picture with a camera which is known to be horizontal (bottom of the sensor horizontal) (likely requires tripod) After correcting the picture for perspective (unless the lens axis was horizontal) compare with other known verticals in the picture (horizontals cannot be used, unless they were exactly parallel to the sensor plane). Draw a long line on the ground, aiming at the minaret. Put yourself at the end of the line. Take a shot that includes the line and the minaret, centered. On the picture a vertical minaret would be aligned with the line. Note that this technique doesn't even require a camera, you can check the verticality on-site (from two directions of course). Unfortunately, I can't go there and retake the shots, please see edit. Then find pictures online taken from the other sides.
common-pile/stackexchange_filtered
ASP.NET MVC : 2d array is null after being passed from javascript to MVC controller action I have a 2d array of strings (12x5) that I want to pass from a javascript function to an asp.net mvc controller action. Using developer tools in IE I know that the array is populated with what I want it to be, so the issue is in or around the post function. var dateArray = new Array(); //Populate Data $.post("/Event/SetDateCalculationParameters", { dates: dateArray }, function () { //Stuff }); } And here is the MVC controller action public ActionResult SetDateCalculationParameters(string[][] dates) { //Do stuff return Json(true); } In the controller action, there are 12 items in the dates array, but they are all null. Ive been at this for a couple hours and am stumped. Is there an easier way to do this? Or am I missing something? how does it look in the request object? Just to get an idea on to how this could be handled? Im not sure I follow. Are you asking for an example of the data in the js before it gets sent? It's worth mentioning that this question is for passing jagged arrays, not 2d which would be defined as string[,]. You could send them as a JSON request: var dateArray = new Array(); dateArray[0] = [ 'foo', 'bar' ]; dateArray[1] = [ 'baz', 'bazinga' ]; // ... and so on $.ajax({ url: '@Url.Action("SetDateCalculationParameters", "Event")', type: 'POST', contentType: 'application/json', data: JSON.stringify({ dates: dateArray }), success: function (result) { } }); The action signature must look like this: [HttpPost] public ActionResult SetDateCalculationParameters(string[][] dates) Any time I tried to use an array in the action sig it would be null. When I used a straight up string it worked. So I just parsed it into the 2d array in the action's code. I know I am a lot late here, but I had switched to using the ajax call instead of the post and got the result I needed. I have a feeling it may have to do with the contentType. I was also able to use List<string[]> parmName instead of string[][] parmName. Just allowed me too loop through the array using a foreach. To solve the same problem I have created JsonModelBinder and JsonModelAttribute that should be applied to the parameter: public class JsonModelBinder : IModelBinder { private readonly static JavaScriptSerializer _serializer = new JavaScriptSerializer(); public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName]; if (string.IsNullOrEmpty(stringified)) return null; return _serializer.Deserialize(stringified, bindingContext.ModelType); } } public class FromJsonAttribute : CustomModelBinderAttribute { public override IModelBinder GetBinder() { return new JsonModelBinder(); } } Your controller will look as follow: public ActionResult SetDateCalculationParameters([FromJson]string[][] dates) Also you should stringify your array: $.post("/Event/SetDateCalculationParameters", { dates: JSON.stringify(dateArray)}, function () { //Stuff }); } It works for me.
common-pile/stackexchange_filtered
The meaning of この+own personal name One of the villains of ジョジョの奇妙な冒険, Dio, frequently refers to himself as「このディオ」 (to the point it became a meme). What's the meaning of this grammar: この+own personal name? Is it just emphasis? Or are there other nuances? (might be related to What is the nuance of この + [first person pronoun]?) Yes that's basically the same as この in この俺. この by itself just means "this". This type of この is an emphasis, and in this context it has a nuance of "nobody else but me/Dio", "of all others, me/Dio", etc. この俺 usually sounds more or less prideful, but この私 can be a humble and polite expression depending on the context.
common-pile/stackexchange_filtered
use dup2 to redirect printf failed The code is following. Q1: If dup2(fd3, STDOUT_FILENO), string2 will be in log.txt. If dup2(g_ctl[0], STDOUT_FILENO), string2 won't be received by g_ctl[1]. string1 and ls -al output will be received, Why ? Q2: The third library have some stdout/stderr log, if using dup2(socket_fd, STDOUT_FILENO), all logs will be collected by socket. But I also want to print all logs to screen at the same time, how to do it? #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> static pthread_t g_pid; static int g_ctl[2] = {-1, -1}; void *_run_loop(void *args) { char buf[1024]; int n; while (1) { n = recv(g_ctl[1], buf, 1024, 0); if (n > 0) { fprintf(stderr, "%.*s\n", n, buf); } } } int main(int argc, char const *argv[]) { int fd3 = open("./log.txt", O_CREAT | O_RDWR | O_APPEND, 0666); int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, g_ctl); assert(ret == 0); ret = dup2(g_ctl[0], STDOUT_FILENO); assert(ret > 0); pthread_create(&g_pid, NULL, _run_loop, NULL); send(STDOUT_FILENO, "string1", 5, 0); system("ls -al"); printf("string2\n"); sleep(5); return 0; } Q1. Try fflush(stdout) and SOCK_DGRAM. Q2. Intercept the logs and print them twice. Q1: You need to fflush(stdout); after your printf. Otherwise printf may buffer your output. It will be written when your program exits if it hasn't already, but by that time your reading thread has already been canceled, so you don't get to read it. Q2: As far as I know, the only way to get your output written to two files is to actually write it to both file descriptors. There is no way in Unix to "double-dup" a file descriptor. Even a command like tee is really just calling write() twice for each chunk of data read. You can do it manually, or inside a function, or in a thread, but you have to do it.
common-pile/stackexchange_filtered
text field cursor issue in chrome I am using following css in my form section. CSS .username input{ background-color: #FFFFFF; border: 2px solid #DDDDDD; border-radius: 5px 5px 5px 5px; color: #9E9E9E; height: 30px; width: 330px; padding:0px 10px 0px 0px; padding-left:10px; margin:15px 0px 0px 0px; line-height:30px; } It works fine in all browsers. But in the Chrome, cursor displays in the same height of input tag. I found the solution, if I remove the line-height it displays as I want it to. But in IE, the values are in top of the field. I need the solution for this issue. Please see the my fiddle. [It is not good in chrome] If you are not opposed to using CSS hacks, then you can target IE8 and below using: line-height: 30px\9 If i have not found a solution, i will use this IE css hack. Thank You so much. related https://code.google.com/p/chromium/issues/detail?id=47284 just added an answer that does not use CSS hack to fix this across browsers, see in the answers below Remove line-height attribute from your css class, I think it will help you updated fiddle: http://jsfiddle.net/4Etyn/16/ <div class="username"> <input name="txtFullName" id="txtFullName" type="text" class="user" value="Username" onBlur="if(this.value=='') this.value='Username'" onFocus="if(this.value =='Username' ) this.value=''" /> </div> .username input{ background-color: #FFFFFF; border: 2px solid #DDDDDD; border-radius:5px; color: #9E9E9E; height: 30px; height: 22px\0/; width: 330px; padding:0px 10px 0px 10px; padding:8px 10px 0px 10px\0/; margin:15px 0px 0px 0px; vertical-align:middle; } :root .username input{ height: 30px\9; padding:0px 10px 0px 10px\9; } @BarryKaye can you see my fiddle once, after removing line-height attribute it's working fine Please check this fiddle in IE8. No. Your css works fine in all browser. I have used your idea only. Updated for readability: http://jsfiddle.net/4Etyn/14/ (and there was a semicolon missing in your CSS) Up-to-date answer (October 2014) After playing around & observing what "reference" projects are doing, I realized one thing: we're doing it wrong. In short: for a solid & clean cross-browser solution one must not use line-height property to make the input type="text" element higher but rather the padding property. Cross browser issues As pointed out in the question, browsers interpret the line-height property for the input type="text" element in different ways. In this case, for Chrome back then in 2012 & even still now in October 2014 (version 37), it is for the cursor position. Notice that a related bug was filed in June 2010, https://code.google.com/p/chromium/issues/detail?id=47284, but then closed as obsolete (who knows why?): but the provided live bug replication, http://jsbin.com/avefi/2 , still shows the chrome bug at the time of writting (October 2014 - chrome 37). Note that Valli69's answer also identified line-height property as the source of the problem. But then used some rather hacky/dirty/risky IE8 & IE9 fixes (with \0/ and \9). A related question on those technics on Ie8 CSS Hack - best method? What about NOT using line-height nor height property ? This solution is simple & is even supported by modern and old browsers! 1) Solution in a streamlined example /* * [1] overrides whatever value "line-height" property was given by any other selector * note: make it "line-height: normal !important;" if necessary * [2] overrides whatever value "height" property was given by any other selector * note: make it "height: auto !important;" if necessary */ .username { line-height: normal; /* [1] */ height: auto; /* [2] */ padding-top: 10px; padding-bottom: 10px; } <input class="username" type="text" placeholder="Username" /> Live demo on http://jsbin.com/yadebenoniro/1/edit?html,css,output (ps. test on IE8 using this url http://jsbin.com/fugegalibuha/1 ) Tested on Windows OS on: IE8+, IE11, Chrome 38, & Firefox 32. 2) Solution in the context of the question /* * [1] overrides whatever value line-height property was given by any other selector * note: make it "line-height: normal !important;" if necessary * [2] overrides whatever value "height" property was given by any other selector * note: make it "height: auto !important;" if necessary * * [3] use the padding-top, padding-bottom to adjust the height of your input type text * [4] keep in mind that when changing the font-size value you will have to adjust the padding top and padding bottom if you want to keep the same height as previously */ .username input { background-color: #FFFFFF; border: 2px solid #DDDDDD; border-radius: 5px; color: #9E9E9E; height: auto; /* [2] */ line-height: normal; /* [1] */ margin: 15px 0px 0px 0px; padding: 10px 5px 10px 5px; /* [3] */ width: 330px; font-size: 20px; /* [4] */ } Live demo on http://jsbin.com/busobokapama/1/edit?html,css,output (ps. test on IE8 using this url http://jsbin.com/busobokapama/1 ) Tested on Windows OS on: IE8+, IE11, Chrome 38, & Firefox 32. 3) Further explanations This idea came to me after taking a look at Foundation: it uses the height and padding properties only: the line-height property is left to its default brower-provided value, that is line-height: normal. See by yourself: by inspecting the input type="text" elements on foundation's form component demo page http://foundation.zurb.com/docs/components/forms.html The only thing is that even "just" using height and padding seems a problem for IE8 so I decided to even remove the height property. Conclusion This solution obviously has the massive advantage of a simple code, that "just works" across all browsers. But it also has the drawback of NOT letting you have full control of the calculated total height: computed height property (font-size + abitrary number of pixels) + padding-top + padding-bottom + (border-width x 2). The "computed height property" seems to vary from browsers to browsers, hence the "abitrary number of pixels" naming. It's up to you to decide what you favor most: simple code or pixel-precise design. Resources https://developer.mozilla.org/en-US/docs/Web/CSS/height https://developer.mozilla.org/en-US/docs/Web/CSS/line-height HTML: is input box default/calculated content height different across browsers note: I just re-created an issue for Chrome https://code.google.com/p/chromium/issues/detail?id=424606 because the original one from 2010 was closed without getting fixed June 2010, see https://code.google.com/p/chromium/issues/detail?id=47284 I found a solution that works in the latest versions of Chrome and Firefox, and IE 8 and 9. I didn't test any other browsers because I didn't need to support anything lower than IE 8. <input class="issue" type="text" /> <input class="solution" type="text" /> .issue { font-size: 14px; height: 44px; line-height: 44px; padding: 0 10px; vertical-align: top; } .solution { font-size: 14px; line-height: 14px; height: 14px; padding: 15px 10px; } see the live demo on http://jsbin.com/usimeq/1 Edit: Forgot to add that the first input shows the issue, second shows the solution. Basically just setting the line-height and height to the same as the font size and adjusting the input using padding afterwards to match the intended overall height. Hopefully it helps anyone else running into this annoying issue. Using outside links for source is awkward - what if it goes away or changes? Ideally, all necessary code should be in the answer. Unfortunately, in Firefox 21, the bottoms of some letters are cut off with your solution ('g's for example). Just replacing line-height:30px; with height:30px; in your jsFiddle worked for me. Yeah it is correct. But in the ie browser the values are going to top the field. Not for me in IE9 - which version of IE are you using? Here's sample css for inputs that will be aligned in IE8 and won't show giant cursor in Chrome. line-height: 14px/*to enclose 13px font, override this if needed*/; height: 14px/*to enclose 13px font, override this if needed*/; /*Padding is needed to avoid giant cursor in webkit, which we get if height = line-height = 22px.*/ padding: 6px 8px;
common-pile/stackexchange_filtered
Match a View in WebView from Espresso in Android I want to match the user name text field inside a WebView which loads the Salesforce login page (but can also be applied to any other page with text fields). I have tried with: onView(withHint("User Name")).perform(typeText("test@sf.com")); But that doesn't work. Any better idea? Did any one try with Espresso 2.2 Web APIs to accomplish this? This can be accomplished using Espresso Web 2.2 API onWebView().withElement(findElement(Locator.ID,"username")).perform(webKeys("test@sf.com")); What if I dont know Locator ID and only Hint(of the TextView), for example "User Name"? this above code working fine with above mentioned website. Thanks for your logic. I have tried with some other website, its not working for me. is there any restriction for specific public domain website? please update. I have tried www.google.com to click Sign in button. not working for me. can you please suggest on this. Please use Locator.Xpath if you don't know ID. To find xpath first you need to check the html code based on which you can write xpath. To get html source code you can use chrome inspector. connect the device to the PC and then open chrome inspector.You can right click on the html code and click on copy xpath to get the xpath. can we apply this xPath logic for any public domain website. ex: www.google.com page contains Sign in button. can we try signin button for BDD webview auto click. is there any restriction for websites? You can fill form just run js code in WebView. For example: webView.loadUrl(" javascript:document.getElementById('username-field').value =<EMAIL_ADDRESS>");
common-pile/stackexchange_filtered
HTTPS implementation. Should I change pre-head tags? I implemented HTTPS on all the webpages of my website. My browser tells me it's a "Secure connection" with a green signal. I double-checked that all the images, CSS files, JS files, etc. were HTTPS, and I think it's everything ok. However, I'm still using the following pre-head code: <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> Should I change this two HTTP calls from 'http' to 'https'? Not needed since those are not external resources that the browser will download. Is this website a CMS? Related / duplicate(?): https://webmasters.stackexchange.com/questions/108855/is-incorrect-to-have-the-https-version-of-the-sitemaps-org-url-in-the-xmlns-site Like Simon Hayter said, those are not links to resources but identifiers (URIs and not URLs). The browser will not fetch anything at these endpoints, and they must remain as is because they identify something special with a specific sense, and it may not work anymore if you replace http by https. You apply the same response to basically any attribute that is xmlns or xmlns:whatever. The ns here means namespace which is a kind of identifier used in XML world with which HTML has ties.
common-pile/stackexchange_filtered
Compare distributions of values in two arrays (of same size) using range argument I want to compare distributions of values in two arrays (of same size), but the histogram display changes when I specify range argument: def plot_compare(values1, values2, bins=100, range=None): fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) ax.hist(values1.ravel(), alpha=0.5, bins=bins, range=range, color= 'b', label='1') ax.hist(values2.ravel(), alpha=0.5, bins=bins, range=range, color= 'r', label='2') ax.legend(loc='upper right', prop={'size':14}) plt.show() plot_compare(a1, a2) plot_compare(a1, a2, range=(-1200, 300)) How do I make the proper comparison? My goal is to get a visual clue of how the values are different in two arrays. Both arrays have the same number of values. Should I use same number of bins for the two arrays (but bins would be of different width), or should I use different number of bins (but bins of the same width)? You should use bins of the same width, if you want to compare two histograms. Therefore your second plot is correct. The difference between two plots is that when range is specified, the width of bins is computed based on this range (i.e. your range is divided by the number of bins). With the first plot, the ranges of both arrays are different. Therefore the bins width is different.
common-pile/stackexchange_filtered
Wine Tasting Problem (Probability) Mr. Kim claims to be a connoisseur of wine. To test his expertise, he is given 8 cards with the names of 8 types of red wine. He is then presented 8 glasses of these wines and, after tasting them, he has to put one card at each glass. To be acknowledged as a connoisseur of wine, he should guess at least 5 names correctly. Suppose Mr. Kim is not an expert on wines at all. What is the probability that he will be acknowledged as a connoisseur of wine? I don't think one can use the binomial setting here, as the different choices corresponding to each wine are not pairwise independent (for instance, the last choice is totally determined by the first seven). It's a problem of counting the number of permutations on a set of cardinality $n$ which have exactly $k$ fixed point (here $n=8$ and $k$ ranges from $5$ to $8$). We have $P(X=k) = \frac{1}{k!}\sum_{i=0}^{n-k}\frac{(-1)^i}{i!}$ thus $P(X\ge 5)=\frac{1}{360}+\frac{1}{1440}+0+\frac{1}{40320}=\frac{141}{40320}$ if I'm not mistaken. You've computed a few elements of the sequence https://oeis.org/A008290 here. In particular the OEIS gives the number of permutations of $[8]$ with $5, 6, 7, 8$ fixed points as $112, 28, 0$ and $1$ respectively, which agrees with your computation. Could you please elaborate on why we have to use permutations instead of combinations? As far as I know, while the last choice is determined by the first seven, doesn't that only affect the probability of choosing the last card but not the order itself? Denote by $G={1, 2, ..., 8}$ the set of different glasses, and denote by $W={w_1, w_2, ..., w_8}$ the set of different wines. Then, associating a card to each glass amounts to choosing a bijection $f: G\rightarrow W$, such that $f(i)=w_j$ if we put the card corresponding to the wine number $j$ at the glass number $i$, for all $i$, $j\in{1, ..., 8}$ . Thus the number of all possible choices is the number of bijections from $G$ to $W$, i.e., the number of permutations of a set of cardinality $8$. Now let's look at is the number of correct answers. Among all these choices exist a "canonical" one: the "perfect choice", which we denote $f_0: G\rightarrow W$, that corresponds to mapping each glass to the correct wine (Mr. Kim totally ignores $f_0$,but it still exists). A random choice $f:G\rightarrow W$ made by Mr. Kim will have exactly $k$ good answers ($1\le k\le 8$) if and only if the set ${g\in G; f(g)=f_0(g)}$ has cardinality $k$. In other words, the set ${g\in G; f_0^{-1}\circ f(g)=g}$ of fixed points of the permutation $f_0^{-1}\circ f$ of $G$, has cardinality $k$. Clear enough? I guess via using Binomial. $P(X;r \geq 5) $ with $p=q=1/2$ (He can only guess in right/wrong) .Thus Using $$P(X)=^{n}C_r * p^{r}*q^{n-r}$$ We get $(^8C_5+^8C_6+^8C_7+^8C_8)*\frac{1}{2^8}$. Please point out errors. (If any)
common-pile/stackexchange_filtered
Under what condition on $f$ is $f(d(x,y))$ a metric $f:\mathbb{R}\rightarrow \mathbb{R}$ and $(X,d)$ is a metric space. Under what condition on $f$ is $\rho:X\times X \rightarrow \mathbb{R} $ given by $$\rho(x,y)=f(d(x,y))$$ also a metric? My attempt (intuitively): $f$ must be defined everywhere (well defined) i.e. it has to be continuous and differentiable. I am also thinking that for the triangle inequality to hold, $f$ must be monotonically increasing. Does $f(x)=tan^{-1}(x)$ work? You need $f(0) = 0$, obviously enough. @AlfredYerger, wait is it sufficient to state that $f$ must satisfy the 4 properties of a metric? Positivity, nondegeneracy, homogeneity, and triangle inequality? It's clear that you need \begin{align} f(0) = 0 \end{align} and \begin{align} f(x+y) \leq f(x)+f(y). \end{align} I'm assuming $x, y\geq 0$. @JackyChong, it's assumed that $x,y\in\mathbb{R}$ but I don't know if I can assume that $x,y \geq 0$. I know that $f$ must be monotonically increasing for the triangle inequality to hold. If the above are the only requirements, $f$ doesn't have to be continuous or differentiable at all? I think you want $f(x) \geq 0$ if $x \geq 0$. There is certainly no need for $f$ to be differentiable. I don't think it needs to be continuous either, but funny things might happen to the topology with that. @JackyChong, ok, so this looks very much similar to the properties of $d(x,y)$. In which case $f(x)\geq 0$ for all $x$. We also need $f(0) = 0$, and $f(x) > 0$ for $x > 0$. Consider the function \begin{align} f(x)= \begin{cases} 0 & \text{ if } x\leq 0\ 1 & \text{ if } x>0 \end{cases}. \end{align} Suppose $d$ is a metric, then we see that $f(d(x, y))$ is also a metric since \begin{align} f(d(x, x)) = f(0) = 0 \end{align} and \begin{align} f(d(x, y)) \leq f(d(x, z)) + f(d(y, z)). \end{align} @Omnomnomnom, is this incorrect: $f = 0$ iff $x=y$? Under what condition on $f$ will $\rho(x,y)=\rho(y,x)$? clearly, my example indicates otherwise. @ozarka for any $f$, we have $\rho(x,y) = \rho(y,x)$ It's silly to consider $f:\mathbb{R}\to\mathbb{R}$; there's no reason not to restrict to $f:(0,\infty)\to(0,\infty)$. @EricWofsey, yes. I think by virtue of $d(x,y)$ being a metric, the domain of $f$ is $(0,\infty)$ and for $\rho$ to be a metric, the codomain must be all non-negative reals. @JackyChong, thank you. I think I understand now. If $f(x)=tan^{-1}(x)$, I see that $f(0)=0$ and $f(x)\geq 0$ of $x\geq 0$.But since $tan^{-1}\in[-\frac{\pi}{2},\frac{\pi}{2}]$ I am not sure if the triangle inequality holds... https://www.wolframalpha.com/input/?i=arctan(x)%2Barctan(y)-arctan(x%2By)+%3C0 So, it seems like $\arctan(x)+\arctan(y)\geq \arctan(x+y)$ when $x, y\geq 0$. Note that $f$ does not have to be monotonic. For instance, $f(x)$ could randomly take values in $[1,2]$ over all positive values of $x$, and this will always satisfy the triangle inequality. @JackyChong, I forgot to realize that $x,y\geq 0$. Thank you so much for your help. @ozarka: I would suggest you unaccept Zelos Malum's answer, as it is very far from a complete answer to the question. Let's check the conditions that a metric must satisfy $d(x,y)\ge 0$ $d(x,y) \iff x=y$ $d(x,y)=d(y,x)$ $d(x,y)+d(y,z)\ge d(x,z)$ Those are the conditions for a metric. So clearly we must have that $f(x)\ge 0$ when $x\ge 0$ to sate the first condition. For the second condition we must have that $f(0)=0$, but it is important also that that there is no non-zero $r$ such that $f(r)=0$ as otherwise we pick $x,y$ such that $d(x,y)=r$ and then the second condition is broken. The third is trivially true. For the last one we need to have $$f(d(x,z))=\rho(x,z)\le\rho(x,y)+\rho(y,z)=f(d(x,y))+f(d(y,z))$$ which means we must have the function being subadditive, that is $f(x+y)\leq f(x)+f(y).$ This is necessary (if you want $f$ to work for any possible $d$), but it's far from obvious that it's sufficient. Can't say everything, some fun must be left for the reader! :P In fact, it is not sufficient. For instance, $f(x)=1/x$ for $x>0$ is subadditive, but it doesn't work because (for instance) $1,3,3$ satisfies the triangle inequality in all permutations but $1,1/3,1/3$ does not. @EricWofsey ,thank you! Can I say that $f$ must be increasing? On second thought, if I impose such restriction $tan^{-1}(x)$ is not increasing when $x\geq 0$ but I know this function has to work... @ozarka: No, $f$ does not need to be increasing (see this comment). I don't know why you say $\tan^{-1}(x)$ is not increasing though; it is! @EricWofsey,oh I missed your previous comment! Thank you for the clarification. From the comment above with counterexample $f(x)=\frac{1}{x}$, all I'm getting is that $f(x)\geq x$. Could you provide additional hint(s)? @ozarka: Sorry, I'm not sure what you mean or how you're getting $f(x)\geq x$. $f(x)=1/x$ fails because you could have a triangle in $X$ with side lengths $1$, $3$, and $3$, but then with respect to $\rho$ you would get a triangle with side lengths $1$, $1/3$, and $1/3$ and $1/3+1/3<1$. @EricWofsey, I was going off of your counterexample - trying to impose a condition so that $f(x)=1/x$ is not allowed. The reason $1/d(x,y)$ cannot be a metric is because for $d(x,y)>1$, you're getting $f(d(x,y))<1$. Is the additional conditional blatantly obvious? @ozarka: No, I don't know a simple way to formulate the additional condition (if I did I would have posted it as an answer!). You can of course just say "whenever $a,b,c$ satisfy the triangle inequality in all permuations, so do $f(a),f(b),f(c)$", but this is not very concrete...
common-pile/stackexchange_filtered
cakePHP security I am thinking of using cakePHP to build a web app. My question is how much of security stuff will I have to code myself to prevent (SQL injection etc)? What security stuff cakePHP takes care of by itself and what will I have to code? http://book.cakephp.org/view/1296/Security-Component cake does a lot of things automatically but some not. depending on how secure you want you forms you should also consider "white-listing": details the easiest method would be to use the security component. CakePHP itself is pretty good at it, you will not have to worry about what is submitted. But if you are using the data, everything will be of course unescaped. So a Form built from the Helper classes will be XSS safe, but once you are printing out what is int $this->data you must know and take care to escape it. h() is an often used alias for htmlspecialchars(). CakePHP has no protection against XSRF out of the box. For ACL it provides you some components. For sure it depends what is your code style and what is your understanding of the framework. For sure if you are using CakePHP function for storing data it will be pretty much ok. But currently I am working on a paid CakePHP "Application" which is far from secure code :) So it really depend from the developer. Cake provides its own features like Data validation, MVC coding pattern, Controllers, Auth component, Automated configuration process and also the Security component. So it's not a thing to worry about, If you are not satisfied with this and want to add your own security component, go through the blog: http://goo.gl/ZoQzLx Security in cake can be enable with few lines of code and using it's built in classes. For Sql Injection protection use cakephp $this->find will automatically sanitize your parameters but if you want to use raw query you can still sanitize your data using Sanitize::escape() method For CSRF protection you can enable it app/Controller/AppController.php ``` public $components = [ 'Security' => [ 'csrfUseOnce' => false, 'csrfExpires' => '+1 hour', ], ]; ``` For XSS if possible, always use cakephp Form Helper (http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html) when your data is from text field, always print it using h() (Text to wrap through htmlspecialchars) https://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
common-pile/stackexchange_filtered
History of history Is there a way in github to see the history of a branch's history? What I mean is that a branch is obviously just a pointer to a commit hash. What I want is every time the hash being pointed to by the branch changes on the server, for that change to get logged somewhere, i.e. in gitorious every time someone pushes a branch there's a new entry added to the news feed, something like "username changed branchname from oldhash to newhash". This is nice because git allows you to edit history via rebase, but if you can see the old hash you can still get back to the old history. I just can't find similar functionality in github. If you allow non-ff pushes, having a history of what hash a branch used to point to can be a real lifesaver. There isn't a way to do this on GitHub itself, but your own local clone has it built-in - it's called the reflog. Take a look at git help reflog for more details (and another link for more info). I'm aware of the reflog, but unfortunately it's not quite the same thing. For one thing it's far too verbose; it includes every change ever, so if I discover a week later that somehow master is screwed up because I did a rebase and thought I was in a different branch...what are the chances that I can reasonably figure out where it was supposed to be by looking through the reflog? The other problem of course is if someone else does that upstream, how can I find out who did it or when? GitHub doesn't keep reflogs, so basically, you can't. (Be careful who you give write access to your repository.) git log --walk-reflogs <branchname> can help for figuring out what the heck was going on. Well that's a bummer. I'd hate to think that gitorious is superior to github in any way. ;)
common-pile/stackexchange_filtered
Why doesn't the map charge correctly? I have uploaded the map from a zip file. After loaded if you change the zoom level, the part that is outside the mobile screen is not loaded correctly. Why doesn't it work? Thanks! Loaded map is from cached data and remaining is not loading as Data connection is off, assumption according to your screenshot. Also, Do you have Internet Permissions in Manifest file? Ok, If I don't have any onnection to internet, it won't never charge?? How would you expect the map to load if you don't have Internet? You can use offline KML files to load the map without the internet, until then Internet is a must to load the map. Also, as you're using zip files to load the map, the remaining part is the data of map you don't have in your files. Actual answer if there were no tiles in .zip no tiles will be shown on subject zoom level. But if you already have tiles to be shown from lower zoom level - yes you can try! There is a method, which you can try by your own map.getTileProvider().rescaleCache({some parameters olso is here}); Another, maybe not so simple decision, is described below. It looks like you`re using simple approach like: XYTileSource tileSource = new XYTileSource("map", MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL, 256, ".png", new String[]{}); map.setTileSource(tileSource); However you can go over to steps that are more complicated: XYTileSource tileSource = new XYTileSource("map", MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL,256, ".png", new String[]{}); SimpleRegisterReceiver simpleRegisterReceiver = new SimpleRegisterReceiver(getContext()); MapTileModuleProviderBase[] mapTileModuleProviderBases = new MapTileModuleProviderBase[1]; mapTileModuleProviderBases[0] = new MyMapTileFileArchiveProvider(simpleRegisterReceiver, tileSource, mapArchiveFiles); //mapArchiveFiles - your Array of IArchiveFile //IArchiveFile iArchiveFile = ArchiveFileFactory.getArchiveFile(file); //file - your .zip MapTileProviderArray mapTileProviderArray = new MapTileProviderArray(tileSource, simpleRegisterReceiver, mapTileModuleProviderBases); map.setTileProvider(mapTileProviderArray); Question - what is a MyMapTileFileArchiveProvider class? It's not just subClass of MapTileFileArchiveProvider but both of them have common parent: public class MyMapTileFileArchiveProvider extends MapTileFileStorageProviderBase {} At this point you`re welcome to copy-paste default implementation of MapTileFileArchiveProvider class to your own class, and look for this method: private synchronized InputStream getInputStream(final MapTile pTile, final ITileSource tileSource) { for (final IArchiveFile archiveFile : mArchiveFiles) { if (archiveFile!=null) {final InputStream in = archiveFile.getInputStream(tileSource, pTile); if (in != null) { if (Configuration.getInstance().isDebugMode()) { Log.d(IMapView.LOGTAG, "Found tile " + pTile + " in " + archiveFile); } return in; } } } //Good place for your logic (as we call it - crutch) //to look for available tiles for subject area on lower zoom level //Do not surrender before return null! return null; } Thanks for paying attention:)
common-pile/stackexchange_filtered
Expression of $x^n+\frac1{x^n}$ by $x+\frac1{x}$ where $n$ is a positive odd number. There was a problem in a book: Denote that $y=x+\dfrac{1}{x}$, express $x^7+\dfrac{1}{x^7}$ using $y$. It's not a hard question, but I find a special sequence: $x+\dfrac{1}{x}=y\\x^3+\dfrac{1}{x^3}=\left(x+\dfrac{1}{x}\right)^3-3\left(x+\dfrac{1}{x}\right)=y^3-3y \\ x^5+\dfrac{1}{x^5}=\left(x+\dfrac{1}{x}\right)^5-5\left(x^3+\dfrac{1}{x^3}\right)-10\left(x+\dfrac{1}{x}\right)=y^5-5\left(y^3-3y\right)-10y=y^5-5y^3+5y\\x^7+\dfrac{1}{x^7}=\left(x+\dfrac{1}{x}\right)^7-7\left(x^5+\dfrac{1}{x^5}\right)-21\left(x^3+\dfrac{1}{x^3}\right)-35\left(x+\dfrac{1}{x}\right)=y^7-7\left(y^5-5y^3+5y\right)-21\left(y^3-3y\right)-35y=y^7-7y^5+14y^3-7y$ I find that the coefficient has some relationship between the Pascal Triangle, such as $y^7-7y^5+14y-7y=y^7-7 \binom{2}{0}y^5+7\binom{2}{1}y^3-7\binom{2}{2}y$. That's strange but funny! However, I can't really prove this, or show that it is false. Hope there is someone who can answer me. Thank you! Your pattern does not seem to work for $n=9$: $ y^9 - 9 y^7 + 27 y^5 - 30 y^3 + 9 y$. $2T_{n}(y/2)$ where $T_n$ are these polynomials. See also https://math.stackexchange.com/questions/1691899/analysis-of-coefficients-of-xk-dfrac1xk-polynomials Let $x=e^{iz}$. We want to express $x^n+\frac{1}{x^n}=2\cos(nz)$ in terms of $x+\frac{1}{x}=2\cos(z)$, which can be done through Chebyshev polynomials of the first kind: $$ x^n+\frac{1}{x^n}=2\cos(nz) = 2\,T_n(\cos z) = 2\, T_n\left(\frac{x+\frac{1}{x}}{2}\right).$$ I don't see a clear pattern in the coefficients but there is a recurrence: $$ y_{n+2} = y_2 y_n -y_{n-2} = (y^2-2)y_n -y_{n-2} $$ where $$ y_n = x^n+\dfrac{1}{x^n} $$ Krechmar's `A problem book in Algebra' gives an identity if $x+z=p$ and $xz=q$, then $$x^n+z^n=p^n-\frac{n}{1}p^{n-2} q+\frac{n(n-3)}{1.2}p^{n-4} q^2+...+(-1)^k \frac{n(n-k-1)(n-k-2)....(n-2k+1)}{k!} p^{n-2k} q^k+...$$ Take $z=1/x$ then $q=1$ and letting $x+\frac{1}{x}=y$ we can write $$f_n(x)=x^n+\frac{1}{x^n}=\sum_{k=0}^{n/2} A_{n,k} ~y^{n-2k},...(1)$$ where $$A_{n,k}=(-1)^k \frac{n(n-k-1)(n-k-2)....(n-2k+1)}{k!}....(2)$$ We can re-write $A_{n,0}=1$ and $$A_{n,k}=(-1)^k\frac{n}{k}{n-k-1 \choose k-1}, ~ 0<k <n/2 ......(3)$$ Fpr $n=5$ we get $A_{5,0}=1, A_{5,1}= -5, A_{5,2}=5.$ For $n=7$ we get $A_{7,0}=1, A_{7,1}=-7, A_{7,2}= 14, A_{7,3}=-7$ For $n=8$, we get $A_{8,0}=1, A_{8,1}=-8, A_{8,2}= 20, A_{8,3}=-16, A_{8,4}=2.$ So $$x^8+1/x^8=y^8-8y^6+20y^4-16y^2+2,~ y=x+1/x.$$ Similarly $$x^9+1/x^9=y^9-9y^7+27y^5-30y^3+9y.$$ Finally, we would like to assert that the expansion (1) along with (2) or (3) is the required generalization which works for both even and odd $n$.
common-pile/stackexchange_filtered
How long can you wait/hang out at the Oakland airport lobby? I have an early morning flight at 6:00 am from OAK (Oakland airport). The public transport doesn't get there early enough in the morning so I'm planning to take it the night before and arrive around midnight. Is it okay to just chill in the lobby for a few hours? (I'm pretty sure you can't check in that early) Will probably just read or something (not going to sleep). Is this allowed? It's fine, and many airlines allow early check in (6 hrs) I have also seen airlines that allow check ins as early as 12 hrs. https://en.wikipedia.org/wiki/Mehran_Karimi_Nasseri and http://www.sleepinginairports.net/ How well can you hide? ;) Monday through Friday, public transportation (the new train connected to BART) arrives before 5:00 a.m. No joy on weekends though. According to the Oakland International Airport's FAQ: May I remain overnight in the terminals? Connecting passengers with an overnight layover may remain overnight in the terminals pre-security only. Since we are open 24 hours a day, 7 days a week, law enforcement officers are always on site and you may be asked to show your identification and proof of travel. If you decide to you want a little more comfort than an airport can provide, and want to stay in a near-by hotel rather than remaining in the terminals, Oakland International Airport suggests you stay at one that has a complimentary airport shuttle available in the early morning hours. The closest hotels are on either Airport Access Road or Hegenberger Road, or read "Airport Area". You may find the list of area hotels on our website at: visitoakland.org
common-pile/stackexchange_filtered
Android Google Maps Activity only shows small crosses I currently have a Google Map Activity which is apparently working well but doesn't show the map (this sounds stupid!) Here is a picture that will make you understand better my problem: I already confirmed my apiKey, checked the tutorial over and over and even the manifest seems not be missing anything. I get only this on adb: 276 MapActivity W Recycling dispatcher com.google.googlenav.datarequest.DataRequestDispatcher@43ea39b0 276 MapActivity V Recycling map object. 51 GpsLocationProvider D setMinTime 1000 276 MapActivity I Handling network change notification:CONNECTED 276 MapActivity E Couldn't get connection factory client Does anyone have a clue about what may be causing this? Thanks. Are you running the app signed with your key from your key store, or the debug key (clicking run in eclipse will sign the apk with a debug key and install it on the device - be it the emulator or a physical device). If you have a map key (apikey), the keystore will have two different hash codes depending on whether you use the debug key, or your key - so you need two different map keys depending how you are running the app (the debug one will only be needed when you are developing the app). Take a look at the debug section: http://code.google.com/android/add-ons/google-apis/mapkey.html#getdebugfingerprint I'm still running it with the debug key, in the emulator. This means I don't need to associate the app now with my key, right ? I made all those steps correctly.. You will still need to get a map key for use with the debug key for the emulator. If you follow the instructions, you will need to get the MD5 hash from the debug.keystore eclipse uses. Then once you have finished your app and signed it with your own keystore, you will need a map key for that version. But I do have the apiKey which i got from the md5 hash from the debug.keystore! Thank you for signing up for an Android Maps API key! Your key is: .... But it never worked. Check, and double check your key, make sure there is no white space at the end of it or the begining of your code. Alternatively make sure the point you are viewing (where your marker is) is on the map - try zooming the map right out, it could be a co-ordinate off the map. Hey, eheh actually it was working but it was so zoomed that it couldn't show anything. (and the coordinate is wrong anyway)! Thank you for the support! No problem, glad to have helped - I thought about the 2nd bit as I have had the same fault my self with a marker off the map! IF you are using setSatellite(boolean) and setStreetView(boolean) then you can face such situations. This is a BUG in Map View. Use only one of these two methods or you can try with some combinations of these two. Some times, use of only one of them solves the problem sometimes, you need to use a combination of both...like I did in my particular case.. streetView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mapView.invalidate(); mapView.setSatellite(false); //mapView.setStreetView(true); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("satelliteView", false); } }); satelliteView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mapView.invalidate(); mapView.setStreetView(false); mapView.setSatellite(true); } }); Are you sure that you are properly setting the API key for the MapActivity/View?. Can you post your layout xml and source code? Make sure to follow the steps from this tutorial: http://code.google.com/android/add-ons/google-apis/maps-overview.html The problem was that the coordinate was wrong and that way the map was so zoomed that it wasn't able to show anything. I zoomed out and I there was the map; so it was a coordinate problem and not a key/map activity problem. For those who can't zoom out in these cases add this to your code mapView.setBuiltInZoomControls(true); and in the layout android:clickable="true" It will also show a map like that if it you send it a fake lat/lon pair where there is no useful map data, eg. "geo fix 0.0 0.0" (North Pole) Try "geo fix -0.1 51.5" (over South London) where there is Google map data.
common-pile/stackexchange_filtered
String format doesn’t show int number 1 I have this method that receives seconds (as an integer) and returns a string with the years, days, hours, minutes and seconds. When any of the values (years, days, hours, minutes or seconds) = 1 it's not formatted. I have tried to parse to a string but still doesn't work. Does anybody have a clue of what is happening? def seconds_to_text(sec): m = sec//60 h = m//60 d = h//24 years = d//365 days = d - years*365 hours = h - d*24 minutes = m - h*60 seconds = sec % 60 text = '' if years != 0: text += f'{years}' + ' years, ' if years > 1 else ' year, ' if days != 0: text += f'{days}' + ' days, ' if days > 1 else ' day,' if hours != 0: text += f'{hours}' + ' hours, ' if hours > 1 else ' hour, ' if minutes !=0: text += f'{minutes}' + ' minutes ' if minutes > 1 else ' minute ' if seconds != 0: text += f'and {seconds}' + ' seconds' if seconds > 1 else ' second' return text print(seconds_to_text(1501011301)) // Output: 47 years, 217 days, 19 hours, 35 minutes second I have tried with a print(f'and {seconds}') and the output is fine, it shows 1. I have also tried with str(seconds) and it doesn't work either. Thanks for the help Use one long f-string: text += f"{years} year{'s' if years > 1 else ''}, " It's been a problem with putting the if-statement between parenthesis text += f'and {seconds}' + ( ' seconds' if seconds > 1 else ' second')
common-pile/stackexchange_filtered
Show that a subspace is closed in a Hilbert space $H$ If $T$ is a bounded linear operator in a Hilbert space $H$, and $T$ is self-adjoint and is equal to its inverse, how can I show that $\widehat{H} = \{h + Th : h \in H\}$ is closed? If I consider the sequence $\{\widetilde{h_n} \}$ with $\widetilde{h_n} \equiv h_n+Th_n$ that converges to the limit $x$, can I use the uniqueness of representation of the limit to show that $x\equiv h+Th$, to show that $\widehat{H}$ is closed? Suppose a sequence $(h_n+Th_n)$ in $\hat{H}$ converges to some $x$, i.e., $h_n+Th_n\to x$. Applying $T$ and using the fact that $T^2=id$, we obtain $$Tx=\lim T(h_n+Th_n)=\lim Th_n+h_n=x,$$ so $x=\frac{x+Tx}{2}=\frac{x}{2}+T\frac{x}{2}\in\hat{H}$, which shows that $\hat{H}$ is closed.
common-pile/stackexchange_filtered
Can we add a subordinate enterprise certificate authority linked to an existing enterprise Root certificate authority The Root CA is domain joined. The Sub CA will be domain joined. The Sub CA will deliver workstation Authentification (template) to PC clients via GPO. Is there any known issue with this configuration? Should the root CA be only standalone? I know the security recommendation for the root CA to be standalone but is there any operational issue if it's domain joined? Is there any known issue with this configuration? No. Should the root CA be only standalone? This is not mandatory at all. Is there any operational issue if it's domain joined? If you have multiple AD-integrated CAs (regardless of their level in the PKI hierarchy), you will need to manage certificate templates, enrolling permissions and auto-enrollment policies so that users and computers get their certificates from the correct CA.
common-pile/stackexchange_filtered
why the way to call asynchronous is wrong? const before = () => { const p = new Promise((resolve, reject) => { // resolve('before') console.log("ok"); reject(new Error("error!!!")); }); return p; }; const handleClick = () => { const p = new Promise((resolve, reject) => { resolve(true); }); p.then(() => { before(); }) // .then(before) // .then(async () => { // await before(); // }) .then(() => { console.log("then"); }) .catch((e) => { console.error(e); }); }; The above three ways to call 'before' function, the last two ways could catch the exception but not the first one, why and what's the execution sequence of the above code? also the commented await before(); approach was good You need to return the before(). Right now the function returns nothing, hence no error. Why not use await instead? why the return is necessary to catch the exception There is no exception. before is just a rejected promise. If you don't return it, then nothing at all happens with it. Having a rejected promise you don't act on, does not affect anything else in the code.
common-pile/stackexchange_filtered
good book on Jquery and it's compatibility with asp.net Any recommendations? I have used Jquery already but I would like to really delve into it and find out how I can use it with asp.net, specifically instead of updatepanel and ajax toolkit. I use asp.net forms. Regarding jQuery, I found jQuery in Action very useful. It is not just as exciting as the bungee book on prototype, but it is very pragmatic, just as the library is. Prototype is so clever and jQuery is so powerful. Skimming the book and browsing examples is enough to get you started, but be sure to read also the appendix on advanced JavaScript because it is where you will learn what language features have been leveraged to create the library. Regarding jQuery and ASP.NET, two things are worth noticing. 1) Microsoft is supporting jQuery as is in visual studio. No forks, no embrace and extend, just clean support, so you will be able to learn all you need in a non specific book. 2) developing with jQuery is orthogonal to ASP.NET. You will use Visual Studio as a powerful text editor without thinking in terms of ASP.NET components and code behind. There is no code behind in an interactive web application built with jQuery. If you need to do something on the server, you will build an aspx page processing parameters and returning raw data without user interface and call it with ajax. The ideal format is JSON. I would not choose a book particularly targeted to jQuery and ASP.NET without good reason, especially at the beginning. JQuery/Javascript works on the client site, so it's server side language agnostic. I have not done a whole lot of .NET coding, but If I wanted to use jQuery with my .NET app, I would use MVC more instead of Webforms and build all the html/css/js by hand. This is a good book I would recommend. Depending on how advanced you already are with jQuery, this book may be a good one. It is broader in scope than just the jQuery library itself, so the jQuery coverage may not be as thorough as you would like. It does target .net though, and also discusses other relevant libraries such as the Telerik asp.net ajax control library. that's what i mean. in my opinion, all these ajax libs would be redundant if you use jquery. correct me if i am wrong, though. being a simplicity person, i would like to use one ajax lib and use it well. for instance, i wouldn't mix up updatepanel with jquery ajax calls. i am already using jquery in my asp.net app, and as many here noted it language agnostic. for example, how do i achieve updatepanel funcionality with jquery....that type of thing. MS supports jquery because they basically have to these days - with it being a standard in client side dev. While I agree in principle that you might be able to make all the other ajax libraries redundant just by rolling your own controls with jQuery, I'm not sure you would want to take the time and effort to do so. I think a strength of Dino's book is the comparing/contrasting of different approaches to ajax on the asp.net platform, including using other libraries and the shortcomings of controls like the updatepanel. That said, some of the material may be outdated soon and you can't go wrong pairing it with a good platform agnostic ajax (like Ajax in Action) or jQuery (if you're set on it) book. I haven't read this book but it does seem to cover what you are looking for, it only seems to be available as an ebook though. I plan to get this book when it comes out, its MVC 2 instead of webforms but from what I have read MVC2 uses jQuery out of the box. For a general jquery book, I like this one, Its not out yet but I've seen some chapters from the early access program and it looks good, one of the authors is on the jQuery core team so the code is solid and they have been updating the book to match the latest 1.4 release (I'm not sure about 1.4.1 and 1.4.2) One point I would make about using jQuery with asp.net is the way asp.net up until 3.5 renders client id tags, its a pain to work with and you end up doing selectors by regular expression ( "id$=myTextBox" ) or by class, both of which are slower than selecting by id. In asp.net 4 you have more control over how the ids are rendered so that is better, but you have most control with MVC. HTH
common-pile/stackexchange_filtered
ListItemTemplate stopped working after latest SAPUI5 update 1.56.5 I upgraded to the latest version of SAPUI5 - 1.56.5 and the ListItemTemplate inside Combobox stopped working. Although the dropdown length is equal to the number of items supposed to be displayed, there is no text displayed in the dropdown. var formatterItemTemplate = function (myText) { return myText.toUpperCase()); }; var oItemTemplate = new ListItem({ key: "{CityId}", text: { path: 'Address/CityName', formatter: formatterItemTemplate } }); var oComboBox = oCore.byId('MyComboBox'); oComboBox.bindItems({ path: "/Companies/FetchCompanyBasedonCity" + "(CompanyCode='" +oModelData.CompanyCode + "',CityId=" +oModelData.CityId+ ")",", template: oItemTemplate, templateShareable: true, parameters: { $expand: 'Address' }, }); Please note that FetchCompanyBasedonCity in the path attribute is a custom function implemented in .NET which returns a list of companies based on the parameters. Even If I remove the formatter and simply assign text as below, the text inside dropdown in not populated. var oItemTemplate = new ListItem({ key: "{CityId}", text: "{Address/CityName}" }); If I revert to my previously used version 1.54.3, everything works fine. Any ideas why the same code doesn't work with new SAPUI5 version 1.56.5 You can file an issue here if it's an obvious bug: https://github.com/SAP/openui5/issues Thanks Marc, I have reported the issue at Github. Kindly share the screenshot of ERROR.. Hi Inizio, there is no error, just the combobox is empty Issue reported in GitHub : https://github.com/SAP/openui5/issues/2189 Please share the error from console in chrome or any browser you testing on.
common-pile/stackexchange_filtered
How to delete all posts from a custom post type? I want to delete all posts from a custom post type "TV-Serie". The number of all posts in this post type are 150,000. Moreover, when I try to delete them all manually while selecting more than 500 posts at once this provides "timeout error". Any idea on how to delete them all? It may be possible to do a raw SQL "DELETE FROM wp_posts WHERE wp_posts.post_type='TV-Serie'; ". I'm not convinced that is the best or even a recommended way to do it but it would remove the records (brutally). Seriously, use with the utmost caution; this could go very wrong with the smallest error. My post type is episodes and while submitting the SQL querry as: DELETE FROM wp_posts WHERE wp_posts.post_type='episodes'; which provides the following error: "Error in processing request - Error code: 524 Error text: error" You got me there, I cannot find that error code in Google. Try LIMIT 500? This one might be beyond me. Few method or approaches you can take to delete all posts from a custom post type. 1 Use WP-CLI (WordPress Command Line Interface) If you have access to WP-CLI, you can use the following command to delete all posts from your custom post type. wp post delete $(wp post list --post_type=your_custom_post_type --format=ids) Replace your_custom_post_type with the slug of your custom post type. This command will list all post IDs of the specified post type and then delete them one by one 2 Delete Posts Programmatically in Batches Delete posts programmatically within WP, you can write a custom script to delete posts in batches. Add code in your themes functions.php file or in a custom plugin function delete_posts_in_batches() { $post_type = 'your_custom_post_type'; $args = array( 'post_type' => $post_type, 'posts_per_page' => 500, // Adjust the number of posts to delete per batch 'fields' => 'ids', // Retrieve only post IDs to improve performance ); $posts = get_posts($args); if ($posts) { foreach ($posts as $post_id) { wp_delete_post($post_id, true); // Set second parameter to true to force delete } } } // Call the function to start deleting posts delete_posts_in_batches(); You can place this code in your theme's functions.php file or in a custom plugin. Adjust the 'posts_per_page' parameter according to your server's capabilities to avoid timeout errors 3 Increase Server Timeout you can try increasing the maximum execution time and memory limit to prevent timeout errors during the deletion process
common-pile/stackexchange_filtered
jQuery Carousel not repeating I am trying to create a carousel for my site and am having trouble getting the slides to move to the back of the list, so it is a continuous stream with no white space. Here is the code: <div class="maskleft"></div> <div class="maskright"></div> <div class="slideshow"> <div class="views-row views-row-1 views-row-odd views-row-first"> <div class="panel-text">text</div> <div class="views-field views-field-field-image-feature"> <img typeof="foaf:Image" src="" alt="" /> </div> <img typeof="foaf:Image" src="" alt="" /> </div> <div class="views-row views-row-2 views-row-even"> <div class="panel-text">text</div> <div class="views-field views-field-field-image-feature"> <img typeof="foaf:Image" src="" alt="" /> </div> <img typeof="foaf:Image" src="" alt="" /> </div> <div class="views-row views-row-3 views-row-odd"> <div class="panel-text">text</div> <div class="views-field views-field-field-image-feature"> <img typeof="foaf:Image" src="" alt="" /> </div> <img typeof="foaf:Image" src="" alt="" /> </div> <div class="views-row views-row-4 views-row-even views-row-last"> <div class="panel-text">text</div> <div class="views-field views-field-field-image-feature"> <img typeof="foaf:Image" src="" alt="" /> </div> <img typeof="foaf:Image" src="" alt="" /> </div> </div> The jQuery is: function slideChange() { var $slider = $('.slideshow'); var $next = $slider.next().length ? $slider.next() : $('.slideshow'); $next.animate({marginLeft: '-=1024'}, 1000, function() { }); } $(document).ready(function() { setInterval( "slideChange()", 5000 ); }); The live dev site is here: http://dev.shoeboxdesign.co.uk/ You have only one div whitch is moving, why do you need this code: var $next = $slider.next().length ? $slider.next() : $('.slideshow'); You need to reset your marginLeft style when you reach end of your slideshow: if (... check the end of slideshow ...) { // could be calculation of the widht, count of slides, etc. $slider.css({marginLeft: '0'}); } I think he tries to do the following: Uppercase means visible. | A b c | A -> B c | a B c | a B -> C | a b C | b C -> A | A b c | and so on. Your solution would jump back to the beginning without a nice transition. No, I mean that he need to move back slider before nice transition and then perform animation. I didn't said to replace animation. Yes, but when he moves back again there is a jump cut. There wouldn't be a transition from C to A. It would just reset the whole slide without an animation at all. But Chris wanted an continous stream of slides. If I get you right, you want to append the first slide to the end of the slideshow so you have a constant stream instead of a jump cut back to the start. Assuming this is correct, we found an important keyword: append. You have to virtually take the first slide and append it to the last slide. Do this by every animation step. We end up with something like this. function slideChange() { var $slider = $('.slideshow'); var $first = $slider.first(); $slider.append($first); // Append a copy of the first slide to the last one $slider.animate({marginLeft: '-=1024'}, 1000, function() { $first.remove(); // Remove the first slide we just copied. So we virtually swapped the slide from the first to the last place $slider.css({marginLeft: '+=1024'}); // Reset the margin }); } This solution is untested but should do the trick. But I still see some problems in your code. Do you want to use this function only for this slider? If your answer is 'yes' you should definetly give your slider an #id and not a .class selector. And because you won't use your function anywhere again, there's no need for a publicly accessible function. You could make it anonymously, which saves some ressources. setInterval(function() { /* Your stuff goes here */ }, 5000); Hi, Yes I would like to add other functions to this, like sliding the main img down and hiding the non active bits Is this correct? 'function slideChange() { var $slider = $('.slideshow'); var $first = $slider.first(); $slider.append($first); // Append a copy of the first slide to the last one $slider.animate({marginLeft: '-=1024'}, 1000, function() { $first.remove(); // Remove the first slide we just copied. So we virtually swapped the slide from the first to the last place $slider.css({marginLeft: '+=1024'}); // Reset the margin }); } setInterval(function() {"slideChange()"}, 5000);)' Would you be satisfied if your slider would work like this one? http://www.hybritalk.com/?page=info#slideshow (Takes some seconds to load. The images aren'nt compressed yet.) Not really this does not scale the hole page.
common-pile/stackexchange_filtered
Make an array function of javascript Is it possible to make a function like an array? so that the following functions can become simple and be easily edited. function q1() { var theForm = document.forms["contact-form"]; var quantity = theForm.elements["q1"]; var howmany = 0; if (quantity.value != "") { howmany = parseInt(quantity.value); } return howmany; } function q2() { var theForm = document.forms["contact-form"]; var quantity = theForm.elements["q2"]; var howmany = 0; if (quantity.value != "") { howmany = parseInt(quantity.value); } return howmany; } function q3() { var theForm = document.forms["contact-form"]; var quantity = theForm.elements["q3"]; var howmany = 0; if (quantity.value != "") { howmany = parseInt(quantity.value); } return howmany; } now i changed like this GetQuantity() is used to get the value from the Qty field. e.g. q_A01.. GetPrice() is used to get the readonly value Price field. e.g. p_A01.. calculateTotal() is used to calculate the totalprice and return to the field ID "Total". function GetQuantity(e) { var theForm = document.forms["contact-form"]; var quantity = theForm.elements[e]; var howmany =0; if(quantity.value!=0) { howmany = parseInt(quantity.value); } return howmany; } function GetPrice(e) { var theForm = document.forms["contact-form"]; var price = theForm.elements[e]; var howmany =0; if(price.value!=0) { howmany = parseInt(price.value); } return howmany; } function calculateTotal() { var cakePrice = GetPrice(p_A01)*GetQuantity(q_A01)+ GetPrice(p_A02)*GetQuantity(q_A02)+ GetPrice(p_A03)*GetQuantity(q_A03)+ GetPrice(p_F11)*GetQuantity(q_F11); var Totalordered = document.getElementById ("Total"); Totalordered.value = cakePrice; } You could certainly write it shorter, maybe just function fetch() { return 0 } as they all return the same thing ? when only 1 things changes, a switch or even an object lookup table would be more apropos. I suppose that your function should return return quantity.length not howmany sorry everyone. i missed a script to post. it's updated now. Not sure why none of the answer suggested the obvious - keep the common code in the function body, and make the changeable code a function parameter: function q(e) { var theForm = document.forms["contact-form"]; var quantity = theForm.elements[e]; var howmany = 0; if (quantity.value != "") { howmany = parseInt(quantity.value); } return howmany; } or a shorter version, almost identical to your original one: function q(e) { var quantity = document.forms["contact-form"].elements[e]; return (quantity && quantity.value) || 0; } All your functions do the same thing. Just pass the varying data into a single function: function q1(qty) { var theForm = document.forms["contact-form"]; var howmany = 0; // Do whatever you need to with the qty argument. return howmany; } But interestingly, the one thing that varies (quantity) is is something your functions don't actually do anything with. This is the fundamental premise of functions in any programming language and the basis for the general best-practice principle of DRY (don't repeat yourself). Since all your functions do the same thing, just take what varies (quantity) and separate that out of the function. Now, you don't have 5 functions to store and maintain. many thanks to all guys replied to my question. i missed a script. sorry about that. now updated. Here you can use one function for all the inputs just pass the input id or name in it and get values of that element. var q = 'q2'; function qty(q1) { var theForm = document.forms["contact-form"]; var quantity = theForm.elements[q1]; var howmany =0; return howmany; } document.write(qty(q)); thanks Hitesh, thanks every guys, thanks stackoverflow Hi check the following code as you updated function GetQuantity(e) { var theForm = document.forms["contact-form"]; var quantity = theForm.elements[e]; var howmany =0; if(quantity.value!=0) { howmany = parseInt(quantity.value); } return howmany; } function GetPrice(e) { var theForm = document.forms["contact-form"]; var price = theForm.elements[e]; var howmany =0; if(price.value!=0) { howmany = parseInt(price.value); } return howmany; } function calculateTotal() { var cakePrice = GetPrice('p_A01')*GetQuantity('q_A01')+ GetPrice('p_A02')*GetQuantity('q_A02')+ GetPrice('p_A03')*GetQuantity('q_A03')+ GetPrice('p_F11')*GetQuantity('q_F11'); var Totalordered = document.getElementById ("Total"); Totalordered.value = cakePrice; } calculateTotal();
common-pile/stackexchange_filtered
Flex cancel a change event on a Tree Brief details: I'm using Flex 3.5. I have a Tree component that's used as a navigation menu between different 'pages'. When the user clicks a certain option in the menu, I switch the 'page' by switching between State components in my application. The thing is that when the user indeed clicks an option in the menu, I want to perform a validation of some of the information in a certain component. If the validation fails, I show an alert, and I'd like to prevent the navigation to the other page. One part of this is simply not changing the currentState of the document, but the tree component still goes on with the change event, and the result is page A still being shown on the screen, whereas the selected option in the tree is page B (to which the user wanted to navigate, but failed since some of the information wasn't valid). I tried to figure out how I can cancel the change event on the tree component itself. The thoughts I had didn't quite fit nicely: I searched for a slightly different event (such as 'changing' or 'startChange') on which I can call the stopPropagation() method (since the regular 'change' event is not cancelable), but none exists for the Tree component. I also thought about always saving the current option that's selected in the Tree component by myself, and when the validation fails, I will set the Tree's selectedItem to that saved option. That's also ugly because such an action will raise another change event on the Tree, thus another change to the States components, and another population of the page in which I'm already at. That's something I really don't want to do. I also though about using a different component, such as Menu (and I also found an implementation of a vertical Menu), but that doesn't even seem to help. The same problem will exist there. Is there a proper way to do this? There must be a best-practice for preventing a change process to commit! <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*"> <mx:Script> <![CDATA[ import mx.controls.Alert; import mx.events.ListEvent; private function tree_changeHandler(event:ListEvent):void { trace("Change, selectedItem.label is: " + tree.selectedItem.label); } protected function tree_itemClickHandler(event:ListEvent):void { var data:Object = event.itemRenderer.data; if (!tree.isItemSelectable(data)) Alert.show("Item \"" + data.label + "\" is not selectable"); } ]]> </mx:Script> <local:MyTree id="tree" change="tree_changeHandler(event)" itemClick="tree_itemClickHandler(event)"> <local:dataProvider> <mx:ArrayCollection> <mx:Object label="Label 1"/> <mx:Object label="Label 2"/> <mx:Object label="Label 3 (non-selectable)"/> <mx:Object label="Label 4"/> </mx:ArrayCollection> </local:dataProvider> </local:MyTree> </mx:Application> Source for MyTree.as: package { import mx.controls.Tree; public class MyTree extends Tree { override public function isItemSelectable(data:Object):Boolean { if (!super.isItemSelectable(data)) return false; var label:String = data.label; if (label.indexOf("non-selectable") >= 0) return false; return true; } } } Eventually I found the place to put the code that determines each item's selectability: when the information that should be validated is changed, I perform the validation, and according to its result I set a property to all of the items in the Tree component, indicating whether they can be navigated to or not. If the validation was successful, the property is set to allow navigation, and if unsuccessful, it is set not to allow navigation. Like Maxim, I extend the Tree component and overrode the isItemSelectable() method to check this property of the specified item, this way preventing the change process. The access between the view that holds the information to-be-validated, and the view that holds the Tree component (they are not necessarily the same view) is done via a presentor class that holds both views (I use the MVP mechanism). This is not the most elegant design, but it is much better than anything else I could have thought of. The alleged problem with the design is the coupling between the views and the complexity of the presentor, that has to deal with more than one view and have methods that are related to the interaction between the views (instead of methods that represent actions of a specific view). The thing is that business-wise, the two views are coupled (since the information in one affects the navigation tree in the other), thus the presentor couples between them. The coupling is also done through the interface of the presentor, so that each view doesn't really "know" the other view. I hope it might help other people. Thanks, Daniel
common-pile/stackexchange_filtered
Error in block pushing thread : Kafka Spark streaming The following error occured while running kafka consumer: ERROR receiver.BlockGenerator: Error in block pushing thread java.io.NotSerializableException: org.jnetpcap.packet.PcapPacket at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347) at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:42) at org.apache.spark.serializer.SerializationStream$class.writeAll(Serializer.scala:102) at org.apache.spark.serializer.JavaSerializationStream.writeAll(JavaSerializer.scala:30) at org.apache.spark.storage.BlockManager.dataSerializeStream(BlockManager.scala:996) at org.apache.spark.storage.BlockManager.dataSerialize(BlockManager.scala:1005) at org.apache.spark.storage.MemoryStore.putValues(MemoryStore.scala:79) at org.apache.spark.storage.BlockManager.doPut(BlockManager.scala:663) at org.apache.spark.storage.BlockManager.put(BlockManager.scala:574) build.sbt file : name := "testpacket" version := "1.0" scalaVersion := "2.10.3" libraryDependencies += "org.apache.spark" % "spark-core_2.10" % "1.0.2 libraryDependencies += "org.apache.spark" % "spark-streaming_2.10" % "1.0.2" libraryDependencies += "org.apache.spark" % "spark-streaming-kafka_2.10" % "1.0.2" libraryDependencies += "javax.servlet" % "javax.servlet-api" % "3.0.1" resolvers += "Akka Repository" at "http://repo.akka.io/releases/" What could be the reason for the error? I've run into this problem in two situation before so with out seeing your code I can't be sure exactly what the problem is. You're including non-serializable classes in your RDD data set. You're importing non-serliazable classes outside of your driver only class/function/code. My guess is that you're experiencing #1 and are including a PcapPacket as part of your RDD. If this is the case then you'll need to create a serializable version of PcapPacket which shouldn't be to difficult as a PcapPacket is supported by an underlying byte array.
common-pile/stackexchange_filtered
how to read the contents of file and convert it into dictionary in python I have a text file (applications.txt) containing n number of lines of data (with 2 delimiters) in the below format. 1) mytvScreen|mytvScreen|Mi TV,Mí TV, My Tv, TV 2) watchNextScreen|watchNextScreen|Seguir viendo,Mi TV Seguir viendo 3) recordingsScreen|recordingsScreen|Grabaciones,Mis Grabaciones,Mi TV Note: 1,2,3 are just line numbers for reference. Original file doesn't contain the number. I am trying to write a function that would read each line and convert it into a dictionary using the value before the first delimiter and the values after the second delimiter, like the example shown below. eg: The below line one should be converted into dictionary as expected below. 1) mytvScreen|mytvScreen|Mi TV,Mí TV, My Tv, TV Expected Format: mytvScreen : Mi TV, Mí TV, My Tv, TV Also, Upon giving any value which are comma separated, it should return the value before the colan . Eg: When the value Mi TV is given, it should return mytvScreen or for the other comma separated values also, it should return mytvScreen I was able to read the file and print the values as expected. But not sure how can i convert each line into a dictionary. with open('applications.txt') as f: for line in f: details=line.split("|",2) print (details[0] + ' : '+ details[2]) Your Help is highly appreciated. Please share your existing code that doesn't work so we can help you. you should be adding items to dictionary, one of the approach is given below. s_dict= dict() with open('applications.txt') as f: for line in f: details=line.split("|",2) print (details[0] + ' : '+ details[2]) s_dict[details[0]] = details[2] print (s_dict) I build a file-object to mimic applications.txt content: >>> import io >>> f = io.StringIO("""mytvScreen|mytvScreen|Mi TV,Mí TV, My Tv, TV ... watchNextScreen|watchNextScreen|Seguir viendo,Mi TV Seguir viendo ... recordingsScreen|recordingsScreen|Grabaciones,Mis Grabaciones,Mi TV""") Your file is obviously a csv file, thus you should use the csv module to parse it: >>> import csv >>> reader = csv.reader(f, delimiter='|') The last part is just a dict-comprehension: >>> {row[0]: row[2] for row in reader} {'mytvScreen': 'Mi TV,Mí TV, My Tv, TV', 'watchNextScreen': 'Seguir viendo,Mi TV Seguir viendo', 'recordingsScreen': 'Grabaciones,Mis Grabaciones,Mi TV'}
common-pile/stackexchange_filtered
How to get flat files with no file structure as source and insert same data into table as target in IICS I wanted to get the flat files as source without any file structure specified using IICS(Informatica Intelligent cloud services). Flat files names can be anything, and structure also will change any. And also need to create table dynamically based on flat file and insert into table. There's a number of options here. You can use a fully parameterized mapping niside a taskflow that will start on file listener, prepare the parameters and statements to be executed as part of the pre-SQL statement on your Target. Inside the mapping you define Source and Target as parameterized - and that's briefly it! Have tried as per your suggestions. Now my source and target is fully parameterized. Same calling from TF, and also am using FL for input file name and assigning same to input as Data task in TF. But TF is getting suspended while running, unable to see input parameter values of Data task and output of FL. Can you please share any other ways solve this issue. Please download and review the session log Now am trying to pass input parameters to Mapping task through Task flow. But in My Task flow File listener is picking multiple files at a time(more than 1) but when i passing to Mapping task, its passing only one file name as input parameter. Do we have any ways to call multiple input parameters to Mapping task so that all files will move to target location. Please suggest. The File Listener will capture all files - this is by design. At any given time there may be many new files. File Listener returns an array. You need to create a loop. Create Assignment Task and get one file to a variable. Create Decision Task to check if array is not empty. Invoke mapping and pass the current file name as parameter. Jump to Assignment Task. Thanks, it worked for me. Also if you free time, can you see my another post https://stackoverflow.com/questions/75522058/how-to-drop-and-create-new-table-everytime-using-mapping-iics In this case consider upvoting and marking as correct - thanks!
common-pile/stackexchange_filtered
How can I fix Laravel 5.1 - 404 Not Found? I am trying to use Laravel 5.1 for the first time. I was able to install it and https://sub.example.com/laravel/public/ is displaying what is should. However, views I create are giving me a 404 error Page not found. Here is what I have done so far: I created a controller in laravel\app\Http\controllers\Authors.php Here is the code behind the Authors.php file <?php class Authors_Controller extends Base_Controller { public $restful = true; public function get_index() { return View::make('authors.index') ->with('title', 'Authors and Books') ->with('authors', Author::order_by('name')->get()); } } Then I created a view in laravel\resources\views\Authors\index.blade.php Here is the code behind the index.blade.php file @layout('layouts.default') @section('content') Hello, this is a test @endsection Then I created a layout in laravel\resources\views\layouts\default.blade.php Here is the code behind the default.blade.php file <!DOCTYPE html> <html> <head> <title>{{ $title }}</title> </head> <body> @if(Session::has('message')) <p style="color: green;">{{ Session::get('message') }}</p> @endif @yield('content') Hello - My first test </body> </html> Finally I created a route in laravel\app\Http\routes.php <?php Route::get('/', function () { return view('welcome'); }); Route::get('authors', array('as'=>'authors', 'uses'=>'authors@index')); But for some reason I keep getting 404 error Page not found. I enabled the mod_rewrite on my Apache 2.4.9 by uncommenting out the line LoadModule rewrite_module modules/mod_rewrite.so Then restarted Apache. From what I can tell in the php_info() output the mod_rewrite is enabled Loaded Modules core mod_win32 mpm_winnt http_core mod_so mod_php5 mod_access_compat mod_actions mod_alias mod_allowmethods mod_asis mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_socache_shmcb mod_ssl My current .htaccess file looks like this "which is the factory default" Options -MultiViews RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] I have also tried to change it to the code below as per the documentation: Options +FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] However, I am still getting the 404 page when I go to https://sub.example.com/laravel/public/authors What am I doing wrong? How can I fix this problem? I see the same behaviour of being able to visit the / route but all other pages return a 404 when I first setup Laravel sites. In your apache config file httpd.conf or httpd-vhosts.conf you need to enable the directives that can be placed in the .htaccess file. Here is an example of my VirtualHost configuration: <VirtualHost *:80> ServerAdmin<EMAIL_ADDRESS> DocumentRoot "C:/www/laravel_authority-controller_app/public" ServerName authoritycontroller.www ErrorLog "logs/AuthorityController.www-error.log" CustomLog "logs/AuthorityController.www-access.log" common <Directory "C:/www/laravel_authority-controller_app/public"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks Includes ExecCGI # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # AllowOverride FileInfo AuthConfig Limit # AllowOverride All # # Controls who can get stuff from this server. # Require all granted </Directory> </VirtualHost> The key entry for your issue is AllowOverride All. This should be enough to get the website working but you can also include options and Require all granted if they are consistent across the entire website. How do i do this in a windows server? or could this be my problem, i have the same issue, home url works but no other url works, even when route is defined. if you are on ubuntu you shoud do 3 thing. 1. check if "/var/www/html/YourProject/public/ .htacess " is like this. <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 2. Add this lines on /etc/apache2/sites-available/000-default.conf <Directory "/var/www/html"> AllowOverride all Require all granted </Directory> Note: remember that is an system file so you should use this comamd sudo gedit /etc/apache2/sites-available/000-default.conf by last enable rewrite module. LoadModule rewrite_module modules/mod_rewrite.so or sudo a2enmod rewrite If your Laravel routes aren't working, and you're getting "Not Found" errors whenever you try and load a page, your .htaccess file is likely lacking permission to do its duty. The key is the apache AllowOverride directive. If you don't have AllowOverride set to All, your Laravel .htaccess file (/public/.htaccess) won't be able to enable mod_rewrite, and your routes won't work. The first step is to open your apache httpd.conf file. In OS X, it is located at: /private/etc/apache2/httpd.conf Option 1) Modify your main directive This will change the AllowOverride value for all your websites. In your httpd.conf file, look for the main directive: <Directory "/var/www/html"> ... AllowOverride None ... </Directory> Simply change it to this: <Directory "/var/www/html"> ... AllowOverride All ... </Directory> Option 2) Add a directive to your site's directive. <VirtualHost <IP_ADDRESS>:80> DocumentRoot "/var/www/html/epigroove/public" ... <Directory "/var/www/html/epigroove/public"> AllowOverride All </Directory> </VirtualHost> Save the changes to your httpd.conf file, restart or reload apache, and your routes should be up-and-running. If you are running Apache HTTPD 2.2.15 on Linux (CentOS 6.7 in my case), then the directory directive will look like this <Directory /> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All allow from all </Directory> You probably don't need the Options line though, unless you're using those options. Thank you to the 2.4 answer. It helped me solve this issue for me on 2.2 and I have another server running 2.4 I can apply it to too. if its on a live server, try this, it worked for me tho. <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> Options +FollowSymLinks RewriteEngine On RewriteBase / # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] also, the URL is case sensitive to the folder name folder name: camelCase then the url must be localhost/camelCase/route-1 hope this help someone xD, little bit silly
common-pile/stackexchange_filtered
why does applying probability distributions and transformations result in the same value? I'm applying multiple Beta, Gamma and HalfNorm Transforms to each column of my pandas dataframe. The dataframe consists of marketing spend; each row indicates spend per week and each column indicates type of spend: The python functions and code to apply the transform is as follows: def geometric_adstock_tt( x, alpha=0, L=12, normalize=True ): # 12 (days) is the delay or lag we expect to see? """ The term "geometric" refers to the way weights are assigned to past values, which follows a geometric progression. In a geometric progression, each term is found by multiplying the previous term by a fixed, constant ratio (commonly denoted as "r"). In the case of the geometric adstock function, the "alpha" parameter serves as this constant ratio. """ # vector of weights assigned by decay rate alpha set to be 12 weeks w = np.array([alpha**i for i in range(L)]) xx = np.stack( [np.concatenate([np.zeros(i), x[: x.shape[0] - i]]) for i in range(L)] ) if not normalize: y = np.dot(w, xx) else: y = np.dot( w / np.sum(w), xx ) # dot product to get marketing channel over time frame of decay return y ### non-linear saturation function def logistic_function(x_t, mu=0.1): # apply the logistic function to spend variable return (1 - np.exp(-mu * x_t)) / (1 * np.exp(-mu * x_t)) ################# response_mean = [] # Create Distributions halfnorm_dist = st.halfnorm(loc=0, scale=5) # Create a beta distribution beta_dist = st.beta(a=3, b=3) # Create a gamma distribution gamma_dist = st.gamma(a=3) delay_channels = [ 'TV', 'Referral', 'DirectMail', 'TradeShows', 'SocialMedia','DisplayAds_Standard', 'ContentMarketing', 'GoogleAds', 'SEO', 'Email', 'AffiliateMarketing', ] non_lin_channels = ["DisplayAds_Programmatic"] ################ ADSTOCK CHANNELS for channel_name in delay_channels: xx = df_in[channel_name].values print(f"Adding Delayed Channels: {channel_name}") # apply beta transform y = beta_dist.pdf(xx) # apply geometric adstock transform geo_transform = geometric_adstock_tt(y) # apply gamma transform z = gamma_dist.pdf(geo_transform) # apply logistic function transform log_transform = logistic_function(z) # apply halfnorm transform output = halfnorm_dist.pdf(geo_transform) # append output response_mean.append(list(output)) ################# SATURATION ONLY for channel_name in non_lin_channels: xx = df_in[channel_name].values # apply gamma transform z = gamma_dist.pdf(xx) # apply logistic function transform log_transform = logistic_function(z) # apply halfnorm transform output = halfnorm_dist.pdf(log_transform) # append output response_mean.append(list(output)) I'm not quite understanding why all values are being transformed to the same value. I would be so appreciative of any insight! Thanks so much:) I believe what's happening is that the beta distribution you defined expects your data to be in the range 0 ≤ x ≤ 1 (see the notes for the beta distribution documentation), and anything outside of this range will have a pdf value of 0. So one possibility is to first min-max scale all of your columns to be in the range 0-1 using the following: df_in = (df_in-df_in.min())/(df_in.max()-df_in.min()) Using some made up data: delay_channels = [ 'TV', 'Referral', 'DirectMail', 'TradeShows', 'SocialMedia','DisplayAds_Standard', 'ContentMarketing', 'GoogleAds', 'SEO', 'Email', 'AffiliateMarketing', ] non_lin_channels = ["DisplayAds_Programmatic"] sample_dates = pd.date_range('2023-01-01','2024-01-01',freq='7D') sample_data_dict = { channel: 1000 + 100*np.random.rand(53) for channel in delay_channels+non_lin_channels } sample_data_dict['Date'] = sample_dates np.random.seed(42) df_in = pd.DataFrame(sample_data_dict) df_in = df_in.set_index('Date') df_in = (df_in-df_in.min())/(df_in.max()-df_in.min()) After applying your transformations, I get the following: You're welcome - happy to have helped!
common-pile/stackexchange_filtered
Column identified in an update from a returned value I trying to update one table with column variable. Example: Table: BILLING (ORIGIN OF DATA) Columns: - CUSTOMER - PERIOD - REVENUE TABLE: BILLING_MONTHLY Columns: - CUSTOMER - M201301 (this value is REVENUE per year/month) - M201302 (this value is REVENUE per year/month) - M201303 (this value is REVENUE per year/month) I need update BILLING_MONTHLY with value column of BILLING (PERIOD), but I don't achieve set column in update equal result in select of table BILLING. Example: Table BILLING CUSTOMER PERIOD REVENUE 05031 201301 1000 05013 201301 550 05031 201302 800 05032 201303 930 05031 201303 880 Expected Result Table BILLING_MONTHLY CUSTOMER M201301 M201302 M201303 05013 550 05031 1000 800 880 05032 930 My idea: 1) Create "FOR" to insert customer in BILLING_MONTHLY; 2) Create "UPDATE" for valorize customer per year/month; The problem: I don’t' obtain a update functionally due result be the column. To create a survey: CREATE TABLE BILLING ( CUSTOMER VARCHAR2(5 BYTE), PERIOD VARCHAR2(6 BYTE), REVENUE NUMBER ); INSERT INTO BILLING (CUSTOMER, PERIOD, REVENUE) VALUES ('05031', '201301', 1000); INSERT INTO BILLING (CUSTOMER, PERIOD, REVENUE) VALUES ('05013', '201301', 550); INSERT INTO BILLING (CUSTOMER, PERIOD, REVENUE) VALUES ('05031', '201302', 800); INSERT INTO BILLING (CUSTOMER, PERIOD, REVENUE) VALUES ('05032', '201303', 930); INSERT INTO BILLING (CUSTOMER, PERIOD, REVENUE) VALUES ('05031', '201303', 880); COMMIT; CREATE TABLE BILLING_MONTH ( CUSTOMER VARCHAR2(5 BYTE), M201301 NUMBER, M201302 NUMBER, M201303 NUMBER ); Can someone help me, please? Thanks in advance! You need to redesign your tables. That BILLING_MONTHLY is all wrong. Now the tables are certain, thanks for tip "gvee". This is what you want select customer, sum(c1) M201301, sum(c2) M201302, sum(c3) M201303 from( select customer, case when period='201301' then revenue else 0 end 'C1', case when period='201302' then revenue else 0 end 'C2', case when period='201303' then revenue else 0 end 'C3' from billing ) t group by customer You need to control the range of month and the name of column of the result yourself. If this query is a part of coding, you can let the code handle that sqlfiddle here http://sqlfiddle.com/#!2/7aa98/13 Must update the columns per client, however, the months in table BILLING_MONTH are the values in table BILLING. When I try to do the update, I can't reference the column to extract value, because the column name M201303 (for example) must be referenced to the customer and the period, only that at the update, the column would have to be variable and not fixed. You Understand? Your example is good, however, I have the data already in a table and are relevant to more than 3 years (40 months). With the CASE the SELECT will be very large and will have to be adjusted where. If I use a table with several years already identified if get tow the values the columns, I do not get by modifying the commands This is the select used for extract values: SELECT PERIOD, CUSTOMER, SUM(VALUES_INVOICE) REVENUE FROM BILLING GROUP BY PERIOD, CUSTOMER 'C1' is not a valid column alias, it's String literal. Object names need to be quoted using double quotes " in standard SQL (and in Oracle which is what the OP is using).
common-pile/stackexchange_filtered
Extract only text part of email body using javamail, without html content In my project I am required to read mails and save its content in hard drive, from a MS Exchange email box using javamail. But I found that even the simplest email I receive is saved with html content, like head body and so on, even when I only write two words with format, without images, no attachment. But I just want the text of email. Part of code: Object content = part.getContent(); if (content instanceof InputStream || content instanceof String) { if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) { String messageBody = part.getContent().toString(); ....(write this string to files) } } I may write: Hello world. And I get a txt with all its html code, and fontface and tags like <html> and so on. I saw this question and I found him only retrieving text content but I cannot comment there, so I must post a new question, and I see no difference between my code and his. He wrote: if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) { DataHandler handler = bodyPart.getDataHandler(); s1 = (String) bodyPart.getContent();` So is it about the DataHandler? But it is not used anywhere? Can someone help? First of all, you'll want to read this JavaMail FAQ entry that tells you how to find the main message body. As written, it prefers an html body over a plain text body in cases where the message contains both. It should be clear how to reverse that preference. But, not all messages will contain both html and plain text versions of the message body. If you get only html, you're going to have to write your own code to process the string and remove the html tags, or use some other product to process the html and remove the tags. Thanks for comment, but I cannot see why the order means something in the link you posted. And change the order of if - else changes the preference and the output? Can you specify a little more? Per RFC 2046, which defines multipart/alternative, the alternatives appear in order of increasing faithfulness to the original content. That means you'll find text/plain before text/html. If you prefer text/plain, you can change that code to return as soon as it finds text/plain content; there's no need to continue looking for other body parts. Ok thanks. I decide to retrieve whole message as html because it contains more information. I prefer maintain the structure of emails and not mess up all the text. At last I used Jsoup and it works fine. The trick is, you have to remove the <head> part manually first, and Jsoup does the rest.
common-pile/stackexchange_filtered
SQL - query as parameter I have code: DECLARE @sqlQuery NVARCHAR(4000); DECLARE @stn NVARCHAR(4000); SET @stn=N'SELECT cast(isnull(SUBSTRING(CDN.DokSumT(16,739684,1045,1,32768,1,1,739684,1,2,1,0,78877,0,3,1,1,0,0,0,0,0,-1) , 9 , 7 ),0) as decimal (28,4))'; SELECT @sqlQuery = 'SELECT GIDNumber, Name, @stn as stn FROM Table_342 WHERE Name LIKE ''%ABLE%'''; EXEC sp_executesql @sqlQuery, N'@stn NVARCHAR(4000)', @stn; This request returns In column "stn" I want to have a query result not a query. How to do it ? Please help. I have to ask, although I suspect the answers are "yes" and "no idea" - is this definitely the most efficient way to solve the problem you have, and who designed this database? I have no idea but I think so :) Try something like this.... DECLARE @sqlQuery NVARCHAR(MAX) , @stn NVARCHAR(MAX) , @stn_R DECIMAL(28,4); SET @stn = N'SELECT @stn_R = cast(isnull(SUBSTRING(CDN.DokSumT(16,739684,1045,1,32768,1,1,739684,1,2,1,0,78877,0,3,1,1,0,0,0,0,0,-1) , 9 , 7 ),0) as decimal (28,4))'; EXEC sp_executesql @stn , N'@stn_R DECIMAL(28,4) OUTPUT' , @stn_R OUTPUT SELECT @sqlQuery = 'SELECT GIDNumber, Name, @stn_R as stn FROM Table_342 WHERE Name LIKE ''%ABLE%'''; EXEC sp_executesql @sqlQuery , N'@stn_R DECIMAL(28,4)' , @stn_R; Note Your whole query is being treated as a parameter because sp_executesql only first parameter expects a SQL Statement any following parameters are either variable declarations or variable values. You will need to split the execution of dynamic query into two and use output parameter to get the value out of first query and pass it to the second query. I have this error Msg 137, Level 15, State 2, Line 1 Must declare the scalar variable "@stan". First try with non dynamic manner. once you got..execute dynamically using EXEC(@sqlquery)
common-pile/stackexchange_filtered
Adding an Image to a sqlite database I've been struggling for a while now with this, and i want to be able to store an image to my database. I know storing an image to a database directly is bad practice but i simply do not know enough to be able to do it another way. So, i'm currently stuck with a few issues. Firstly, I'm not even sure my path is correct; i want to get a drawable file and store it to my database and there must be an easier way than doing a path straight from the C drive right? Secondly, I don't know much about this but i need to convert my file to a bitmap so that it can be converted to a byte array? And i'm not sure how to do this exactly. I've tried several things, wrote this code out about 10 times already in different ways and not getting anywhere. Thanks all for help in advance. public void insertAvatar(String Email, byte[] head) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); String sql = "INSERT INTO Avatar VALUES (?, ?)"; File head = new File("C:\\Users\\PC\\Desktop\\capaa\\src\\main\\res\\drawable\\head2.png"); Bitmap imageToStoreBitmap = head; // doesn't work as my file isnt a bitmap yet objectByteArrayOutputStream = new ByteArrayOutputStream(); imageToStoreBitmap.compress(Bitmap.CompressFormat.JPEG, 100, objectByteArrayOutputStream); imageInBytes = objectByteArrayOutputStream.toByteArray(); contentValues.put("Email", Email); contentValues.put("head", imageInBytes); long checkIfQueryRuns = db.insert("Avatar", null, contentValues ); } why you put Android tag, does this code run on Android ?! Yeah its for my android app :) when the code run on Android on your phone , it will not have access to the file you are specifying here, put your file on an SD card or on your pictures folder .... and use the path in your Android phone(ex: /storage/sdcard0/...) and not of your windows computer (c:....) Is there no other way to do this? Say you had to use several devices, it would be long winded to transfer the images to each device. yes , you can install a server on your pc , and fetch images from that server ahh but that isnt sqlite is it, don't think that would work for me if you need to put images in a database you can encode them into base64 and put them as string, to display them pull them and then decode them The Android device will likely not have acces to "C:\Users\PC\Desktop\capaa\src\main\res\drawable\head2.png", that is it is very likely a file on the PC. The head2.png will be an Android RESOURCE as far as the device is concerned. See App resources overview Why do you want to save images in the database? I was looking to create a sort of character so that when the app loads, it can get the correct images from the database. I've created a sort of shop that changes items on my character and i needed the images to be saved to a database so that when the app is closed, the images bought can be saved. You need to use Blob to store images in your SQLite database. Create a table to store the images CREATE TABLE " + DB_TABLE_NAME + "("+ KEY_NAME + " TEXT," + KEY_IMAGE + " BLOB);"; To store an image in the table public void addImage( String name, byte[] image) throws SQLiteException{ ContentValues cv = new ContentValues(); cv.put(KEY_NAME, name); cv.put(KEY_IMAGE, image); database.insert( DB_TABLE_NAME, null, cv ); } As you can see before inserting the image to the table, you need to convert the bitmap to a byte array. // To convert from bitmap to byte array public static byte[] getImageBytes(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0, stream); return stream.toByteArray(); } To retrieve image from database //search your image using the key and get the cursor ............ byte[] image = cursor.getBlob(1); ............ As you can see the image returned is in a byte array. Now you can convert this byte array to bitmap to use in your app. //To convert from byte array to bitmap public static Bitmap getImage(byte[] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } Having written the answer, I myself is not a big fan of storing images in the database. I am not sure what is your need for storing the images but you can check the following libraries to handle images in your app. https://github.com/bumptech/glide/ https://square.github.io/picasso/ https://github.com/nostra13/Android-Universal-Image-Loader Thanks for your answer :) I have one question though, you know the add image method, where does it pulls the image from? Assuming you have to declare a path or something? I've seen lots of tutorials of people selecting images from the device to save to db, but this is not what i want. The code you've done is what im looking for, although i need to add a specific image to the db, rather than an image being passed into the add image. See how i've done in my example with the File head. And i know its not best practice to add images straight to the db, but i'm a bit of a noob when it comes to android so not sure of any other SIMPLE way. I do appreciate your response though :) what do you want to do in your app?
common-pile/stackexchange_filtered
Can I use percentage units for box shadow? That's it :), Is there a way to make a box shadow in css with percentage units? I'd like if it were with pure css. But if you guys think js is the only way, please let me know how... Why would you need this? You can't do this with CSS because how would the percentage be arbitrarily calculated? If you provide an example use case, then a JavaScript solution could be written for that situation. According to the W3C, you can't use percentages in box-shadow. And it doesn't get more authoritative than that, so, that's the final word. Use JS.
common-pile/stackexchange_filtered
Header Files Mystery Possible Duplicate: what is the difference between #include <filename> and #include “filename” Why do we use Quotation Marks ("...") for custom build classes and braces for built in classes(<...>)? Yeah, from what I've heard, angle brackets (<'s) are used to denote that the header was provided with the compiler, OR that the compiler has been told about a directory in which the header file can be found (-I). Quotes ("'s) are usually used for header files within the source tree. But like others have mentioned, it's not a requirement. Even if the header is within the source tree, you still have to tell the compiler how to find it. -I. is not the default. What? I never said -I was the default ... I said < is for something like , or if you specify a path with -I It's to denote that the header isn't system-wide. This is a convention, not a requirement. By the way, those aren't inverted commas, they're quotation marks. There is a difference in the field of typography. <> aren't braces either ... :p typographically speaking, they're not true quotation marks either. Quotation marks look like “this”, not "this". :) At least for C, it makes no difference nowadays. The ISO standard states that the location of the files is implementation defined in both cases. The usual way is to use <> for system headers (things under /usr/include for example) and "" for your own headers, but it's not required. The relevant bits of C99 are from 6.10.2, "Source file inclusion", quoted below. A preprocessing directive of the form # include <h-char-sequence> new-line searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. A preprocessing directive of the form # include "q-char-sequence" new-line causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read # include <h-char-sequence> new-line with the identical contained sequence (including > characters, if any) from the original directive. quote and link the standard for bonus points :D Why bother, Matt? It's quoted in probably every other dup of this: http://stackoverflow.com/questions/3162030/difference-between-angle-bracket-and-double-quotes-while-including-header/3162067#3162067 http://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename/77092#77092
common-pile/stackexchange_filtered
how to do "or" in substring matching for bash echo `expr "hello" : '\(hi|hello\)'` echo `expr "hi" : '\(hi|hello\)'` obviously i'm trying to match "hello" and then "hi" to regex hello and hi, but neither matches. how do i express it properly?? expr doesn't support extended regex This came as a surprise to me, since alternation ('|') is one of the three regular operations (along with concatenation and the Kleene star '*') in formal language theory. Also depends on what exactly you are trying to accomplish. What is the problem you are attempting to solve? In any event, you should rarely want or need to use expr in this day and age. The failure of POSIX BRE to support | is baffling, since it supports bracket expressions ([ab] is just syntactic sugar for (a|b)), and it supports back references, which allow non-regular languages to be recognized! Alternately, plain globs case $str in *hi* | *hello*) echo "pleased to meet you" esac The best option in this simple case is to use extended globs instead of regular expressions (it'll be more efficient and save you from headaches): string=hello if [[ $string = @(hi|hello) ]]; then echo "String matches" fi Or (as you're mentioning substring matches in the title), string="hello world" if [[ $string = *@(hi|hello)* ]]; then echo "String matches" fi Note. With the [[ construct, it is not necessary to turn extglob on: the reference manual specifies: When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching. and the rules in the Pattern Matching describe extended globs. @glennjackman Thanks for your edit... but it turns out that extglob is not needed here as seen in the manual about the [[ keyword: When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching. I was surprised too when I was pointed to this sentence, but it actually makes sense, as these are proper to Bash (in contrast to POSIX shells). I did not know that. I tested with extglob explicitly turned off and it does match. As far as I can tell (based on reading the release notes; I don't have anything older than 3.2 to try it out), that's been true ever since both [[...]] and extglob were added to bash, way back in bash 2.02 :) @chepner it was you who pointed this out to me a few days back... thanks ;) @chepner does seem to work since 3.1 (seems that shopt -s extglob is needed in 3.0). A more modern alternative to expr is to use Bash regular expressions: re='hi|hello' string=hi [[ $string =~ $re ]] && echo "$string matched" The | character is available in extended regular expressions, but expr only uses basic regular expressions with the : operator. [UPDATE: at least in the POSIX version of basic regular expressions; expr hello '\(hello\|\hi\)' will work with GNU expr, as pointed out by Glenn Jackman]. You would need to rewrite the command as two separate calls to expr: $ expr hello : '\(hello\)' || expr hello : '\(hi\)' hello $ expr hi : '\(hello\)' || expr hi : '\(hi\)' hi $ expr foo : '\(hello\)' || expr foo : '\(hi\)' $ This is still less than ideal, since the failed matches still output an empty string. It's far better to use one of the alternatives presented in the other answers. In particular, the case statement is POSIX-compatible and does not rely on any bash extensions. Update: While the regular expression itself cannot use |, you can combine two : expressions within the same call to expr: expr hi : '\(hello\)' \| hi : '\(hi\)' When the first : fails to find a match, it tries the second. This prevents expr from outputting an empty string for the failed first match. With BRE, use \| for alternation I tried; it doesn't work. Alternation isn't mentioned at all in the description of BREs, escaped or no. (See the POSIX spec for BREs.) Ugh, GNU and POSIX use different definitions for "basic regular expression". In this case, I think GNU's definition is more sane, at least on the point of including alternation in its definition. for posterity, GNU BRE syntax: https://www.gnu.org/software/gnulib/manual/html_node/ed-regular-expression-syntax.html
common-pile/stackexchange_filtered
Anyone have a pointer for what is needed to make an MP3 Tag applicaiton? I get FLAC files a lot and want to automate the taging of the end point MP3 files after I have converted them. What is my best library to interface with? Vista machine and C# for my code base. The flac files come with a text file for the show, and the numbers performed. I'll edit that any way possible. I use winamp for a player but will try others if free. :) TIA. Check out libid3tag... http://sourceforge.net/project/showfiles.php?group_id=12349... And, actually, the ID3 tag is prettty simple, it's just text (with fixed length fields) tacked on to the front of the MP3 file... Just make sure you follow the standard, as not all players, etc. do. For more on that, check out this article on Wikipedia link text You might also want to check out TagLib# (google it). It's not too hard to use, and makes reading and writing ID3 tags and other metadata pretty easy. I've used it an ASP.NET project in the past, to automatically populate a database record using metadata from the ID3 tag of uploaded mp3 and mp4 files, with no major problems.
common-pile/stackexchange_filtered
Inserting a variable from a batch file into a text file How would I insert a variable previously established in a batch file into a text file. I have the inserting text into a text file down, i just cant figure out the insertion of a variable. What I am doing SET name = "Casey" ECHO "Hey" + name > file.txt The result "Hey" + name What I want "Hey Casey" You should do it like this: SET name=Casey ECHO "Hey %name%" > file.txt Note that there is no spaces before and after the = in name=Casey did a direct copy paste and it did not work RESULT: "Hey" + "$name" What operating system are you using? This works great on Ubuntu for me. Sorry I mismatch bash and batch. I'll still help you to find the answer. Too bad syntax, you need to forget other programming languages, this is Batch. First you can't use spaces when assing values to variables, this is the way to do it: SET "name=Casey" Also you can do this: SET "name= Casey" Second Batch don't have ANY concatenate operator for strings, forget + and &, & is for concatenating commands. So this is the correct syntax: SET "name=Casey" (ECHO Hey %name%)> "file.txt" Try to use () agrupation operators when Echo a numeric ending string like "MyName 2", to avoid problems in large scripts with Batch redirections.
common-pile/stackexchange_filtered
How to undo flagging? I've erroneously flagged an answer as spam (some anonymous user tried to edit it by seemingly injecting some spam and this confused me), how do I cancel my action? I think you cannot undo a flag, but a single spam flag has no consequences for the flagged post (it takes 6 spam flags to delete). @StefanKohl Thanks! Actually I now discovered in the related column that this is possibly a duplicate. I think I will remove this question. Maybe. -- Though it can also be a useful pointer when closed as a duplicate (and not deleted), I think.
common-pile/stackexchange_filtered
How to use arbitrary text as node name in tikz graph in a simple way? I would like to use tikz graph to draw graphs of function calling relations. But I have trouble with function names from C programming language, where underscore is allowed in a function name. \documentclass{article} \usepackage{tikz} \usetikzlibrary{graphs} \usepackage{shortvrb} \MakeShortVerb{\|} \begin{document} |func_one()| calls |func_two()|: \tikz \graph { "|func_one()|" -> "|func_two()|"; }; \end{document} For the above example, TeX complains Missing $ inserted. } Is there a simple way to let C function name be the name of a tikz graph node without much handling with the function name? In my case, there will be many functions in a calling graph and each name may include multiple underscores. Sigh. Thanks in advance. Welcome to TeX.SX! Try with \_ @CarLaTeX Thanks for your comments. Since many C function names have underscore, to append a backslash to each underscore is heavy for me. I prefer some way like shortvrb or to make shortvrb to work in graph node. OK, I leave the answer to some expert :) You could just use \catcode\_=11 before the picture, or if you are happy to use \scantokens, you could try using a custom typesetter using the key /tikz/graphs/typeset: \documentclass{article} \usepackage{tikz} \usetikzlibrary{graphs} \def\typesetter{{\catcode`\_=11 \ttfamily\expandafter\scantokens\expandafter{\tikzgraphnodetext}}} \begin{document} \tikz\graph [typeset=\typesetter, grow down] { "func_one()" -> "func_two()"; }; \end{document}
common-pile/stackexchange_filtered
Custom short citations style (philosophy-verbose) I need to make a change to a LaTeX template. Specifically, in the \footcite that, after researching, I don't know how to do. This would be as follows: include the short name (not just the surname) in the \footcite. I give you an example. After I have cited a book for the first time, the following times it automatically makes me this style of short citation: Tolkien, The Lord of the Rings, p. 12 But they ask me to also get the letters of the author's name, as in the following example: J. R. Tolkien, The Lord of the Rings, p. 12 The template has a separate document where the styles are. There is a coding for the footer references: \usepackage[ backend=biber, style=philosophy-verbose, isbn=false, giveninits=true, idemtracker=context, ibidtracker=context, loccittracker=context, opcittracker=context, citetracker=context, latinemph=true, commacit=false, scauthors=all, lowscauthors=false annotation=true, classical=true, singletitle=false, editionformat=superscript, shorthandintro=true, %volumeformat=romansc, %library=true, hyperref, %backref, sorting=cst, % if one wants to implement a custom sorting of reference list lowscauthors=false]{biblatex} \addbibresource{biblio.bib} % The filename of the bibliography %\addbibresource{biblio-secondary.bib} % Other bibliography sources \NewBibliographyString{opted} \DefineBibliographyStrings{english}{% %idem = {\textsc{Id}\adddot} idem = {\textsc{Idem}}, ibidem = {Ibid\adddot}, %ibidem = {Ibidem}, %loccit = {}, opcit = {\addcomma\,op\adddot\,cit\adddot,}, %opcit = {}, opcited = {}, } % To put the names of the curators in the majority \renewcommand*{\mkbibnamefamily}[1]{\textsc{#1}} Would anyone know how to do this? It should be enough to redefine the name format labelname to print the name initials. The original definition can be found in philosophy-standard.bbx. We just change the \case switch checking the value of uniquename to a simple \ifnum that only distinguishes whether or not the full name is needed for disambiguation. \documentclass[british]{article} \usepackage[T1]{fontenc} \usepackage{babel} \usepackage{csquotes} \usepackage[ backend=biber, style=philosophy-verbose, isbn=false, giveninits=true, idemtracker=context, ibidtracker=context, loccittracker=context, opcittracker=context, citetracker=context, latinemph=true, commacit=false, scauthors=all, lowscauthors=false, annotation=true, classical=true, singletitle=false, editionformat=superscript, shorthandintro=true, %volumeformat=romansc, %library=true, %backref, % sorting=cst, lowscauthors=false, ]{biblatex} \NewBibliographyString{opted} \DefineBibliographyStrings{english}{% %idem = {\textsc{Id}\adddot} idem = {\textsc{Idem}}, ibidem = {Ibid\adddot}, %ibidem = {Ibidem}, %loccit = {}, opcit = {\addcomma\,op\adddot\,cit\adddot,}, %opcit = {}, %opcited = {}, } \renewcommand*{\mkbibnamefamily}[1]{\textsc{#1}} \DeclareNameFormat{labelname}{% \iftoggle{cbx:scauthorscite}{\usebibmacro{bbx:scswitch}}{}% \iftoggle{cbx:scauthorscitefn}{\iffootnote{\usebibmacro{bbx:scswitch}}{}}{}% \bibhyperref{\nameparts{#1}% \ifnum\value{uniquename}<2 \ifuseprefix {\usebibmacro{name:given-family}% {\namepartfamily}% {\namepartgiveni}% {\namepartprefix}% {\namepartsuffixi}}% {\usebibmacro{name:given-family}% {\namepartfamily}% {\namepartgiveni}% {\namepartprefixi}% {\namepartsuffixi}}% \else \usebibmacro{name:given-family}% {\namepartfamily}% {\namepartgiven}% {\namepartprefix}% {\namepartsuffix}% \fi \usebibmacro{name:andothers}}}% \addbibresource{biblatex-examples.bib} \begin{document} Lorem \autocite{sigfridsson} ipsum \autocite{nussbaum} dolor \autocite{sigfridsson} \printbibliography \end{document} Thank you very much! I already included the code you put in! It worked perfectly! @nrlat If the answer worked for you and resolved your issue, please consider accepting it to show that the question is answered: https://tex.stackexchange.com/help/someone-answers
common-pile/stackexchange_filtered
D3: How can I change data in an existing bar chart I have successfully build my initial bar chart. Now I want to add more bars to that existing chart using transitions to have a nice user experience. Here's my code: var data = [23, 85, 67, 38, 70]; //dummy, normally much more labellist = ['label1','label2','label3','label4','label5']; var w = 815, h = 500, labelpad = 165, x = d3.scale.linear().domain([0, 100]).range([0, w]), y = d3.scale.ordinal().domain(d3.range(data.length)).rangeBands([0, h], .2); mySvg = d3.select("#chart") .append("svg"); vis = mySvg.attr("width", w + 40) .attr("height", h + 20) .append("svg:g") .attr("transform", "translate(20,0)"); bars = vis.selectAll("g.bar") .data(data) .enter().append("svg:g") .attr("class", "bar") .attr("transform", function(d, i) { return "translate(" + labelpad + "," + y(i) + ")"; }) bars.append("svg:rect") .transition() .duration(500) .attr("width", x) .attr("height", y.rangeBand()) ; var rules = vis.selectAll("g.rule") .data(x.ticks(10)) .enter().append("svg:g") .attr("class", "rule") .attr("transform", function(d) { return "translate(" + x(d) + ", 0)"; }); rules.append("svg:line") .attr("y1", h) .attr("y2", h + 6) .attr("x1", labelpad) .attr("x2", labelpad) .attr("stroke", "black"); rules.append("svg:line") .attr("y1", 0) .attr("y2", h) .attr("x1", labelpad) .attr("x2", labelpad) .attr("stroke", "white") .attr("stroke-opacity", .3); How can I programmatically change the data to add and remove other bars and let the existing ones slide up/down? You need to assign some form of key to the bars' data so d3 can identify ones that existed in the previous set. The default is index-based, and that may be what you want. As far as the transitions go, you want to change your code to something like this: bars = vis.selectAll("g.bar") .data(data); bars.enter().append("svg:g") .attr("class", "bar") .append("svg:rect"). bars.transition().duration(500) .attr("transform", function(d, i) { return "translate(" + labelpad + "," + y(i) + ")"; }) .selectAll("svg:rect") .attr("width", x) .attr("height", y.rangeBand()) ; bars.exit().transition().duration(500) .selectAll("svg:rect") .attr("height", 0) .remove(); The "enter()" function is best used to create the structure immediately. Then use the initial selection object (bars) to apply the new data to all elements. You also probably want to remove any obsolete bars. Here I've resized them to 0 and then removed them, but you can tinker with it to get the effect you want. Thanks for your answer, I'm new to d3 - do you know of any tutorial or example showing the use of the keys you mentioned? What would my updateChart() function look like? When I try your code for transitions the chart is not displayed, I get a "Uncaught Error: SYNTAX_ERR: DOM Exception 12" in d3.v2.js at d3_selection(groups) (I already fixed your typo in the second call, period instead of semicolon) I haven't run this code, so there's likely other issues with it. I was just trying to show you the idea of using enter/exit functions for add/remove of elements. This is a good one with bar charts, showing how to nicely add bars: http://mbostock.github.com/d3/tutorial/bar-2.html
common-pile/stackexchange_filtered
Basic LISP Issue So (car '(2 3)) -> 2 (cdr '(2 3)) -> (3) Which function should I use to be able to get something to yield 3? (function-name '(2 3)) -> 3 As posed, the question could also be answered (defun foo (something) (declare (ignore something)) 3). The very best explanation of how lists work internally (and therefor how to use car, cdr, cadr, ... I found in the old but excellent book Common Lisp: A gentle introduction to symbolic computation. http://www.cs.cmu.edu/~dst/LispBook/ It should be fine to simply do: (car (cdr '(2 3))) Which is the same as: (cadr '(2 3)) This works because "car" gets the first element in the expression, whereas cdr returns the remainder of the list, without the first element. You've already shown that "(cdr '(2 3))" returns a list of "(3)". Therefore, the "car" of this is the element (not the list), "3". By the way, the "(cdr (cdr ('2 3)))" is the "(cdr (3))", which is "()". Isn't LISP fun? If you're going to answer his homework for him, you might as well explain why this works. Thank you so much! I don't know how I didn't think of just running car on the single element. No problem. I've added additional explanation for clarification. @Drew: To be clear, it helps to distinguish between running on an element and running on a list, even if that list has only a single element. So when you mention "running car on the single element", you are actually "running car on a list that has a single element in it" (or the single element + the null list, "()", which is always there). Hints: car refers to the first element in the list. cdr refers to the remainder of the list, and is itself a list. So what you need is a function that returns the first element from a list containing the last element. You could also use (second '(2 3)). second is another name for cadr.
common-pile/stackexchange_filtered
Does DIXML for Delphi support unicode in XSTL transformations I need to perform an XSLT transformation of a complex XML file using Delphi, and have found that MSXML is not up to the task. I have found that DIXML for Delphi can perform the transformation, but the sample code that ships with DIXML for Delphi is returning an AnsiString, and certain Unicode characters in the XML file are getting mangled. I have tried modifying the demo code in a number of different ways, but none produce the desired result. Does anyone know of a way to perform an XSLT transformation on a Unicode XML file using DIXML for Delphi that preserves the Unicode characters in the XML? "MSXML is not up to the task" - why not? @kobik, this question is a result of discussion in a previous question on getting MSXML to work in Delphi with (lot's of) imports, where I tried to help but, at least in part, failed. I can assume if that can be fixed, DIXML is not needed. OT: there's at least one way you can workaround this: set the <xsl:output> to encoding="US-ASCII". This will properly escape anything using XML character entities. For a computer this does not matter (the character entity is the same as the actual character octet in an encoding supporting it), but for a human reader this can be less-then ideal. MSXML seems to be unable to handle the several layers of xsl:import elements with relative paths to the import files (there are 3 levels, with 2 imports on the third level, although those files are in the same directory as the file from which they are being imported). When calling TransformNode, MSXML reports that it cannot find a namespace in an import. At least DIXML can parse the XSL files.
common-pile/stackexchange_filtered
Building an app that creates 360 degree panoramic photo Got a request from a client to build a mobile app that has the ability to create a 360 degree panoramic photo (while spherical isnt a necessity, must at least be cylindrical). I am trying to find some mobile frameworks that offer the functionality, but coming up mostly blank. I have found a number of viewers, which is helpful, but no SDK that can actually capture the image. There are apps on the app store that do this, so not sure if they are using a common library or if it was developed in-house. Google Sphere is kinda what Im looking for, but it seems like Google Sphere is limited to be used only within their apps. Is anybody familiar with a framework that I can use for this? Else, can you offer any alternative advice? Thanks! Maybe it's allowed to make it a web service that can be called from the app? The app can send a picture or range of pictures to the web service, and the web service can put the pictures together into a format that can be viewed with a 360 viewer. That way you're not limited to libraries that run on mobile. That could also be a possible solution. But now the question is, are you familiar of any of these web services by any chance? :) Nope. Just trying to broaden your possiblities. :) ah thanks! Good suggestion though, will try do some digging around that space! :)
common-pile/stackexchange_filtered
Check the users position (city, state I was wondering how I can use JavaScript to get a user's location (city or state0 and use the document.write ("") to print out the user's location in the window. The location doesn't need to update if the user is moving somewhere it just needs to print out the current location. By location, I mean the state or city that the user is in. Note: I would not like to use google maps or any map to show the users location, I wish to have the user's location printed out on the screen, not on a map. the problem is, that you can only get the position data (e.g. lat and lon). Check out https://www.w3schools.com/html/html5_geolocation.asp for more information. If you want to print the state and/or city, you need to rely on a service that resolved the position to a state/city. You can set up an own database for that or you use services like google maps. Possibly this might be interesting for you as well: https://geolocation-db.com/
common-pile/stackexchange_filtered
Google Satellite Imagery Offset in QGIS I am using Google Satellite imagery as a base map to capture the vector data in QGIS 3.2.2 for past couple of months. Yesterday i noticed that the google imagery has offset issue in some locations where i have already worked on. Since that location was already captured with reference to the google imagery but now it shows major offset(approx 70 meters) between the vector and google imagery. This location is belongs to California, USA. (-119.17907,34.23393). I have attached the screen shot of the vector location which was captured with reference to the Google imagery(before imagery updates) and this location almost matching with bing imagery but it showing major offset while using recent Google imagery as a base map. I hope this explains well about this issue. I also attached screen shot from the Google Earth Pro and its almost lined up with the vector data as similar to bing imagery. Does google updated their imagery on these locations, if yes then how its possible they update imagery with major offset issue? Does anyone can let me know what is the issue for this and how it will be resolved. Please help me on this. No. Typically, that kind of difference is caused by trying to render the project to a CRS other than EPSG: 3857. Whether to digitize or render, use EPSG: 3857 for your layers and the project, the tiles can not be reprojected on the fly to another system. Then, if you wish, you can export the vector layers to another CRS. Hi, The issues are in some locations (i found in california) and i believe all other locations are matched perfectly with imagery. If i check with that location using bing imagery then the vector data is almost matched perfectly. Honestly, I do not think there's been a change in google images. In any case, it would be necessary to consult them. Disadvantages with displacements of digitalizations made over their images yes, they usually happen and can be due to many reasons. My recommendation is that you edit your question with the most detailed information possible of the procedures so that someone can reproduce the problem, screenshots of your visualizations, and even files with sample data so they can be verified. I have updated the problem with screen shot, hope this helps to understand better. I have attached one more screen shot of the Google Earth Pro and its properly lined up with vector data as similar to bing imagery. The only issues is, there is a major offset while using the Google Satellite Imagery as base map in QGIS. How are you adding the Google Satellite Imagery in QGIS? I am adding Google Satellite imagery in QGIS using this link "http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}" in XYZ Tiles option @GabrielDeLuca I also tried with QGIS and came here... there is a slight shift between Bing and Google imagery with OSM vectors. Google: https://imgur.com/a/EexvMQv Bing: https://imgur.com/E96OHfE @LasithNiroshan, Hi. You can try loading the basemaps from QuickMapServices plugin to see if the problem is in the way of the xyz tiles are being called. If the difference persists, seems to me a problem at Google or Bing side georeferencing their imagery.
common-pile/stackexchange_filtered
Removing spaces from a string using Powershell I have an issue where extracting data from database it sometimes (quite often) adds spaces in between strings of texts that should not be there. What I'm trying to do is create a small script that will look at these strings and remove the spaces. The problem is that the spaces can be in any position in the string, and the string is a variable that changes. Example: "StaffID": "0000 25" <- The space in the number should not be there. Is there a way to have the script look at this particular line, and if it finds spaces, to remove them. Or:"DateOfBirth": "23-10-199 0" <-It would also need to look at these spaces and remove them. The problem is that the same data also has lines such as: "Address": " 91 Broad street" <- The spaces should be here obviously. I've tried using TRIM, but that only removes spaces from start/end. Worth mentioning that the data extracted is in json format and is then imported using API into the new system. for the props that you KNOW you want to remove all spaces, you can use -replace '\s{1,}' to replace 1-or-more spaces with nothing. Possible duplicate of Removing more than one white space in powershell This looks like JSON. A good question, I think, to ask is - where is this 'bad' data coming from? Is it in the original database like this 23-10-199 0? If so, you've got data issues that are VERY complicated to overcome. This may be a "fix your data" answer first. Otherwise, is the extract process causing the problem? It is a JSON. I've gone over the database and its recorder properly in the database i.e. no spaces. Obviously something to do with how its extracted and then formatted, but I cant seem to find the issue, so thought it might be easier to do a script to remove the spaces. Looks like I was wrong.. You should think about the logic of what you want to do, and whether or not it's programmatically possible to determine if you can teach your script where it is or is not appropriate to put spaces. As it is, this is one of the biggest problems facing AI research right now, so unfortunately you're probably going to have to do this by hand. If it were me, I'd specify the kind of data format that I expect from each column, and try my best to attempt to parse those strings. For example, if you know that StaffID doesn't contain spaces, you can have a rule that just deletes them: $staffid = $staffid.replace("\s+",'') There are some more complicated things that you can do with forced formatting (.replace) that have already been covered in this answer, but again, that requires some expectation of exactly what data is going to come out of what column. You might want to look more closely at where those spaces are coming from, rather than process the output like this. Is the retrieval script doing it? Maybe you can optimize the database that you're drawing from? Nowadays, you use: # "some spaces here" -replace (' ') somespaceshere
common-pile/stackexchange_filtered
Persistent CSS problem on Stack Overflow For several days now, I have seen the following rendering problem on questions: This problem seems to be on and off. I am on a Safari browser, using a MacBook Air, and I don't seem to see this on my Android phone, which uses a mobile Chrome browser. I actually posted this a few days ago, but then deleted when reloading the page seemed to make it go away. Yet, it is happening again. I wonder if the underlying problem is the same as that of all the other layout bugs that have been reported in the meantime, albeit mostly around comments, not posts. @BoltClock That would make sense if, for example, the devs at SO recently did a big refactor which introduced some collective CSS bugs. This is fixed in the next build, see Short answers are floating right in Safari 10.1.2 on MSE. Hi Alf, thank you for explaining the cause of this +1.
common-pile/stackexchange_filtered
How should I use BizTalk's Business Rules Engine from a .NET Windows application? We're developing a WPF business application for internal users, but this problem could apply to WinForms easily as well. We want to leverage a business rules engine to make modifying the rules in the future easier as well as to possibly let the business folks to do it themselves at some point. BizTalk (we're using 2010) exposes its Business Rules Engine and, while complex, this looks to be a potentially worthwhile solution especially if we look to using it for future applications as well. We've loaded up a virtual server with the developer edition to try it out, as well as its own SQL Server instance to run off of. Everything I've read (example and example) seems to show adding the BRE assemblies to the application project as references and then using the provided classes to call and execute policies. But they also suggest that these assemblies require a license and we can't exactly license BizTalk for each of the dozens of possible end users that will use this WPF app. Am I wrong about the licensing issue? Is it okay (and normal) to deploy the BRE assemblies with your app to all client machines in order for them to communicate with the BizTalk server where the policies exist? Should I look into exposing the BRE API via a Web Service or something? Are there any implementations out there already for doing that? Exposing the API like that seems like no small undertaking... or is it? Microsoft says that the BRE is only available for server-side usage, e.g., in BizTalk orchestrations, ASP.NET apps, and Windows Services running on a server. The engine cannot be embedded in client applications. From their FAQ on licensing: All technical support and licensing for the BRE is only for server-side solutions. Note that you need to acquire a BizTalk Server 2010 license to utilize the Rules Engine, as the Rules Engine is considered server software requiring a valid processor license. The Rules Engine is not licensed separately from BizTalk Server. Because of that, it may be worthwhile to look at using the BRE from an ASP.NET service that can be called from your WPF clients. If you want the clients to be able to update the rules, that is within the scope of the licensing agreement: the Rules Composer is considered a client tool and may be installed on a separate internal client device to support development and testing of your BRE server solution Be sure to check out Tellago's BRE Data Services API (available on CodePlex). They've done a lot of the work for you if you want to query the rules engine via your own service. I had seen Tellago's code, though I was wondering just how production-ready it really was. We certainly intend only to install BRE and/or BizTalk on a single server and just wanted to interact with the rules and such remotely from our client applications (and NOT to host the entire engine on their machines). So I guess exposing the API via a web service is the typical way to go? I've seen that, at a minimum, we would probably just need to deploy with our WPF applications the Microsoft.RuleEngine.dll assembly. I guess that still falls under the whole BRE package and thus license, huh? if you were to use Tellago's code, then you shouldn't have to embed any of the BizTalk DLLs. They have an example on the page I linked to, showing how to execute a rule using an HTTP POST. Doing that means you should not have to include the Microsoft.RuleEngine.dll on the client. The client just needs to pass in the proper parameters.
common-pile/stackexchange_filtered
Spring CSRF: Ajax giving 403 error even after setting request headers I have set up CSRF authentication using Spring Security 4.0. While using AJAX i am getting 403 error each time. I have set up the request headers. The meta tags: <!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta name="_csrf" th:content="${_csrf.token}"/> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> AJAX looks like this: var token = $("meta[name='_csrf']").attr("th:content"); var header = $("meta[name='_csrf_header']").attr("th:content"); $.ajax({ type : "POST", url : "/PRIT/Home/PopulateVisits", async: false, beforeSend: function(xhr) { if (header && token) { xhr.setRequestHeader(header, token); } }, . . . I can see the request headers in the ajax request : > Accept:*/* Accept-Encoding:gzip, deflate, br > Accept-Language:en-US,en;q=0.9 Cache-Control:no-cache > Connection:keep-alive Content-Length:9 > Content-Type:application/x-www-form-urlencoded; charset=UTF-8 > Cookie:JSESSIONID=C3CAAD64269BD0B96FF35B87053B5899 Host:localhost:8082 > Origin:http://localhost:8082 Pragma:no-cache > Referer:http://localhost:8082/PRIT/Login User-Agent:Mozilla/5.0 > (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) > Chrome/63.0.3239.132 Safari/537.36 > X-CSRF-TOKEN:23c07d26-0494-4588-a158-624791258762 > X-Requested-With:XMLHttpRequest Request URL:http://localhost:8082/PRIT/Home/PopulateVisits Request Method:POST Status Code:403 Remote Address:[::1]:8082 Referrer Policy:no-referrer-when-downgrade I am not sure what's going wrong. The requested controller is never accessed. The controller is like this: @RequestMapping(value = "/Home/PopulateVisits", method = RequestMethod.POST) public @ResponseBody List<DataCollectionForm> PopulateVisits(DataCollectionForm dataCollectionForm, HttpServletRequest request) { I ran into a similar issue, in my case i was invalidating the spring session during login. Make sure you are not invalidating the Spring session anywhere in your controller prior to the request you are trying to access. Spring associates the token with the session, invalidating it would produce a new token.
common-pile/stackexchange_filtered
create a composite from bitmap and video file with FFmpeg or other binary via as3 frontend After receiving much help with reading all the great stackoverflow topics in the past, I finally have to post a question myself. For a client I need to create some sort of video-editor for dummies, which has to generate a video file as output. The editor has to load a movie-file scale and rotate it to a certain degree, and generate a composite video of a background bitmap and the rotated and placed video. The frontend will be done in Flash/AS3 and has to use some background tools for processing the video. Can I use FFmpeg to generate such a composite? Or is there any other good background task available? edit: update 19.12. ... still did not find a solution... any ideas from others? thanks! I don't think ffmpeg is the best tool for compositing. Instead, you could simply have Flash do the compositing, create the frames (as BitmapData objects) and upload them to some server-side script. Then once all the frames have been uploaded, use Flash to call a second script that will build the video using ffmpeg. thanks for the answer. but isnt flash a little low to generate a full-hd movie with bitmapsdata objects?
common-pile/stackexchange_filtered
Should I install these Ubuntu-Mate packages? I'm looking at what Ubuntu Mate 16.04 installed when I installed it a few days ago and I'd like some opinions on some software that was left out. Right now, it appears that I only have mate-desktop-environment-core/xenial,xenial,now 1.12.0+1 all [installed] installed. (Which I'm going to call "M-D-E-C" for the rest of this post). I do not have the following installed: mate-desktop-environment/xenial,xenial 1.12.0+1 all MATE Desktop Environment (metapackage) mate-desktop-environment-extra/xenial,xenial 1.12.0+1 all MATE Desktop Environment (extra components, dummy package) mate-desktop-environment-extras/xenial,xenial 1.12.0+1 all MATE Desktop Environment (extra components, metapackage) ubuntu-mate-desktop/xenial 1.154 amd64 Ubuntu MATE - full desktop Is there any reason I should install any of those other ones? Is M-D-E-C sufficient? What are the pros and cons when it comes to installing those additional packages and/or metapackages? I'm very happy with my set up right now, however I just want to be certain I'm not missing out on anything important/fun/interesting/etc by sticking with M-D-E-C only. Just find out whether they contain anything interesting for you yourself by using the command-line: To read the general package description and the direct dependencies and recommended (automatically installed as well) packages: apt show PACKAGENAME To find out exactly what would happen if you install it (e.g. which other packages will get installed as dependencies): apt install --simulate PACKAGENAME Here are the important parts of the apt show outputs for you: mate-desktop-environment: This package installs the standard set of applications that are part of the official MATE release. . It also suggests a few non-MATE standard desktop applications like an internet browser, a mail reader and a network management applet. It will install the packages atril, desktop-base OR ubuntu-wallpapers, engrampa, eom, ffmpegthumbnailer, galculator, mate-applets, mate-icon-theme-faenza, mate-media, mate-notification-daemon, mate-power-manager, mate-screensaver, mate-system-monitor, mate-themes, mate-user-guide, mate-utils, pluma mate-desktop-environment-extra: Depends: mate-desktop-environment-extras (= 1.12.0+1) [...] This package (mate-desktop-environment-extra) is a dummy package and can be safely removed. So this package's only purpose is to install mate-desktop-environment-extras - it's only an alias name if you want to call it like that. mate-desktop-environment-extras: This package installs an extra set of MATE components that are also part of the official MATE release. It will install the packages blueman, caja-gksu, caja-image-converter, caja-open-terminal, caja-sendto, caja-share, caja-wallpaper, dconf-editor, gnome-keyring, mate-gnome-main-menu-applet, mate-netspeed, mate-sensors-applet, mate-user-share, mozo, yelp ubuntu-mate-desktop: Description: Ubuntu MATE - full desktop This package is the Ubuntu MATE desktop environment. . It is safe to remove this package if some of these packages are not desired. It will install these packages: a11y-profile-manager-indicator account-plugin-facebook account-plugin-flickr account-plugin-google accountsservice acpid alsa-base alsa-utils anacron apport apport-gtk apport-symptoms apturl at-spi2-core atril avahi-autoipd avahi-discover avahi-dnsconfd avahi-utils bc blueman brasero brasero-cdrkit brltty brltty-x11 ca-certificates caja caja-gksu caja-open-terminal caja-sendto caja-wallpaper cheese colord compiz compiz-core compiz-mate compiz-plugins compiz-plugins-default crda cups-browsed cups-core-drivers cups-filters-core-drivers cups-pk-helper cups-ppdc dconf-cli dconf-editor deja-dup deja-dup-backend-cloudfiles deja-dup-backend-gvfs deja-dup-backend-s3 deja-dup-caja dialog dmz-cursor-theme engrampa eom espeak ethtool exfat-fuse exfat-utils ffmpegthumbnailer firefox folder-color-caja fonts-dejavu-core fonts-freefont-ttf fonts-liberation fonts-nanum fonts-noto fonts-noto-cjk fonts-noto-mono fonts-noto-unhinted fonts-opendyslexic foomatic-db-compressed-ppds galculator gdb gdebi gdisk genisoimage ghostscript ghostscript-x gksu gnome-disk-utility gnome-keyring gnome-orca gnome-session-canberra gnome-system-tools grub2-themes-ubuntu-mate gstreamer1.0-alsa gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-pulseaudio gstreamer1.0-tools gstreamer1.0-x gucharmap gufw gvfs gvfs-backends gvfs-fuse hddtemp hexchat hwdata ideviceinstaller ifuse im-config indicator-application-gtk2 indicator-sound-gtk2 inputattach inxi iproute iputils-arping iso-codes iw language-selector-gnome libaacs0 libaccount-plugin-generic-oauth libaccount-plugin-google libavahi-compat-libdnssd1 libbdplus0 libbluray-bdj libbluray-bin libbluray1 libcanberra-gtk-module libcanberra-gtk3-module libcanberra-pulse libdvdnav4 libdvdread4 libegl1-mesa-drivers libfile-mimeinfo-perl libgpod-common libimobiledevice-utils libmtp-runtime libnet-dbus-perl libnotify-bin libp11-kit-gnome-keyring libpam-gnome-keyring libpaper-utils libplist-utils libproxy1-plugin-gsettings libproxy1-plugin-networkmanager libpurple-bin libqt5libqgtk2 libreoffice-avmedia-backend-gstreamer libreoffice-calc libreoffice-gnome libreoffice-impress libreoffice-ogltrans libreoffice-pdfimport libreoffice-style-human libreoffice-writer librsvg2-common libsasl2-modules libtopmenu-client-gtk2-0 libtopmenu-client-gtk3-0 libtopmenu-server-gtk2-0 libtopmenu-server-gtk3-0 libtxc-dxtn-s2tc0 libwmf0.2-7-gtk libx11-protocol-perl lightdm lightdm-gtk-greeter lightdm-gtk-greeter-settings marco mate-accessibility-profiles mate-applet-topmenu mate-applets mate-desktop-environment-core mate-dock-applet mate-gnome-main-menu-applet mate-icon-theme mate-icon-theme-faenza mate-indicator-applet mate-media mate-menu mate-menus mate-netbook mate-netspeed mate-notification-daemon mate-optimus mate-polkit mate-power-manager mate-screensaver mate-sensors-applet mate-settings-daemon mate-system-monitor mate-terminal mate-themes mate-tweak mate-user-guide mate-utils memtest86+ mobile-broadband-provider-info modemmanager mozo network-manager network-manager-gnome network-manager-pptp-gnome ntp onboard onboard-data openprinting-ppds pidgin pidgin-libnotify pidgin-otr pinentry-gtk2 plank pluma plymouth-theme-ubuntu-mate-logo plymouth-theme-ubuntu-mate-text pm-utils ppa-purge printer-driver-gutenprint printer-driver-hpcups printer-driver-pnm2ppa printer-driver-postscript-hp pulseaudio-module-bluetooth pulseaudio-module-x11 pulseaudio-utils python3-aptdaemon python3-aptdaemon.gtk3widgets python3-aptdaemon.pkcompat qt4-qtconfig rfkill rhythmbox rhythmbox-plugin-cdrecorder rhythmbox-plugins rtkit samba-common-bin sane-utils seahorse sessioninstaller shotwell simple-scan smbclient software-properties-gtk speech-dispatcher synapse syslinux-utils system-config-printer-gnome system-config-printer-udev thunderbird tilda tlp tlp-rdw topmenu-gtk-common topmenu-gtk2 topmenu-gtk3 toshset transmission-gtk ubuntu-drivers-common ubuntu-mate-artwork ubuntu-mate-core ubuntu-mate-default-settings ubuntu-mate-libreoffice-draw-icons ubuntu-mate-lightdm-theme ubuntu-mate-welcome ubuntu-release-upgrader-gtk ubuntu-sounds unity-control-center-faces unzip update-manager update-notifier usb-creator-gtk usb-modeswitch usbmuxd vbetool vlc vlc-plugin-notify whoopsie wireless-tools wpasupplicant x11-utils x11-xserver-utils xbitmaps xbrlapi xcursor-themes xdg-user-dirs xdg-user-dirs-gtk xdg-utils xkb-data xorg xserver-xorg xserver-xorg-input-all xserver-xorg-video-all xterm xul-ext-calendar-timezones xul-ext-gdata-provider xul-ext-lightning xul-ext-ubufox xzoom yelp zenity zip
common-pile/stackexchange_filtered
Querying data from firebase using if else I have retrieved data from my firestore storage using this code: class User { bool isActive; String databaseID; String email; User() { this.isActive = ''; this.databaseID = ''; this.email = ''; } toJson() { return { 'isActive': this.isActive, "databaseID": this.databaseID, "email": this.email, " }; } fromJson(Map<String, dynamic> json) { this.isActive = json['isActive']; this.databaseID = json["databaseID"]; this.email = json["email"]; }); } } The data consists of databaseID, email address and isActive method which determines if a user is active or not. This isActive is a boolean value in the database with true and false methods. Now I want to write a query where if isActive is false it should print "User is NOT active" else it should print User is active. I have written this code but it is giving error try { // get isActive if available bool isActive = this.isActive; if (isActive == false) { return false; } else { return true; } } catch (error) { print(error); return null; } } can you please share what error you are getting Invalid reference to 'this' expression how is getIsActive being called? It seems isActive is not in the scope of getIsActive. can you share any simple way? I am actually using previously available code where are you calling getIsActive()? Also this has nothing to do with node or javascript sorry that function is not created. I updated the code. Please check @ajay131 I mean the whole code where is it getting called? In a seperate class? yes outside the user class Change the class to the following: class User { bool isActive; String databaseID; String email; User() { this.isActive = true; this.databaseID = ''; this.email = ''; } toJson() { return { 'isActive': this.isActive, "databaseID": this.databaseID, "email": this.email, }; } fromJson(Map<String, dynamic> json) { this.isActive = json['isActive']; this.databaseID = json["databaseID"]; this.email = json["email"]; } } isActive is of type bool so you should either assign true or false not string. Then to assign isActive to a variable you have to create an instance of class User: User user = new User(); user.isActive = false; bool isActive = user.isActive; Yes. After that how to query based on if else? `if (isActive == false) { return false; } else { return true; }` what are you getting? on this line bool isActive = user.isActive; I am getting "Instance member 'isActive' can't be accessed using static access" can you please share the complete code. I am really having a hard time figuring this out. Let us continue this discussion in chat.
common-pile/stackexchange_filtered
How to use AT commands for switch 2G only Huawei E220 modem Hey everyone I'm new with AT commands, maybe someone can help which command I need to send with minicom to the modem for switching it to 2g gsm mode only? AT Command Interface Specification - Huawei Please state a language and show your code. It is no different than your other question at How to make Huawei E220 modem 2G only Linux
common-pile/stackexchange_filtered
CSS3 Rotate from the left? I'm trying to make kind of a "fold-in" effect for a submenu, but i'm having some issues. See this codepen: http://codepen.io/anon/pen/Lotav As you can see, by default the submenu has a rotation of 90 deg. When a menu item is hovered, the submenu animates to 0 deg, giving it kind of a folding effect. The problem is, when the submenu starts animating (at 90 deg), it's centered within it's width. Even though the submenu has a width of X pixels, when rotated, the width shrinks and it is then centered within the actual width (X). To achieve the wanted effect, the submenu would have to be positioned to the left when rotated. The second issue, which i find really strange, is that although i have set the rotation of the submenu to 90 deg, it doesn't quite appear so. It kind of overlaps a little bit. 90 deg should make it completely vertical (and therefore invisible), or am i missing something? I've only tested the effect in Chrome 24 and Firefox 18. I can't get the 3d effect to work in Firefox, it kind of just shrinks in width, while in chrome you can actually see it rotate. I have the auto-prefix option turned on in the codepen, but i don't know whether it works correctly or not. Here's a demo of the disired effect: http://davidwalsh.name/demo/folding-animation.php The only difference is i want it to "fold in" from the left instead of the top. First issue:change the default transform-origin for the submenu. Use: transform-origin: left; Second issue is caused by perspective: 1000; - if you remove it and add it just on hover you won't have this problem. demo. Transform-origin is exactly what i needed! I do however need the perspective there. Putting it in the hover state is the equivalent of removing it entirely, or it yields the same result at least. In your demo it just looks flat, as if the width is just pushed together. In my demo, with the perspective in the li, you can see it kind of "turn" (it gives it a 3d effect). I figured the perspective had something to do with the overlapping of the rotation, but removing it just messed it up more. Do you see the difference? I managed to fix it, kind of. Using backface-visability i just hid the overlapping part: http://codepen.io/anon/pen/zwcaI
common-pile/stackexchange_filtered
What is impeding current when voltage is stepped up in a transformer? What is physically impeding electric current when a transformer steps up voltage? Is there some EM field along the conductor impeding electron movement? FYI, I'm not asking about losses or leakage. (assuming ideal transformer) I'm trying to get an electromagnetic explanation of how increasing turns on the secondary winding exchanges current for voltage. Thank you. you cannot create power from nothing ... if voltage goes up, then current has to go down and vice versa Do you understand what opposes current when you apply voltage to an inductor? If you say something about how you model that scenario in your mind, we might be able to build on that to explain a transformer. Nothing is 'impeding the current' in a step-up transformer. If you drive a low resistance load on the output, it will draw a large current. The action of a good transformer is to tend to equalise the Ampere.Turns product in the primary and secondary, in an ideal transformer they are equal. The primary of a step-up transformer will have fewer turns than the secondary, so whatever current the secondary is providing, a correspondingly larger current will be drawn by the primary. Ultimately, if you short circuit the secondary, then the current will be limited by the resistance of the windings (both primary and secondary, and connecting leads), the output impedance of the source, and in a non-ideal transformer its leakage reactance (the inability to have an infinite permeability core, or the windings in physically the same space rather than simply close). However, because of the ratio of turns, the secondary current will still be smaller than the primary current by approximately that ratio. The idea of the transformer, not including losses, is that Power out = Power in. Or said another way, Primary power = Secondary power. If you have a simple 2 winding, 2:1 Step Up transformer, and drive the Primary with 100 VAC, then you will measure 200 VAC as the Secondary voltage. Now add a load to the Secondary. Let's make it simple and make it 200 ohms. The Secondary current will be: 200V/200 ohm = 1 amp. Now, what is the primary current? Since the turns ratio is: 2, then the Primary current will be 2.0 amp. Power Pri = Power Sec 100v x 2 amps = 200v x 1 amp = 200 watts The Secondary current is determined by the Secondary voltage and Secondary load. As you increase the the load on the Secondary (lower the resistance) then the current in the Secondary and Primary both increase, and they will always be in the 2:1 ratio. Hope this helps. All the Best.
common-pile/stackexchange_filtered
ES6; Nested Promise.all (Maybe?) The post title may not be entirely accurate as I'm not even sure if my approach to this is the best way. I'll let the community decide. Working with Javascript(ES6), in a React app. Example Data (Original): dataArray = [ {"uid": 3, "region": "bru", "hostname": "bru-002.domain.com", "status": "active"}, {"uid": 1, "region": "bru", "hostname": "bru-001.domain.com", "status": "disabled"}, {"uid": 4, "region": "apc", "hostname": "apc-001.domain.com", "status": "active"} ]; The object key names with-in each array are static. We can assume if there is an object, it will contain the key name 'hostname', etc. Live data will have hundreds of entries for each region and dozens of other object fields (keys). Not really relevant for the code, just FYI. The end goal is to perform a HTTP request for each host and collect the results from the request. That functionality is already written and in use. The brain-breaker I've run into is a CR to separate these calls into 'blocks by region'. In other words, perform all calls for first region and when that is done, THEN initiate calls for next region, etc. The final results of all calls will go into a setState(). The existing code uses Promise instead of async/await. Most of the time I use await, but in some cases I do like the clear code readability that a Promise in conjuction with a .then provides. This is a snippet of current in-use code. It's in an useEffect block.: ... Promise.all( dataArray.map(function(host) { if (host['status'] !== 'disabled') { // pinger() is a function that makes the calls. // Assume it returns what we want. return pinger(host.hostname); } return ''; // Default return to satisfy map function })) .then(result => { setPingedData(result); // Using a React set State } ); ... The above code works, but en masse. To separate it out, I started by creating a new object that ends up looking like this: sortedByRegionObj = { "bru": [{"uid": 3, "hostname": "bru-002.domain.com", "status": "active"}, {"uid": 1, "hostname": "bru-001.domain.com", "status": "disabled"}], "apc": [{"uid": 4, "hostname": "apc-001.domain.com", "status": "active"}] }; The top level object key names represent 'region groups'. The region names will be dynamic. We can only assume if there is a region, the value of that region will be an array of 1 or more objects. The arrays represent how we want to group the HTTP calls. The array would be one group of Promises. And the idea was to walk through the object using something like: for (const regionArray of Object.values(sortedByRegionObj)) { Promise.all( regionArray.map(function(host) { ... (The above code is not valid- just depicting the general idea) and create Promise arrays and then use Promise.all... but then I got lost. The part that stumped me was having a dynamic number of objects when trying to create an array for Promise.all... I can't wrap my head around how to do this. Thoughts? So have you got a function to create the separated-by-region-name object by taking in the "en masse" array of objects? "The part that stumped me was having a dynamic number of objects when trying to create an array for Promise.all" - but you already did that just fine? Your working code handles a dataArray with a dynamic number of objects, and so does the new code with the regionArray. To "perform all calls for first region and when that is done, THEN initiate calls for next region", use an await in a loop. Doing that with promises is possible but much uglier. I'd use Array.filter instead of map, you might get some undefined elements in your mapped array. The above code is not valid- just depicting the general idea -- I think you're wrong in this. The code you wrote is the answer to your question except you've forgotten to await the Promise.all -- for (.....) { let regionData = await Promise.all(..... You've basically answered your own question in the qustion itself without realising it. You're stumped because you forgot the await may be something like this: const dataArray = [ { uid: 3, region: "bru", hostname: "bru-003.domain.com", status: "active" }, { uid: 3, region: "bru", hostname: "bru-002.domain.com", status: "active" }, { uid: 1, region: "bru", hostname: "bru-001.domain.com", status: "disabled" }, { uid: 4, region: "apc", hostname: "apc-001.domain.com", status: "active" }, ]; const pingHosts = async (data) => { const regions = new Set(data.map((d) => d.region)); const results = {}; for (const region of regions) { results[region] = await Promise.all( data .filter((d) => d.status !== "disabled" && d.region === region) .map((host) => pinger(host.hostname)), ); } return results; }; // simulate network request const pinger = (hostname) => new Promise((resolve) => { setTimeout(() => { console.log(`pinger: ${hostname}`); resolve(`pinger: ${hostname}`); }, 500); }) console.log('results: ', await pingHosts(dataArray)); demo: https://livecodes.io/?x=id/mndyfu329vr&console=open
common-pile/stackexchange_filtered
Multiple loops logic and speed optimization in Python? Here is two python functions to transfer data from one file to another file. Both source file and target file have the same number of objects but with different data. def getBlock(rigObj, objName): rigObj.seek(0) Tag = False block = "" for line in rigObj: if line.find("ObjectAlias " + str(objName) + "\n") != -1: for line in rigObj: if line.find("BeginKeyframe") != -1: Tag = True elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"): Tag = False break elif Tag: block += line return (block) def buildScene(sceneObj, rigObj, objList): sceneObj.seek(0) rigObj.seek(0) newscene = "" for line in sceneObj: newscene += line for obj in objList: if line.find("ObjectAlias " + obj + "\n") != -1: Tag = True for line in sceneObj: if line.find("BeginKeyframe") != -1: newscene += line newscene += getBlock(rigObj, obj) Tag = False elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"): newscene += line Tag = True break elif Tag: newscene += line return (newscene) getBlock is a sub-function for getting data from rigobj; buildScene is my main function, it has three parameters: First parameter(sceneobj) is the file that I want to put data into; Second parameter(rigobj) is the file that I get the data from; Third parameter(objlist) is a list of what object's data to be transfered. So far, the function does its job, the only problem is a bit of slow(sceneobj<10MB, rigobj<2MB, objlist<10 objects), I am not sure if there are a logic problem in the code, should I loop the sceneObj first or loop the objList first? Does it affect the speed? UPDATE: Both sceneObj and rigObj have similar data like this: lines BeginObject lines ObjectAlias xxx #--> object in transfer list lines BeginKeyframe 10 12 -9.000 4095 default #--> transfer begins lines #--> transfer from rigObj to sceneObj and override lines in sceneObj -8.000 63 default #--> same lines #--> same -7.000 63 default #--> same lines #--> same -1.000 63 default #--> same lines #--> transfer ends 0.000 -1 default lines EndKeyframe EndMotion lines EndObject The data want to be transfered and overrided is only lines bewteen BeginKeyframe and 0.000 -1 default of any specified objects(by objList) Can you add profiler result, and example of input data? @Arnial updated my post Is it possible that rigObj has same ObjectAlias multiple times but with different data? @Arnial I am not quite sure what you mean. But the sceneObj consist of rigObj with more extra data, so each object exist in rigObj should be existed in sceneObj. Most obvious optimization is to index data for getBlock function, so you will able to seek to needed position instead of always parsing full file from beginning. like so: def create_rig_index(rig_obj): """ This function creates dict of offsets for specific ObjectAlias Example: data: line with offset 100: ObjectAlias xxx more lines line with offset 200: ObjectAlias yyy more lines line with offset 300: ObjectAlias xxx more lines result will be: xxx: [100, 300] yyy: [200] """ idx = defaultdict( list ) position = 0 for line in rig_obj: strip_line = line.strip() if strip_line.startswith( "ObjectAlias" ): obj_name = strip_line.split()[1] idx[ obj_name ].append( position ) # unfortunately python prevent `tell` calls during iteration. position += len( bytes( line, 'utf-8' ) ) # if data guaranteed to be ascii only its possible to use len( line ) # or you can write custom line generator on top of read function. return idx; def getBlock(rigObj, rigIdx, objName): """ same as your getBlock, but uses precalculated offsets""" block = "" for idx in rigIdx[ objName ]: rigObj.seek( idx ) Tag = False for line in rigObj: if line.find("BeginKeyframe") != -1: Tag = True elif line.lstrip().startswith("0.000 ") and line.rstrip().endswith("default"): break elif Tag: block += line return (block) In buildScene method you should create rig_index before running for loop, and use this index in getBlock function. Thanks for help. From what you mean, my code didn't has any logic problem, and the most time-waste part is getBlock searching(I totally agree about this), right? I have an question about if line.find("ObjectAlias " + obj + "\n") != -1: in buildScene, if a line don't not start with ObjectAlias, will the code still interate in for obj in objList? Yes it will iterate over objList even if line don't start with "ObjectAlias". Also you can use "ObjectAlias " + obj + "\n" in line instead of line.find("ObjectAlias" + obj + "\n") != -1. Python docs asks to not use in operator instead of find. Thanks for suggestions. So if I add a line something like if line.startswith("ObjectAlias "): before for obj in objList:, will it help to speed-up a bit? Thanks, I am quite new to programming, I have to spend some time to figure out your code, hopefully it will speed up.
common-pile/stackexchange_filtered
Community approved my suggested Edit Clicking on Community, you'll find: Hi, I'm not really a person. I'm a background process that helps keep this site clean! I do things like Randomly poke old unanswered questions every hour so they get some attention Own community questions and answers so nobody gets unnecessary reputation from them Own downvotes on spam/evil posts that get permanently deleted Own suggested edits from anonymous users But now he approved one of my edits. How can that be? What else does "he" (or "she"?) do, that is not in the list? He/she also rejects edits, votes and has Badges in Area51...strange... Good question! :) related It seems that when somebody who reviews the edit presses "Improve" instead of "Accept" or "Reject", the edit gets recorded as being approved by Community instead of the actual reviewer. (This is arguably a bug, I think). Note that in the edit history, your suggested edit shows up with the same timestamp (down to the second, as can be seen by mousing over the human-friendly "$n$ hours ago") as Arturo's subsequent edit, strongly suggesting that he was the approver. I think rejects by Community was recently explained as happening when somebody else edits the post before the suggested edit had a chance to be acted on. More technically, the explanation as far as I understand is that Community is even more not-really-a-user than its profile text seems to suggest -- it is just the string that the software displays when the "responsible user" column in its database has not been filled in. So it's not a matter of Community deliberately doing this-or-that; it's just that the programmer who coded the feature didn't bother to give credit to someone else. The "rejects" can also be because someone chose to "Improve" the suggested edit, but decides that the original edit was not helpful by unticking the box that says "suggested edit was helpful".
common-pile/stackexchange_filtered
How to configure partials and layouts for Handlebars in Sails.js? I run Sails 0.9.7 and have installed Handlebars which is supported by Consolidate.js and therefore is supported by Sails I can serve pages from .handlebars files, it works just fine. I can't figure where, in Sails workflow, and in a Sails way, I should register partials, helpers etc... I'm more looking for best practices than just a working solution but any help will be appreciated. I'm having the same issue. I've tried making views/partials/ and putting them there, I've tried in views/ and in views// and even views//partials/ :-( I don't think Sails' going to pick these up automatically. The comments are clear Layout support is only implemented for the ejs view engine! For most other engines, it is not necessary, since they implement partials/layouts themselves it just doesn't say how/where it should be done. I don't know if I'm ready to give up on it. Underneath, it's just express, right? I've used other template engines with Express after a little tweaking. Here's what I'm trying to do with Sails: http://www.bearfruit.org/2013/08/22/a-better-template-engine-for-express-apps/ I'm running v0.10 beta but this shouldn't affect how I got it working below: Engine should be handlebars as expected Routes need to explicitly define controller and action. Setting view won't work. (Unless there's a way I couldn't figure out of setting the partials in the routes file) Controller needs partials defined as paths relative to the view. config/views.js module.exports.views = { engine : 'handlebars', layout : false }; config/routes.js '/': { controller: 'site', action: 'index' }, SiteController.js module.exports = { // Render Index View index: function(req, res) { res.view({ partials: { head: 'partials/head', tail: '../partials/tail', }, }); } }; views/site/index.handlebars {{> head}} <h3>SITE INDEX</h3> views/site/partials/head.handlebars <h1>HEAD</h1> {{> tail}} views/partials/tail.handlebars <h2>HEAD TAIL</h2> OUTPUT <h1>HEAD</h1> <h2>HEAD TAIL</h2> <h3>SITE INDEX</h3> Yes, so it's basically the same as @christopher-pappas answer or did I misunderstood something ? Thanks for your detailed answer. His answer is incomplete - You have to explicitly set the controller and action in the route definition - it's the only way I could get it to work - but i've since moved on to nunjucks for template inheritance Ok, I guess it's as far as I can go with raw sails, then I would need to write some sort of policie or plugin to only declare a partials folder, and have the partials option be filled automatically with all the partials I have put in my partials folder. Thanks for your complete answer. @JeremieParker I got around this issue by storing all my partials as an object literal in config/views.js, and then using underscore to clone that object whenever I render a new view: res.view({ partials: _.clone(sails.config.views.partials) }); Still no luck in figuring out how to integrate helpers, so if anyone knows that, please share. I use nunjucks also. what would I need to change to get nunjucks to work? I'm using the answers given above, but I seem to have made partials work with sails 0.9.8 with no hacks. Here's what I have. Config/views.js => engine: "handlebars" views/home/index.handlebars => main file using the partial. views/home/partials/partial.handlebars => partial being used. Then as long as you use something like this, it works perfectly. res.view({ partials: { partial: 'partials/partial', footer: 'partials/footer' } }) The paths are relative to the template file called by default. So if you want different partials per controller you use partials/ and if you want global partials for all templates you use ../partials/ Obviously this is completely unto you as you need to specify every partial manually in the controller anyway. Yes, I've figured that out too, but I was more looking for a way to call partials from the template itself, {{> partial }}. Thanks for your help. so following the above - im passing {partials: {header: 'partials/header'}} and calling the partial {{> header}}. I'm given the following error message: verbose: Running res.view([object Object]) method... error: Error rendering view at :: error: Using layout located at :: error: Server Error (500) error: Error: The partial header could not be found Where is partial actually saved? The folder partials should be in the same place as the template, and it should have a file inside called header.handlebars does that work? And Jeremy, I guess you want a way to be able to import partials from within the template, so you can use {{> path to partial}} I would love a solution like that but Handlebars seems to be coded in a way that it needs all partials to be registered, sadly. there's a module called mmm on npm that is the same as mustache, and automatically finds partials by pathname. I've used it with express before. It doesn't have the extra handlebar features, but its usually good enough. Edit: This was fairly easy to implement via the express3-handlebars module while changing none of the default Sails functionality with the exception of asking you to move your layout file into views/layouts. I've opened up a pull-request here (https://github.com/balderdashy/sails/pull/1075) if you would like to check it out. After a bit of digging in the sails source-code, it's fairly easy to bring in partials when you render your view. When you call res.view in your controller actions, just pass in a partials object as part of your "locals" which contains a list of partials you'd like rendered. // LoginController.js new: function (req, res) { res.view({ partials: { header: '../partials/header', footer: '../partials/footer' } }) } // new.handlebars {{> header}} <b>Main content</b> {{> footer}} Helpers can be registered in a similar way, by attaching a key named helpers and passing in the functionality. It would be nice if there was a more formalized way to do this in the Sails core, but for now this should suffice for those who want to use handlebars instead of ejs while preserving some semblance of layouts. To be clear, if your pull request gets merged, I'll be happy to accept your answer, otherwise, hacking sails core is kind of a no-go right now considering we'd like to be able to update Sails (to leverage coming functionalities such as transaction) without having to patch every time. In the mean time I've upvoted your answer since its actually close to what I'm looking for but not as reusable as I would like it to be. Agreed. The more comfortable I get with sails the more I'm hacking the core to achieve what I need. Its unfortunate, but then again the framework is new. Just trying to point a way ;) This did not work for me. Using absolute paths and relative paths failed. Where exactly should the partials folder live? Is the .. relative to the parent view? Should it live in views/partials? It should live in views/partials. But keep in mind that sails 0.10 is significantly different and so I would avoid the above; I tried refactoring it but it seems like sails.js decided to leave a hard .ejs dependency in favor of a plugin-like architecture (that has yet to be written / documented) Yeah I've mostly given up on this. I figured if I need partials - I can register them using hbs.registerPartial(); but its a single page app that doesn't need server side rendering aside from the wrapping head and body markup. Thanks for responding. FYI, If you're using Sails 0.10 or above, I have published an NPM package to generate default handlebars views at https://www.npmjs.org/package/sails-generate-views-handlebars There is also a proposed PR for sails-generate-backend in order to properly support layouts and partials for handlebar when using ‘sails generate –template==handlebars’ with no additional code and automatic discovery of partials based on a path (aka. views/partial/**) See: https://github.com/balderdashy/sails-generate-backend/pull/9 I'm running out of time but I'm getting close to an answer, I think. I'll update this reply when I get more details, but if you want to poke at it, check out line 501 in the included consolidate.js file. View on github here: https://github.com/balderdashy/sails/blob/master/lib/configuration/consolidate.js#L501 It looks like for Handlebars there is a for loop that registers partials from options.partials. That is not exactly a very satisfying solution, but if you push your partials on to that options object then maybe it will pull from that. The big question I have next is, what is the options object, and where does it get set at? The options object is the read from the locals variable passed in from your view controller. See answer above. For configuring handlebars template in sails js , follow below steps: 1) install handlebars in your application's node_modules folder: npm install handlebars 2) change your config/views.js engine: 'handlebars', layout: 'layouts/layout', // layouts is subfolder of view folder in sails app and layout is a handlebars inside layouts folder. partials: 'partials' Sails supports handlebars and its (multiple-layout, partials) natively, if we use .handlebars extensions for our files instead of .hbs. So to use handlebars in Sails instead of EJS, it advised to use consolidate(Its a template engine consolation library). Handlebars works good with SailsJs + consolidate. You need to install consolidate. npm install consolidate --save And then you just have to update the config/views.js file with the following content. module.exports.views = { engine: { ext: 'handlebars', fn: require("consolidate").handlebars }, layout: 'layouts/layout', partials: 'partials/' }; Update all your .ebs files to .handlebar files and update the code inside it. Everything will work fine. There is a view-generator, for the later purpose which will generate default views for Sails(It will make a default directory structure with default files in it). You can find it in the github repository.(https://github.com/bhaskarmelkani/sails-generate-views-hbs) It is similar to the one officially launched by SailsJs for jade called balderdashy/sails-generate-views-jade.
common-pile/stackexchange_filtered
How to test macOS afctl (the built-in adaptive firewall)? Setting up macOS afctl (the adaptive firewall) on a 10.12 server. We had problems with this on a 10.11 server, and numerous online discussions reported that the thing just didn't work as advertised on 10.10 and 10.11. So I'm kicking the tires on 10.12. (Yes, we're aware that 10.13 is out; we've decided to let the rest of you be the guinea pigs for the next while.) I've got the thing working for manually-added IP addresses, but I need to trigger the afctl rules with bad logins to make sure that new malefactors are added. I'm not sure how to do this. I just tried deliberately screwing up an ssh login a few times, but it didn't block my IP. So I'm thinking of scripting an ssh attack, or maybe ping flooding the server (later tonight, when no one will mind if it slows down the office network a tad). Any thoughts on how I can do this? And yes, this will be for whitehat purposes only.
common-pile/stackexchange_filtered
Cell array text manipulation I need to keep only the elements after the nth place in a cell array. Example: cell_in = {'test string no (1)'; 'test string no (2)'; 'test string no (3)'} and I need to get this result: cell_out = {'no (1)'; 'no (2)'; 'no (3)'} I have tried the following which failed: cell_out = cell_in{:}(13:end) Is there a way to sort this out, perhaps using cellfun? Welcome to Stack Overflow! You can't directly apply an index to all cells' contents. A way to achieve that you want is to use cellfun to apply the desired indexing to all cells' contents via an anonymous function: cell_out = cellfun(@(c) c(13:end), cell_in, 'UniformOutput', false); That's precisely what I was looking for, thank you very much Luis!
common-pile/stackexchange_filtered
403 Forbidden Error When Attempting to Log In to Amazon ECR Public Using AWS CLI I’m trying to log in to Amazon ECR Public to push Docker images from the AWS CLI on an EC2 instance (Ohio region, us-east-2). I've configured my credentials with full access to ECR and followed the necessary steps to log in to the public ECR registry. When I run the following command: aws ecr get-login-password --region us-east-2 | docker login --username AWS --password-stdin public.ecr.aws/g0n5y2m3 I get this error: Error response from daemon: login attempt to https://public.ecr.aws/v2/ failed with status: 403 Forbidden aws-cli/1.18.69 Verified that my credentials are properly set up in ~/.aws/credentials. Confirmed that my IAM user has both AmazonEC2ContainerRegistryFullAccess and AmazonElasticContainerRegistryPublicFullAccess policies attached. Ensured that I am in the correct region (us-east-2). What could be causing this 403 Forbidden error when trying to log in to a public ECR repository? Is there anything additional I need to configure to access ECR Public from the CLI? Try aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws. ("When authenticating to a public registry, always authenticate to the us-east-1 Region when using the AWS CLI.") More details here: https://docs.aws.amazon.com/AmazonECR/latest/public/public-registry-auth.html The --region parameter in aws ecr get-login-password isn’t necessary for public ECR in most cases. You might try without it: aws ecr-public get-login-password | docker login --username AWS --password-stdin public.ecr.aws also, You mentioned using aws-cli/1.18.69, which is an older version. Public ECR support and certain features require at least AWS CLI version 2.x.
common-pile/stackexchange_filtered
Converting PostgreSql timestamp query to MS SQL/Azure SQL I'm currently in the process of converting some basic sql scripts from Postgresql to Azure Sql. I'm newbie to sql, but I really can't understand epoch/unix time in Azure SQL / SQL Server. My application is using bigint epoch time as event timestamp and I want to make a housekeep script for the database and for the table where events are stored. How do you work with epoch time intervals in MS or Azure SQL? What would be the equivalent in Azure SQL to the following query? SELECT count(*) FROM info_event WHERE event_time < (SELECT cast(EXTRACT(epoch FROM current_timestamp - INTERVAL '1 MONTH') AS bigint) * 1000); There are plenty of examples of how to convert a date and time value to a epoch here; what were wrong with those examples? What didn't you understand about them or why don't they work for your scenario? I can't understand how to work with epoch time interval in MSSQL The solution was. SELECT * FROM table WHERE epoch_column < (SELECT cast(DATEDIFF(second,'1970-01-01 00:00:00',(DATEADD(month,-1,GETDATE())))AS bigint)* 1000 ); Thanks for the help!
common-pile/stackexchange_filtered
Adding junk character in currency symbol while exporting data to CSV I am getting strange Issue that whenever I am exporting the data in csv which have a currency symbol, It has added junk extra character in the data beside the currency symbol. For example if My data = France - Admin Fee 1 x £100 I am getting the result like = France - Admin Fee 1 x £100 when i open this in Excel. My code is : <html> <head> <script type="text/javascript"> function CreateCSV() { var buffer = "France - Admin Fee 1 x £100"; buffer = "\"" + buffer + "\""; // buffer = "" + euro; //"\u2034"; var uri = "data:text/csv;charset=UTF," + encodeURIComponent(buffer); var fileName = "InvoiceData.csv"; var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute link.setAttribute("href", uri); link.setAttribute("download", fileName); } else if (navigator.msSaveBlob) { // IE 10+ link.addEventListener("click", function (event) { var blob = new Blob([buffer], { "type": "data:text/csv;charset=UTF;" }); navigator.msSaveBlob(blob, fileName); }, false); } else { // it needs to implement server side export } link.innerHTML = "Export to CSV"; link.click(); } </script> </head> <body> <input type="button" value="Download CSV" onclick="CreateCSV()" /> </body> </html> When i open the same in notepad. I cannot see the junk character. I am very thankful if you can get me a work around. The character set should probably be UTF-8. Also check the unicode for the £, I do believe it is u2034. You can find a chart here, and it lists it as U+00A3. If you have something more advanced than just Notepad, like Notepad++ for example, check the encoding type when you open the time. Excel can be finicky. yes it is UTF-8. but can you please tell what should i need to edit to resolve this issue in above code. So I ran the snippet and opened it in Notepad++, which immediately showed the issue. The encoding is UTF-8 without Byte Order Mark (BOM), there's another post about it here. You need to prepend the buffer string with \ufeff so it would look like this: buffer = "\ufeff\"" + buffer + "\""; I have tried with above way but still have a same issue.
common-pile/stackexchange_filtered
Rails CanCan only show data that user created I am using Devise for registering accounts and signing in/out. The next functionality I want to add is to only show the data entered for a given user. For instance, if I create a new "something" (a client in my case, at /clients/new), I only want the person who created that something to be able to view it. Right now, if I log in and create a new client, then log out and back in as a different user, I'm able to see the client I created as the other user. This should be restricted so that the author is the only one who can read, update and destroy their own clients. I've watched Ryan Bate's screencast on CanCan 3 times now, but it seems to only touch on setting it up for different roles, and not for limiting content based on the author. How can I go about this with CanCan? My current ability.rb has nothing in it but an empty initialize(user) method. I have tried this inside that method: can :update, Client do |client| client.try(:user) == user end with <% if can? :update, @client %> ... <% end %> around the loop that displays the clients in the index view, but to no avail. I think you want to reference current_user there I think that filtering the results using CanCan is not an optimal solution. If User 'has_many' Clients, then in your controller method just query for Users' clients: @clients = current_user.clients Duh, I knew it shouldn't have been that complicated. Got it working using your method. Building off of my question about authentication, what would prevent a user from going to say /clients/6 and viewing and editing (or even deleting) the client that a different user created? Is that where CanCan comes in? Or does Devise have that capability as well? Give this a try def initialize(user) can :update, Client, :user_id => user.id end From cancan wiki
common-pile/stackexchange_filtered
Rails 4.2 ActiveJob: Every adapter results in PhusionPassenger error: Could not find [gem] in any of the sources (Bundler::GemNotFound) I'm trying to implement asynchronous email processing with Rails 4.2's ActiveJob API. So far I've tried using two of the supported adapters: Sucker Punch and Delayed Job, and I get the same problem with each. Things seem to work correctly in development. However, after deploying to the staging server and trying to load the website in my browser, I get the purple PhusionPassenger error screen with this error: Could not find delayed_job-4.0.6 in any of the sources (Bundler::GemNotFound) The above is for when I tried Delayed Job. My gem setup looks like this: # Gemfile gem 'delayed_job_active_record' # Gemfile.lock delayed_job (4.0.6) activesupport (>= 3.0, < 5.0) delayed_job_active_record (4.0.3) activerecord (>= 3.0, < 5.0) delayed_job (>= 3.0, < 4.1) When I tried Sucker Punch, the PhusionPassenger error was the same except the gem that supposedly couldn't be found in any sources was hitimes, which is a dependency of celluloid, which is itself a dependency of sucker_punch. I initially thought the problem was with Sucker Punch. After installing the Hitimes gem on my staging server and still getting the error, I decided to switch to Delayed Job, and now I'm getting pretty much the same problem, so I'm guessing there's some more low-level problem but I am not sure what it could be. I've also tried updating bundler on the staging server, but no dice. Thanks in advance for any help! EDIT I did some more poking around on the Delayed Job github and found this command RAILS_ENV=production bin/delayed_job restart. When I tried to run RAILS_ENV=staging bin/delayed_job restart on my staging server I was alerted to the absence of a delayed_job binstub in my bin/ directory. Looking back at my local development environment, I do see that bin/delayed_job exists and can run bin/delayed_job restart successfully. Could this lack of a binstub in staging be contributing to the problem? If so, why wouldn't that binstub have been created correctly? I am pretty sure that my capistrano deploy process uses bundle exec bundle install --binstubs. EDIT 2 Through some steps outlined below I was able to get delayed_job to appear in my bin/ in staging. I also tried adding the "daemons" gem per a suggestion on the Delayed Job GitHub, but still getting the same error, now about "daemons" rather than "delayed_job" itself. Are you sure that passenger is using the correct ruby? I'm not sure. Unfortunately I also don't (currently) have the sysadmin knowledge to check which ruby passenger is using or change it. However, I can say that my base rails4 branch with no activejob adapter deploys and runs fine on the staging server. Also, I'm going to add some more information that I've gleaned related to binstubs that may or may not be helpful no, but I do use rbenv Do you have multiple ruby versions? Your app runs in a other version different of the default.? the only ruby that is installed by rbenv is 2.2.0. so there's that and 'system' How aré you using pssenger? Stand alone or with apache? I'm using it with nginx. So, you start passenger with passenger start? It turns out the problem was not with ActiveJob adapters, but with any gem that I tried to install and use in staging after doing the Rails 4 upgrade. I had installed rbenv on the staging server and added 2.2.0 as the global ruby, but Passenger was still looking for gems associated with the system ruby (1.9.3). It could well be the absence of your binstub, which can be fixed: There was an 'issue' with capistrano-bundler, in that it would try to generate its own bin stubs, rather than taking them from the committed git repo. This has since been fixed, but can be seen in this issue: https://github.com/capistrano/bundler/issues/45 You can force the committed binstub to be used by removing bin from your linked dirs so: set :linked_dirs, fetch(:linked_dirs, []).push('bin', 'log', 'tmp/pids', 'tmp/cache' ... becomes: set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache' ... and also setting set :bundle_binstubs, nil Or upgrading your cap-bundler gem. I think I'm following you but am still not quite there. I upgrade capistrano-bundler to 1.1.4, redeployed, still don't have bin/delayed_job. Then I ran bundler binstubs delayed_job and got "There are no executables for the gem delayed_job." Do I still need to do everything you listed above? Also, I found the same issue here: http://stackoverflow.com/questions/22659507/bundler-with-capistrano-doesnt-generate-a-binary-for-delayedjob. One person added the "daemons" gem and another did ore or less what you've listed above. If the above works, though, and was added in the PR you linked too, not sure why I'm still having the prob after upgrading I tried adding daemons and now i'm just getting "Could not find daemons-1.1.9 in any of the sources (Bundler::GemNotFound)" as my PhusionPasseneger error
common-pile/stackexchange_filtered
Subscribing on topic. MQTT I have the following part of code: package com.company; import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import javax.security.auth.callback.Callback; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main implements MqttCallback { private static String sTopic; private static int iQos; private static MqttClient mqttClient; private static String sUsername; private static Frame frame = new Frame(); public static void main(String[] args) throws MqttException { frame.getConnect().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int iPort; String sIp = frame.getBrokerAddressValue(); sUsername = frame.getUsernameValue(); try { String broker = "tcp://"; //bridge and host iPort = frame.getPortValue(); broker+=sIp+":"+iPort; mqttClient = new MqttClient(broker, sUsername, new MemoryPersistence()); //URI, ClientId, Persistence MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(true); System.out.println("Connecting to broker: "+broker); mqttClient.connect(); System.out.println("Connected"); }catch (NumberFormatException exc){ System.out.println("Wrong port format"); } catch (MqttException e1) { e1.printStackTrace(); } } }); frame.getSubscribe().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sTopic = frame.getTopicValue(); try { mqttClient.subscribe(sTopic); } catch (MqttException e1) { e1.printStackTrace(); } System.out.println("Subscribed"); } }); frame.getPublish().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String sMessage = frame.getMessageValue(); MqttMessage message = new MqttMessage(sMessage.getBytes()); iQos = frame.getQosValue(); message.setQos(iQos); try { mqttClient.publish(sTopic,message); } catch (MqttException e1) { e1.printStackTrace(); } System.out.println("Message published"); } }); } @Override public void connectionLost(Throwable throwable) { } @Override public void messageArrived(String topic, MqttMessage message) throws Exception{ frame.getTextArea().setText(String.valueOf(message)); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } } Here's a part of my realization of the mqtt client. Method getConnect is processing a click on button 'Connect', method getSubscribe is processesing a click on button 'Subscribe', method getPublish is processing a click on button 'Publish'.The problem is the following: when I subscribe on the topic, messages don't arrive on the clients, which are subscribed on this topic. What's the matter? subscribing is not the same as publishing.... @ΦXocę웃Пepeúpaツ,yes,I know. I have two methods: one for publishing and one for subscribing If I understand your question correctly,You are subscribed to a topic 'sTopic' but you are not receiving messages when some one publish message to the topic 'sTopic'. Are you sure Mqtt client is connected successfully to broker ? Make mqtt client is connected before making subscribe call. if( mqttClient.isConnected()) { mqttClient.subscribe(sTopic); } and same applies for publish also. if( mqttClient.isConnected()) { mqttClient.publish(sTopic,message); } Once if these call goes, you should see published messages in messageArrived call back method. You need to set the callback method to mqttClient clientCallback = new MqttCallback() { @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }; mqttClient.setCallback(clientCallback); Yes, you understood me right. I used in debugger and yes, client is connected in all cases. I probably think that there's the problem in publish method. I saw some examples of clients and there is the same line in all of them: client.setCallback(this); But I don't know how to add it to my project, as arguement 'this' is always underlined and writes that setCallback (org.eclipse.paho.client.mqttv3.MqttCallback) in MqttClient cannot be applied to (anonymous java.awt.event.ActionListener) yes, now it works, thanks. So, as I understand, there's no need in connectionLost, messageArrived and deliveryComplete methods in the end of the class?
common-pile/stackexchange_filtered
Program to switch active window/program? I'm interested in program that can utilize additional buttons of G15, or can be bound to special hotkey like ctrl+alt+shift+F9 in order to change active window. Why do i need it? I'm playing game EVE-Online in 2 windows. And using alt+tab sometimes fails to winamp/vlc/any 3rd part program. Frequency of alt-tabbing: every 3-5 minutes. And what i want: Dedicated program to choose "new" active program, like switch-app.exe /setActive:'EVE-Online - CharName1' or switch-app.exe /setActive:'EVE-Online - CharName2' And i'll be able to use G15 config tool to bind this commands to G-keys. Dedicated program which have same functionality, but with hotkey-bind system in it. Any suggestions? Solution found: http://www.commandline.co.uk/cmdow/ Command line tool to manipulate windows + G15 Profiler = Exactly what i want :) please post it as an answer.. Solution found: http://commandline.co.uk/cmdow Command line tool to manipulate windows + G15 Profiler = Exactly what i want :)
common-pile/stackexchange_filtered
How to make a rule return all details of a fact using Prolog Using Prolog, I first created two facts called grade and food: The first fact is grade(X,Y) where X is the student (rob or matt) and Y is the grade level (freshman or sophomore). The second fact is food(X,Y) where X is the student (rob or matt) and Y is the food (pizza, burger, pasta, wrap). I created a rule called preference(X,Y), where X is the student (rob or matt) and Y is the students' preference. I want to enter preference(rob,X). in the GNU Prolog and have it return: sophomore, pizza, burger. However, it keeps returning: sophomore, pizza, pizza. How do I fix this problem? I've spent hours looking into this. Thanks This is the code I have: grade(rob, sophomore). grade(matt, freshman). food(rob, pizza). food(rob, burger). food(matt, pasta). food(matt, wrap). preference(X,Y):- grade(X,A), food(X,B), food(X,C), Y = (A, B, C). Just making sure I understand the question, why do you want Y to have both food and a grade in preference? I would like to first return the grade level and then both of the foods because rob likes pizza and burger. I can't have it only return pizza. The way you have defined your facts is nice. The way you query it is not conventional. Here is how I would do it. The "preference" rule is simpler: grade(rob, sophomore). grade(matt, freshman). food(rob, pizza). food(rob, burger). food(matt, pasta). food(matt, wrap). preference(X, A, Y):- grade(X, A), food(X, Y). You conventionally query the database and get all solutions with backtracking: ?- preference(rob, Grade, Food). Grade = sophomore, Food = pizza ; Grade = sophomore, Food = burger. If you want to collect the foods, you can use bagof/setof, like this: ?- bagof(Food, preference(rob, Grade, Food), Foods). Grade = sophomore, Foods = [pizza, burger]. What if you want to query all freshmen? ?- bagof(Food, preference(Person, freshman, Food), Foods). Person = matt, Foods = [pasta, wrap]. You need to state that the value of B and C are different; there are multiple ways to do that, for the simplicity I go with \==/2 (documentation): preference(X,Y):- grade(X,A), food(X,B), food(X,C), B\==C, Y = (A, B, C). Gives the output | ?- preference(X,Y). X = rob Y = (sophomore,pizza,burger) ? ; X = rob Y = (sophomore,burger,pizza) ? ; X = matt Y = (freshman,pasta,wrap) ? ; X = matt Y = (freshman,wrap,pasta) ? ; no If you don't want to have the basically doubled entries you can go with the (in this case lexical) "less than" @</2: preference(X,Y):- grade(X,A), food(X,B), food(X,C), B @< C, Y = (A, B, C). | ?- preference(X,Y). X = rob Y = (sophomore,burger,pizza) ? ; X = matt Y = (freshman,pasta,wrap) ? ; no I may be wrong, but I suspect this may be a misunderstanding of prolog in general in addition to a non-intuitive REPL. Prolog doesn't really "return" a value, it just tries to match the variables to values that make your predicates true, and I would be willing to bet you're hitting enter after you see the first result. The way preference is currently written B and C will match any two foods that rob is associated with. This could be pizza, pizza or pizza, burger or burger, pizza, or so on. It does not check whether B and C are equal. When I run preference(rob,X). prolog does not only give me the first result UNLESS I hit enter. | ?- preference(rob,X). X = (sophomore,pizza,pizza) ? ? Action (; for next solution, a for all solutions, RET to stop) ? If you hit a (or spam ; a few times) prolog will give you the rest of the results. | ?- preference(rob,X). X = (sophomore,pizza,pizza) ? a X = (sophomore,pizza,burger) X = (sophomore,burger,pizza) X = (sophomore,burger,burger) yes | ?- I think that all you really need to get all of a person's preferences is just food unless you specifically need them in a tuple or list which will take some slightly more complicated logic (let me know in a comment if that's what you're looking for) | ?- food(rob, X). X = pizza ? a X = burger yes | ?-
common-pile/stackexchange_filtered
Why is the range of the great highland bagpipe so limited? The Great Highland Bagpipe has a range of only one octave + one note. Why is the range so limited, and would there be a way to increase it? I think the range bagpipes should operate is pretty large. They should operate 2 - 1 km under the sea. As a Scot, I am deeply offended by that remark, @NeilMeyer :-P What's the definition of a Scottish gentlemen? A person who owns a pair of bagpipes and chooses not play them. Jokes are fun and ask, but I genuinely love bagpipes. They have such a rich and full sound - and when they play aires, they are breathtakingly mournful. The number of notes depends on the number of fingers available to close holes with, remembering that you don't want to drop the pipe either. It also depends on the size of the hand. In theory lengthening the chanter and adding holes would give a longer range. This might mean adding a key system so that more holes could be managed with a limited number of fingers. There is already a large difference in tone between the top and bottom of the range; this would be larger, but people could get used to that. The piper obviously does not have the option of using lip pressure to change the note as an oboist does, and cannot change the air pressure too much either because of the effect on the drone pipes. Mouth-blown woodwind instruments let you "overblow" to get higher notes. You can't do that on bagpipes. There are some possibilities to increase the number of tones for a woodwind instrument: Increase the number of holes: things become tricky, since holes left open (e. g. due to lack of additional fingers) limit the effect of other closed holes. This is why keywork helps: the connected springs close holes automatically, so the fingers have a choice, which hole to open - alas, no bagpipe I have seen provides any keywork. (The other important purpose of keys is, that holes with bigger distances can be managed.) Overblowing; whether this works depends on a number of parameters. A acquaintance of me, who plays Scottish bagpipe, assumed, that the form of the bore (conical or cylindrical) has an influence. It is also clear, that the resonator (here the reed of the chanter) has to support the double frequency of resonating (in case of an open tube) or even the triple frequency in case of a tube closed at one end (as clarinet). Scottish bagpipes are not observed to be played using overblowing; not even the practice chanter, which is blown directly - as opposed to mediated by a bag - allowing the same control as other reed instruments. Assumption: the reed may be simply to inflexible to resonate so fast for other conditions as intended volume. To establish the intended overblow frequency, some instruments sport as special overblow key The increased air pressure must be provided; since bagpipes have drones besides the chanter, which also require air, the arm pressure on the bag may only supply the increased pressure for a short moment, before ther air is exhausted. In other types of bagpipes (Flemish, Galician, English) the compass is wider than the 9 notes of the GBH. The reed can be forced to 'overblow' by a momentary increase in bag pressure, giving a range of an octave and a fourth or even two octaves in the case of the gaita. I'm not an instrument maker so am happy to be contradicted, but I believe this ability is down to the internal profile of the bore of the chanter and the chanter reed construction, rather than just the length of the chanter. Why is the range so limited? The part of the instrument responsible for generating the main notes is the chanter. That is the part the piper plays. The three drones, two tenor drones tuned an octave below the chanter keynote (low A) and a base drone two octaves below the keynote, do not change pitch. The chanter produces notes according to the spacing of the holes and the volume of the pipe. These are low G, low A (usually in the range 470-480 Hz), B, C#, D, E, F#, high G, high A, so basically a D major instrument. The physical characteristics of the chanter (the volume of air inside it which can be set vibrating and the way that volume can change via the holes) determines the range and pitches available. would there be a way to increase it? Increase the length of the chanter and introduce more holes suitably spaced. Thanks Brian! So then, the reason that an oboe has more range than a bagpipe is simply because the instrument is longer? I suppose if we did that to a bagpipe chanter we'd also have to add keys like there are on the oboe. On a related note, what determines the range of air pressures a reed plays at? E.g. an oboe's reed can clearly handle whatever range of air pressure is required for 2+ octaves, but if you put a little bit too much pressure on most practice chanter reeds, they stop. Indeed, if you could make the reed play in a wider range of air pressure, could one not in theory play the octave above with the same chanter? In a tin whistle, you get your 2nd octave simply by using more air pressure. @AlexLee as the other answers state, an oboist can change the air pressure and the pressure on the reed directly. Those, plus the "octave key" , allow far greater range than the bagpipe chanter.
common-pile/stackexchange_filtered
Events from Email || Automatic Event Recognition Use-case: Say I am sending an invite email from SFMC, with details about a new Product launch event. I would like to pop up a event details like here Upon researching on this feature, I got to know this feature auto detects email content and is currently supported in specific counties and types of events. Outlook official doc: https://support.microsoft.com/en-gb/office/automatically-add-events-from-your-email-to-your-calendar-32e5cf0c-3e65-4870-9ff9-df3683d3fc97 Supported senders: https://support.microsoft.com/en-gb/office/supported-senders-for-events-from-email-in-outlook-2c447af8-9e6c-481b-85df-e6d95325d6fd My Question: Does anyone know which all domains is supported. Will it work if I send email from any domain from SFMC. It is likely based on the sender's domain, the format and structure of the email. And implementation logic to an event that is automatically created in Outlook is probably determined by Outlook's own code and not the sender.
common-pile/stackexchange_filtered
security access for groups symfony Hi i have a group system and i'd like to add some security to it. Users can belong to multiple groups and id like to know the best way to authorize people to see the groups only if they are in it. If they aren't i want to redirect them to a another page, which is different according to the group. For now i created a service but i have to use it in every controller... I've heard of multiple things but not sure if they are appropriate for my situation. Thanks for your help There are several different ways to do this depending on the approach/complexity. Here are a few: 1) Use Symfony ACLS. When a user is added to a particular group, you can use the symfony ACL system to grant them view access to that group, and then later check isGranted() against that group to see if they have view permissions. 2) Create a custom voter http://symfony.com/doc/current/cookbook/security/voters.html#creating-a-custom-voter 3) If the number of groups is limited in number, you could even use Doctrine query filters to automatically add a where clause to all queries where the group_id is in a list of allowed groups for that user. You can bypass this for all admin users. http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html thanks. my number of groups is not limited . i think ill go with acls
common-pile/stackexchange_filtered
Round robin probability question Lets say there are $n$ players playing in a round robin tournament and they have to each play against another player exactly once. 1) How many outcomes are there for the tournament? (Outcome lists out who won and who lost for each game) 2) How many games are played in total? What would be the correct way to approach this question? I have seen answers saying it is $\frac{n(n-1)}{2}$ games and each game has 2 outcomes so there are $2^\frac{n(n-1)}{2}$. How are these answers reached? Each player plays $n-1$ games. There are $n$ players. Each game has $2$ players playing. Hi, I edit my question a bit, what about the $2^\frac{n(n-1)}{2}$ part? why is it 2 to the power of? I think Alexander gives the best argument for why there are $\frac{n/n-1)}{2}$ games. Another argument is that the number of possible games is equal to the choices for player $1$ and player $2$ in match (since we have every possible matchup in the tournament exactly once). There are $n$ choices for player $1$ and $n-1$ choices for player $2$. Of course if we do this every game is counted twice since we count the match between players $a$ and $b$ once when $a$ is player $1$ and $b$ is player $2$ and a second time when $b$ is player $1$ and $a$ is player $2$. This tells us there are $\frac{n(n-1)}{2}$ games played. As to why the tournament can have $2^{\frac{n(n-1)}{2}}$ outcomes, notice that for every match there are two possible outcomes.
common-pile/stackexchange_filtered
Draw the curve $8x^2+6xy-\frac x{\sqrt{10}}+3\frac y{\sqrt{10}}=1$ Draw the curve Draw the curve $8x^2+6xy-\frac x{\sqrt{10}}+3\frac y{\sqrt{10}}=1$. let $v = (x,y)\in \mathbb{R}^2$ and $B=\{(\frac 3{\sqrt{10}},\frac 1{\sqrt{10}}),(\frac {-1}{\sqrt{10}},\frac 3{\sqrt{10}})\}.$ I'm going to represent $v$ in relation with the base $B$. so then $$v=x'(\frac 3{\sqrt{10}},\frac 1{\sqrt{10}})+y'(\frac {-1}{\sqrt{10}},\frac 3{\sqrt{10}})$$ so we have a system with $2$ equations and $2$ unknowns: $3x'-y'=x\sqrt{10}$ $x'+3y'=y\sqrt{10}$ and I get the solutions $x'=\frac{y+3x}{\sqrt{10}}$ and $y'=\frac{3y-x}{\sqrt{10}}.$ And when I introduce them into the equation, theoretically (based on the problem, also they gave me that specific base to work with) I should've a simpler curve equation, so then I get : $$26y^2+96xy+8y-6x+54x^2=10.$$ which I have no idea how to represent. Am I doing something wrong? Also: I know I can just isolate the $y$ and then represent it like that, but I have to use this method. You have a cross term that can be eliminated as in this link: https://math.stackexchange.com/questions/1102328/rotating-a-conic-section-to-eliminate-the-xy-term It is a hyperbola $x'=\frac{y+3x}{\sqrt{10}},y'=\frac{x-3y}{\sqrt{10}}$ gives $-y^2-y+9x^2-1=0$. I think you dropped a sign. You should have a $+48 xy$ canceling with a $-48 xy$ The given equation is for $x$ and $y.$ The wrong step was in uploading $x', y'$. You should upload $x=(3x'-y')/\sqrt{10}$ and $y=(x'+3y')/\sqrt{10}.$ @DougM Right... however when i obtain that, how do I really draw it? @C.Cristi: I updated my answer. Your basis is close to a basis that diagonalises$$M=\begin{pmatrix}8&3\\3&0\end{pmatrix}$$ $M$ has matrix of unit length eigenvectors $$P=\begin{pmatrix}\frac{3}{\sqrt{10}}&\frac1{\sqrt{10}}\\\frac1{\sqrt{10}}&-\frac{3}{\sqrt{10}}\end{pmatrix}$$ so that $$P^tMP=\begin{pmatrix}9&0\\0&-1\end{pmatrix},$$ transforming your equation $$\begin{pmatrix}x&y\end{pmatrix}\begin{pmatrix}8&3\\3&0\end{pmatrix}\begin{pmatrix}x\\y\end{pmatrix}+\begin{pmatrix}-\frac1{\sqrt{10}}&\frac{3}{\sqrt{10}}\end{pmatrix}\begin{pmatrix}x\\y\end{pmatrix}-1=0$$ by $\begin{pmatrix}x\\y\end{pmatrix}=P\begin{pmatrix}x'\\y'\end{pmatrix}$ into $$\begin{pmatrix}x'&y'\end{pmatrix}\begin{pmatrix}9&0\\0&-1\end{pmatrix}\begin{pmatrix}x'\\y'\end{pmatrix}+\begin{pmatrix}0&-1\end{pmatrix}\begin{pmatrix}x'\\y'\end{pmatrix}-1=0$$ or $$9x'^2-y'^2-y'-1=0,$$ from which you can easily get by $x''=x', y''=y'+\frac12$ that $9x''^2-y''^2-\frac34=0$ or $$(\frac{x''}{\frac1{2\sqrt{3}}})^2-(\frac{y''}{\frac{\sqrt{3}}{2}})^2=1$$ which is in standard form $\frac{x^2}{a^2}-\frac{y^2}{b^2}=1$ and is just a rotation and translation of your original hyperbola. Now you can find the foci: $b^2=c^2-a^2\implies c^2=\frac56$. So $(x',y')=(\pm \sqrt{\frac{5}{6}},-\frac12)$ or $(x,y)= (\frac{\sqrt{30}-1}{2\sqrt{10}},\frac{10\sqrt{3}+9\sqrt{10}}{60})\approx(0.71,0.76)\text{ and }(-\frac{1+\sqrt{30}}{2\sqrt{10}},\frac{3}{2\sqrt{10}}-\frac1{2\sqrt{3}})\approx(-1.02,0.19)$ and use the definition to draw it using $2a=\frac1{\sqrt{3}}\approx 0.58$ and this video: If you just want to plot it, use something like geogebra and the command ImplicitCurve(8x^2+6x y-x/sqrt(10)+3y/sqrt(10)-1)
common-pile/stackexchange_filtered
Start algorithm step numbering not at 1 I have part of an algorithm that branches off from another algorithm, so I would like to present the numbering of the steps starting from that number instead of 1. Right now, I have it set up as follows: \begin{algorithm} \begin{algorithmic}[1] \STATE Step 5 \STATE Step 6 \end{algorithmic} \end{algorithm} I've found a few things about how to change line numbering, but couldn't make anything affect the step numbering. Store the counter and restore it using TeX's \label-\ref system and the support of refcount: \documentclass{article} \usepackage{algorithm,algorithmic,refcount} \begin{document} \begin{algorithm} \begin{algorithmic}[1] \STATE First step \STATE Second step \STATE Third step \STATE Fourth step \label{alg:last-step} \end{algorithmic} \end{algorithm} \begin{algorithm} \begin{algorithmic}[1] \setcounterref{ALC@line}{alg:last-step} \STATE Fifth step \STATE Sixth step \end{algorithmic} \end{algorithm} \end{document} Note that algorithmicx provides \algsave and \algrestore, specifically for this purpose. Actually it's ALG@line not ALC@line. @foobar: Why do you say that? Have you tried it? Yes. I tried with ALC@line and it didn't work. Changing it to ALG@line it was fine. Not sure, maybe different settings. @foobar: The algorithms bundle - that produces algorithmic.sty - has not been updated since 2009. You can search for ALC@line in algorithms.dtx. My guess is you may have a local (updated/variation) copy of algorithmic.sty.
common-pile/stackexchange_filtered
ios - getting part of an NSString I have seen this question that talks about getting the last part of a NSString. I require a slight variation on this. How do I get everything after the http:// Would be good if it was almost as simple as 1 line of code:-) Cheers NSString *str = @"http://www.abc.com/news/read/welcome-new-gig/03276"; str = [str stringByReplacingOccurrencesOfString:@"http://" withString:@""]; hope this will help you..... Thank you - you where first so I will accept your answer when I can. (SO requires me to wait another 6 minutes) substringFromIndex:. You'd be wise to do some bounds checking too. Also, I'd advice taking a look at the documentation before asking a question. This is a better answer than those that rely on stringByReplacingOccuranceOfString, which replaces ALL instances of the string rather than just the initial instance. Use Benedict Cohen's answer with something like [str substringFromIndex:@"http://".length] to be sure that you don't experience these side effects. NSString *originalString = @"http://google.com"; NSString *substring = [originalString stringByReplacingOccurrencesOfString:@"http://" withString:@""]; May want to actually check that you are using "http://" at the front and not replace it in every instance. How about this: if([[str substringToIndex:@"http://".length] isEqualToString:@"http://"]) str = [str substringFromIndex:@"http://".length]; That would be more robust and will actually make sure it starts with "http://" and not replace every instance of it.
common-pile/stackexchange_filtered
C# - Intersection of Dictionary<int, SortedList<int, List<int>>> Consider the following code: Dictionary<int, SortedList<int, List<int>>> ddl1 = new Dictionary<int, SortedList<int, List<int>>>(); ddl1.Add(1, new SortedList<int,List<int>>()); ddl1[1].Add(2, new List<int>()); ddl1[1][2].Add(3); ddl1[1][2].Add(4); ddl1[1][2].Add(5); ddl1[1].Add(3, new List<int>()); ddl1[1][3].Add(3); ddl1[1][3].Add(4); ddl1[1][3].Add(5); ddl1.Add(2, new SortedList<int, List<int>>()); ddl1[2].Add(2, new List<int>()); ddl1[2][2].Add(3); ddl1[2][2].Add(4); ddl1[2][2].Add(5); Dictionary<int, SortedList<int, List<int>>> ddl2 = new Dictionary<int, SortedList<int, List<int>>>(); ddl2.Add(1, new SortedList<int, List<int>>()); ddl2[1].Add(3, new List<int>()); ddl2[1][3].Add(3); ddl2[1][3].Add(4); ddl2.Add(2, new SortedList<int, List<int>>()); ddl2[2].Add(2, new List<int>()); ddl2[2][2].Add(3); I am looking to get the intersection of these 2 complex dictionaries. The result should contain 1 { 3 {3,4} } 2 { 2 {3 } } Can someone please help me with the LINQ query for this? Also, is it more efficient than the manual foreach and .contains method? Thanks in advance! Specify intersection. @TimSchmelter According to the expected output, a deep intersection is meant @Tim, By Intersection , i mean i want the elements that are common in all the 3 deep levels. So where all is equal, the dictionary key, the sortedlist key and all of it's values? @Tim yes. For example, if 2 dictionary have the same key but different value, then the intersection returns nothing. if they have the same key with the same value, then the intersection should return that key value pair. I'm looking for somethign similar to my complex data structure. I am currently doing it manually using foreach/trygetvalue but I need better performance, so i was looking to use LINQ / PLINQ, and thats where I'm haiving trouble. Shouldn't the first result be 1, {3 { 3, 4 }}? @Gert Arnold Oops my bad. Yes you are right, I've corrected it. Thanks for pointing it out Curious to know: does PLINQ actually improve performance here? In short, better do it manually with foreach. I guess if you really want to do this through LINQ, you will have to create some custom IEqualityComparers and this won't be less coding effort than just a manual foreach solution. If you do it through LINQ, however, you may benefit from PLINQ. Apart from this, I don't see why the LINQ solution could be faster. However, you can of course utilize Intersect. But remember that everytime you call ToDictionary as you suggested in the comments, you will create a new dictionary, which is time and memory consuming. So this is the best solution I can think of, assuming you still need the SortedList. If not, replace by a usual dictionary. var result = new Dictionary<int, SortedList<int, List<int>><(); foreach (var key1 in ddl1.Keys.Intersect(ddl2.Keys)) { var subList1 = ddl1[key1]; var subList2 = ddl2[key1]; var common1 = new SortedList<int, List<int>>(); result.Add(key1, common1); foreach (var key2 in subList1.Keys.Intersect(subList2.Keys)) { var subList1L2 = subList1[key2]; var subList2L2 = subList2[key2]; var common2 = subList1L2.Intersect(subList2L2).ToList(); if (common2.Count > 0) common1.Add(key2, common2); } } Thanks for your reply Georg. I dont think there is a need to create custom equality comparer. For a datastructure like Dictionary<int,List>, i can do the intersection 2 levels using the code below: " var result1 = Primary.Keys.Intersect(Secondary.Keys).ToDictionary(key => key, key => Primary[key].Intersect(Secondary[key]).ToList());" I'm looking for similar code for the 3 levels.. Also, performance is a major factor for me, so I'm looking forward to acheive it through linq. I can get significant improvement by using PLINQ right? The trick is to join the two dictionaries on the dictionary keys and the SortedList keys: var q1 = from d1 in ddl1 from sl1 in d1.Value select new { d1.Key, sl1 }; var q2 = from d2 in ddl2 from sl2 in d2.Value select new { d2.Key, sl2 }; var q = from ds1 in q1 join ds2 in q2 on new { key1 = ds1.Key, key2 = ds1.sl1.Key } equals new { key1 = ds2.Key, key2 = ds2.sl2.Key } select new { key1 = ds1.Key, key2 = ds1.sl1.Key, Intersect = ds1.sl1.Value.Intersect(ds2.sl2.Value) }; The subqueries (q1, q2) flatten the dictionaries into a list of lists, so for the join the dictionary keys and the list keys can be combined. Now you can benchmark whether parallelization does indeed increase performance, first by using q2.AsParallel() and then also q1.AsParallel(). Try this method: public static IDictionary<int, SortedList<int, List<int>>> Intersect(IDictionary<int, SortedList<int, List<int>>> x, IDictionary<int, SortedList<int, List<int>>> y) { IDictionary<int, SortedList<int, List<int>>> one = x.Keys.Intersect(y.Keys).ToDictionary(k => k, k => x[k]); foreach (KeyValuePair<int, SortedList<int, List<int>>> kvp in one.ToList()) { one[kvp.Key] = new SortedList<int,List<int>>(kvp.Value.Keys.Intersect(y[kvp.Key].Keys).ToDictionary(k => k, k => y[kvp.Key][k])); } return one; }
common-pile/stackexchange_filtered
How to catch event onclick without ng-click Angular.js I'm developing an Angular App but I want to catch onclick event without ng-click, I want to use something like that $scope.onClick(...) Why? what purpose would that serve? @KevinB I want to separate all logic and use event handlers for it. but... that's what ng-click does... binds event handlers... you can still have the handler defined in the controller. You could use a directive, but then... you'd have ot put the directive on the html, just like ng-click, so it's no better. If you're trying to avoid ng-click, you're probably looking for a different framework. Backbone.js does what you're describing pretty much. lol very strange indeed :P AngularJs use directive to operate dom. you can add a directive like this. AngularJs YourApp.directive('testClick', function () { return { restrict: 'A', link: function (scope, element) { element.onclick = function() { //do some thing. } } } }) html <button test-click>Test Click</button> Depends on what you're trying to click. If we're talking about normal DOM,you could use the regular, non-angular way of doing this. I.e. Assuming for an element like <div id="elementID" onclick = "clicked">Element</div> Javascript: function clicked(){ console.log("I was triggered!"); } var element = document.getElementById('elementID'); element.onclick = function(){ console.log("I was also triggererd!"); } Or even use JQuery if you want: $('#elementID').bind('click', function () { console.log("I would also be triggered!"); }); Hope this helped! Thanks, but I want to use with Angular.js So why exactly do you want to use onclick() without ng-click()? Because I have all my logic on Angular Controller and services, but I want to declare on my Controller something like $scope.Element.OnClick(...) But what difference does it make to have $scope.clickfunc = function(){...} with 'ng-click = "clickfunc()"' instead of what you want? Theres almost no reason to use onclick as angular provides you with the ng-click functionality. The only way it worked for me was: JS: .directive('testClick', function () { return { restrict: 'A', link: function (scope, element) { element.on('click', function() { console.log('Clicked'); }) } } }) HTML: <button test-click> Here </button>
common-pile/stackexchange_filtered