source
sequence
text
stringlengths
99
98.5k
[ "travel.stackexchange", "0000018405.txt" ]
Q: Where to eat Suzumebachi (Giant Sparrow Bee) in Japan? Today I've read a lot about the craziest insect in Japan, the Suzumebachi. It's a kind of giant bee and, apparently, it's the most dangerous animal in Japan: Being stung is extremely painful and requires hospital treatment. On average 40 people die every year of anaphylactic shock after having been stung, which makes the Japanese giant hornet the most lethal animal in Japan (bears kill zero to five people and venomous snakes kill five to ten people each year). I've also read that there are places "in the mountain" where the Suzumebachi is served grilled but I couldn't find any precise information about this. So my question is: where can I eat Suzumebachi in Fuji area or Iya Valley, Shikoku, area? Feel free to suggest other places if it's unlikely I'm gonna find any in the aforementioned places. A: Not quite -- the bees are not eaten, but it is possible to eat their larvae (はちのこ/蜂の子 hachinoko, lit. "bee children"). Here's the process of preparation documented in detail (in Japanese, but with pictures). This is by no means a common dish (in fact I'd never heard of it before I started looking into this!), but apparently in the Tono region of Gifu prefecture, more specifically the towns of Ena and Nakatsugawa, it's considered a regional delicacy. The most famous dish is hebomeshi (ヘボめし), which is basically rice with bee larvae mixed in: And there's a place called, appropriately enough, Hachinosu (はちのす, "Bee's Nest") that will serve you a full course of not only bee larvae rice but pickled grasshoppers (イナゴの佃煮 inago no tsukudani), raw horsemeat (馬刺し basashi) and more for ¥1800: Address Gifu-ken, Kani-gun, Mitake-chō, Nakagiri 1133-1 (岐阜県可児郡御嵩町中切1133の1), open daily except Fridays from 7:30 AM. Do tell us if you end up going, I hear it's the bee's knees! And an important disclaimer: while you'll certainly get bees there, they may not be giant sparrow bees. The only reference I could find to specifically giant sparrow bees being eaten was this rather dodgy TV show claiming that they're used for a dish called bee noodles (蜂そうめん hachi-somen) in the northern mountains of Miyazaki, Kyushu, but the only other references to this dish seem to be talking about the TV show... A: We were up at Chichibu last weekend, and they were selling the Giant Sparrow Bees in a baby food jar in some kind of syrup and were told by the vendor that the stingers are removed and that the bees are Eaten after drinking the syrup. She demonstrated for us. They are supposedly food for building muscle and considered a delicacy
[ "stackoverflow", "0062085931.txt" ]
Q: How to use a handler to loop an if statement every 20 seconds Hi I have been having issues using the handler (I have used nearly every single example in any thread about looping stuff using handler)to loop a if statement that I need to rerun every 20 secs, I'm very new to java, and please ignore my stupid toast messages, could someone edit it so it will rerun the code every 20 seconds, Thanks in advance DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); for (final Display display : dm.getDisplays()) { Toast.makeText(MainActivity.this, "for loop reached", Toast.LENGTH_LONG).show(); int state = display.getState(); String StateString = Integer.toString(state); Toast.makeText(MainActivity.this, StateString, Toast.LENGTH_LONG).show(); if (display.getState() == 1) { String command = "dumpsys deviceidle force-idle deep"; try { Process process = Runtime.getRuntime().exec(command); } catch (Exception e) { Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show(); } //Toast.makeText(MainActivity.this, "not failed yayay", Toast.LENGTH_LONG).show(); TextView tv9 = (TextView) findViewById(R.id.text_view_id); tv9.setText("The screen was turned off"); Toast.makeText(MainActivity.this, "The screen is offfffffffff lolol", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "The screen is on lolol", Toast.LENGTH_LONG).show(); } } A: Here is a second example: package samples; public class Emitter2 { public static final int MS_IN_SEC = 1000; public static final int[] DELAYS = { 1, 3, 4, 5, 7 }; public static void main(String[] args) { Emitter[] emitters = new Emitter[ DELAYS.length ]; Thread[] emitterThreads = new Thread[ DELAYS.length ]; for ( int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++ ) { int delay = DELAYS[emitterNo]; System.out.println("main: Emitter [ " + emitterNo + " ] has delay [ " + delay + " s ]"); Emitter emitter = newEmitter(MS_IN_SEC * delay); emitters[emitterNo] = emitter; emitterThreads[emitterNo] = new Thread(emitter); } System.out.println("main: Starting emitters"); for ( int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++ ) { emitterThreads[emitterNo].start(); } System.out.println("main: Started emitters"); System.out.println("main: Running emitters for 50s"); sleep("main", MS_IN_SEC * 50); System.out.println("main: Completed running emitters for 50s"); System.out.println("main: Requesting emitters to stop"); for ( int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++ ) { emitters[emitterNo].requestStop(); } System.out.println("main: Requested emitters to stop"); System.out.println("main: Waiting for emitters to stop"); for ( int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++ ) { try { emitterThreads[emitterNo].join(); } catch ( InterruptedException e ) { System.out.println("main: Interrupted waiting for emitter to stop"); } } System.out.println("main: Waited for emitters to stop"); } public static boolean sleep(String threadName, int mSec) { try { Thread.sleep(mSec); } catch ( InterruptedException e ) { System.out.println(threadName + ": Interrupted on delay of [ " + mSec + " ms ]!"); return false; } return true; } public interface Emitter extends Runnable { void requestStop(); boolean getStopped(); } public static Emitter newEmitter(int delayMs) { return new Emitter() { private final String emitterName = "emitter" + delayMs; private boolean stopped; public synchronized void requestStop() { stopped= true; } public synchronized boolean getStopped() { return stopped; } public void run() { int counter = 0; while ( !getStopped() ) { System.out.println(emitterName + ": Count [ " + counter + " ]"); counter++; if ( !sleep(emitterName, delayMs) ) { break; } } System.out.println(emitterName + ": Stopped at count [ " + counter + " ]"); } }; } }
[ "stackoverflow", "0028487194.txt" ]
Q: Equals method not working Java So I have my equals method here in the class below, and I doesn't seem to be returning true when the if statement is true! I can't seem to find out why... public class Player { private int[] anyplayer = new int[5]; // constructor for each player at the table public Player(int[] anyplayer) { this.anyplayer = anyplayer; } // checks if the player has a winning bet in the european roulette public boolean europeanequals(){ boolean truth = false; for (int i = 0; i < anyplayer.length; i++) { if (roulettedriver.eurowinningnumber == anyplayer[i]) { truth = true;} else { truth = false; } } return truth; } Here is my driver where I call the method: public class roulettedriver { // declaring the two roulettes final static int[] europeanroulettegame = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26}; final static int[] americanroulettegame = {0,28,9,26,30,11,7,20,32,17,5,22,34,15,3,24,36,13,1,00,27,10,25,29,12,8,19,31,18,6,21,33,16,4,23,35,14,2}; // declaring the two winning numbers public static int eurowinningnumber = europeanroulette.getRandom(europeanroulettegame); public static int uswinningnumber = americanroulette.getRandom(americanroulettegame); public static void main(String[] args) { Scanner keyin = new Scanner(System.in); // initializing the six players (First player) int[] player1 = {-1,-1,-1,-1,-1}; // the numbers are set to -1 because 0 is a winning number Player first_player = new vipplayer(player1); // First player is automatically a VIP try{ for(int i=0;i<=5;i++) { player1[i] = Integer.parseInt(keyin.nextLine()); } } catch(NumberFormatException e){ System.out.println("Player 2 : "); } // booleans are set to true if the bets match the randomly generated number boolean winbet1 = first_player.europeanequals(); And basically my equals isn't comparing the right values I think... Can't seem to make this work? Any input? The value is supposed to be returned in the boolean winbet1 A: Your code continues even after finding a match, potentially resetting truth back to false, and returning that. You need to change the method like so: public boolean europeanequals(){ for (int i = 0; i < anyplayer.length; i++) { if (roulettedriver.eurowinningnumber == anyplayer[i]) { return true; } } return false; } or using a for-each loop: public boolean europeanequals(){ for (int number : anyplayer) { if (roulettedriver.eurowinningnumber == number) { return true; } } return false; }
[ "stackoverflow", "0013508622.txt" ]
Q: Position in relative to parent view with auto layout in Objective C I have a UITextView that I want always to be 10px from the bottom of it's parent view (the scrollview). Problem is that I don't know how to tell the auto layout that it is supposed to do Bottom Space To: Parentview, instead of superview. This is what I have now: Update: I need something similar to this: I got that from here - http://www.techotopia.com/index.php/Working_with_iOS_6_Auto_Layout_Constraints_in_Interface_Builder - I want to have a UITextView in relation to the view it is in. A: Click the gear for the “Bottom space to: superview” constraint and edit it. Set the constant to 10. UPDATE I've investigated this a bit and decided there's a bug in autolayout. Specifically, autolayout acts as if the size of the scroll view is 0⨉0 instead of its actual size. Because of tis, if your text view has top-space-to-superview constraint and a bottom-space-to-superview constraint, only the top constraint will be honored. (I tried setting the priority of the top constraint to 1, the minimum, and the bottom constraint was still ignored.) If you delete the top constraint in viewDidLoad, the bottom constraint will be honored, but the text view will be laid out as if the scroll view's height is zero. This means that the text view's bottom edge will be 10 points above the top edge of the scroll view. This happens in my testing with both a storyboard and a xib.
[ "math.stackexchange", "0002768594.txt" ]
Q: Proving entireness of a piecewise function I have tried solving this problem with this strategy. We know that if a function has a power series representation with radius of convergence R, it is analytic on that radius. I can clearly get infinite radius of convergence for the upper part of the piecewise function, implying that g is analytic everywhere except maybe 0. I need to check that g(z) is differentiable at 0, but unfortunately, we are not allowed to use L'Hoptial's rule. I know the limit of the upper half as g approaches 0 is 1/2, by looking at the series expansion. Any ides on how to proceed? A: As you noted, the only possible issue is at $0$. The upper piece has a singularity at $0$; try determining what kind of singularity it is. Since the power series converges at 0 to g(0), we know more than that g is continuous at 0 -- we know g is analytic at 0.
[ "stackoverflow", "0006783120.txt" ]
Q: R package lattice won't plot if run using source() I started using the lattice graphic package but I stumbled into a problem. I hope somebody can help me out. I want to plot a histogram using the corresponding function. Here is the file foo.r: library("lattice") data <- data.frame(c(1:2),c(2:3)) colnames(data) <- c("RT", "Type") pdf("/tmp/baz.pdf") histogram( ~ RT | factor(Type), data = data) dev.off() When I run this code using R --vanilla < foo.r it works all fine. However, if I use a second file bar.r with source("bar") and run R --vanilla < bar.r the code produces an erroneous pdf file. Now I found out that source("bar", echo=TRUE) solves the problem. What is going on here? Is this a bug or am I missing something? I'm using R version 2.13.1 (2011-07-08) with lattice_0.19-30 A: It is in the FAQ for R -- you need print() around the lattice function you call: 7.22 Why do lattice/trellis graphics not work? The most likely reason is that you forgot to tell R to display the graph. Lattice functions such as xyplot() create a graph object, but do not display it (the same is true of ggplot2 graphics, and Trellis graphics in S-Plus). The print() method for the graph object produces the actual display. When you use these functions interactively at the command line, the result is automatically printed, but in source() or inside your own functions you will need an explicit print() statement.
[ "math.stackexchange", "0002967653.txt" ]
Q: Finding the position of a given circle that contains the most randomly placed points Given are a random number of points, randomly scattered in a finite plane, and a circle of a given size. How do I know where to position the circle so that the most points possible are inside the circle? A: We may assume wlog that at least one point is on the circle boundary, for otherwise we can translate the circle until one of th einterior points is about to leave it. The only exception is when the maximal number is $0$, i.e., there are no points to begin with. In fact, we can usually assume wlog that there are two points on the boundary, for otherwise we can rotate around the one point on the boundary that we already have from the preceeding paragraph, until another point is about to leave the interior. As above, the only exception to this is when it is impossible to cover two points to begin with. This suggests the following algorithm: Loop over all ${n\choose 2}$ pairs of points. If their distance is $\le $ the circle diameter, check which other points are inside the two possible circles with the given chord. All in all, this is an $O(n^3)$ algorithm. I am confident that this can be sped up by first determining a Delaunay triangulation and use that to reduce the number of chords to be tested.
[ "stackoverflow", "0004021956.txt" ]
Q: How to position a view off-screen so that it can be Animated to move on-screen? I have a RelativeLayout filling the screen and a couple of ImageView positioned on it using LayoutParams margins. These ImageView are animated in different ways, and in one case I want an image to "fly in" to the screen from the right. Unfortunately, if I set leftMargin for that ImageView greater than the width of the screen, it does not appear (or appears cropped if it partially visible at the start of animation). I tried setting width and height of RelativeLayout to be bigger than screen size - it works, but only partially: if the image is positioned completely off-screen, it does not work, and if the image is partially visible, it is not cropped, but that works only for right and bottom sides. So, my question is this: how to position several ImageViews on and off the screen so that I can animate them using Animation? A: In the end, I used a trick: I combined AnimationDrawable and view animation. I did the following (assuming that the animation has to run T milliseconds): Position that ImageView on-screen. Set as its background an AnimationDrawable with following frames: empty Drawable: 1ms, normal Drawable: Tms. Change view's animation to this: jump to off-screen position (translation with duration=1ms), do normal animation.
[ "stackoverflow", "0016953042.txt" ]
Q: Generate texture coordinates for procedural texturing I'm reading the Procedural Texturing chapter in the red book (OpenGL Programming Guide). In their procedural texturing example, one of the parameters that gets passed in from the application to the shaders is the texture coordinates. However, they do not show how to generate the texture coordinates. Can someone provide an example of how to go about generating texture coordinates when doing procedural texturing? A: I don't have the OpenGL Programming Guide, so I can't comment specifically on their example, but in general: If your procedural texture calculates colours based on two dimensional coordinates, these are no different from ordinary texture coordinates. Just pass them in from the application (or calculate them based on some projection in the vertex shader) as you would normally. If your procedural texture calculates colours based on three dimensional coordinates, you will typically use the (untransformed) vertex positions as input to the procedural texture calculation. Copy the vertex position attribute to a varying (or out in recent GLSL dialects) vec3 variable in your vertex shader.
[ "math.stackexchange", "0000671003.txt" ]
Q: Strange function limit Can anyone show me how to evaluate this limit where $B>A>0$? If I try with some $A,B$ and give values to $n$, I discover that the limit is $B$ (the biggest number), but I don't know how to solve it. A: Notice that \begin{equation} \frac{A^n+B^n}{A^{n-1}+B^{n-1}} = \frac{\left(\frac{A}{B}\right)^n+1}{\left(\frac{A}{B}\right)^{n-1}\cdot\frac{1}{B}+\frac{1}{B}} \end{equation} You know that $A/B<1$ so we have $(A/B)^n\to 0$, which gives you that the limit value is $B$ as you discovered before.
[ "drupal.stackexchange", "0000003363.txt" ]
Q: Complete backup solution I'm trying to backup my Drupal website (not only database) as complete as possible, because It's in the desired state. The backup should cover actual versions of all modules, themes, database tables, settings, just everything. Now my method is to zip everything under /var/www/ folder and backup the database with Backup migrate module. The restore process is delete everything in /var/www drop database and create it again and set permissions on it unzip my backup to /var/www restore with Backup migrate module Will this method work? Do you know smarter method to make a complete Drupal web backup? A: Will this work? Yes Is there a smarter method? Drush + drush make Drush is a command line tool that you can use for various things, one of them is to create a site. With a drush make file, you can save all of the modules you use (including version and even patches applied to them if needed). Once create you could recreate all of the modules by doing something like this: drush make --no-core --contrib-destination=[path to the contrib folder like sites/all] [path to the make file] You can read more about drush and drush make which has documentation about usage. Also backup and migrate will or can add a drop syntax, so that it automatically drops tables when restoring the database. So using it, you wont need to wipe out your database completely. If need be, you can truncate it so you wont have to setup permissions again.
[ "unix.stackexchange", "0000206765.txt" ]
Q: "no matching cipher found" error in `rsync` I am trying to copy a directory from one system to another with rsync; but it erred. Can you please advise me on what to check? Command: [M root@aMachine ~]# rsync -e "ssh -c blowfish" -v -a /home/aDir/ [email protected]:/home/aDir Output: ssh_dispatch_run_fatal: no matching cipher found rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: error in rsync protocol data stream (code 12) at io.c(605) [sender=3.0.9] I tried couple attempts in /etc/ssh_config, but to no avail. This is what I have in my /etc/ssh_config now: # Host * # ... # ... # Port 22 # Protocol 2,1 # Cipher 3des # Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc # MACs hmac-md5,hmac-sha1,[email protected],hmac-ripemd160 IdentityFile /root/.ssh/identity IdentityFile /root/.ssh/id_rsa IdentityFile /root/.ssh/id_dsa IdentityFile /etc/static_keys/CURRENT A: You are trying to force the use of the blowfish cipher ("ssh -c blowfish"). According to your configuration, this cipher is not available (the SSH configuration, by default, shows the default configuration settings as comments). Unless you have any compelling reason to do so (none was mentioned in your post), do not force the use of a particular cipher. Notice also that you usually do not have to fiddle with /etc/ssh/ssh_config. As a user, it's easier to modify $HOME/.ssh/config. You are working on this system as a non-root user, aren't you?
[ "stackoverflow", "0035986037.txt" ]
Q: Detect if an R session is run in RStudio at startup I use R both in the terminal and in RStudio (on mac and linux) and wonder if it is possible to use different .Rprofiles for the two, or preferably use the same base .Rprofile but source different environment specific tweak scripts. I thought it would work to place the following code in my .Rprofile, but unfortunately session_info isn't set at the time .First is run. Neither is Sys.getenv. .First <- function(){ # [STUFF I ALWAYS WANT TO DO] # Load my favourite packages # Set CRAN mirror # etc. etc. # [ENVIRONMENT SPECIFIC TWEAKS] if(grepl("RStudio", session_info()$platform$ui)){ tryCatch(source("~/.R_RStudio"), error=print) } else { tryCatch(source("~/.R_terminal"), error=print) } } I also tried setting alias R='R --args terminal' in .bash_profile which does allow me to detect if the session was started from bash, but it screws up R CMD ... and any script that uses other command line arguments. I realise it might not be possible to detect from within an R session where it was started from, but perhaps there is some clever option in RStudio I am not aware of. A: You can detect whether RStudio is hosting the R session by checking for the value of the RSTUDIO environment variable. For example, if (!is.na(Sys.getenv("RSTUDIO", unset = NA))) { # RStudio specific code }
[ "askubuntu", "0000411992.txt" ]
Q: How to track down the copy and move operations of files and folders? I use drag and drop to copy and move files. One disadvantage of that is files might end up to the wrong places. So, let's say I copied/moved many files and folders to multiple different destinations. How can I track down where everything ended up to make sure that everything was copied/moved to the right places? A: What you are asking for is a "file system watcher". iWatch iWatch is a realtime filesystem monitoring program. It's a simple perl script to monitor changes in specific directories/files and send email notification immediately. It reads the dir/file list from xml config file and needs inotify support in kernel (Linux Kernel >= 2.6.13). There are more but this seems the most simple method, is native to Ubuntu and uses inotify (so it does not hog the system). iWatch comes in 2 methods: command line daemon Some command line options for logging: -m <email address> Specify the contact point's email address. Without this option, iwatch will not send any email notification. -s <on|off> Enable or disable reports to the syslog (default is off/disabled) Some command line examples: iwatch /tmp monitor changes in /tmp directory with default events iwatch -r -e access,create -m cahya@localhost -x /etc/mail /etc monitor only access and create events in /etc directory recursively with /etc/mail as exception and send email notification to cahya@localhost. iwatch -r -c "(w;ps -ef)|mail -s '%f was changed' cahya@localhost" /bin monitor /bin directory recursively and execute the command. iwatch -r -X '\.svn' ~/projects monitor ~/projects directory recursively, but exclude any .svn directories inside. This can't be done with a normal '-x' option since '-x' can only exclude the defined path. Example config file when using daemon mode mode. Logging is done with XML options in the configuration file: <config> <guard email="myadmin@localhost" name="IWatch"></guard> <watchlist> <title>Public Website</title> <contactpoint email="webmaster@localhost" name="Web Master"/> <path type="single">/var/www/localhost/htdocs</path> <path type="single" syslog="on">/var/www/localhost/htdocs/About</path> <path type="recursive">/var/www/localhost/htdocs/Photos</path> </watchlist> <watchlist> <title>Operating System</title> <contactpoint email="admin@localhost" name="Administrator"/> <path type="recursive">/etc/apache2</path> <path type="single">/etc/passwd</path> <path type="recursive">/etc/mail</path> <path type="exception">/etc/mail/statistics</path> <path type="single" filter="shadow|passwd">/etc</path> </watchlist> <watchlist> <title>Only Test</title> <contactpoint email="root@localhost" name="Administrator"/> <path type="single" alert="off" exec="(w;ps -ef)|mail -s %f root@localhost">/tmp/dir1</path> <path type="single" events="access,close" alert="off" exec="(w;ps -ef)|mail -s %f root@localhost">/tmp/dir2</path> <path type="single" events="default,access" alert="off" exec="(w;ps -ef)|mail -s '%f is accessed' root@localhost">/tmp/dir3</path> <path type="single" events="all_events" alert="off">/tmp/dir4</path> </watchlist> </config> With this configuration, iwatch will monitor a single directory /var/www/localhost/htdocs without its sub directories, and any notification will be sent to the contact point webmaster@localhost. But it will monitor the whole directory tree of /etc/apache2, including any sub directories created later after the IWatch is started. You can use also create exceptions here if you don't want to get notification for a file or subdirectory inside the monitored directory.
[ "stackoverflow", "0021324266.txt" ]
Q: two factor authentication for a wifi network? is it possible to setup two factor authentication for known users of a wifi network? I imagine that this might add security to wifi networks whose keys are stored by an untrusted device or third party smartphone os-maker. A: Yes we can apply on Cisco Router(as much as I know) and we have the following options: OTP using external RADIUS server and RSA tokens EAP-Chaining using the AnyConnect Agent and Cisco ISE MAR (machine access restrictions). If the machine had not performed authentication the user will not be authorized Layer 3 security on the Wireless LAN Controller
[ "stackoverflow", "0004657047.txt" ]
Q: CSLA Framework CanReadProperty In the CSLA.NET Framework, what is the purpose of the CanReadProperty method? A: It's a method that allows to check whether it is allowed to read a certain property: /// <summary> /// Returns <see langword="true" /> if the user is allowed to read the /// calling property. /// </summary> /// <param name="property">Property to check.</param> [EditorBrowsable(EditorBrowsableState.Advanced)] public virtual bool CanReadProperty(Csla.Core.IPropertyInfo property) { bool result = true; VerifyAuthorizationCache(); if (!_readResultCache.TryGetValue(property.Name, out result)) { result = BusinessRules.HasPermission(AuthorizationActions.ReadProperty, property); // store value in cache _readResultCache[property.Name] = result; } return result; }
[ "stackoverflow", "0041254582.txt" ]
Q: Overriding CSS on github pages using slate theme? I am trying to override the "forkme" banner on my github.io page to get a better understanding of how Jekyll, HTML, CSSand GitHub works. For that purpose, I created my ./assets/css/style.css file as mentioned in the readme of the official documentation on how to customize the CSS of the officially supported GitHub themes. I added the following CSS to it: #forkme_banner { display: none; } However, no luck, the banner doesn't disappear. Even adding fictitious elements to the CSS file like #test {testing: testtest;} doesn't add the line to my CSS file. A: rename assets/css/style.css to style.scss and change your scss code to : --- --- @import "{{ site.theme }}"; #footer_wrap {display: none;} #forkme_banner {display: none;} #downloads {display: none;} #whocares {haha: hehe;}
[ "stackoverflow", "0015550389.txt" ]
Q: What's the best way to grab the latest 10 pictures from Facebook Page with more than 10,000 likes? I need to create a script in PHP that automatically grabs the latest 10 pictures from a Facebook Page (example: https://www.facebook.com/stackoverflowpage) that have more than a specific amount of likes (example: 10,000). I want to run the script every hour to make sure I grab all the pictures with their titles. I don't think this has ever been done before. What is the best approach to this problem in your opinion? I think I have three choices: Fetch the data via Facebook Page's HTML Code Fetch the data via Facebook Graph Fetch the data via Facebook API A: I just finished my script. Here's my solution in PHP: $album_id = "20531316728"; $like_minimum = 5000; $album_data = file_get_contents("https://graph.facebook.com/".$album_id."/photos"); $album_data_array = json_decode($album_data,true); // loop album foreach($album_data_array as $item){ // loop posts foreach($item as $item){ // grab id, source, message $photo_id = $item[id]; $photo_source = $item[source]; $photo_message = $item[name]; // count likes // facebook doesn't allow us to grab this data. we'll do it anyway. $like_data = file_get_contents("http://www.facebook.com/photo.php?fbid=".$photo_id); $like_count = explode(' others like this.","ranges":', $like_data); $like_count = $like_count[0]; $like_count = explode('and ', $like_count); end($like_count); $key = key($like_count); $like_count = $like_count[$key]; $like_count = str_replace(",", "", $like_count); $like_count = intval($like_count); // check if like_minimum reached if($like_count>$like_minimum){ // SUCCESS! // Do stuff... } } }
[ "stackoverflow", "0007340169.txt" ]
Q: Help interpreting Python code snippet I found the below on the web, however from my little exposure with Python I am aware that one can attach functions to object in the fly. I am also aware that everything in Python is object. I am yet to understand what one intend to achieve with the below and its use case. This is the part I need help: run_sql_command.c = c def get_sql_object(c): def run_sql_command(command, arguments=[]): c.execute(command, arguments) return c.fetchall() run_sql_command.c = c return run_sql_command A: The idea here (I believe) is that someone is creating a placeholder object that keeps reference to a cursor c so that it may be used to execute queries later. Proposed usage is probably something like this: c = DBConnectionObject.cursor() myExecutor = get_sql_object(c) # some amount of code later rows = myExecutor(Queries.GetAllUsersByFName, ['Larry', 'Bob']) -- To address some of the comments -- I find that attempting to keep cursors around can cause problems in volatile environments where it's not always guaranteed that the database connection remains connected. I opt for this approach instead: class DBConnection(object): def __init__(self, dbpath): self.dbPath = dbpath # Any connection object here, really. self._conn = kinterbasdb.connect() def cursor(self, query, params = None): try: cursor = self._conn.cursor() if params: cursor.execute(query, params) else: cursor.execute(query) return cursor except (kdb.ProgrammingError, AttributeError), e: print e def qry(self, query, params = None): cursor = self.cursor(query, params) return [[x[0].title() for x in cursor.description]] + [r for r in cursor.fetchall()] Then, you'd create a global database connection like so: dbcon = DBConnection('/path/to/mydb.fdb') and run queries with: rows = dbcon.qry(Queries.GetSomething) or: filtered = dbcon.qry(Queries.FilteredQuery, ['my', 'parameters']) I've omitted some of the code that does error handling / reconnects to the database if the connection has dropped, but the general idea is there. This way, cursors are created when they're needed, used, and allowed to go out of scope, letting me centralize error handling. A: That line adds an attribute c to the function run_sql_command, giving it the value passed to the function get_sql_object(), presumably a database cursor. You probably already knew that much. With the limited scope of this snippet, the statement has no use at all. In a larger context, the cursor may be re-used elsewhere in the code. Look for accesses to the .c attribute in other parts of the code, and see what's done with it.
[ "stackoverflow", "0025893998.txt" ]
Q: how to install express js on ubuntu? I am using ubuntu 14.04 LTS. I installed nodejs as mentioned here, and then I installed express by running sudo npm install -g express@3 it got installed but when I try to create an app or even try to look at the version by running express -v or express -V it doesn't give any sort of output. Any help is much appreciated, Thanks in advance! A: Installation of node in ubuntu is fairly a straight forward process. I don't know what gone wrong with your earlier attempt.anyway you can install it again if you wish. there are two ways to install node. Download and install from nodejs.or Use NVM(node version manager) I always prefer the NVM method because it not only allows you to switch between versions but also avoids some of issues that otherwise you may face later. example, can't install npm packages globally without sudo. Before you start remove your old installation sudo rm -r ~/.npm Now install nvm curl https://raw.githubusercontent.com/creationix/nvm/v0.16.1/install.sh | bash To activate nvm source ~/.nvm/nvm.sh Then install node nvm install 0.10 nvm use 0.10 To set a default Node version to be used in any new shell nvm alias default 0.10 Check everything done properly node --version Then install express npm install -g express
[ "math.stackexchange", "0002604409.txt" ]
Q: Find the number of relatively prime numbers from $10$ to $100$ Find the number of ordered pairs $(a,b)$ such that $10\le a,b\le100$ and $gcd(a,b) = 1$ My attempt: It is clear that for any $a$ you need to start checking from $b = a+1$ wether the two numbers are relatively prime or not, to prevent repetitions. Any prime $p$ would have $100-p- \lfloor\frac{100}{p}\rfloor$ pairs in which it is present. How do I proceed after this? A: THere are $91$ numbers between $10$ and $91$ inclusively. So there are $91^2$ ordered pairs. There are $46$ even numbers. An ordered pair with $2$ even numbers can't be relatively prime. So we toss out those $46^2$ pairs. We now have $91^2 - 46^2$ ordered pairs. There are $30$ multiples of $3$. And ordered pair with $2$ numbers divisible by $3$ can't be relatively prime so we toss those $30^2$ pairs. But we that is double tossing the multiples of $3$ that are even-- we've already tossed those. There are $16$ multiples of $6$ so we now have $91^2 - 46^2 - 30^2 + 16^2$. These are the sets of ordered pairs $(a,b)$ where $a$ and $b$ are not both even, nor are they both multiples of three. There $19$ multiples of $5$ or which $9$ are even, $6$ are multiples of $3$ and $3$ are multiples of $6$. We toss those out. We now have $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)$ On to the next prime; $7$. There are .... geeze let's se $100\div 7 = 14$ and subtract the one less than $10$... $13$ multiples of $7$. $7$ are multiples of $14=2*7$ and $4$ of them are multiples of $21=3*7$ and $2$ of them are multiples of $35=5*7$. But $2$ are multiples of $2*3*7=42$ and $1$ is $2*5*7=70$. Yet there are no multiples if $3*5*7$ nor $2*3*5*7$. When we toss all the ordered pairs that are both multiples of $7$ we have. $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)$ Now that the primes are more than the square root of $100$ things will get. Easier. There are $9$ multiples of $11$ but $4,3,1,1$ of them are multiples of $2,3,5,7$. $1$ of them is a multiple of $6$. So now we have: $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)$ There are $7$ multiples of thirteen $3,2,1,1$ of them are multiples of $2,3,5,7$ and $1$ of them is a multiple of $6$. So now we have: $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2)$ There are $5$ multiples of $17$ and $2,1,1$ of them are multiples of $2,3,5$. So now we have: $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2) - (5^2 - 2^2 - 1^2 -1^2)$ There are $5$ multiples of $19$ and $2,1,1$ of them are multiples of $2,3,5$ so now we have: $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2) - (5^2 - 2^2 - 1^2 -1^2) - (5^2 - 2^2 - 1^2 -1^2)$ There are $4$ multiples of $23$ and $2$ and $1$ are multiples of $2$ and $3$. So : $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2) - (5^2 - 2^2 - 1^2 -1^2) - (5^2 - 2^2 - 1^2 -1^2)-(4^2 - 2^2 - 1^2)$ There are $3$ multiples Of $29$ and one of them are mutiplse of $2$ and $3$ so: $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2) - (5^2 - 2^2 - 1^2 -1^2) - (5^2 - 2^2 - 1^2 -1^2)-(4^2 - 2^2 - 1^2)-(3^2 - 2)$ The remaining primes are $31,37,41,43,47$ of which there are $2$ multiples of but one of them is a mulitiple of $2$. And $53,61,67,71,73,79,83,89,97$. So we have $(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2) - (5^2 - 2^2 - 1^2 -1^2) - (5^2 - 2^2 - 1^2 -1^2)-(4^2 - 2^2 - 1^2)-(3^2 - 2)- 14$ Ordered pairs $(a,b)$ in which $a,$ and $b$ have no factors in common. But we want unordered pairs. And as we have no pairs $(a,a)$ we just divide this result in half. Total number is $\frac {(91^2) - (46^2) - (30^2 - 16^2) - (19^2 - 9^2 - 6^2 + 3^2)-(13^2 - 7^2 -4^2 -2^2 + 2^2 + 1^2)- (9^2 - 4^2-3^2-1^2-1^2 + 1^2)-(7^2 - 3^2-2^2-1^2-1^2 + 1^2) - (5^2 - 2^2 - 1^2 -1^2) - (5^2 - 2^2 - 1^2 -1^2)-(4^2 - 2^2 - 1^2)-(3^2 - 2)- 14}2$
[ "stackoverflow", "0033294699.txt" ]
Q: Dynamic Polymorphism with Parametrized methods I want some clear idea about Dynamic Polymorphism. When methods in child class are over-ridden and overloaded, I am unable to figure out method calls. Here is the Parent class: Parent Class: public class Parent { void print(Parent parent){ System.out.println("I am parent classes only print method."); } } Child Class: public class Child extends Parent { void print(Child child) { System.out.println("I am child class' child print method."); } void print(Parent parent) { System.out.println("I am Child class' parent print method "); } } And this is the caller class. public class Caller { public static void main(String[] args) { Parent p = new Parent(); Child c = new Child(); Parent pc = new Child(); p.print(p); p.print(c); p.print(pc); c.print(p); c.print(c); c.print(pc); pc.print(p); pc.print(c); pc.print(pc); } } I can see the output in console but cannot understand the reason behind the method calls. A: The working is simple - overloading is resolved at compile time, and overriding is resolved at runtime (polymorphism). So, let's see what happens in each of your method calls... We will ignore calls using Parent p = new Parent(); since it doesn't have overloading or overriding and all the method calls will directly use the parent's single method "I am parent classes only print method.". Also note that, the compiler cares only about the variable's reference type. And the runtime cares only about the actual object's type. So, in the statement Parent pc = new Child(), any compile time decision on pc will refer to Parent and any runtime decision on pc will refer to Child. Here's the logic for the other method calls, c.print(p); //Compiler resolves that `print(Parent)` method should be called. //Runtime resolves that child objects method should be called. //Prints "I am Child class' parent print method " c.print(c); //Compiler resolves that `print(Child)` method should be called. //Runtime resolves that child objects method should be called. //Prints "I am Child class' child print method " c.print(pc); //Compiler resolves that `print(Parent)` method should be called. //Runtime resolves that child objects method should be called. //Prints "I am Child class' parent print method " pc.print(p); //Compiler resolves that `print(Parent)` method should be called. //Runtime resolves that child objects method should be called. //Prints "I am Child class' parent print method " pc.print(c); //PAY ATTENTION TO THIS... //Compiler resolves that `print(Parent)` method should be called. // This is because PC is Parent type reference and compiler doesn't find `print(Child)` in Parent class, so it uses `print(Parent)`. //Runtime resolves that child objects method should be called. //Prints "I am Child class' parent print method " pc.print(pc); //Compiler resolves that `print(Parent)` method should be called. // This is because Compiler knows only about the variable's reference type (And PC is of type Parent). Hence `print(Parent)` would be chosen. //Runtime resolves that child objects method should be called. //During runtime, the type of the actual object is used. And PC is referring to an Child object... So `pc.print(...)` will call the child's method. //Prints "I am Child class' parent print method "
[ "stackoverflow", "0041117220.txt" ]
Q: Search two different string patterns in one line THE SCENARIO I have a *.txt file containing 3 lines: test-1234.htm test-5678.htm somefile.htm I need a script which will find specific string patterns in that *.txt file. Currently, following script will find all *.htm files in *.txt file and store results in specified results.log file. dir *.txt | Select-String -pattern "\.htm$" |Select-Object -Expandproperty line | Out-File results.log -Encoding utf8 -Width 500 QUESTION How to modify it, so it only finds all "test-****.htm" lines? (Will only log lines containing "test-" and ".htm") A: Thank you all for the hints! Ultimately I got it working with: test-.{4,}\.htm$ This way I was able to also include in results lines with digits+characters (for example "test-a12c.htm") and lines where there was something before the key word "test" (for example "this is a test-13bg.htm". @ user1432893 The site you've provided helped me with this! THX! @ Dave Sexton with ^ in argument it didn't work.
[ "stackoverflow", "0042634020.txt" ]
Q: Java - install Spring from maven I Have started to learn on springs recently and I am stuck at the very beginning. in the tutorial that I follow on youtube it says that i have to install maven and from maven i can install spring, i have installed maven and now i want to install Spring framework from it. it sounds pretty simple. As i understand, maven searches for the spring framework from its repositories and downloads. I have referred these two links - First and Second But when i try to search for dependencies, i dont see any dependencies dispalyed to me when i search for "springframework" as shown in the tutorial. everywhere i google, they say the maven indexes have to be updated on startup, the update process starts when i start eclipse , but its not finishing/ending. This is my pom.xml file, <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.caveofprogramming.spring.test</groupId> <artifactId>testprog</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>testprog</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> A: Try to add this to your dependencies: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.7.RELEASE</version> </dependency>
[ "stackoverflow", "0010737671.txt" ]
Q: Segue'ing to a new view from a custom cell I've created a custom table where I can scroll through a list of items vertically, but I can also scroll left and right through those vertical index. How would I go about moving to a new view (in storyboards)? Does anyone know how to programmatically add a segue from the custom cell to a new view? Here's the code where I created the custom cell: static NSString *CellIdentifier = @"ArticleCell"; __block ArticleCell_iPhone *cell = (ArticleCell_iPhone *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; Here's a screenshot of my custom table: http://i200.photobucket.com/albums/aa42/mininukinfuts/ScreenShot2012-05-24at145417.png And here's a link to a tutorial I was following: http://www.raywenderlich.com/4723/how-to-make-an-interface-with-horizontal-tables-like-the-pulse-news-app-part-2 A: In order for me to fix this problem, I had to add the following code to my didSelectRowAtIndexPath method: musicTime *MP = [self.sb instantiateViewControllerWithIdentifier:@"playMusic"]; [self.navCon pushViewController:MP animated:YES]; I gave my new view the identifier above, then in my .h I had: @interface HorizontalTableCell_iPhone : HorizontalTableCell { musicTime *Music; UINavigationController *navCon; UIStoryboard *sb; } @property (nonatomic, retain) musicTime *Music; @property (nonatomic, retain) UINavigationController *navCon; @property (nonatomic, retain) UIStoryboard *sb; @end
[ "stackoverflow", "0034366122.txt" ]
Q: Laravel - Foreach loop from a language file? have a language file called "faq" which lists all the frequently asked questions and answers. I have no idea how to do a foreach loop from those language files. My faq.php language file: return [ 'faq_1' => 'Question here', 'faq_1_ans' => 'Answer here', 'faq_2' => 'Question here', 'faq_2_ans' => 'Answer here', ]; How can I make that into a foreach loop? I really don't know where to start. A: You might want to change the structure return [ 'faq_1' => [ 'q' => "Question", 'a' => "Answer Here" ], 'faq_2' => [ 'q' => "Question", 'a' => "Answer Here" ], ]; or even return [ [ 'q' => "Question", 'a' => "Answer Here" ], [ 'q' => "Question", 'a' => "Answer Here" ], ]; this way you can loop: $faqs = Lang::get('faq'); foreach($faqs as $faq) { echo "question: " . $faq['q']; echo "answer: " . $faq['a']: }
[ "stackoverflow", "0003492230.txt" ]
Q: ELMAH Logging Variables Does anyone know if there is a patch or anything kicking around for ELMAH that will extend its logging capabilities to include variables and/or session variables. Sometimes the errors i am logging are hard to trace without a bit more info. If there is nothing i might have a go at altering myself Cheers Luke A: An issue like this exists on ELMAH site. There, Martin provides a patch that allows you to log exception Exception.Data variable. Apply the patch (manually if your ELMAH version isn't the right one) and just add ex.Data["yourInfoKey"]="yourInfoValue"; to your exception just before throwing it. It worked for me. However, if you want to add columns to your ELMAH_Error table to be able to filter on them, I'm afraid you'll have to edit ELMAH source yourself.
[ "stackoverflow", "0008788690.txt" ]
Q: Destroy timeout for HistoryRecord I able to process half the items I have in a ginormous string but I am losing half my data. Here is my log cat errors. 12-08 15:03:44.011: W/ActivityManager(59): Launch timeout has expired, giving up wake lock! 12-08 14:40:49.528: W/ActivityManager(59): Activity destroy timeout for HistoryRecord{4501c938 package.data/.class1 12-08 14:40:44.318: W/ActivityManager(59): Activity idle timeout for HistoryRecord{450204b8 package.data/.class2 Here is what I did, I placed method(which consist of a new bufferReader(new inputstream(String), 8 *1024) in a while loop. The main reason for this is because I am manipulating the string and changing its info on the fly.So in summary I am losing half data but I am able to show half of them. I want to be able to show the remaining. I understand that this post is similar to other stuff but it seems different. If anyone can assist me in anyway i would be most appreciated. A: See if changing the declaration of your activity in the manifest to something like: <activity android:name=".Activity3"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
[ "stackoverflow", "0022134989.txt" ]
Q: Using MYSQL are keys required on individual fields if in a unique key? I have a simple linking table, see the create sql below. My question is, do i need to have the individual indexes for amtw_propnameid_idx, and amt_amt_concept_id_idx if i have amtw_u1? I use this table to join and filter on both amtw_propnameid and amtw_amt_concept_id. I use the unique index to enforce the restriction that no two rows can be identical. $sql= "CREATE TABLE `refset_amt_webster` ( amtw_id int unsigned not null AUTO_INCREMENT, amtw_propnameid int null default null comment 'links to the Webster proprameid drugs table', amtw_amt_concept_id bigint not null comment 'links to the AMT concept id', amtw_disabled tinyint unsigned not null default 0 comment '1=disabled', PRIMARY KEY(amtw_id), KEY amtw_propnameid_idx (amtw_propnameid), KEY amtw_amt_concept_id_idx (amtw_amt_concept_id), UNIQUE KEY amtw_u1 (amtw_propnameid,amtw_amt_concept_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT 'AMT to MIMS linking table.';"; A: Indexes can only be used to optimize queries which use leftmost columns; as barry-johnson commented, If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3). MySQL cannot use an index if the columns do not form a leftmost prefix of the index. Suppose that you have the SELECT statements shown here: SELECT * FROM tbl_name WHERE col1=val1; SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2; SELECT * FROM tbl_name WHERE col2=val2; SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3; If an index exists on (col1, col2, col3), only the first two queries use the index. The third and fourth queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3). See the mysql documentation for more info
[ "stackoverflow", "0031903318.txt" ]
Q: angular float number fraction down how get number with no fraction in angular in view with filter? i mean like 1.777 i want to output 1 (angular makes that 2) how round float number down! myvalue is 1.777 myvalue| number:0 the output will be 2 how approach to 1? something like parseInt in jquery i need in view???? is there filter in angular that ! A: It should be simply {{ number_expression | number : fractionSize}} Markup <h6>flight duration: {{item.travelTime | number: 0}}</h6></div> Look at Number filter API Update For making round number then you need to use number filter inside your custom filter. Markup <h6>flight duration: {{item.travelTime | numberFormat: 0}}</h6></div> Filter app.filter('numberFormat', function($filter){ return function(value, fractionSize){ if(value){ $filter('number')(Math.round(value), fractionSize) } } })
[ "stackoverflow", "0009077233.txt" ]
Q: XSLT Format Date I have a date in this format 10/12/2011 12:55:00 PM (MM-DD-YYYY time) I would like to format this date into 12/10/2011 (DD-MM-YYYY) time to be removed using XSLT? the complexity I find is sometimes the input date can look like 7/12/2011 12:55:00 PM (only one number to the front instead of 07) Can someone please show me a way to implement this? many thanks in advance. A: It is easy to obtain desired result using only standard XPath string functions like substring-before, substring-after and substring, e.g.: <xsl:variable name="input">7/12/2011 12:55:00 PM</xsl:variable> <xsl:value-of select="concat( substring-before(substring-after($input, '/'), '/'), '/', substring-before($input, '/'), '/', substring(substring-after(substring-after($input, '/'), '/'), 1, 4) )"/>
[ "mathematica.meta.stackexchange", "0000002242.txt" ]
Q: Ask Question - Large amount of numbers I am new in StackExchange. I would like to ask a question in Mathematica Stack Exchange about a code I am writing. I would need to write in the question a table of data which is long. Is it possible to do it? I'm sorry if this is a stupid question but I am having problems orientating myself. A: Your question is probably answered as well as it presently can be in these: What is a good way to make sample data points available in a question? Upload large amount of data more easily
[ "stackoverflow", "0037951454.txt" ]
Q: AEM - import static pages? We're considering using Adobe Experience Manager for an upcoming project. But we have a number of pre-made static pages we'd like to import into this project. What would be the best way to 'import' these pages into an AEM project? Note: these pages are HTML that may contain some CSS and JS. A: You can serve static HTML, CSS and JS files from AEM. There are multiple ways of getting your files in AEM including but not limited to: 1) Through CRXDE, goto Create > Create File... name your HTML file and save. On the jcr:content subnode, double click on the jcr:data binary property, upload your HTML file and click save. 2) cURL your files into AEM. See the documentation on the SlingPostServlet. You can write a script in Bash, Python or your language of choice to loop over your files and POST to the AEM instance. 3) Go to CRXDE Package Manager, create a simple package, download it and unzip the file. Examine the contents of the zip including the .content.xml files and the /META-INF/vault/filter.xml file. Add your HTML files and update the package filters, zip up the files, upload the package to AEM through the CRXDE Package Manager and install.
[ "stackoverflow", "0023606139.txt" ]
Q: How to store string in stream in Delphi 7 and restore on mobile app in XE6? I develop a server and a mobile client that communicate over HTTP. Server is written in Delphi 7 (because it has to be compatible with old code), client is mobile application written in XE6. Server sends to client stream of data that contains strings. A problem is connected to encoding. On the server I try to pass strings in UTF8: //Writes string to stream procedure TStreamWrap.WriteString(Value: string); var BytesCount: Longint; UTF8: string; begin UTF8 := AnsiToUtf8(Value); BytesCount := Length(UTF8); WriteLongint(BytesCount); //It writes Longint to FStream: TStream if BytesCount > 0 then FStream.WriteBuffer(UTF8[1], BytesCount); end; As it's written in Delphi7, Value is a single byte string. On the client I read string in UTF8 and encode it to Unicode //Reads string from current position of stream function TStreamWrap.ReadString: string; var BytesCount: Longint; UTF8: String; begin BytesCount := ReadLongint; if BytesCount = 0 then Result := '' else begin SetLength(UTF8, BytesCount); FStream.Read(Pointer(UTF8)^, BytesCount); Result := UTF8ToUnicodeString(UTF8); end; end; But it doesn't work, when I display the string with ShowMessage the letters are wrong. So how to store string in Delphi 7 and restore it in XE6 on the mobile app? Should I add BOM at the beginning of data representing the string? A: To read your UTF8 encoded string in your mobile application you use a byte array and the TEncoding class. Like this: function TStreamWrap.ReadString: string; var ByteCount: Longint; Bytes: TBytes; begin ByteCount := ReadLongint; if ByteCount = 0 then begin Result := ''; exit; end; SetLength(Bytes, ByteCount); FStream.Read(Pointer(Bytes)^, ByteCount); Result := TEncoding.UTF8.GetString(Bytes); end; This code does what you need in XE6, but of course, this code will not compile in Delphi 7 because it uses TEncoding. What's more, your TStreamWrap.WriteString implementation does what you want in Delphi 7, but is broken in XE6. Now it looks like you are using the same code base for both Delphi 7 and Delphi XE6 versions. Which means that you may need to use some conditional compilation to handle the treatment of text which differs between these versions. Personally I would do this by following the example of TEncoding. What you need is a function that converts a native Delphi string to a UTF-8 encoded byte array, and a corresponding function in the reverse direction. So, let's consider the string to bytes function. I cannot remember whether or not Delphi 7 has a TBytes type. I suspect not. So let us define it: {$IFNDEF UNICODE} // definitely use a better conditional than this in real code type TBytes = array of Byte; {$ENDIF} Then we can define our function: function StringToUTF8Bytes(const s: string): TBytes; {$IFDEF UNICODE} begin Result := TEncoding.UTF8.GetBytes(s); end; {$ELSE} var UTF8: UTF8String; begin UTF8 := AnsiToUtf8(s); SetLength(Result, Length(UTF8)); Move(Pointer(UTF8)^, Pointer(Result)^, Length(Result)); end; {$ENDIF} The function in the opposite direction should be trivial for you to produce. Once you have the differences in handling of text encoding between the two Delphi versions encapsulated, you can then write conditional free code in the rest of your program. For example, you would code WriteString like this: procedure TStreamWrap.WriteString(const Value: string); var UTF8: TBytes; ByteCount: Longint; begin UTF8 := StringToUTF8Bytes(Value); ByteCount := Length(UTF8); WriteLongint(ByteCount); if ByteCount > 0 then FStream.WriteBuffer(Pointer(UTF8)^, ByteCount); end;
[ "stackoverflow", "0009219610.txt" ]
Q: How to trigger an IBAction method programmatically vs. via a button, etc? I can easily "do something", by creating an IBAction method, and connecting it to a button in IB. For example... -(IBAction)popThat:(id)sndr{ [windy setFrame:eRect display:YES];} However, I cannot, for the life of me, figure out how to do this via a simple, callable method... i.e. -(void) popThatMethod { [windy setFrame:eRect display:YES]; } -(void) awakeFromNib { [self popThatMethod]; } I would expect that this method would DO the same thing as clicking the button... as they are identical... but NO. Nothing happens. What am I missing here? A: I don't state that this is categorically the best answer, or the right way to do it, but one approach that works is to put the following in -applicationDidFinishLaunching:: [self performSelector: @selector(popWindow:) withObject:self afterDelay: 0.0]; This causes it to be called on the next pass of the runloop, by which time whatever was not in place before is now in place. A: Depending on what you're trying to do, you might want [buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside]; Which triggers the button as if it had been touched, and forces whatever actions are connected to it. NOTE: that's the answer from when I asked this SO question.
[ "android.stackexchange", "0000049776.txt" ]
Q: How to connect Samsung GT-i8160 and Debian via WiFi-Direct? The wpa_supplicant documentation contains information suggesting it is possible to set up a WiFi-Direct connection between a Linux box and another WiFi-Direct device. It seems it is necessary to use wpa_cli and issue a series of commands first of which is p2p_find. However when I use wpa_cli this command does not seem available. I am using Debian Wheezy. A: The issue is that there is only wpa_supplicant version 1.0 available in Debian Wheezy. For support of WiFi Direct you need wpa_supplicant version 1.1 or higher. You can download and compile the latest wpa_supplicant on your own. This way you make sure wpa_cli is available and WiFi Direct is supported.
[ "stats.stackexchange", "0000479817.txt" ]
Q: Will non-linear data always become linear in high dimension? I was reading the Hands on ML book and I'm on the SVM and Logistic Regression chapters. I started looking up more on these algorithms and apparently they are "linear" classifiers i.e the decision boundary is linear (The classifier needs the inputs to be linearly separable.) Now in the book it is mentioned that since in most of the cases data is not linearly separable, we have to increase the dimensions of the features to make it linearly separable. But is it always true that there is some transformation to convert every non-linearly separable data set into a linearly separable one? If not, what would be an example of such a data set where this is impossible? A: In theory, it is always possible to make any arbitrary dataset linearly separable in higher dimensions. In fact, you ideally only need to add one additional dimension to do so, which is a dimension that represents your true class labels. No matter what the data looks like in the other dimensions, if you have a way to add a dimension that represents the true class values, you can linearly separate on that dimension and perfectly recover the true classes. The only time it's impossible to add a dimension like this is if you have two identical samples with different classes, since there will be no deterministic way to map them to different classes given only the feature data. Otherwise, this mapping is always possible in theory, but in practice, it's usually difficult to come up with a way to generate that extra dimension of class labels which is generalizable and not overfit. A simple transformation is to look at all your datapoints, and just assign the true class as the value on your new dimension, but this method completely fails to generalize to points not in the original data. It's trivial to overfit the mapping to linearly separate the training data, but it's much more difficult to find a mapping that will accurately separate data you didn't train on.
[ "stackoverflow", "0018877172.txt" ]
Q: Adding methods to objects After coding in JS for a while I decided to make my own framework. Something similar to jQuery. But a very very stripped down version. After some googling I put together this code: function $elect(id) { if (window === this) { return new $elect(id); } this.elm = document.getElementById(id); } $elect.prototype = { hide: function () { this.elm.style.display = 'none'; }, show: function () { this.elm.style.display = ''; }, toggle: function () { if (this.elm.style.display !== 'none') { this.elm.style.display = 'none'; } else { this.elm.style.display = ''; } } }; So far this seems to work. But I'm not interested in the functionality. I want to understand the logic. Adding methods part is understandable. Though I didn't understand the function of if (window === this) { return new $elect(id); } If I remove it, function breaks. Since this is an if statement there are 2 results. True or false. So I tried to remove the if statement and just use return new $elect(id); assuming window === this returns true, but that didn't work. Then I thought it might return false, so removed the whole if statement. That also didn't work. Can someone enlighten me? Also is this code valid? I'm probably missing some stuff. Just tested on jsfiddle and it doesn't work. Though it works on jsbin o.O jsfiddle jsbin EDIT: using $elect(id).toggle(); to call it. Though you can check the demos. A: I want to understand the logic. $elect is a constructor function that is supposed to be called with the new keyword (new $select). If it is not ($elect()), what will happen then? There is no instance constructed, and the this keyword will point to the global object (window) - which we do not want. So this snippet is a guard against that occasion, when it detects that it invokes itself correctly with new and returns that. If I remove it, function breaks When you are calling it like $elect(id) without the guard, it will add a elm property to the global object (a global variable in essence) and return nothing. Trying to call the .toggle() method on that will yield the exception undefined has no method 'toggle'. I tried to remove the if statement, assuming window === this returns true Well, then you just created an infinite recursive function that will lead to a stack overflow exception when called. Btw, the proper way to guard against new-less invocation is not to compare against window (the global object might have a different name in non-browser environments) and assume everything else to be OK, but to check for the correct inheritance. You want the constructor only to be applied on instances of your "class", i.e. objects that inherit from $elect.prototype. This is guaranteed when called with new for example. To do that check, you will use the instanceof operator: function $elect(id) { if (! (this instanceof $elect)) { return new $elect(id); } this.elm = document.getElementById(id); } This also makes the intention of the guard explicit.
[ "stackoverflow", "0041826434.txt" ]
Q: NameError: name 'x_train' is not defined i'm new to this but can anyone tell me what's wrong it? I'm actually trying to do a predictive analysis(linear regression graph) based on the data i have in the excel . However , my graph isn't plotted out and i also faced this error. import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy from sklearn import linear_model df = pd.read_csv("C:\MongoDB\MongoData.csv") x_train = np.array(x_train).reshape(len(x_train), -1) x_train.shape y_train= [1,2,3,4,5] x_test = x_test.reshape(-1, 1) x_test.shape linear = linear_model.LinearRegression() linear.fit(x_train, y_train) linear.score(x_train, y_train) print('Coefficient: \n', linear.coef_) print('Intercept: \n', linear.intercept_) predicted= linear.predict(x_test) A: You make use of the variable x_train twice before you ever define it. You need to define it first, then use it. x_train = np.array(x_train).reshape(len(x_train), -1) # ^^^^^^^ ^^^^^^^ ^^^^^^^ # | | | # | +------------------------------------------------+ # | | You use x_train twice before it's ever defined | # | +------------------------------------------------+ # +------------------------------------------+ # | Your first definition of x_train is here | # +------------------------------------------+
[ "stackoverflow", "0035793751.txt" ]
Q: Replacing messed up formatted list on Excel I have such list that all chapters and sub chapters are in a format like the one below. __1________________________ __1__1_____________________ __1__2_____________________ __1__2__1__________________ Is there such way to change this list into the one below? 1 1.1 1.2 1.2.1 I have tried replace, however it replaces all _ of them with dots or spaces thus ruining the list nature. Is there a way to do this using VBA, it doesn't have to be VBA in your answer, because I can work on it to format it to fit VBA. I have many documents like this containing thousands of rows. A: This seems to correct your sample data quickly. Sub Replacing_messed_up_formatted_list() Dim rng As Range With Worksheets("Sheet4") With .Columns(1) .Replace what:=Chr(95), replacement:=Chr(46), lookat:=xlPart Do While Not .Find(what:=Chr(46) & Chr(46), lookat:=xlPart) Is Nothing .Replace what:=Chr(46) & Chr(46), replacement:=Chr(46), lookat:=xlPart Loop .Replace what:=Chr(32), replacement:=vbNullString, lookat:=xlPart .TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 9), Array(1, 2)) For Each rng In Intersect(.Parent.UsedRange, .Cells) If Right(rng.Value2, 1) = Chr(46) Then rng = Left(rng.Value2, Len(rng.Value2) - 1) Next rng End With End With End Sub             
[ "stackoverflow", "0037459574.txt" ]
Q: passing data from php to javascript for hybrid apps i'm building a cross platform mobile application using intel xdk and i need to retrieve data from php running on the server into my javascript...... this is my js code var meRequest; meRequest = new XMLHttpRequest(); meRequest.onreadystatechange=function() { if(meRequest.readyState==4) { alert("request sent"); alert((meRequest.responseText)); } } meRequest.open("GET", "http://127.0.0.1/my_queries_1.php",true); meRequest.send(); and this is my php code: <?php echo json_encode(500); exit; ?> this works when i run them both from localhost, i.e both scripts are on the server but i can't use this since for the app, the js has to be embedded in the mobile application and the php script remaining on the server... but if i run the javascript file outside local host get a null responseText. how do i go about this please?? A: So you need cross domain request and I think something like this should work for you: // (1) var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest; var xhr = new XHR(); // (2) cross domain request xhr.open('GET', 'http://anywhere.com/request', true); xhr.onload = function() { alert( this.responseText ); } xhr.onerror = function() { alert( 'error ' + this.status ); } xhr.send(); Server side should also allow such requests via generating special response headers: HTTP/1.1 200 OK Content-Type:text/html; charset=UTF-8 Access-Control-Allow-Origin: http://example.com
[ "askubuntu", "0000551119.txt" ]
Q: How to install sage from repository? Instructions from here did not work. Instructions: apt-add-repository -y ppa:aims/sagemath apt-get update apt-get install sagemath-upstream-binary After last command I get: $ sudo apt-get install sagemath-upstream-binary Reading package lists... Done Building dependency tree Reading state information... Done Package sagemath-upstream-binary is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'sagemath-upstream-binary' has no installation candidate How to overcome? UPDATE Check command $ sudo grep sage /etc/apt/sources.list.d/ -R /etc/apt/sources.list.d/aims-sagemath-trusty.list.save:deb http://ppa.launchpad.net/aims/sagemath/ubuntu trusty main /etc/apt/sources.list.d/aims-sagemath-trusty.list.save:# deb-src http://ppa.launchpad.net/aims/sagemath/ubuntu trusty main /etc/apt/sources.list.d/aims-sagemath-trusty.list:deb http://ppa.launchpad.net/aims/sagemath/ubuntu trusty main /etc/apt/sources.list.d/aims-sagemath-trusty.list:# deb-src http://ppa.launchpad.net/aims/sagemath/ubuntu trusty main /etc/apt/sources.list.d/aims-sagemath-trusty.list:# deb-src http://ppa.launchpad.net/aims/sagemath/ubuntu trusty main A: The Sage PPA currently only publishes a binary package for 64-bit systems: $ grep '^Package' /var/lib/apt/lists/ppa.launchpad.net_aims*_Packages /var/lib/apt/lists/ppa.launchpad.net_aims_sagemath_ubuntu_dists_trusty_main_binary-amd64_Packages:Package: sagemath-upstream-binary /var/lib/apt/lists/ppa.launchpad.net_aims_sagemath_ubuntu_dists_trusty_main_binary-amd64_Packages:Package: sagemath-optional /var/lib/apt/lists/ppa.launchpad.net_aims_sagemath_ubuntu_dists_trusty_main_binary-i386_Packages:Package: sagemath-optional The PPA page for that package lists only amd64 in the Builds section. Even in a VM, there's no reason not to use 64-bit. So install 64-bit Ubuntu.
[ "stackoverflow", "0044048217.txt" ]
Q: Fabric.io: new app does not show up in the dashboard For some reason we needed to change the package-id of our existing android application. We already use Fabric for Crashlytics. I'm trying to bring that new app up in the Fabric dashboard, but it's not showing there, despite the device log showing no issues (as fas as I can see): device log Any ideas why the new package-id isn't visible in our dashboard? Best, Sven A: I experienced a very similar issue to this when building an app with multiple flavours. The solution is to manually specify the package name, and not let Fabric try to automatically grab it, as it tries very hard to "stick" your old package name. There is a full post available (disclaimer: my site), but essentially you need to use: Fabric.with( Fabric.Builder(this) .kits(Crashlytics()) .appIdentifier(BuildConfig.APPLICATION_ID) .build() )
[ "meta.stackoverflow", "0000388375.txt" ]
Q: Using the code tags causing errors I've followed this answer to attempt to strike out previous erroneous code in this question I asked. My justification for doing this is that the code example I provided was misleading, however removing it removes context from the comments and answers already provided for future readers. Unfortunately the result is a "Your code is not properly formatted" error, which I don't appear to be able to bypass at all: The code previews correctly as expected, so I expect this is an editor validation issue? A: First, create a <s> tag and then inside it open a code block with three backticks ``` For instance <s> ` ` ` e.on(‘state_changed’, function(new_state) { // Kill countForever }); ` ` ` </s> Put the backticks ``` without spaces. This will solve the problem Example e.on(‘state_changed’, function(new_state) { // Kill countForever });
[ "codereview.stackexchange", "0000044335.txt" ]
Q: Slug URL Generator Just a slug generator. I'm wondering if this can be simplified any further. Many thanks. <?php function slug($string) { // Replace all non letters, numbers, spaces or hypens $string = preg_replace('/[^\-\sa-zA-Z0-9]+/', '', mb_strtolower($string)); // Replace spaces and duplicate hyphens with a single hypen $string = preg_replace('/[\-\s]+/', '-', $string); // Trim off left and right hypens $string = trim($string, '-'); return $string; } echo slug('-- This is an example of an ------ article - @@@ ..,.:~&**%$£%$^*'); // outputs "this-is-an-example-of-an-article" Updated version based on feedback: <?php function createSlug($slug) { $lettersNumbersSpacesHyphens = '/[^\-\s\pN\pL]+/u'; $spacesDuplicateHypens = '/[\-\s]+/'; $slug = preg_replace($lettersNumbersSpacesHyphens, '', $slug); $slug = preg_replace($spacesDuplicateHypens, '-', $slug); $slug = trim($slug, '-'); return mb_strtolower($slug, 'UTF-8'); } echo createSlug('-- This is an example ű of an ------ article - @@@ ..,.%&*£%$&*(*'); ?> A: You could create a few explanatory local variables: $lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/'; $spacesAndDuplicateHyphens = '/[\-\s]+/'; Usage: $lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/'; $slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug)); $spacesAndDuplicateHyphens = '/[\-\s]+/'; $slug = preg_replace($spacesAndDuplicateHyphens, '-', $slug); These would eliminate the comments. (I haven't checked the regexps, other names might be more appropriate.) Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler: Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose. And Clean Code by Robert C. Martin, G19: Use Explanatory Variables. slug could be renamed to cleanSlug (contains a verb) to describe what the function does. I'd rename the $string variable to $slug It would be more descriptive, it would express the intent of the variable. I'd use a whitelist instead of the blacklist. Defining the allowed characters (A-Z, 0-9 etc) would create proper URLs from URLs which contain special characters like é or ű.
[ "stackoverflow", "0000647172.txt" ]
Q: What are the pros and cons of using an email address as a user id? I'm creating a web app that requires registration/authentication, and I'm considering using an email address as the sole user id. Here are what I see as the pros and cons (updated with responses): PROS One less field to fill out during registration (it would just be email address, password, and verify password). I'm a big fan of minimalistic registration. An email address is easier to remember. (thanks Mitch, Jeremy) You don't have to worry about your favorite username being taken already - you're the only one who uses your email address. (thanks TStamper) CONS User has more to type every time they log in. What if a user wants multiple accounts? They'll need another email address. (Do I even want a user to be able to create multiple accounts?) Easy for a potential attacker to guess (if they know the target's email address, they know the login id). (thanks Vasil) Users may be tempted to use the same password they use for their email account, which is bad security. (thanks Thomas) If you change email addresses frequently, it may be difficult to remember which address you used to sign up for a site after a long hiatus. (thanks Software Monkey) A hacker could spam the registration form and use "email already taken" responses to generate a list of valid emails. (thanks David) Not everyone has an email address. (thanks Nicholas) If I went with email as id, I would provide a mechanism to allow it to be changed in the event a user changes address. In this case users would not be posting content to a public site, so a separate username won't be necessary to protect the email addresses (but it is something to consider for other sites). Another option is to implement OpenID (which is a whole other debate). This seems to work for Google, but their services are tightly integrated. What have I missed in my analysis? Do you have any recommendations? Does anyone have experiences to share? FINAL EDIT Thank you all for your responses. I have decided to use email as an id, but then allow the creation of a username for login purposes after registration. This allows a little flexibility while keeping registration as short as possible. It also prevents problems when a user changes email addresses (they can just log in with their username and update it). I will also be implementing methods to prevent brute-forcing of email addresses out of the registration and login systems (mainly a cool-down period after repeated attempts). A: Personally, I prefer just using my email address as a username. It's one less thing to remember, and I never have to worry about my preferred name being already taken. Just my 2 cents! A: I think you missed a PRO: Users are likely to remember their email address; and as email addresses are unique, they never have to worry about their preferred username being taken already. A: CONS When the same password is used for the e-mail account, compromising the one automatically means compromising the other.
[ "stackoverflow", "0041515234.txt" ]
Q: Extract a specific word from string in Javascript #anotherdata=value#iamlookingforthis=226885#id=101&start=1 Given the string above how could I extract "iamlookingforthis=226885" in the string? value of it might change as this is dynamic. So, other instance might be "iamlookingforthis=1105". The location/sequence might also change, it could be in the middle or last part. Thank you in advance. A: You can use Regex to match a specific text. Like this for example var str = '#anotherdata=value#iamlookingforthis=226885#id=101&start=1'; var value = str.match(/#iamlookingforthis=(\d+)/i)[1]; alert(value); // 226885 Explanation from Regex101: #iamlookingforthis= matches the characters #iamlookingforthis= literally (case insensitive) 1st Capturing Group (\d+) \d+ matches a digit (equal to [0-9]) + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) Global pattern flags i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z]) See RegExp on MDN Regex 101 - try regex and see the explanation of it and results Another alternative would be to split the string. You could split it by #|?|&. var str = '#anotherdata=value#iamlookingforthis=226885#id=101&start=1'; var parts = str.split(/[#\?&]/g); // split the string with these characters // find the piece with the key `iamlookingforthis` var filteredParts = parts.filter(function (part) { return part.split('=')[0] === 'iamlookingforthis'; }); // from the filtered array, get the first [0] // split the value and key, and grab the value [1] var iamlookingforthis = filteredParts[0].split('=')[1]; alert(iamlookingforthis); // 226885
[ "stackoverflow", "0017044953.txt" ]
Q: How does an JAX-RS 'endpoint' behave when making a request? There is something I am not sure I understand correctlty, therefore, I need help:) I have seen this: example, @Path("/resource") public class Resource { @Context private HttpHeaders headers; @GET public void get(@Context UriInfo uriInfo) { /* use headers or uriInfo variable here */ } } Does this mean that for each request the class that is transformed to 'endpoint' creates a separate thread? Because, otherwise, the headers information would not be accurate... Can you please indicate a (short:) ) resource, not JAX-WS specifications, where I can find info about this? A: I can't think of a shorter and more direct resource than the JAX-RS 1.1 spec itself. It is clear about what you are asking: JAX-RS provides facilities for obtaining and processing information about the application deployment context and the context of individual requests. (...) Context is specific to a particular request (...). May I add for completeness: that context information is obtained through the @Context annotation. As of resources, the context information is only available to the ones annotated with @Path (also called root resources). Also, @Context can inject the following context types: Application, UriInfo, HttpHeaders, Request, SecurityContext and Providers. And about the lifecycle (request/thread management): 3.1.1 Lifecycle and Environment By default a new resource class instance is created for each request to that resource. First the constructor is called, then any requested dependencies are injected (context is one of those dependencies), then the appropriate method is invoked and finally the object is made available for garbage collection. An implementation MAY offer other resource class lifecycles, mechanisms for specifying these are outside the scope of this specification. E.g. an implementation based on an inversion-of-control framework may support all of the lifecycle options provided by that framework. The conclusion is: Each request is, by default, handled by a different resource instance; The context is injected at request time (thus a different context per instance). Each specific implementation may change this lifecycle a bit, but the principles should be maintained (a context specific to each request). As you can see, also, the spec says nothing about thread management. Since most JAX-RS implementations are Servlet-based, we can assume with certain safety that the each request instance goes to a different thread - as servlet containers are thread per request.
[ "stackoverflow", "0011726554.txt" ]
Q: URL sometimes appended with jsessionid Grails / Spring Security Sometimes Spring Security appends a jsessionid to the end of my URL. Wouldn't bother me so much if it happened all the time or never, but it seems almost random. I'm wondering why this is happening and if it has anything to do with remember me not working correctly with LDAP? http://localhost:8080/myapplication/login/auth;jsessionid=A07D52CB78DB999947F3EED1917D60F6 A: JSESSIONID is created by tomcat (or other web container, see docs), it's not from Spring Security. JSESSIONID is the unique id of the http session, used at situation when application uses session (put/read some data from sesson during request), but there're no session cookie exists. At this case server trying both ways: setup cookie and append parameter to all links. Mostly it's because: first request from browser (no cookie at all) browser has sent invalid sessionid (for example when server was restarted, and existing session became invalid) And during such request session was used on server side (and was created new session). PS I'm not sure that it can be related to LDAP auth issue
[ "stackoverflow", "0061172533.txt" ]
Q: TypeError: slides.forEach is not a function I've started learning JS libraries recently and trying to make buttons (slides that are moving down while clicking on dots) white when they are active. And I get this mistake: TypeError: slides.forEach is not a function My code is: function init() { // wrapper function const slides = document.querySelectorAll(".slide"); const pages = document.querySelectorAll(".page"); const backgrounds = [ `radial-gradient(#2B3760, #0B1023)`, `radial-gradient(#4E3022, #161616)`, `radial-gradient(#4E4342, #161616)` ]; slides.forEach((slide, index) => { slide.addEventListener("click", function() { changeDots(this); }); }); function changeDots(dot) { slides.forEach(slide => { slide.classList.remove("active"); }); dot.classList.add("active"); } } init(); What did I do wrong? I guess it's about Arrows but still, don't understand why my friend can run this and it works, and for me it doesn't. (I added the TweenMax.min.js and TimelineMax.min.js from GSAP into my html) Before that, I got the same issue for "querySelectorALL" where I removed "ALL" and the Chrome stopped shouting that it's not a function either. Thank you! A: Because it is not array you should have to use querySelectorAll instead of querySelector it will return NodeLists const slides = document.querySelectorAll(".slide"); slides.forEach(node => { node.addEventListener("click", function() { changeDots(this); }); }); function changeDots(node){ slides.forEach(slide => { slide.classList.remove("active"); }); node.classList.add("active"); } .active{ background-color:#fc0; } <div class="slide"> 1st slide </div> <div class="slide"> 2nd slide </div>
[ "stackoverflow", "0006928157.txt" ]
Q: How to change color of hyperlink in android For displaying hyperlink on a page on my android app I am doing this: MyProgram.java link1.setText(Html.fromHtml(linkText1)); link1.setMovementMethod(LinkMovementMethod.getInstance()); TextView link = (TextView) findViewById(R.id.textView2); String linkText = "Visit the <a href='http://www.mydomain.com'>My Website</a> web page."; link.setText(Html.fromHtml(linkText)); link.setMovementMethod(LinkMovementMethod.getInstance()); // Place email address TextView email = (TextView) findViewById(R.id.textView3); String emailText = "Contact Me: <a href=\"mailto:[email protected]\">[email protected]</a>"; email.setText(Html.fromHtml(emailText)); email.setMovementMethod(LinkMovementMethod.getInstance()); myprogram.XML <TextView android:text="TextView" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:textSize="30dp"></TextView> <View android:layout_width="fill_parent" android:layout_height="30dp"> </View> <TextView android:text="TextView" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:textSize="30dp"></TextView> If you see in my XML, I have tried changing the color to black (android:textColor="#000000") but still I don't see any change in the hyperlink. It is still in default color i.e blue Any Help ? A: You should use another attribute: android:textColorLink="#000000"
[ "stackoverflow", "0039347295.txt" ]
Q: typo3 fluid template: cObject within too many conditions in viewhelper I need to put an hour selection within a form, so I created a custom viewhelper which rounds the minutes to multiples of 5 only. in setup.ts I decalare the time; lib.time = TEXT lib.time { data = date:H:i } in the template I call the cObject; <nr:time value="{f:cObject(typoscriptObjectPath: 'lib.time')}" /> I tried it also inline which works (wrapped in random ViewHelper); <f:link.action action="form">{nr:time(value: '{f:cObject(typoscriptObjectPath: \'lib.time\')}')}</f:link.action> now I get to where I need it which has a condition and here I didn't find any syntax that worked ...; <f:form.textfield property="date" class="date" value="{f:if(condition: ticket.time, then: '{ticket.time}', else: '{f:cObject(typoscriptObjectPath: \'lib.time\')}')}" /> anyone who knows a good solution, maybe I started of completely wrong, maybe no viewhelper is needed but I could format and manipulate the time directly in the lib. ps: this is the TimeViewHelper.php : class TimeViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper { /** * @param string $value * @return */ public function render($value) { $time = strtotime($value); $m = date('i', $time); $f = 5*60; // 5 minutes $r = $time % $f; $t = $time + ($f-$r); $new_time = ($m == 0 || $m % 5 === 0) ? $value : date('H:i', $t); return $new_time; } } A: You can always use the f:if condition with html syntax <f:if condition="{ticket.time}"> <f:then> <f:form.textfield property="date" class="date" value="{ticket.time}" /> </f:then> <f:else> <f:form.textfield property="date" class="date" value="{f:cObject(typoscriptObjectPath: 'lib.time')}" /> </f:else> </f:if>
[ "stackoverflow", "0020639191.txt" ]
Q: debug loads the currentt view instead of the view specified in routeconfig Mvc4 I have been working on a mvc4 solution and up until now when I pressed the debug button, the browser would open up to the /Home/Index action. no matter what class or view I was working on, it would load the default, just as specified in routeConfig.cs public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } since this morning this has changed. now if I am currently working on /Home/Example and press debug, the browser opens to that instead of Home/Index. I have no Idea what configuration I changed or what is causing this. any suggestions are welcome. A: Your problem has nothing to do with routing. It is related to the default startup page in Visual Studio. Right click on the ASP.NET MVC project in your solution explorer and choose Properties. Then navigate to the Web tab and on Specific Page write Home/Index: Maybe in your project you've got Current Page selected.
[ "scifi.stackexchange", "0000216042.txt" ]
Q: Was Willow's first magic display (blazing arrow through arm) actual magic, and if not, what's the trick? At the beginning of Willow, before the wizard chooses his apprentice for the year, Willow participates in a Nelwyn fair where he demonstrates two magic tricks: pushing a blazing arrow through a cylinder he wears on his arm (so supposedly, the burning arrow goes through his arm as well) while staying unscathed; making a piglet disappear. The piglet's disappearance is quickly shown to be some sleight-of-hand trick (the piglet was under the stage), which implies the arrow thing was a setup as well. However, throughout the movie, it seems Willow already has a bit of experience with magic. Sure, he's not really good at it, (transforming Fin Raziel into a crow instead of her human shape, etc.) but the impression I had, through him uttering the words and all, was that Willow had actually practiced some magic already. Thus, I'm curious whether the fire arrow trick may have been actual magic? It could still be a trick, but in this case I'm wondering what the trick is. The cylinder doesn't look wide enough for Willow to push his arm to the side and have the arrow going besides it, and anyway he would have been burned. Googling terms like willow nelwyn magic trick explained or magic trick fire arrow through arm don't seem to bring up anything relevant, except a "stage magic" wikia page which doesn't say much more than "illusions." Is there an answer as to how Willow seemingly managed to push a blazing arrow through his arm? I've only seen the movie, not read any novels; perhaps there is an answer there. A: The film's official novelisation confirms that Willow performed a variety of "tricks" (i.e. not magic) before the piglet illusion. But Willow had his own cheering-section, and they were so enthusiastic that they even drew some curious spectators away from the tug-of-war. Willow’s boyhood friend, Meegosh. stood solidly in his leather miner’s apron, one arm around Ranon and the other around Mims. All three wildly applauded every trick, even the old pull-the-feathers-out-of-nowhere maneuver, which Willow actually did quite well. Meegosh slapped his apron and yelled, “Bravo! Bravo!” so lustily that he attracted the attention of Burglekutt. The Prefect watched disdainfully from across the fairgrounds, pudgy hands spread on his stomach. Willow: Official Novelisation As to how it was performed, it's typically done by having the arm simply be out of the way of the candle. The holes (in this case knotholes) are placed in such a way that they look like they're opposite, but in reality they're slightly offset, leaving enough space for the arm. You can see the illusion performed here and here A: It appears to be based directly on this trick. Thus I assume it is meant to be sleight of hand like the piglet trick.
[ "stackoverflow", "0061686453.txt" ]
Q: Convert panda dataframe group of values to multiple lists I have pandas dataframe, where I listed items, and categorised them: col_name |col_group ------------------------- id | Metadata listing_url | Metadata scrape_id | Metadata name | Text summary | Text space | Text To reproduce: import pandas df = pandas.DataFrame([ ['id','metadata'], ['listing_url','metadata'], ['scrape_id','metadata'], ['name','Text'], ['summary','Text'], ['space','Text']], columns=['col_name', 'col_group']) Can you suggest how I can convert this dataframe to multiple lists based on "col_group": Metadata = ['id','listing_url','scraping_id] Text = ['name','summary','space'] This is to allow me to pass these lists of columns to panda and drop columns. I googled a lot and got stuck: all answers are about converting lists to df, not vice versa. Should I aim to convert into dictionary, or list of lists? I have over 100 rows, belonging to 10 categories, so would like to avoid manual hard-coding. A: my_vars = df.groupby('col_group').agg(list)['col_name'].to_dict() Output: >>> my_vars {'Text': ['name', 'summary', 'space'], 'metadata': ['id', 'listing_url', 'scrape_id']} The recommended usage would be just my_vars['Text'] to access the Text, and etc. If you must have this as distinct names you can force it upon your target scope, e.g. globals: globals().update(df.groupby('col_group').agg(list)['col_name'].to_dict()) Result: >>> Text ['name', 'summary', 'space'] >>> metadata ['id', 'listing_url', 'scrape_id'] However I would advise against that as you might unwittingly overwrite some of your other objects, or they might not be in the proper scope you needed (e.g. locals).
[ "stackoverflow", "0023025702.txt" ]
Q: PHP Code to Twig Code Recently a programmer converted my Wordpress templates to Twig code and I'm not quite sure from looking at the code how I would write the following examples out in Twig code. Can anyone point me in the right direction? Thank you so much! <?php if ( $post->post_date >= date("2003-07-15 00:00:00") && $post->post_date <= date("2004-07-17 23:59:59")) { ?> <?php } elseif ( $post->post_date >= date("2004-12-23 00:00:00") && $post->post_date <= date("2005-07-16 23:59:59")) { ?> <?php } else { ?><?php } ?> A: Twig is a template engine. You should do most if not all of the processing with PHP. Only then you pass the processed data to Twig as a variable. For example, you can do something like this. PHP <?php $data['posts'] = array('type' => 0, 'post' => ''); if ( $post->post_date >= date("2003-07-15 00:00:00") && $post->post_date <= date("2004-07-17 23:59:59")) { $data['posts'][] = array('type' => 1, 'post' => $post); } elseif ( $post->post_date >= date("2004-12-23 00:00:00") && $post->post_date <= date("2005-07-16 23:59:59")) { $data['posts'][] = array('type' => 2, 'post' => $post); } else { $data['posts'][] = array('type' => 0, 'post' => $post); } ?> Twig {% for post in posts %} {% if post['type'] == 1 %} $post->post_date >= date("2003-07-15 00:00:00") && $post->post_date <= date("2004-07-17 23:59:59") goes here {% elseif post['type'] == 2 %} $post->post_date >= date("2004-12-23 00:00:00") && $post->post_date <= date("2005-07-16 23:59:59") goes here {% else %} Everything else goes here {% endif %} {% endfor %}
[ "stackoverflow", "0004161666.txt" ]
Q: Android AudioRecord fails to initialize I've been having an issue with using AudioRecord for Android. I've read as much as I can find online about it, but I cannot seem to get a good initialization. I have tried the Android 2.2 emulator, 1.5 emulator and my phone, an HTC Incredible running Froyo. The emulators and my phone fail initialization. I've tried sampling rates of 8000, 11025, and 44100, formats of CHANNEL_IN_MONO/STEREO and CHANNEL_CONFIGURATION_MONO/STEREO, 8bit and 16bit encoding (8 bit makes the getMinBufferSize fail), and AudioSource of MIC and DEFAULT. All result in the variable test becoming 0 after running a get state(failed initialization). It seems from everything I've read that this should correctly initialize the object. I have played around with the multiplier on buflen, to have it range from 512 (the result of the function) to 102400 because I had heard that HTC devices require something above 8192. For testing my problem I made a new, small project that recreates my problem as simply as possible. I pull out the constants needed into local ints then run the constructor and access the getState method for checking if it worked. package com.example.audiorecordtest; import android.app.Activity; import android.os.Bundle; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; public class audioRecordTest extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); int freq =8000; int chan = AudioFormat.CHANNEL_IN_MONO; int enc = AudioFormat.ENCODING_PCM_16BIT; int src = MediaRecorder.AudioSource.MIC; int buflen = AudioRecord.getMinBufferSize(freq, chan, enc); AudioRecord ar = new AudioRecord(src,freq,chan,enc,20*buflen); int test = ar.getState(); } } A: I think he means you need the RECORD_AUDIO permission in the manifest: <uses-permission android:name="android.permission.RECORD_AUDIO" /> That worked for me. A: --edit-- Please see Bill's answer. --end edit-- Maybe you should check whether you acquired the correct permission. e.g. you need to get android.permission.VIBRATE in your AndroidManifest.xml file if you need to vibrate the device.
[ "stackoverflow", "0007211807.txt" ]
Q: Deleting lines from the middle of a TextCtrl I need to delete X lines from the middle of a textctrl starting from line number Y Is there any easy way to do this? I can't see one: it seems like I have to somehow search through the contents of the TextCtrl counting newlines to find the position of Y... A: if self._log.GetNumberOfLines() > MAX_LINES: if self._log.GetLineText(DELETION_POINT) != DELETION_LINE: start = self._log.XYToPosition(0, DELETION_POINT) self._log.SetInsertionPoint(start) self._log.WriteText(DELETION_LINE) while (self._log.GetNumberOfLines() > MAX_LINES): start = self._log.XYToPosition(0, DELETION_POINT+1) len = self._log.GetLineLength(DELETION_POINT+1) self._log.Remove(start, start+len+1)
[ "stackoverflow", "0027213470.txt" ]
Q: Why this subquery is 10x faster than inner join I have two tables ecdict and favourite and one view which just inner join two tables. CREATE TABLE ecdict('_id' INTEGER PRIMARY KEY, 'word' VARCHAR NOT NULL UNIQUE, 'meaning' VARCHAR, 'phonetic_string' VARCHAR, 'example' VARCHAR); CREATE TABLE favourite('_id' INTEGER PRIMARY KEY, 'word' VARCHAR NOT NULL UNIQUE); CREATE VIEW favourite_word as select ecdict.* from ecdict INNER JOIN favourite ON ecdict.word = favourite.word; Here is the execution time of result: Time: 0.010 select ecdict.* from ecdict where word in (select word from favourite); Time: 0.226 select * from favourite_word; Why they differ so much? It if is related to query plan, why sqlite chooses a slower one? How can I guide sqlite to choose the faster one? Thanks A: You need to look at the query plan to see what is really happening. The following is (informed) speculation. When you have an inner join with two sets of indexes, you basically have two possible query plans: Scan the edict table and look up words in the favourites using the index on favourite.word. Scan the favourite table and look up words in edicts using the index on edicts(word). Then look up the record in edit when there is a match. (A unique contraint creates an index.) All these being equal -- that is, with no information about table sizes -- the first approach would be preferred in this case. Why? Because there is no additional step to look up the additional columns. When you phrase the query using in, I think that SQLite will always use the first approach. In this case, I am guessing that the favourite table is much smaller than the edict table, so the second approach is actually better. When you write the query as a join, both possibilities are considered and the better one is chosen.
[ "stackoverflow", "0044922267.txt" ]
Q: Access ApiController User in class library I have a Web API 2.2 application and want to filter data based on the current user that is accessing the Web API. The User property on the ApiController has the information that I need. But how can I get that information to my service class? Of course I don't want to pass everything around via parameters, but via my DI. A: You want to pass your principal into the methods of the service class, not as a constructor parameter. Depending on how you are using DI, that service class can hang around for a while, and you don't want the class to have the principal in that case. You want your principal to be short lived.
[ "electronics.stackexchange", "0000143670.txt" ]
Q: How to wire subwoofer to 2.0 channel amplifier How to wire the sub-woofer amp to existing 2 channel amplifier? I have dual LM386 for left and right channel and I would like to connect a sub-woofer. where should I wire the sub ? Is it in the right channel or the left channel and before LM386 or after or combine both channel ? (The sub will be use different IC and power source) simulate this circuit – Schematic created using CircuitLab A: You should mix channels at line level and then amplify each of them with individual amplifier. Take a look at this article to get some ideas on how to mix audio channels: https://sound-au.com/project18.htm
[ "stackoverflow", "0003196084.txt" ]
Q: accessing one mercurial repo with different methods I want to make the same (physically same) Mercurial repository accessible via ssh and https (hgwebdir). Are there transaction problems when ssh users and http users push at the same time? A: No, Mercurial is set up to handle this, and will (write) lock the repo once a transaction begins. The second user will just have to wait a little bit before their push goes through. Simultaneous requests can happen if it is served just by one or the other, so setting up both won't cause any additional problems.
[ "stackoverflow", "0003489926.txt" ]
Q: search box won't float to the right in IE8 this search box won't float to the right in IE8 on a wordpress site. See a screenshot how it looks in FF and how it looks in IE8: http://www.abload.de/img/searchbox_bugl4z5.jpg Code of the header.php (added float:right here but I guess that is not useful that way?): <div id="topnav"> <?php echo qtrans_generateLanguageSelectCode('image'); ?> <br /> <form style="float:right;" role="search" method="get" id="searchform" name="searchform" action="#" > <div style="float:right;"> <input class="text" type="text" value="Search for..." onfocus="if(this.value == 'Search for...'){this.value = '';}" name="s" id="s" /> <input class="button-secondary" type="submit" id="searchsubmit" value="Search" /> </div> </form> </div><!-- /#topnav --> CSS code: #topnav{ font:17px/17px Helvetica, Arial, sans-serif; padding:0; float:right; margin-top:23px; } I looked at some threads here but wasn't really able to figure out the solution. Thanks guys! A: If your #topnav doesn't need to be floated next to anything, you can fix it by removing all the style="float:right;" from your HTML and changing the #topnav CSS as follows: #topnav{ text-align: right; font:17px/17px Helvetica, Arial, sans-serif; padding:0; margin-top:23px; } What the above does is make the #topnav container a 100% width, non-floated element that aligns everything inside to the right. You can see it in action here. Feel free to post more code/screenshots if the above won't work for you. If you've got a dev link we can look at, even better.
[ "stackoverflow", "0004279048.txt" ]
Q: How to detect that the window is unfocused? Or more specifically - how (or actually - can you) detect if the current window has focus (i.e. it is the active window) when the window just opens? I know I can listen for window.onblur and window.onfocus, but I'm trying to figure out how to address users that "open link in background tab/window" and the code starts running without either the onblur or onfocus events being called. A: Unfortunately, You cannot detect if window has focus in Javascript. You can only notice when it get or lost focus using onfocus and onblur, as You said.
[ "stackoverflow", "0043024411.txt" ]
Q: Angular 2 Parent Component Losing Input Binding from Child Component I'm working with a parent component that references a child component that plays an audio file in Angular 2. Initially, I'm passing the audio file an input variable of _audioState which contains a string value of "Listen". When the audio button is clicked, this value changes to "Playing" and then "Replay" once the audio file is done playing. These string value changes happen in the audio child component. When the button with the nextAudio function is clicked in the parent component, I want to reassign _audioState back to "Listen", but the input binding isn't working in the parent once the child component changes this value. I'm still learning Angular 2 and wasn't sure the best way to get this working. I appreciate any suggestions. My code is below. Parent Component: @Component({ selector: 'parent-component', template: ' <div> <button (click)="nextAudio()"></button> <audio-button [audioPath]="_audioPath" [audioSrc]="_audioCounter" [audioState]="_audioState"> </audio-button> </div>', styleUrls: ['./parent-component.less'] }) export class ParentComponent { _audioPath: string = "../audio/"; _audioCounter: number = 1; _audioState: string = "Listen"; nextAudio(): void{ this._audioCounter = this._audioCounter + 1; this._audioState = "Listen"; } } Child Component: @Component({ selector: 'audio-button', template: '<button (click)="playSound()"><i class="fa fa-volume-up"></i> {{audioState}}</button>', styleUrls: ['./audio-button.component.less'] }) export class AudioButtonComponent { @Input() audioPath: string; @Input() audioSrc: string; @Input() audioState: string; playSound(): void { let sound: any = new Audio(this.audioPath + this.audioSrc + ".mp3"); sound.play(); this.audioState = "Playing"; sound.addEventListener('ended', () => { this.audioState = "Replay"; }, false) event.preventDefault(); } } A: there are several ways to do it, including of 1. (Recommand) Using ngrx/store References Adding Redux with NgRx/Store to Angular (2+) – Part 1 (Oren Farhi) 2. EventEmitter For example, @Component({ selector: 'parent-component', template: `<div> Current state : {{_audioState}} <hr /> <audio-button [audioPath]="_audioPath" [audioSrc]="_audioCounter" [audioState]="_audioState" (emit-status)="updateStatus($event)" > </audio-button> </div>` }) export class ParentComponent { _audioPath: string = "../audio/"; _audioCounter: number = 1; _audioState: string = "Listen"; nextAudio(): void{ this._audioCounter = this._audioCounter + 1; this._audioState = "Listen"; } private updateStatus(status:string){ this._audioState= status; } } import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'audio-button', template: `<button (click)="playSound()"><i class="fa fa-volume-up"></i> {{audioState}}</button>`, }) export class AudioButtonComponent { @Input() audioPath: string; @Input() audioSrc: string; @Input() audioState: string; @Output('emit-status') emitStatus = new EventEmitter<any>(); playSound(): void { //... //emit data to parent this.emitStatus.emit("playing"); } } 3.ViewChild @Component({ selector: 'parent-component', template: `<div> Current state : {{audioBtn.audioState}} <hr /> <audio-button [audioPath]="_audioPath" [audioSrc]="_audioCounter" [audioState]="_audioState" (emit-status)="updateStatus($event)" > </audio-button> </div>` }) export class ParentComponent { @ViewChild(AudioButtonComponent) audioBtn: AudioButtonComponent; } export class AudioButtonComponent { //... @Input() audioState: string; playSound(): void { //... this.audioState = "playing"; } } Result
[ "stackoverflow", "0062256474.txt" ]
Q: Where to store shadow colors in ThemeData? 1- I have a container with a box shadow and that shadow has a different color depending on the theme. Where exactly do I store the shadow color in ThemeData? I stored the container’s color in canvasColor but I am not sure where to put the shadow color. So I can easily do Theme.of(context)... 2- When making separate themes, is it ok if I do return ThemeData(myStuff); instead of doing ThemeData().copyWith(myStuff);? Or is copyWith the recommended way? A: Usually you don't change shadows by theme. If so.. you can create you own class and store shadows there. class MyShadows { static const primaryShadow = Shadow(color: Colors.black, blurRadius: 3, offset: Offset(2, 3)); static const secondaryShadow = Shadow(color: Colors.black, blurRadius: 3, offset: Offset(2, 3)); } ... Container( decoration: BoxDecoration(boxShadow: [MyShadows.primaryShadow]), ); It's okay. When you do ThemeData(). copyWith(yourStuff) - you create new instance of ThemeData, and then create another instance from it, by calling copyWith
[ "math.stackexchange", "0000189225.txt" ]
Q: Generalization of $\frac{x^n - y^n}{x - y} = x^{n - 1} + yx^{n - 2} + \ldots + y^{n - 1}$ I thought about a generalization for the formula $$\frac{x^n - y^n}{x - y} = x^{n - 1} + yx^{n - 2} + \ldots + y^{n - 1}$$ It can be written as $$\frac{x^n - y^n}{x - y} = x^{n - 1} + yx^{n - 2} + \ldots + y^{n - 1} = \sum_{i + j = n - 1}x^iy^j$$ So we would like to generalize: $$\sum_{i_1 + i_2 + i_3 + ... +i_k = n - 1}{x_1}^{i_1}{x_2}^{i_2}{x_3}^{i_3} \cdots {x_k}^{i_k}$$ For example" $$\sum_{i + j + k = n - 1}{x}^{i}{y}^{j}{z}^{k} = \sum_{k=0}^{n - 1}{z}^{k} \sum_{i + j = n - k - 1}{x}^{i}{y}^{j} = \sum_{k=0}^{n - 1}{z}^{k} \frac{x^{n - k} - y^{n - k}}{x -y} = \frac{1}{x-y} \left(\frac{x^{n + 1} - z^{n + 1}}{x - z} - \frac{y^{n + 1} - z^{n + 1}}{y - z}\right)$$ It seems that the generalized expression is the divided difference of $x^{n + k - 2}$ in the points $x_1, x_2, \ldots, x_k$. Does anyone have an idea how to prove it? A: I think that this formula is what you are looking for. If $\mathbf x = (x_1,\dotsc,x_r)$, then $$ \sum_{|I|=n} \mathbf{x}^I = \sum_i\frac{x_i^{n}}{\prod_{j\neq i}(1-\frac{x_j}{x_i})}. $$ With 1 variable, it gives $$ x^n = x^n, $$ for two, $$ \sum_{i+j = n} x^i y^j = \frac{x^{n+1}}{x-y} + \frac{y^{n+1}}{y-x}, $$ and for three, if gives $$ \sum_{i+j+k=n} x^i y^j z^k= \frac{x^{n+2}}{(x-y)(x-z)} + \frac{y^{n+2}}{(y-x)(y-z)} + \frac{z^{n+2}}{(z-x)(z-y)}. $$
[ "stackoverflow", "0026397830.txt" ]
Q: How to display the tooltip in exact location with in the table? I have a table were the row is being looped and and for some instance I want to hover the mouse of one of its tr under the td with a class="updeltd" and display a div element as its tooltip. My problem is when I hover the mouse on that td I can only be able to display my tooltip on the first row of the table instead of the row where I put the mouse. I think I have a problem on my javascript function. Here's the details, Thanks... jQuery/Javascript function: function DispTooltip() { var ttipshow = document.getElementById("tooltip"); ttipshow.style.display = "block"; var coord = $(this).closest('table').find('td[class="updeltd"]').offset(); $('#tooltip').css({ top: coord.top, left: coord.left - 345 }); } Tooltip: <div id="tooltip"> This is my tooltip </div> HTML View: <table> <tr> <th> @Html.DisplayNameFor(model => model.ID) </th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Address) </th> <th> @Html.DisplayNameFor(model => model.Age) </th> <th> @Html.DisplayNameFor(model => model.Occupation) </th> <th> @Html.DisplayNameFor(model => model.Nationality) </th> <th></th> </tr> @foreach (var item in Model) { <tr > <td id="ID"> @Html.DisplayFor(modelItem => item.ID) </td> <td id="Name"> @Html.DisplayFor(modelItem => item.Name) </td> <td id="Addr"> @Html.DisplayFor(modelItem => item.Address) </td> <td id="age"> @Html.DisplayFor(modelItem => item.Age) </td> <td id="occ"> @Html.DisplayFor(modelItem => item.Occupation) </td> <td id="natn"> <input type="text" id="nat" value=" @Html.DisplayFor(modelItem => item.Nationality)" style="display:none" /> @Html.DisplayFor(modelItem => item.Nationality) </td> <td id="image" onmouseover="DispTooltip()" onmouseout="return HideTooltip();"> <img id="detimg" alt="" src="@Url.Content("~/Photos/" + item.Photos)" style="width:50px;height:50px" /> </td> <td id="updel" class="updeltd" onmouseover="DispTooltip()" onmouseout="return HideTooltip();" > @Html.ActionLink("Edit/Delete Records", "UpdateDeleteRec", new { id=item.ID}) </td> </tr> } </table> A: What you currently doing is finding the closest table element then finding all the class="updeltd" elements so .offset() returns the offset of the first one (the first row). What you need is var coord = $(this).closest('tr').children('.updeltd').offset(); Note you are also creating invalid html by duplicating id's for each td element. Use class names instead
[ "stackoverflow", "0048396690.txt" ]
Q: Docker vs Virtual Machine I have read documents that are about dockers and VMs.I guess that our environments like that dev,prod run on virtual machines in a server.Each of them runs on different virtual machine but single computer(server).Also,each virtual machine contains docker.Every docker contains containers.In this containers, application image file is hold.For example; in virtual machineB ,containerB includes image for our application.Am i right? Can a docker contains many containers? Why we need many containers in a docker? Can anyone explain docker,virtual machine,environments and image files?How these enviroments runs server? A: From https://www.docker.com/what-container: A container image is a lightweight, stand-alone, executable package of a piece of software that includes everything needed to run it. Docker is the service to run multiple containers on a machine (node) which can be on a vitual machine or on a physical machine. A virtual machine is an entire operating system (which normally is not lightweight). If you have multiple applications and those require different configurations which are in conflict with each other you can either deploy them on different machines or on the same machine using docker containers, because containers are isolated from each other. So in short containers can make your application deployment and management easier.
[ "pt.stackoverflow", "0000252307.txt" ]
Q: imprimir conteúdo de div noutra página Tenho uma página de php que recebe valores de um formulário (post) e queria imprimir esse resultados em papel. Acontece que ao clicar no botão o valor no textarea não aparece na impressão. Na página de origem tenho este formulário com textarea e um botão para imprimir, assim: <form method="post"> <p><textarea name="textoImprimir" cols="" rows="" class="anamnese-tarea">quero imprimir este texto que acabei de digitar.</textarea></p> <p><iframe src="imprimir.php" name="frame1" style="display:none;"></iframe> <input type="button" onclick="frames['frame1'].print()" value="print!"></p> </form> Na página imprimir.php tenho assim: <?php $textoImprimir = $_POST['textoImprimir']; ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Imprimir</title> <style> html, body { width:100%; height:100%; margin:0px; } .fundo { background: url(../_imagens/fundo_print.png); background-size: 100% 100%; background-repeat: no-repeat; } @page { size: A4; margin: 15mm 15mm 15mm 15mm; } table { top:18%; bottom:20%; position:absolute; } </style> </head> <body class="fundo"> <table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="20%" align="center" valign="middle">ALGUM TEXTO</td> </tr> <tr> <td height="80%" align="justify" valign="top"><?php echo $imprimir;?></td> </tr> </table> </body> </html> A: Altere o form de impressão para ser dessa forma, assim passaremos via POST, para que possamos fazer a impressão no arquivo imprimir.php <form method="post" action="imprimir.php" enctype="multipart-form/data"> <textarea name="textoImprimir" id="textoImprimir" cols="" rows="" class="anamnese-tarea">quero imprimir este texto que acabei de digitar.</textarea> <input type="submit" value="Imprimir!"> </form> Dentro do imprimir.php você poe <script>window.print();</script> E troque $textoImprimir = $_POST['textoImprimir']; por $imprimir = $_POST['textoImprimir'];
[ "stackoverflow", "0013910115.txt" ]
Q: ClaimsPrincipalPermission - Error Code I use the ClaimsPrincipalPermission for authorization in my asp 4.5 website. This works fine. But when the user tries to call a page which he is not allowed the error code returned is a 500 and not some like 401. Is this the expected behavior ? I assume 401 would express more why this page can't be called. Or do I have an error ? In the debugger I see that a securityexception is correctly thrown. Is there a way to chjange this behvaior ? Does anyone know why this happens? A: ClaimsPrincipalPermission throws a SecurityException. You maybe want to use something that playes nicer with web framework... see here: http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/
[ "stackoverflow", "0013965287.txt" ]
Q: unit testing of "delegate" class In some situations, I have to use a delegate class which just delegates the incoming request to another class. for example, public class ServiceDelegate { private EmployeeService service; public List fetchEmployees() { service.fetchEmployees(); } } Though this class does not do any logic other than calling the service class, still I am thinking , we should verify if the delegation happens properly or not , through unit testing, possibly by one positive test case. Is it the correct approach? Some of my friends say that unit testing code which is not doing any logic, like delegation, is a waste of time. Please advise. Appreciate for your answers. A: Unit testing is valuable for two reasons: it tells you what code to write, and it makes sure that code doesn't change accidentally. @RustyTheBoyRobot makes a good point in his comment. I would expand it: if you feel like you don't need a unit test for some piece of code, it likely means you don't need that piece of code. However, I often write very thin proxies or adapters. Caching proxies especially call for some testing around when delegation occurs. In those kind of cases, unit tests are entirely appropriate. Shameless plug: here's a utility class that makes delegation testing easier.
[ "wordpress.stackexchange", "0000098645.txt" ]
Q: Filtering a WP_Query meta_query by numeric values isn't working That was a very dense title. I have a custom post type "event" which has a Date/Time picker field "event_date" thanks to the Advanced Custom Fields plugin. This Date/Time picker saves a UNIX timestamp to the database. I'm trying to use WP_Query to get all events that are today or in the future. This is the code that I have right now: $args = Array( 'post_type' => 'event', 'posts_per_page' => -1, 'meta_key' => 'event_date', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array( 'key' => 'event_date', 'compare' => '>=', 'value' => intval(strtotime(date('Y-m-d'))), 'type' => 'numeric' ), ); $query = new WP_Query( $args ); It's giving me all the events, past and future. I realize that the timestamps are stored as strings in the database so 'compare' => '>=' normally wouldn't work, but what what I've read on Google and in the Codex that 'type' => 'numeric' should cast the string to an integer and allow it to be compared with my value of this morning at midnight. Unfortunately that doesn't seem to be working and I don't understand why. A: Try an array of arrays in your meta query. $args = Array( 'post_type' => 'event', 'posts_per_page' => -1, 'meta_key' => 'event_date', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'event_date', 'compare' => '>=', 'value' => intval(strtotime(date('Y-m-d'))), 'type' => 'numeric' ) ), ); $query = new WP_Query( $args );
[ "stackoverflow", "0030636392.txt" ]
Q: Entity Framework 6 Creating an single related record I am using Entity Framework on a project involving TV Series. The data is loaded by loading Episode files. When I create an Episode it should find the series that it belongs to and use that one or else create a new one. I am using an "EpisodeFactory" to create the Episodes and it works until I save and then it creates a new series for each episode. I am looking for: Series : Id = 01, Name = 'Gotham' Episode : Id = 21, Name = 'GothamS01E01', Series = 01 Episode : Id = 22, Name = 'GothamS01E02', Series = 01 What I am Getting: Series : Id = 01, Name = 'Gotham' Series : Id = 02, Name = 'Gotham' Series : Id = 03, Name = 'Gotham' Episode : Id = 21, Name = 'GothamS01E01', Series = 02 Episode : Id = 22, Name = 'GothamS01E02', Series = 03 Here is my UnitTest for this: [Test] public void ShouldLoadSeriesIfOneExists() { const string testDirectory = TestContstants.TestDir + @"\ShouldLoadSeriesIfOneExists"; var episodeFactory = new EpisodeFactory(); var randomSeriesName = Guid.NewGuid().ToString(); var testEpisodeA = episodeFactory.createNewEpisode(testDirectory + @"\" + randomSeriesName + @"S01E01.avi"); var testEpisodeB = episodeFactory.createNewEpisode(testDirectory + @"\" + randomSeriesName + @"S02E03.avi"); using (var dbContext = new MediaModelDBContext()) { dbContext.Episodes.Add(testEpisodeA); dbContext.Episodes.Add(testEpisodeB); dbContext.SaveChanges(); Assert.That(dbContext.Series.Count(s => s.SeriesName == randomSeriesName), Is.EqualTo(1)); dbContext.Series.Remove(testEpisodeA.Series); } } The EpisodeFactory get a file name and extracts the Episode information from the file. The Series is fetched with: public Series GetSeriesBySeriesName(string seriesName) { using (var dbContext = new MediaModelDBContext()) { if (dbContext.Series.Any()) { var matchingSeries = dbContext.Series.FirstOrDefault(series => series.SeriesName == seriesName); if (matchingSeries != null) return matchingSeries; } var seriesByShowName = new Series(){SeriesName = seriesName}; dbContext.Series.Add(seriesByShowName); dbContext.SaveChanges(); return seriesByShowName; } } And the relevant model: public class Episode { [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key] public virtual int EpisodeId { get; set; } public virtual Series Series { get; set; } // ... } public class Series { [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key] public int SeriesId { get; set; } public string SeriesName { get; set; } public ObservableCollection<Episode> Episodes { get; set; } public Series() { } // ... } A: Are you sharing the same DBContext Instance in test and Factory? If not this is the problem that you are using difererent DBContext Instances in your factory method and in your test. If you use different DBContext instances Entity Framework is not able to kwnow that series object exist in database, series become a deattached object for the DBContest instance in your test (google for deattached entity framework) You have to share the same DBContext instance across test and factory, or work with series as deatthaced object.
[ "stackoverflow", "0017962572.txt" ]
Q: Run external command from within Perl I am using Doxygen to generate HTML documentation and then run a Perl script to get function names. To run Doxygen configuration, I need to run doxygen file_name in cmd. But I want to run everything from Perl. I tried this code my $cmd = "perl -w otherscript.pl"; my $result = system("start $cmd"); But it just opens a cmd window. I need to execute cmd code directly through Perl (not a Perl command line, but through a Perl IDE). Is there a way to achieve this? A: Your usage of system and start is OK. From your description in the comment, I think it's because you're not using the correct escaping method when giving configure files to Doxygen that it throws such an error: Error: configuration file C:SERSGHOSHBCD not found! Try with my $result = `doxygen C:\\Users\\aghosh\\abcd`; In the two back-slashes, the former one is to escape the latter one, so that it's recognized by Windows as the directory separator.
[ "stackoverflow", "0018017118.txt" ]
Q: "smali" grammar specification | smali log injection Is there any grammar specification available for smali code ? I am trying to play around with the smali code and one of the things that is missing me is the fact that some methods in smali have the .prologue section and some don't. Unfortunately the wiki doesn't seem to have information about smali grammar. Has anyone found yourself in this situation before ? Any suggestions/solutions would be much appreciated. EDIT1: My objective is to add log messages to the beginning of onResume method of all activities of an app. EDIT2: I am using ANTLRv4.1 parser to parse my smali files and I get a CommonTree (the parse tree) and a TokenStream from the smaliLexer. Now is creating the Token for the log instruction and altering the parse tree and thereafter generating the classes.dex file the right way to go ? So far I havent found a way to alter the TokenStream and I am not able to generate dex files from the altered ParseTree. A: Almost everything in the smali language has a direct analogue in dalvik bytecode/dex format. In this case, the .prologue directive corresponds to the DBG_SET_PROLOGUE_END debug opcode that is part of the debug_info_item. From http://s.android.com/tech/dalvik/dex-format.html: sets the prologue_end state machine register, indicating that the next position entry that is added should be considered the end of a method prologue (an appropriate place for a method breakpoint). The prologue_end register is cleared by any special (>= 0x0a) opcode.
[ "stackoverflow", "0007255095.txt" ]
Q: Is it a good Idea to fork an open source software which is available under GPL license? I wanted a software with set of requirements, But I do not want to rewrite the basic framework as it is available in few Open source softwares which are available under GPL licenses. What are the things I need to look into when I fork a Open Sourced projects? can I have any rights on the forked software? A: In general the right thing to do is to work with the community and get your modifications into the core project where you can share the cost of maintenance with them. However, this might not always be possible for various reasons (e.g. community doesn't want to go in the direction you want to go or the community is unresponsive). If you choose to fork then you are taking on responsibility for the maintenance of your fork. This means spending resources on staying aligned with the donor "upstream" project in order to be able to upgrade cleanly in the future. In many cases the effort involved in doing this is as great, if not greater, than the effort in collaborating upstream. Many projects are built to use plugins to provide extra features. This is a much better route than forking, when possible. In terms of rights on the fork you have no rights over the original code other than those assigned to you under the GPL. If you distribute your fork you must distribute it under the GPL (other licences provide the right to sub-licence, but the GPL does not). You will retain copyright in your modifications, but they must be distributed under GPL. In summary, if you can avoid forking you should do so. Whether you can avoid it depends on the health of the community managing the project.
[ "serverfault", "0000159381.txt" ]
Q: How can I merge a SSL vhost config and a non-ssl vhost config for a same site? I want my website to support both non-SSL and SSL access. What I had to do is copy the non-SSL config and change the port to 443 and add the SSL stuff. Not ideal to administrate! Is there a way to merge those two configuration? Here's my current config: <VirtualHost *:80> ServerName www.site.tld ServerAlias site.tld suPHP_UserGroup site site DocumentRoot /path/to/site/www <Directory /path/to/site/www> AllowOverride All Order allow,deny allow from all Options -MultiViews </Directory> ExpiresActive On ExpiresByType image/gif "access plus 7 days" ExpiresByType image/jpeg "access plus 7 days" ExpiresByType image/png "access plus 7 days" ExpiresByType image/x-icon "access plus 7 days" ExpiresByType image/ico "access plus 7 days" ExpiresByType text/css "access plus 2 days" </VirtualHost> <VirtualHost *:443> ServerName www.site.tld ServerAlias site.tld suPHP_UserGroup site site DocumentRoot /path/to/site/www <Directory /path/to/site/www> AllowOverride All Order allow,deny allow from all Options -MultiViews </Directory> SSLEngine On SSLCertificateFile /etc/ssl/private/site.crt ExpiresActive On ExpiresByType image/gif "access plus 7 days" ExpiresByType image/jpeg "access plus 7 days" ExpiresByType image/png "access plus 7 days" ExpiresByType image/x-icon "access plus 7 days" ExpiresByType image/ico "access plus 7 days" ExpiresByType text/css "access plus 2 days" </VirtualHost> Running Ubuntu Server Karmic Koala. A: One option is to put the common configuration i separate file, and use the Include directive to have it used in both VirtualHosts.
[ "stackoverflow", "0057240856.txt" ]
Q: Flask REST API Error: The view function did not return a valid response In a Flask REST API route in Python, the return type is a list @app.route('/ent', methods=['POST']) def ent(): """Get entities for displaCy ENT visualizer.""" json = request.get_json() nlp = MODELS[json['model']] doc = nlp(json['text']) return [ {"start": ent.start_char, "end": ent.end_char, "label": ent.label_} for ent in doc.ents ] This errors with: TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list. How can I get the API route on /ent to return a JSON array correctly? A: You can always convert the list into dict as needed by Flask as shown below return { "data": [ {"start": ent.start_char, "end": ent.end_char, "label": ent.label_} for ent in doc.ents ]} Also have you seen Flask REST API responding with a JSONArray ?
[ "diy.stackexchange", "0000150835.txt" ]
Q: Why does my generator throws 220 volts to one leg when put under load My generator when running showed proper voltage on both the 220 and the 110 outlets, and when wired to a house panel during a power outage it reads the proper voltage at the panel. However, when I start throwing breakers on, and putting a load on it, the full 220 volts jumps to one of the 110 legs, and when the breakers are off it is back to normal. I have lost many appliances. I took it to what I thought was a reliable repair shop, and they said they fixed it. Well, needless to say, one more power outage and the same thing, lost my entire kitchen again. I have built many houses with this generator using the 110 outlets, saws, compressors, and all at the same time, and it has kept up with the whole crew, and it always starts on the fist pull. I hate to get rid of it, I have not seen any one online with this problem. Please help. A: Without more information I'm guessing a bit, but I'll bet that you're connecting your generator's 220VAC across your house's two 120VAC phases, with no neutral connection. That will work fine, IF you are drawing equal amounts of power from the two phases. But what if you aren't? Let's say you plug a 1500W hair drier into one 120VAC outlet, and a 100W lightbulb into another 120VAC outlet, and they're on opposite phases. The only path for the current from the generator goes as follows: From one generator output into the hair drier Out of the hair drier into the house neutral Out of the house neutral into the lightbulb Out of the lightbulb back into the generator So, you've basically connected the hair drier and lightbulb in series across the generator. But, since the hair drier's impedance is so much lower than the lightbulb, the lightbulb will bear the brunt of the 220VAC generator output, and will blow before the hair drier even starts to get warm. (This is a general principle; if you have two devices in electrical series, the one with the greatest resistance will dissipate the greatest amount of power.) So, as you flick the circuit breakers on, you're inevitably adding unbalanced loads to the two sides of your breaker panel. Bingo: the less-loaded side will see higher voltage, perhaps even a drastically higher voltage. (Note that even if your generator has a neutral, and you're using it, there's no guarantee that drawing a lot of current from one of the two phases won't mess with the voltage on the other phase.) For way too much detail, here's a simplistic calculation, based on the standard voltage, current, resistance and wattage calculations: Current (amps) = Voltage (volts) / Resistance (ohms) Power (watts) = Voltage * Current = Voltage^2 / Resistance Based on its wattage, the resistance of the lightbulb is: 100 Watts = 110V^2 / Resistance 100 Watts = 12100 / Resistance Resistance = 12100 / 100 = 121 ohms Based on its wattage, the resistance of the hair drier is: 1500 Watts = 110V^2 / Resistance 1500 Watts = 12100 / Resistance Resistance = 12100 / 1500 = 8 ohms The total current of the circuit is: Current = Voltage / Resistance Current = 220 / (121 + 8) Ohms Current = 1.7 amps Voltage across the hair drier is: Voltage = 1.7 amps * 8 ohms = 13.6 volts Probably not enough to even spin the blower. But, what's happening to our poor little 100W lightbulb? Let's see: Voltage = 1.7 amps * 121 ohms = 205 volts. Power = Voltage * Current = 205 * 1.7 = 350 Watts. (Pop!) (To check the calculations: if you add the two calculated voltages, you get 205V + 13.6V = 218.6V, which is close enough to 220V for our purposes.)
[ "sharepoint.stackexchange", "0000083026.txt" ]
Q: Programmatically set a WebPart title to a $Resources value I need to programmatically add a web part to a page where the title is using a $Resources:Filename,Key; string. I know I can use SPUtility.GetLocalisedString() to retrieve the correct value (and loop through the SPWeb.SupportedUICultures to set the value for each language) but the problem with that is that it will only set it for languages in use now ... what happens if we install a new language pack next month? (we'd have to loop through all our web part instances and add the new language text for each one... a PITA). If I was adding a web part in the onet.xml I could just use Title="$Resources:fileName,key;" and it would automatically pick up any translations from available installed RESX files automatically. How can I do this programmatically? (i.e. in C#) A: For this situation you can use feature upgrading. When the new languages are deployed create a new version of the feature in the solution that deployed the WebParts. Upgrade the solution and upgrade the features. During the upgrade process of the feature you can upgrade the title of the WebPart with the new SPWeb.SupportedUICultures
[ "electronics.stackexchange", "0000451092.txt" ]
Q: What is the voltage across the capacitor 3ms after the switch is closed I have this circuit: This circuit is working for a long time like this, with the switch open. So, the circuit is stabilized and the voltage across the capacitor is 40V. At t=0, the switch is closed. What is the voltage across the capacitor 3ms after the switch is closed. MY SOLUTION After the switch is closed, the capacitor will change its voltage to match the one imposed by the voltage divider composed of R1 and R4. At the left side of R1 there is 40V and at the right side of R4 there is 30V. If we remove the capacitor, we can calculate the current in the circuit to be \$V = RI\$ \$(40-30) = (100 + 22)I\$ \$I = 81.96mA\$ So, the voltage drop across R1 is equal to \$V_{R1} = 100 x 81.96mA = 8.1967V\$ So the voltage between the resistors is \$V_{div} = 40 - 8.1967 = 31.80V\$ This will be the voltage across the capacitor after stabilization. So far, so good. This matches the value I get from the simulator I am using. Now I want to know the voltage across the capacitor 3ms after it starts discharging. If I substitute both voltage sources with wires, I see that the capacitor is in parallel with R1 and R4, what gives me an equivalent resistance of 18.0327. Now I use \$V_c(t) = V_s e^{-\frac{t}{RC}}\$ \$V_c(3ms) = 40 e^{-\frac{3e-3}{18.0327 x (1000 e-6)}}\$ \$V_c(3ms) = 33.8695V\$ The problem is that when I simulate that using software simulators I get the voltage across the capacitor after 3ms to be 38.7438V. What is wrong? A: The switch is closed at \$\small t=0\$, and the capacitor voltage for \$\small t \ge 0\$ is: \$\small v_c(t)=40-\frac{1}{C}\int i\: dt\$, where \$\small i\$ is the capacitor discharge current. Now use KCL at the node pointed to by the blue arrow to form the required differential equation, and solve (using the integrating factor method, for example). The initial capacitor current is \$\small i(0)=\frac{10}{22} \:A\$
[ "stackoverflow", "0006208886.txt" ]
Q: Proper structure of AJAX handler My .NET project handles AJAX requests. There are no UI controls at all, it simply responds with text to every AJAX post. This is my current structure: <% SynchLock DBNull.Value Main End SynchLock %> <script language="VB" runat="Server"> Sub Main Dim a() As String = Request.Form("a").Split(" "c) ' a: (0) version, (1) config, (2) userid, (3) sessionid, (4) activity ' Initializations Using conn As DbConnection = sess.Connection Select Case a(4) Case 0 ActivityOne Case 1 ActivityTwo Case 2 ActivityThree ... Case 28 ActivityTwentyEight End Select End Using End Sub 'All the activity functions and lots of other Functions </script> This works but I think it can be improved; I'm not sure how to proceed. Some of the activities call subfunctions and I'm looking at breaking some of the activities out even further. In order to encapsulate all the functionality of an activity, I'm considering changing the activities from functions to classes, like so: Select Case a(4) Case 0 Dim a1 As New ActivityOne a1.Execute ... End Select Is this the right approach? If I proceed with the classes, I have related questions: (1) Do I code the "New" Sub of the classes or an "Execute" (or some other name) Sub? If I code the "New" Sub, then I can reduce the above code to: Select Case a(4) Case 0 New ActivityOne ... End Select This seems easier, but are there disadvantages? (2) The activities all rely on other Request.Form inputs. Do I (a) pass access the HttpContext.Current object from within the classes or (b) pass the Request object to the activity or (c) pass the specific Request.Form variables needed by the activity? e.g. (a) New ActivityOne ' the class accesses HttpContext.Current.Form("b"), etc. Class ActivityOne Sub New Dim p1 As String = HttpContext.Current.Form("b") ... End Sub End Class (b) New ActivityOne(Request) Class ActivityOne Sub New(req As HttpRequest) Dim p1 As String = req.Form("b") ... End Sub End Class (c) New ActivityOne(Request.Form("b")) Class ActivityOne Sub New(p1 As String) ... End Sub End Class A: You shouldn't use ASPX pages for AJAX requests. Just use an HTTPHandler. http://msdn.microsoft.com/en-us/library/system.web.ihttphandler(v=VS.90).aspx
[ "mathoverflow", "0000016023.txt" ]
Q: how to compute a highest weight vector Do you know how to compute highest weight vectors in practice? A: As Mariano says, it will obviously depend what data you are given. I am going to assume that you are given a representation $\rho: \mathfrak{g} \to \mathrm{Mat}_{n \times n}$ of your Lie algebra $\mathfrak{g}$. Let $\mathfrak{b}$ be a Borel, with $\mathfrak{n}$ the nilpotent part. Highest weight vectors $v$ satisfy $\rho(n) \cdot v=0$ for all $n$ in $\mathfrak{n}$, and it is enough to test this condition as $n$ runs through a basis of $\mathfrak{n}$. This is a finite list of linear conditions on $v$, so finding the space of vectors that satisfy them is just linear algebra. Let $V$ be the space of such vectors. Then the action of $\mathfrak{b}$ on $V$ descends to the quotient $\mathfrak{b}/\mathfrak{n} = \mathfrak{t}$. This is an action of an abelian Lie algebra. Diagonalize it. Explicitly, let $t_1$, $t_2$, ... $t_r$ be a basis of $\mathfrak{t}$. Split $V$ into eigenspaces for the action of $\rho(t_1)$; split those spaces further into eigenspaces for the action of $\rho(t_2)$ and so on. Again, finding the eigenvectors of a matrix is a mechanical computation. At the end of the day, you'll have $V$ decomposed into spaces on which $\mathfrak{t}$ acts by scalars. The highest weight vectors are the vectors in these spaces. If you are given a representation of the Lie group instead of the Lie algebra, you will want to solve $\rho(N) v = v$ instead of $\rho(n) v=0$, and then diagonalize $\rho(T)$ instead of $\rho(\mathfrak{t})$.
[ "biology.stackexchange", "0000010836.txt" ]
Q: Cytoplasmic determinants - protostomes and deuterostomes Cytoplasmic determinants are spread unevenly in the egg, and so when embryo starts forming (cells start dividing), the determinants are also unequally divided between cell. This unequal distribution later plays a major role in differentiation and gene regulation. Protostomes undergo determinate cleavage. Their cells' fates are determined very early in development, whereas deuterostomes undergo indeterminate cleavage. So, if you take away a cell at early stage of development, it can be replaced. Now if we compare the division of cytoplasmic determinants in protostomes and deuterostomes, what I said in the first paragraph seems true (to some extent) for only protostomes. My questions: Do deuterostome oocytes have even distribution of cytoplasmic determinants initially and divide unequally only after certain number of divisions? Are there any studies showing correlation between the stage at which determination happens in deuterostome and beginning of unequal division of determinants? A: The two distinct types you have mentioned in your question (determinate/indeterminate cleavage) are actually called autonomous specification and conditional specification, respectively. In the case of the former one, if we were to remove a blastomere, it would still produce the previously determined type of cells, while in the case of conditional specification the cells, which are going to be produced, depend entirely on the neighbouring ones. The latter's ability to alter their fate is called regulation. As for answering your questions, cytoplasmic determinants are spread unevenly in deuterostomes as well, as otherwise no axis could be developed. You might be interested about this answer as well. I've used the following book as source: Gilbert, S. (2000). Developmental Biology [ online version ]
[ "stackoverflow", "0008443286.txt" ]
Q: Select strings by positions of words For the following tuple mysentence = 'i have a dog and a cat', 'i have a cat and a dog', 'i have a cat', 'i have a dog' How to select only the strings 'i have a cat' , 'i have a dog', i.e exclude strings having the word dog or cat in the middle. A: You can do this with regular expressions. The regex .+(dog|cat).+ will match one or more characters, followed by dog or cat, and one of more characters afterwards. You can then use filter to find strings which don't match this regex: import re regex.compile(r'.+(dog|cat).+') sentence = 'i have a dog and a cat', 'i have a cat and a dog', 'i have a cat', 'i have a dog' filtered_sentence = filter(lambda s: not regex.match(s), sentence) A: You could use a Regular Expression to match the sentences you don't want. We can build up the pattern as follows: We want to match dog or cat - (dog|cat) followed by a space, i.e. not at the end of the line So our code looks like so: >>> mysentence = ('i have a dog and a cat', 'i have a cat and a dog', 'i have a cat', 'i have a dog') >>> import re >>> pattern = re.compile("(dog|cat) ") >>> [x for x in mysentence if not pattern.search(x)] ['i have a cat', 'i have a dog']
[ "stackoverflow", "0024725560.txt" ]
Q: javascript: why need to delete the 0 index of an array in underscore source code, after applying shift or splice on an array and in case the length of the array is zero : if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; any idea why still need to do this : delete obj[0] A: Searching around in the Issue tracker shows that my assumption was right, it is just a fix for an IE bug. IE bugs with splice() and shift(): jdalton commented on 6 Dec 2011 IE bugs with splice() and shift(), failing to remove the 0 indexed value, when using an array-like-object with _(...). IE compatibility mode and IE < 9 have buggy Array shift() and splice() functions that fail to remove the last element, object[0], of array-like-objects even though the length property is set to 0.
[ "stackoverflow", "0042539657.txt" ]
Q: SQL convert nvarchar to float I have a table with a column Quantity; in the original table this column is defined as nvarchar(100) so I need to cast it as float to be able to do some analysis: CAST([Quantity] AS FLOAT) AS Quantity The issue is that I have some values which can not be converted to float like No-Quantity, Return etc. I to have filter to exclude these values and then convert rest to float.On option is use where clause: WHERE Quantity IN ('Return', 'Sales') This is not the best way since if we have anew values in the original table then I need to figure out what it is and add it to the where clause. I am wondering is there is better way to identify non-convertible values? A: In any database, you can use cast() and something like this: (case when quantity not in ('No-Quantity', 'Return', . . .) then CAST([Quantity] as float) end) as Quantity The in list would be the list of known string values. You can also do a fast-and-dirty check like this: (case when left(quantity, 1) between '0' and '1' then CAST([Quantity] as float) end) as Quantity (Note: you may need to use substr() or substring() instead of left().) And, in general, any specific database has specific functions that can help with the conversion, such as try_convert() mentioned in a comment.
[ "physics.stackexchange", "0000231591.txt" ]
Q: Quantim efficiency of a radio receiver In optical communication we often know quantum efficiency of the receiver (probability of single photon detection and bitrate per photon). Are there any estimations on typical achievable quantum efficiency and bitrate per photon of typical radio receivers? (HF and sattelite bands - L S C X Ku) A: Photon energies in that frequency range are far below the input noise of the receiver, so one can't do photon counting. The smallest detectable signal will consist of a large number of photons and can be treated like a classical electromagnetic wave. The technically most often used figure of merit that is similar to the quantum efficiency would be the reflection coefficient $\Gamma=V_r/V_f$, i.e. the ratio between reflected voltage and full voltage on the input of a mismatched receiver. From this the VSWR (Voltage Standing Wave Ratio) is derived as $VSWR={{1+|\Gamma|}\over{1-|\Gamma|}}$ Similarly, for reflected power to full power (rather than voltage) the Standing Wave Ratio SWR can be expressed as $SWR={{1+\sqrt{P_r/P_f}}\over{1-\sqrt{P_r/P_f}}}$. For monochromatic waves the power is proportional to the photon flux, so I would say that one would practically use the power ratios or the SWR as an engineering (not physics) equivalent of the quantum efficiency. For modulated signals and wide frequency bands one would have to integrate over the time and/or frequency domain to arrive at an average figure.
[ "tex.stackexchange", "0000272153.txt" ]
Q: TiKz for each iteration over spaced string argument has an extra } This is an example of the functionality of a macro, that should the following: iterate over a spaced string and print the first letter of each part. \newcommand\text{\StrSubstitute{a b c}{ }{,}} \foreach \i in \text{ \StrLeft{\i}{1} , } But apparently, I cannot use \StrLeft or any other when the iteration is over something I have done over a StrSubstitute. Why is that? Error messages: ! Paragraph ended before \reserved@a was complete.<to be read again>\par } ! Paragraph ended before \reserved@a was complete.<to be read again>\par } ! Missing control sequence inserted.<inserted text>\inaccessible } The following do work though: \newcommand\text{\StrSubstitute{a b c}{ }{,}} \foreach \i in \text{ \i } \newcommand\text{a,b,c} \foreach \i in \text{ \StrLeft{\i}{1} , } A: First of all, the choice of \text as a command name is not really good, because amsmath uses it. However, this is not the main point. The big problem is that \text is not the list a,b,c, but rather a set of instructions for producing that list. You're luckier with \StrSubstitute{a b c}{ }{,}[\mytext] \foreach\i in \mytext{% \StrLeft{\i}{1}, % } Now \mytext contains the result of the substitution. Full example, although it's not clear what's the use case: \documentclass{article} \usepackage{tikz,xstring} \begin{document} \StrSubstitute{a b c}{ }{,}[\mytext] \foreach\i in \mytext{% \StrLeft{\i}{1}, % } \end{document}
[ "stackoverflow", "0011731878.txt" ]
Q: Is there a way to customize the threshold for ViewPager scrolling? I am not able to find a way to change the touch threshold for scrolling pages in ViewPager: http://developer.android.com/reference/android/support/v4/view/ViewPager.html Looking at the source code, ViewPager has a method called determineTargetPage that checks to see if the move touch gesture distance > threshold range, but looks like there's no way to modify this range. Any suggestions on how I can control this threshold (if at all possible)? A: Going out on a bit of a limb here; I have no doubt that you may have to tweak this concept and/or code. I will recommend what I did in the comments above; to extend ViewPager and override its public constructors, and call a custom method which is a clone of initViewPager() (seen in the source you provided). However, as you noted, mFlingDistance, mMinimumVelocity, and mMaximumVelocity are private fields, so they can't be accessed by a subclass. (Note: You could also change these methods after the constructors are called, if you wanted to.) Here's where it gets a bit tricky. In Android, we can use the Java Reflection API to make those fields accessible. It should work something like this: Class clss = getClass.getSuperClass(); Field flingField = clss.getDeclaredField("mFlingDistance"); // Of course create other variables for the other two fields flingField.setAccessible(true); flingField.setInt(this, <whatever int value you want>); // "this" must be the reference to the subclass object Then, repeat this for the other two variables with whatever values you want. You may want to look at how these are calculated in the source. Unfortunately, as much as I would like to recommend using Reflection to override the private method determineTargetPage(), I don't believe it's possible to do this--even with the expansive Reflection API.
[ "stackoverflow", "0027309753.txt" ]
Q: How do I secure the URL's of a Symfony Project in fosuserbundle? I am new to Symfony2 and using fosuserbundle. I have created a small project using fosuserbundle which has a registration, login, 2 forms consisting of radio buttons to choose and submit after logging in or registering and a logout. The problem is that after a person logs out and if he/she types in the url of the form say (link for the first form of the project) or (link for the second form of the project) then the forms display !!!!. I wanted to secure these links and show these links only if the user has logged in. routing.yml InstituteProjectevents_student_homepage: path: /hello/{name} defaults: { _controller: InstituteProject:Default:index } InstituteProjectevents_student_formpage: path: /form defaults: { _controller: InstituteProject:Default:form } InstituteProjectevents_student_form: path: /forms defaults: { _controller: InstituteProject:Default:billboard } InstituteProjectevents_student_eventsdayonedisplay: path: /eventsdayonedisplay defaults: { _controller: InstituteProject:Default:eventsdayonedisplay } InstituteProjectevents_student_eventsdaytwodisplay: path: /eventsdaytwodisplay defaults: { _controller: InstituteProject:Default:eventsdaytwodisplay } InstituteProjectevents_student_eventsregistered: path: /eventsregistered defaults: { _controller: InstituteProject:Default:eventsregistered } fos_user_security_login: path: /login defaults: { _controller: InstituteProject:Security:login } fos_user_security_check: path: /login_check defaults: { _controller: InstituteProject:Security:check } fos_user_security_logout: path: /logout defaults: { _controller: InstituteProject:Security:logout } fos_user_profile_show: path: / defaults: { _controller: InstituteProject:Profile:show } fos_user_profile_edit: path: /edit defaults: { _controller: InstituteProject:Profile:edit } fos_user_registration_register: path: / defaults: { _controller: InstituteProject:Registration:register } fos_user_registration_check_email: path: /check-email defaults: { _controller: InstituteProject:Registration:checkEmail } fos_user_registration_confirm: path: /confirm/{token} defaults: { _controller: InstituteProject:Registration:confirm } fos_user_registration_confirmed: path: /confirmed defaults: { _controller: InstituteProject:Registration:confirmed } Security.yml # app/config/security.yml security: encoders: FOS\UserBundle\Model\UserInterface: sha512 role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: ROLE_ADMIN providers: fos_userbundle: id: fos_user.user_provider.username firewalls: main: pattern: ^/ form_login: provider: fos_userbundle csrf_provider: form.csrf_provider default_target_path: /forms logout: path: fos_user_security_logout target: fos_user_security_login anonymous: true access_control: - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/admin/, role: ROLE_ADMIN } RegistrationController.php <?php /* * This file is part of the FOSUserBundle package. * * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace InstituteProjecteventsBundle\Controller; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FormEvent; use FOS\UserBundle\Event\GetResponseUserEvent; use FOS\UserBundle\Event\FilterUserResponseEvent; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use FOS\UserBundle\Model\UserInterface; /** * Controller managing the registration * * @author Thibault Duplessis <[email protected]> * @author Christophe Coevoet <[email protected]> */ class RegistrationController extends Controller { public function registerAction(Request $request) { /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */ $formFactory = $this->get('fos_user.registration.form.factory'); /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */ $userManager = $this->get('fos_user.user_manager'); /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */ $dispatcher = $this->get('event_dispatcher'); $user = $userManager->createUser(); $user->setEnabled(true); $event = new GetResponseUserEvent($user, $request); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event); if (null !== $event->getResponse()) { return $event->getResponse(); } $form = $formFactory->createForm(); $form->setData($user); $form->handleRequest($request); if ($form->isValid()) { $event = new FormEvent($form, $request); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event); $userManager->updateUser($user); if (null === $response = $event->getResponse()) { $url = $this->generateUrl('fos_user_registration_confirmed'); $response = new RedirectResponse($url); } $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response)); return $response; } return $this->render('FOSUserBundle:Registration:register.html.twig', array( 'form' => $form->createView(), )); } /** * Tell the user to check his email provider */ public function checkEmailAction() { $email = $this->get('session')->get('fos_user_send_confirmation_email/email'); $this->get('session')->remove('fos_user_send_confirmation_email/email'); $user = $this->get('fos_user.user_manager')->findUserByEmail($email); if (null === $user) { throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email)); } return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array( 'user' => $user, )); } /** * Receive the confirmation token from user email provider, login the user */ public function confirmAction(Request $request, $token) { /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */ $userManager = $this->get('fos_user.user_manager'); $user = $userManager->findUserByConfirmationToken($token); if (null === $user) { throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token)); } /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */ $dispatcher = $this->get('event_dispatcher'); $user->setConfirmationToken(null); $user->setEnabled(true); $event = new GetResponseUserEvent($user, $request); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event); $userManager->updateUser($user); if (null === $response = $event->getResponse()) { $url = $this->generateUrl('fos_user_registration_confirmed'); $response = new RedirectResponse($url); } $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response)); return $response; } /** * Tell the user his account is now confirmed */ public function confirmedAction() { $user = $this->getUser(); if (!is_object($user) || !$user instanceof UserInterface) { throw new AccessDeniedException('This user does not have access to this section.'); } //Get current time and date date_default_timezone_set('Europe/Paris'); $current_date = date('Y/m/d h:i:s a', time()); //Set expiration date $deadline1 = $this->container->getParameter('deadline_day1'); $date = date_create($deadline1, timezone_open("Europe/Paris")); if ($current_date > date_format($date, "Y/m/d h:i:s a")) { return $this->render('InstituteProject:Default:registrationsclosed.html.twig'); } return $this->render('InstituteProject:Default:confirmed.html.twig', array( 'user' => $user, )); } } A: You need to add those two paths in security.yml files access_control section as follows, Go through This Documentation to learn more about how it works in Symfony2 ROLE_ADMIN or ROLE_USER in ACL means you need to be logged in to access that path. access_control: - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/admin/, role: ROLE_ADMIN } - { path: ^/eventsdayonedisplay, role: ROLE_ADMIN } # you can change user role to ROLE_USER as per your requirement - { path: ^/eventsdaytwodisplay, role: ROLE_ADMIN } I will also suggest that you can add routes as /events/day1 or /events/day2 this way you need to add only one entry in your access_control like, - { path: ^/events/, role: ROLE_ADMIN }
[ "stackoverflow", "0036436592.txt" ]
Q: Can I use wget to run a local file as a cron job using relative path above public_html? I'm trying to setup a script to run in a cron job, and I want it to run once a day. I'm new to cron jobs, and the ones I have seen so far are only using absolute paths like: http://example.com/path/to/file. This is the command I want to do in cpanel: /usr/bin/wget -O - -q -t 1 /home/account/invest/controllers/cron_controller.php Would this work? Or is another command better than wget? A: The best command is php /home/account/invest/controllers/cron_controller.php.
[ "stackoverflow", "0019148806.txt" ]
Q: Can one private key be associated with several public keys? Ok, so my crpto lecturer in Uni posed this question at the end of the RSA key generation lecture as a brain teaser. I have been thinking about this and I think I have come up with a way ( I am aware its not practical and very vulnerable - But I would love for you guys to punch holes through it ): Use RSA to generate public and private key pair. Make an additive hash function that taken in any input and adds the ascii value of each character and gives that as an output. ( I am aware additive hash has horrible distribution for ex ABC , BAC , ACB all have the same hash output -- but theoretically this can be used as an advantage to solve our problem ) Now take your public key and generate several possible keys by jumbling up the on and off bits. Give these jumbled up keys to potential customers. Put our hash function on the server. When customer puts in his jumbled up public key - Hash function calculates the hash - which should be similar to original public key generated by RSA. Customer gets access. Once again I am aware that this is very vulnerable and terrible. It cant be used in the real world. But does it answer the question my lecturer posed ? EDIT: Guys I am sorry for the confusion. This question has nothing to do with collisions and expoiting the maths ( Those are definitely valid ways to do that - but they weren't what my lecturer was referring too - they were discussed in the lecture itself. ). The way my lecturer asked this question was - " come up with ways to make several public keys related to a single private key - nevermind how vulnerable your solution is ". A: I think I know what your lecturer was getting at. I'm not going to give you the full answer but I'll lead you along a few steps. Obviously your lecturer wants you to study the math of RSA. In particular, look at the public and private exponents and how they are related. Now, suppose you have an RSA modulus N, and RSA public exponent e, and an RSA private exponent d. Is there another exponent, say e + x, that works exactly the same way as e in the RSA math? The answer is yes, there is. In fact, there is an entire family of such exponents. Now you have to discover what this x value is, and how it related to the math of RSA.
[ "stackoverflow", "0045444420.txt" ]
Q: Why is Lazy not being lazy? I have several simple database queries using Entity Framework that I would like to load once using Lazy<T> but I can see that the query is executed every time the property is called. Variations I have tried are: public static IEnumerable<string> Foos => new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name)).Value; public static IEnumerable<string> Foos=> new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray()).Value; public static Lazy<IEnumerable<string>> Foos => new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray()); public static IEnumerable<string> LightingEnvironments { get { var lazy = new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray()); return lazy.Value; } } A: You're constructing a new Lazy each time you call the property getter. A Lazy only allows you to re-use an already constructed value if you keep the Lazy instance around and call the Value property on the same Lazy instance each time you need the value.
[ "stackoverflow", "0004591814.txt" ]
Q: using setInnerXHTMl or FBML to show image with specified height/width I am trying to show an image of a specified height and width. Heres the code that I am using: function showpic(var1) { piclink="<span><img src=\""+var1+"\" align=\"bottom\" width=\"400\" height=\"300\" /></span> "; document.getElementById('big_pic').setInnerXHTML(piclink); } where var1=absolute link of the image The problem is, the height/width is getting sanitized (read removed). What can I do ? Please let me know. Thanks. - ahsan A: solved using : myimg = document.getElementById('img_tag'); myimg.setStyle({height: '300px', width: '400px'}); thanks - ahsan
[ "scifi.stackexchange", "0000231172.txt" ]
Q: Story / Trailer about Tom Clancy's The Division where [spoiler] happens I remember watching a trailer (perhaps live-action?) for The Division, where a lady asks a sanitation worker for help with her [brother?]. The sanitation worker asks if her brother is sick and when the lady responds that her brother is sick, he makes a call and tells her to stay where she is. Several moments later, a garbage truck with a group of armed sanitation workers show up and gun her down. Can anyone help identify this story / trailer? I've been looking all over for it, but I can't seem to find it. A: I believe you're looking for this Agent Origins video by Corridor Digital:
[ "math.stackexchange", "0001357083.txt" ]
Q: An optimization problem, in the form of a word problem, The manager of a $1000$ seat concert hall knows from experience that all seats will be occupied if the ticket price is $50$ dollars. A market survey indicates that $10$ additional seats will remain empty for each $ \$5$ increase of the ticket price. What is the ticket price which maximizes the manager's revenue? How many seats will be occupied at that price? My work, so far: The possible scenarios are $50\times1000, 55\times990, 60\times980, \ldots$ Let $x =$ ticket price. Let $y =$ number of tickets sold. Clearly, $x$ and $y$ are $related$ variables. So, I want to use the method of Lagrange multipliers. Here are some difficulties, though: $$\text{revenue} = f(x,y) = xy$$ is not a vector valued function $-$ I want to compute the gradient of some vector-valued function, $f$, and solve $$\nabla(f) = \lambda \nabla(g).$$ And moreover, what would the constraint function, $g$, even be? I can think of two constraints: $$\max(y) = 1000 \text{ tickets}$$ and $$\min(x) = 50 \text{ dollars}$$ I would like hints only for now. Thanks, A: As I pointed out in a comment, the problem is quite simply solved using one-variable techniques. However, let us explore your choice of letting $x$ be the ticket price and $y$ the number of tickets sold. Then the number of $5$ dollar increments is $\frac{x-50}{5}$. The resulting number $y$ of tickets sold is given by $$y=1000-10\cdot \frac{x-50}{5}.$$ This is the constraint, which you may wish to simplify. (There is also the implicit $y\le 1000$.) Now we can use the Lagrange multiplier machinery.
[ "stackoverflow", "0053232915.txt" ]
Q: Sports schedule not showing string It's a program that is a sports league, a group of teams plays through a Schedule of Games and determine the winner. The program runs fine to the point where the final output won't let me see the winner, it shows this instead: The season winner(s) with 9 points: [Ljava.lang.String;@e73f9ac I changed it to teams.length which made the program work but it would show me the teams (i) number instead of the string name like "Vancouver". Thanks in advance. } int peak = 0; int[] total = new int[teams.length]; for (int i=0; i<teams.length; i++){ total[i] = 2*wins[i]+ties[i]; if (total[i] > peak) peak = total[i]; System.out.println(teams[i]+" - " + wins[i] + " wins, " + losses[i] + " losses, " + ties[i] + " ties = " + total[i]); } System.out.println("The season winner(s) with " + peak + " points: " + teams); for (int i=0; i<teams.length; i++){ if (peak < total[i]) peak = total[i]; } } static int indexOfTeam(String team, String[] teams){ for (int i=0; i<teams.length; i++) if (team.compareTo(teams[i]) == 0) return i; return -1; } } A: Instead of printing the winning team you're printing the teams array. While iterating store besides the peak, the index of the winning team: int index = -1; for (int i=0; i<teams.length; i++){ total[i] = 2*wins[i]+ties[i]; if (total[i] > peak) { index = i; peak = total[i]; } System.out.println(teams[i]+" - " + wins[i] + " wins, " + losses[i] + " losses, " + ties[i] + " ties = " + total[i]); } and finally: System.out.println("The season winner(s) with " + peak + " points: " + teams[index]);
[ "stackoverflow", "0010692541.txt" ]
Q: How to find a point where a line intersects an ellipse in 2D (C#) I need to find a point where a line (its origin is ellipse' center) intersects an ellipse in 2D... I can easily find a point on a circle, because I know an angle F and the circle' radius (R): x = x0 + R * cosF y = y0 + R * sinF However I just can't figure how am I supposed to deal with an ellipse... I know it's dimensions (A & B), but what is the way of finding parameter T?! x = x0 + A * cosT y = y0 + B * sinT From what I understand the parameter T (T angle) is not far from the F angle (approximately +-15 degrees in some cases), but I just can't figure how to calculate it!!! If there is a kind hearted soul, please help me with this problem... A: The standard equation of an ellipse, stationed at 0,0, is: 1 = (x)^2 / (a) + (y)^2 / (b) Where a is 1/2 the diameter on the horizontal axis, and b is 1/2 the diameter on the vertical axis. you have a line, assuming an equation: y = (m)(x - x0) + y0 So, let us plug-and-play! 1 = (x)^2 / (a) + (m(x - x0) + y0)^2 / (b) 1 = x^2 / a + (mx + (y0 - mx0))^2 / b 1 = x^2 / a + (m^2 * x^2 + 2mx*(y0 - mx0) + (y0 - mx0)^2) / b 1 = x^2 / a + (m^2 x^2) / b + (2mx*(y0 - mx0) + (y0^2 - 2y0mx0 + m^2*x0^2)) / b 1 = ((x^2 * b) / (a * b)) + ((m^2 * x^2 * a) / (a * b)) + (2mxy0 - 2m^2xx0)/b + (y0^2 - 2y0mx0 + m^2*x0^2)/b 1 = ((bx^2 + am^2x^2)/(ab)) + (x*(2my0 - 2m^2x0))/b + (y0^2 - 2y0mx0 + m^2*x0^2)/b 0 = x^2*((b + a*m^2)/(ab)) + x*((2my0 - 2m^2x0)/b) + (((y0^2 - 2y0mx0 + m^2*x0^2)/b) - 1) That last equation follows the form of a standard quadratic equation. So just use the quadratic formula, with: ((b + a*m^2)/(ab)) ((2my0 - 2m^2x0)/b) and (((y0^2 - 2y0mx0 + m^2*x0^2)/b) - 1) to get the X values at the intersections; Then, plug in those values into your original line equation to get the Y values. Good luck! A: Don't do it this way. Instead check the equation that forms an ellipse and that forming a line and solve the set: The ellipse: (x/a)^2 + (y/b)^2 = 1 Your line: y = cx You know a, b and c, so finding a solution is going to be easy. You'll find two solutions, because the line crosses the ellipse twice. EDIT: Note I moved your ellipse's center to (0,0). It makes everything easier. Just add (x0,y0) to the solution.