source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0013820664.txt" ]
Q: Windows Azure Access Control and Windows Phone 8 I'm currently developing an app which has single sign on via Windows Azure Access Control Service. I am using the Access Control Service for Windows Phone NUGET package (the same control can also be found in the Windows Azure for Windows Phone toolkit). I am just wondering if there is a new way of doing this in Windows Phone 8? These current controls haven't been updated for about a year and a lot seems to have changed since then. I have searched but search engines still seem to be returning Windows Phone 7 results mostly. A: Azure Mobile Services (still currently in preview) has new functionality designed to help make user authentication easier. See http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-users-dotnet/
[ "stackoverflow", "0051889908.txt" ]
Q: How to use wp:featuredmedia in WP REST API response? I am trying to get blog posts from another WordPress site, as of now I am successfully fetching the posts, I am using the following snippet: $response = wp_remote_get( add_query_arg( array( 'per_page' => 1, 'categories' => 38 ), 'https://www.remotesite.com/wp-json/wp/v2/posts?_embed' ) ); if( !is_wp_error( $response ) && $response['response']['code'] == 200 ) { $remote_posts = json_decode( $response['body'] ); foreach( $remote_posts as $remote_post ) { echo '<h2>'. $remote_post->title->rendered . '</h2> <p>' . $remote_post->excerpt->rendered . '</p>'; } } with the above code, I can fetch all the required details, title, excerpt, and Featured Image. But I am having a very hard time to find how to get the Featured Image url from the above response. Can anyone tell me how to use the wp:featuredmedia from the response. I have seen somewhere the below code to get the featured image URL, but this won't helped me: echo [your-data]._embedded['wp:featuredmedia']['0'].source_url A: Based on your code, the featured image URL can be retrieved like this: $remote_post->_embedded->{'wp:featuredmedia'}[0]->source_url That is, however, the full-sized version of the featured image file. To get the URL of a specific thumbnail size, you can access if from: $remote_post->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes .. which is an array of object data (unless of course you use true in the second parameter of the json_decode() function). By default, the available thumbnail sizes are: thumbnail, medium, and medium_large. Here's an example for the medium size: $remote_post->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes->medium->source_url So try this foreach: foreach( $remote_posts as $remote_post ) { $thumb_full_url = ''; $thumb_url = ''; if ( ! empty( $remote_post->featured_media ) && isset( $remote_post->_embedded ) ) { $thumb_full_url = $remote_post->_embedded->{'wp:featuredmedia'}[0]->source_url; $thumb_url = $remote_post->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes->medium->source_url; } echo '<h2>'. $remote_post->title->rendered . '</h2>' . '<p>' . $remote_post->excerpt->rendered . '</p>' . '<p>' . 'Medium-sized thumbnail: ' . $thumb_url . '<br>' . 'Full-sized / source: ' . $thumb_full_url . '</p>'; }
[ "stackoverflow", "0007961002.txt" ]
Q: styles over riding somewhere? my html <link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" type="text/css" href="css/nav.css"> that's the order I call in the style sheets .btn { border-top-right-radius:10px; -webkit-top-right-radius:10px; margin-right:20px; display:block; text-align:center; float:right; color:#ffffff; background-color:#000000; font-size:15px; font-weight:bold; line-height:30px; text-decoration:none; cursor:pointer; width:150px; height:30px; box-shadow:5px 3px 3px #888888; -moz-box-shadow:5px 3px 3px #888888; -webkit-box-shadow:5px 3px 3px #888888; -o-box-shadow:5px 3px 3px #888888; } .over_contact { color:#00a8ff; } .over_resume { color:#9848c2; } .over_portfolio { color::#f0ff00; } .over_rates { color:#00A000; } here's a working example http://www.dsi-usa.com/yazaki_port/hair-by-steph/ the problem is that when i hover over the portfolio button it doesn't show the over class. I was looking at it w/ the chrome debugger and I noticed that the class is getting added and deleted fine, the only problem is that when I look at the structure of the CSS the main .btn class color is overriding the over_portfolio class color change. It doesn't do that with the other ones, and I'm not quite exactly sure what I'm missing here. A: You have a syntax error in your rule for .over_portfolio, it should be: .over_portfolio { color:#f0ff00; } I've removed the extra : you had in there
[ "stackoverflow", "0056519127.txt" ]
Q: How to programmatically change selected text font/color? I'm trying to make a custom Text Editor that can change font and color of specific typed words. How do I change the Font and or Color of text that I highlight over using the cursor? I haven't tried to do the highlighting portion quite yet. I have tried to get the entire hEdit(HWND) area and change the font, but that doesn't seem to be working. //In my WndProc (Being handled when I click the Format->Color menu item) HWND hEdit; hEdit = GetDlgItem(hwnd, IDC_MAIN_EDIT); DoSelectColor(hEdit); //In my WndProc (Being handled when I click the Format->Font menu item) HWND hEdit; hEdit = GetDlgItem(hwnd, IDC_MAIN_EDIT); DoSelectFont(hEdit, hFont); //Selecting Color void DoSelectColor(HWND hwnd) { CHOOSECOLOR cc = {sizeof(CHOOSECOLOR)}; cc.Flags = CC_RGBINIT | CC_FULLOPEN || CC_ANYCOLOR; cc.hwndOwner = hwnd; cc.rgbResult = g_rgbBackground; cc.lpCustColors = g_rgbCustom; if(ChooseColor(&cc)) { g_rgbBackground = cc.rgbResult; } } //Selecting Font void DoSelectFont(HWND hwnd, HFONT f) { CHOOSEFONT cf = {sizeof(CHOOSEFONT)}; LOGFONT lf; GetObject(f, sizeof(LOGFONT), &lf); cf.Flags = CF_EFFECTS | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS; cf.hwndOwner = hwnd; cf.lpLogFont = &lf; if(ChooseFont(&cf)) { HFONT hf = CreateFontIndirect(&lf); if(hf) { f = hf; } } } I'd like for the hEdit area to change, but I'm quite new to C/C++ and can't seem to figure out why it isn't changing the color of the hEdit area. A: As pointed out in the positive commentary.Your not going to be able to do that directly with a Edit Control. What you want to use instead is a Richedit Control. What you'll probably want to do is first call SendMessage(hWndRichEdit, EM_SETEDITSTYLE, SES_EMULATESYSEDIT, SES_EMULATESYSEDIT); in your WM_CREATE handler after you create the Richedit Control and then to append text of any style use: SETTEXTEX stex = { ST_SELECTION, CP_ACP }; SendMessage(hWndRichEdit, EM_SETTEXTEX, &stex, (LPARAM)"{\rtf1 Inserting {\b bold} text. \par }"); Here's a few links that should help you. You want to use version 2 or 3 of the Richedit Control. Don't just go copying and pasting code. Read these pages in full before trying to implement them. MSDN: Rich Edit MSDN: About Rich Edit Controls MSDN: Using Rich Edit Controls Wikipedia: Rich Text Format
[ "stackoverflow", "0001164668.txt" ]
Q: Chained comparisons in Scala Python supports an elegant syntax for "chained comparisons", for example: 0 <= n < 256 meaning, 0 <= n and n < 256 Knowing that it's a fairly flexible language syntactically, is it possible to emulate this feature in Scala? A: Daniel's answer is comprehensive, it's actually hard to add anything to it. As his answer presents one of the choices he mentioned, I'd like just to add my 2 cents and present a very short solution to the problem in the other way. The Daniel's description: You could, theoretically, feed the result of the one of the methods to another method. I can think of two ways of doing that: Having <= return an object that has both the parameter it received and the result of the comparision, and having < use both these values as appropriate. CmpChain will serve as an accumulator of comparisions already made along with a free rightmost object, so that we can compare it to the next: class CmpChain[T <% Ordered[T]](val left: Boolean, x: T) { def <(y: T) = new CmpChain(left && x < y, y) def <=(y: T) = new CmpChain(left && x <= y, y) // > and >= are analogous def asBoolean = left } implicit def ordToCmpChain[T <% Ordered[T]](x: T) = new AnyRef { def cmp = new CmpChain(true, x) } implicit def rToBoolean[T](cc: CmpChain[T]): Boolean = cc.asBoolean You can use it for any ordered types, like Ints or Doubles: scala> (1.cmp < 2 < 3 <= 3 < 5).asBoolean res0: Boolean = true scala> (1.0.cmp < 2).asBoolean res1: Boolean = true scala> (2.0.cmp < 2).asBoolean res2: Boolean = false Implicit conversion will produce Boolean where it is supposed to be: scala> val b: Boolean = 1.cmp < 2 < 3 < 3 <= 10 b: Boolean = false A: Not really. One have to remember that, aside from a few keywords, everything in Scala is a method invokation on an object. So we need to call the "<=" and "<" methods on an object, and each such method receives a parameter. You need, then, four objects, and there are three explicit ones, and two implicit ones -- the results of each method. You could, theoretically, feed the result of the one of the methods to another method. I can think of two ways of doing that: Having <= return an object that has both the parameter it received and the result of the comparision, and having < use both these values as appropriate. Having <= return either false or the parameter it received, and having < either fail or compare against the other parameter. This can be done with the Either class, or something based upon it. These two solutions are very similar, in fact. One problem is that consumers of such comparision operators expect Boolean as a result. That is actually the easiest thing to solve, as you could define an implicit from Either[Boolean,T] into Boolean. So, theoretically, that is possible. You could do it with a class of your own. But how would you go about changing the existing methods already defined? The famous Pimp My Class pattern is used to add behavior, not to change it. Here is an implementation of the second option: object ChainedBooleans { case class MyBoolean(flag: Either[Boolean, MyInt]) { def &&(other: MyBoolean): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) other.flag else Left(false) def <(other: MyInt): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) flag.right.get < other else Left(false) def >(other: MyInt): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) flag.right.get > other else Left(false) def ==(other: MyInt): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) flag.right.get == other else Left(false) def !=(other: MyInt): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) flag.right.get != other else Left(false) def <=(other: MyInt): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) flag.right.get <= other else Left(false) def >=(other: MyInt): Either[Boolean, MyInt] = if (flag.isRight || flag.left.get) flag.right.get >= other else Left(false) } implicit def toMyBoolean(flag: Either[Boolean, MyInt]) = new MyBoolean(flag) implicit def toBoolean(flag: Either[Boolean, MyInt]) = flag.isRight || flag.left.get case class MyInt(n: Int) { def <(other: MyInt): Either[Boolean, MyInt] = if (n < other.n) Right(other) else Left(false) def ==(other: MyInt): Either[Boolean, MyInt] = if (n == other.n) Right(other) else Left(false) def !=(other: MyInt): Either[Boolean, MyInt] = if (n != other.n) Right(other) else Left(false) def <=(other: MyInt): Either[Boolean, MyInt] = if (this < other || this == other) Right(other) else Left(false) def >(other: MyInt): Either[Boolean, MyInt] = if (n > other.n) Right(other) else Left(false) def >=(other: MyInt): Either[Boolean, MyInt] = if (this > other || this == other) Right(other) else Left(false) } implicit def toMyInt(n: Int) = MyInt(n) } And here is a session using it, showing what can and what can't be done: scala> import ChainedBooleans._ import ChainedBooleans._ scala> 2 < 5 < 7 <console>:14: error: no implicit argument matching parameter type Ordering[Any] was found. 2 < 5 < 7 ^ scala> 2 < MyInt(5) < 7 res15: Either[Boolean,ChainedBooleans.MyInt] = Right(MyInt(7)) scala> 2 <= MyInt(5) < 7 res16: Either[Boolean,ChainedBooleans.MyInt] = Right(MyInt(7)) scala> 2 <= 5 < MyInt(7) <console>:14: error: no implicit argument matching parameter type Ordering[ScalaObject] was found. 2 <= 5 < MyInt(7) ^ scala> MyInt(2) < 5 < 7 res18: Either[Boolean,ChainedBooleans.MyInt] = Right(MyInt(7)) scala> MyInt(2) <= 5 < 7 res19: Either[Boolean,ChainedBooleans.MyInt] = Right(MyInt(7)) scala> MyInt(2) <= 1 < 7 res20: Either[Boolean,ChainedBooleans.MyInt] = Left(false) scala> MyInt(2) <= 7 < 7 res21: Either[Boolean,ChainedBooleans.MyInt] = Left(false) scala> if (2 <= MyInt(5) < 7) println("It works!") else println("Ow, shucks!") It works!
[ "stackoverflow", "0049937248.txt" ]
Q: Uncaught ReferenceError: makeDrink is not defined WHen i run the code with the buyDrink() method is commented it's work. But when the method is uncommented, it's not. I tried to solve the problem during some hours but didn't succeed. Could you help me,please? Thanks. var coffeeShop = { beans: 40, money: 100, beanCost: 2, drinkRequirements: { latte: { beansRequirements: 10, price: 5 }, americano: { beansRequirements: 5, price: 2.5 }, doubleShot: { beansRequirements: 15, price: 7.5 }, frenchPress: { beansRequirements: 12, price: 6 } }, buySupplies: function(numBeansBought) { if (this.money - (numBeansBought*this.beanCost) >= 0) { this.money-= numBeansBought*this.beanCost; this.beans+=numBeansBought; } }, makeDrink: function(drinkType) { /* How to check if value exists in an object Let's consider an example which would answer this question var priceOfFood = { pizza: 14, burger 10 } priceOfFood.hasOwnProperty('pizza') // true priceOfFood['pizza'] // 14 priceOfFood.hasOwnProperty('chips') // false priceOfFood['chips'] // undefined */ //if (this.drinkRequirements.hasOwnProperty(drinkType) === false) if (!this.drinkRequirements[drinkType]) { alert("Sorry, we don't make "+ drinkType); return false; } else { var beansRest = 0; beansRest = this.beans - this.drinkRequirements[drinkType].beansRequirements; if (beansRest < 0) { alert("Sorry, we're all out of beans!"); return false; } else { this.beans = beansRest; return true; } } } , buyDrink: function(drinkType) { if (makeDrink(drinkType)) { this.money+= drinkRequirements[drinkType].price; console.log('the new coffeeShop money is ' + this.money); } } } coffeeShop.makeDrink("latte"); console.log("latte, " + coffeeShop.beans); coffeeShop.buyDrink("latte"); console.log("latte, " + coffeeShop.beans); I have this error message : "Uncaught ReferenceError: makeDrink is not defined", Coul you help me, please? Thanks, Regards A: You need to reference the calling context - the this, which refers to the coffeeShop the object the current function is being called on, which has the makeDrink and drinkRequirements properties. They're not standalone functions/objects - they're properties of another object. var coffeeShop = { beans: 40, money: 100, beanCost: 2, drinkRequirements: { latte: { beansRequirements: 10, price: 5 }, americano: { beansRequirements: 5, price: 2.5 }, doubleShot: { beansRequirements: 15, price: 7.5 }, frenchPress: { beansRequirements: 12, price: 6 } }, buySupplies: function(numBeansBought) { if (this.money - (numBeansBought * this.beanCost) >= 0) { this.money -= numBeansBought * this.beanCost; this.beans += numBeansBought; } }, makeDrink: function(drinkType) { /* How to check if value exists in an object Let's consider an example which would answer this question var priceOfFood = { pizza: 14, burger 10 } priceOfFood.hasOwnProperty('pizza') // true priceOfFood['pizza'] // 14 priceOfFood.hasOwnProperty('chips') // false priceOfFood['chips'] // undefined */ //if (this.drinkRequirements.hasOwnProperty(drinkType) === false) if (!this.drinkRequirements[drinkType]) { alert("Sorry, we don't make " + drinkType); return false; } else { var beansRest = 0; beansRest = this.beans - this.drinkRequirements[drinkType].beansRequirements; if (beansRest < 0) { alert("Sorry, we're all out of beans!"); return false; } else { this.beans = beansRest; return true; } } } , buyDrink: function(drinkType) { if (this.makeDrink(drinkType)) { this.money += this.drinkRequirements[drinkType].price; console.log('the new coffeeShop money is ' + this.money); } } } coffeeShop.makeDrink("latte"); console.log("latte, " + coffeeShop.beans); coffeeShop.buyDrink("latte"); console.log("latte, " + coffeeShop.beans);
[ "stackoverflow", "0037507521.txt" ]
Q: "Named tuples" in r If you load the pracma package into the r console and type gammainc(2,2) you get lowinc uppinc reginc 0.5939942 0.4060058 0.5939942 This looks like some kind of a named tuple or something. But, I can't work out how to extract the number below the lowinc, namely 0.5939942. The code (gammainc(2,2))[1] doesn't work, we just get lowinc 0.5939942 which isn't a number. How is this done? A: As can be checked with str(gammainc(2,2)[1]) and class(gammainc(2,2)[1]), the output mentioned in the OP is in fact a number. It is just a named number. The names used as attributes of the vector are supposed to make the output easier to understand. The function unname() can be used to obtain the numerical vector without names: unname(gammainc(2,2)) #[1] 0.5939942 0.4060058 0.5939942 To select the first entry, one can use: unname(gammainc(2,2))[1] #[1] 0.5939942 In this specific case, a clearer version of the same might be: unname(gammainc(2,2)["lowinc"]) A: Double brackets will strip the dimension names gammainc(2,2)[[1]] gammainc(2,2)[["lowinc"]] I don't claim it to be intuitive, or obvious, but it is mentioned in the manual: For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). The partial matching can be employed like this gammainc(2, 2)[["low", exact=FALSE]]
[ "workplace.stackexchange", "0000118652.txt" ]
Q: Help as newbie to a job The situation: I am a newbie to my new job (IT) in a as it seems, quite decent company in Stuttgart(Germany) where I live.The problem is that at the moment I don't have experience in the job and I don't speak very good German, because of this I have some issues at work. My supervisor is a good person (and job-skilled), but as it seems doesn't want to spend much time with me or it seems like he is ignoring me, (maybe) because of my low level of experience and my difficulty with the language. I had some tasks that I completed, but he doesn't give me a new one or "orders" me to do something or give me a new guideline. So the questions are... 1.How do you translate his stance? 2.And how can I acquire more experience if I don't have something to do? 3.Is there something that I can do to change the situation? A: Doesnt want to spend much time with me It is not the managers job to "spend time" with you. They are there to distribute jobs to staff and to make sure all legal aspects are covered in their team/company. but he doesn't give me new tasks or orders me to do something Have you asked for them? If not do so, do what he "orders" you to do. Do as the manager says, avoid trouble, get paid. You will slowly learn the language and develop experience/skills in the field. That will come naturally by following what your manager says. If you have a direct issue with anything said then you can try have a simple conversation with the manager and ask for more tasks and say that you are slowly learning the language so give you time to progress (they will understand that the language is not easy to learn)
[ "stackoverflow", "0062322627.txt" ]
Q: How to annotate inside the plot when using datetime on the X axis with ggplot2? I have successfully created a line a graph in R using ggplot2 with percentage on Y axis and Date/Time on the X axis, but I am unsure how to annotate inside the graph for specific date/time points when their is a high/low peak. The examples I identified (on R-bloggers & RPubs) are annotated without using date/time, and I have made attempts to annotate it (with ggtext and annotate functions, etc), but got nowhere. Please can you show me an example of how to do this using ggplot2 in R? The current R code below creates the line graph, but can you help me extend the code to annotate inside of the graph? sentimentdata <- read.csv("sentimentData-problem.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE) sentimentTime <- sentimentdata %>% filter(between(Hour, 11, 23)) sentimentTime$Datetime <- ymd_hm(sentimentTime$Datetime) library(zoo) sentimentTime %>% filter(Cat %in% c("Negative", "Neutral", "Positive")) %>% ggplot(aes(x = Datetime, y = Percent, group = Cat, colour = Cat)) + geom_line() + scale_x_datetime(breaks = date_breaks("1 hours"), labels = date_format("%H:00")) + labs(title="Peak time on day of event", colour = "Sentiment Category") + xlab("By Hour") + ylab("Percentage of messages") Data source available via GitHub: A: Since you have multiple lines and you want two labels on each line according to the maxima and minima, you could create two small dataframes to pass to geom_text calls. First we ensure the necessary packages and the data are loaded: library(lubridate) library(ggplot2) library(scales) library(dplyr) url <- paste0("https://raw.githubusercontent.com/jcool12/", "datasets/master/sentimentData-problem.csv") sentimentdata <- read.csv(url, stringsAsFactors = FALSE) sentimentdata$Datetime <- dmy_hm(sentimentdata$Datetime) sentimentTime <- filter(sentimentdata, between(Hour, 11, 23)) Now we can create a max_table and min_table that hold the x and y co-ordinates and the labels for our maxima and minima: max_table <- sentimentTime %>% group_by(Cat) %>% summarise(Datetime = Datetime[which.max(Percent)], Percent = max(Percent) + 3, label = paste(trunc(Percent, 3), "%")) min_table <- sentimentTime %>% group_by(Cat) %>% summarise(Datetime = Datetime[which.min(Percent)], Percent = min(Percent) - 3, label = paste(trunc(Percent, 3), "%")) Which allows us to create our plot without much trouble: sentimentTime %>% filter(Cat %in% c("Negative", "Neutral", "Positive")) %>% ggplot(aes(x = Datetime, y = Percent, group = Cat, colour = Cat)) + geom_line() + geom_text(data = min_table, aes(label = label)) + # minimum labels geom_text(data = max_table, aes(label = label)) + # maximum labels scale_x_datetime(breaks = date_breaks("1 hours"), labels = date_format("%H:00")) + labs(title="Peak time on day of event", colour = "Sentiment Category") + xlab("By Hour") + ylab("Percentage of messages")
[ "stackoverflow", "0020807582.txt" ]
Q: Android: Centering text in a textview when texview is centered in a layout I need the text to be in the direct center of the screen, and want the textview to fill the parent. but it keeps aligning the start of the text to the center of the screen. How do i center the text in the middle of the screen when using a textview in android? this is what i have this is the xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_gravity="center" //removing this line has no effect android:gravity="center" android:text="TextView" /> </RelativeLayout> ------------------------------------- A: If you have to use a RelativeLayout here your solution: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:gravity="center" android:text="TextView" /> </RelativeLayout> You can also use a LinearLayout if you want: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="TextView" /> </LinearLayout>
[ "stackoverflow", "0005516308.txt" ]
Q: Custom Order Menus in WordPress I'm using WordPress Menus for my main navigation, at the moment it's displaying the navigation alphabetically. How can I get it to display my menus in the order I have them arranged in WordPress? Thanks in advance! A: Appearance > Menus Select the menu you want to edit (this view is editing Main Nav) Select that pages you want to include in your menu from PAGES on the left Add To Menu NOTE: You can also add post categories and nest pages within each other like shown in the image below. Make sure that your template is set up for menu nesting if you do this.
[ "stackoverflow", "0061509541.txt" ]
Q: Faceting a Dataset This is a beginner question. I have spent most of the day trying to work out how to facet my data, but all of the examples of faceting that I have come across seem unsuited to my dataset. Here are the first five rows from my data: Date Germany.Yield Italy.Yield Greece.Yield Italy_v_Germany.Spread Greece_v_Germany.Spread 2020-04-19 -0.472 1.820 2.287 2.292 2.759 2020-04-12 -0.472 1.790 2.112 2.262 2.584 2020-04-05 -0.345 1.599 1.829 1.944 2.174 2020-03-29 -0.441 1.542 1.972 1.983 2.413 2020-03-22 -0.475 1.334 1.585 1.809 2.060 I simply want to create two line charts. On both charts the x-axis will be the date. On the first chart, the y-axis should be Italy_v_Germany.Spread and on the second, the y-axis should be Greece_v_Germany.Spread. The first chart looks like this: So I want the two charts to appear alongside each other, like this: The one on the left should be Italy_v_Germany.Spread, and the one on the right should be Greece_v_Germany.Spread. I really have no idea where to start with this. Hoping that someone can point me in the right direction. In the interest I making the example reproducible, I will share a link to the CSV files which I'm using: https://1drv.ms/u/s!AvGKDeEV3LOsmmlHkzO6YVQTRiOX?e=mukBVy. Unforunately these files convert into excel format when shared via this link, so you may have to export the files to CSVs so that the code works. Here is the code that I have so far: library(ggplot2) library(scales) library(extrafont) library(dplyr) library(tidyr) work_dir <- "D:\\OneDrive\\Documents\\Economic Data\\Historical Yields\\Eurozone" setwd(work_dir) # Germany #--------------------------------------- germany_yields <- read.csv(file = "Germany 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F) germany_yields <- germany_yields[, -(3:6)] colnames(germany_yields)[1] <- "Date" colnames(germany_yields)[2] <- "Germany.Yield" #--------------------------------------- # Italy #--------------------------------------- italy_yields <- read.csv(file = "Italy 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F) italy_yields <- italy_yields[, -(3:6)] colnames(italy_yields)[1] <- "Date" colnames(italy_yields)[2] <- "Italy.Yield" #--------------------------------------- # Greece #--------------------------------------- greece_yields <- read.csv(file = "Greece 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F) greece_yields <- greece_yields[, -(3:6)] colnames(greece_yields)[1] <- "Date" colnames(greece_yields)[2] <- "Greece.Yield" #--------------------------------------- # Join data #--------------------------------------- combined <- merge(merge(germany_yields, italy_yields, by = "Date", sort = F), greece_yields, by = "Date", sort = F) combined <- na.omit(combined) combined$Date <- as.Date(combined$Date,format = "%B %d, %Y") combined["Italy_v_Germany.Spread"] <- combined$Italy.Yield - combined$Germany.Yield combined["Greece_v_Germany.Spread"] <- combined$Greece.Yield - combined$Germany.Yield #-------------------------------------------------------------------- fl_dates <- c(tail(combined$Date, n=1), head(combined$Date, n=1)) ggplot(data=combined, aes(x = Date, y = Italy_v_Germany.Spread)) + geom_line() + scale_x_date(limits = fl_dates, breaks = seq(as.Date("2008-01-01"), as.Date("2020-01-01"), by="2 years"), expand = c(0, 0), date_labels = "%Y") A: You need to get your data into a long format, for example, by using pivot_wider. Then it should work. library(dplyr) library(tidyr) library(ggplot2) data <- tribble(~Date, ~Germany.Yield, ~Italy.Yield, ~Greece.Yield, ~Italy_v_Germany.Spread, ~Greece_v_Germany.Spread, "2020-04-19", -0.472, 1.820, 2.287, 2.292, 2.759, "2020-04-19", -0.472, 1.820, 2.287, 2.292, 2.759, "2020-04-12", -0.472, 1.790, 2.112, 2.262, 2.584, "2020-04-05", -0.345, 1.599, 1.829, 1.944, 2.174, "2020-03-29", -0.441, 1.542, 1.972, 1.983, 2.413, "2020-03-22", -0.475, 1.334, 1.585, 1.809, 2.060 ) data %>% mutate(Date = as.Date(Date)) %>% pivot_longer( cols = ends_with("Spread"), names_to = "country", values_to = "Spread_v_Germany", values_drop_na = TRUE ) %>% ggplot(., aes(x = Date, y = Spread_v_Germany, group = 1)) + geom_line() + facet_wrap(. ~ country)
[ "stackoverflow", "0000511829.txt" ]
Q: MSBuild - how to copy files that may or may not exist? I have a situation where I need to copy a few specific files in a MSBuild script, but they may or may not exist. If they don't exist it's fine, I don't need them then. But the standard <copy> task throws an error if it cannot find each and every item in the list... A: Use the Exists condition on Copy task. <CreateItem Include="*.xml"> <Output ItemName="ItemsThatNeedToBeCopied" TaskParameter="Include"/> </CreateItem> <Copy SourceFiles="@(ItemsThatNeedToBeCopied)" DestinationFolder="$(OutputDir)" Condition="Exists('%(RootDir)%(Directory)%(Filename)%(Extension)')"/> A: The easiest would be to use the ContinueOnError flag http://msdn.microsoft.com/en-us/library/7z253716.aspx <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <MySourceFiles Include="a.cs;b.cs;c.cs"/> </ItemGroup> <Target Name="CopyFiles"> <Copy SourceFiles="@(MySourceFiles)" DestinationFolder="c:\MyProject\Destination" ContinueOnError="true" /> </Target> </Project> But if something else is wrong you will not notice it. So the condition exist from madgnome's answer would be better.
[ "stackoverflow", "0058495712.txt" ]
Q: C# Initialize class properties from REST client inside constructor I've searched a lot and I think this is possible, but I feel like I am just blocked from knowing how to properly format it. I have a class representing a product that is a relation class from our CRM to Magento. Inside the constructor, I have to do some stuff like this... public Product(IBaseProduct netforumProduct, MagentoClient client) { Product existingMagentoProduct = client.GetProductBySku(netforumProduct.Code); if (existingMagentoProduct != null) { this.id = existingMagentoProduct.id; this.name = existingMagentoProduct.name; ... many of them ... this.visibility = existingMagentoProduct.visibility; this.extension_attributes.configurable_product_links = existingMagentoProduct.extension_attributes.configurable_product_links; } else { // its a new product, new up the objects this.id = -1; this.product_links = new List<ProductLink>(); this.options = new List<Option>(); this.custom_attributes = new List<CustomAttribute>(); this.media_gallery_entries = new List<MediaGalleryEntry>(); this.extension_attributes = new ExtensionAttributes(); this.status = 0; // Keep all new products disabled so they can be added to the site and released on a specific day (this is a feature, not an issue / problem). this.attribute_set_id = netforumProduct.AttributeSetId; this.visibility = 0; } } It seems silly to have to initialize all of the properties like that. I could use a mapper but that seems like a bandaid. I have to see if the product exists in magento first, and populate its ID and values, otherwise whenever I save the product it creates an additional one. I considered doing the class constructor calling a static method, but I couldn't get the syntax right. It might just be too late and I need to think about something else for awhile. A: If you must do it in the constructor, you can get rid of a lot of code by first setting 'default' values to the 'Product' properties. This will remove the need to do them in the constructor. Next, if you wanted to automatically set the class's properties, you can use reflection. public class Product { public int Id { get; set; } = -1; public List<ProductLink> Product_Links { get; set; } = new List<ProductLink>(); .... public int Visibility { get; set; } = 0; public Product(IBaseProduct netforumProduct, MagentoClient client) { var existingMagentoProduct = client.GetProductBySku(netforumProduct.Code); if (existingMagentoProduct != null) { foreach (PropertyInfo property in typeof(Product).GetProperties().Where(p => p.CanWrite)) { property.SetValue(this, property.GetValue(existingMagentoProduct, null), null); } } } } Though, I would like to point out that you probably shouldn't be using a REST client inside a class constructor, especially to just populate its data (also, you are performing a synchronous operation). It would be cleaner to have another layer that is responsible for populating this class using the client, and then use something like AutoMapper to map the data to it.
[ "tex.stackexchange", "0000490619.txt" ]
Q: Tabular shifts when on a new page I'm trying to implement a list of symbols in my document. The first page of the list of symbols looks fine. However, on the second page (and subsequent pages), the tabular is indented for an unknown reason, as can be seen in the figure below (watch the red line). I would like both pages to line up. I'm not able to achieve this. I don't care whether I have to change the first page for the text to appear as in the second page, or vice-versa, as long as they line up. Does someone know why this behavior happens and how I can achieve what I would like? The code I used: \chapter*{List of Symbols} \label{list} \addcontentsline{toc}{chapter}{List of Symbols} \begin{tabular}{cp{1.0\textwidth}} $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ ... \end{tabular} \clearpage \thispagestyle{plain} \begin{tabular}{cp{1.0\textwidth}} $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ ... \end{tabular} Edit: Here, I describe the new problem where the header of the earlier page is displayed in the pages after List of Symbols. This happens when using a tabular spanning over multiple pages. When I manually split the tabular of List of Symbols into multiple pages, the header doesn't appear in the List of Symbols. \documentclass[english,12pt,a4paper,pdftex,twoside]{report} \usepackage[english]{babel} \usepackage{array} \usepackage{lmodern} \usepackage{graphicx} \usepackage{amsfonts,amssymb,amsbsy} \usepackage{fancyhdr} \usepackage[utf8]{inputenc} \usepackage{tabularx} \usepackage{xltabular} \usepackage{hyperref} \usepackage{setspace} \usepackage{amsmath} \usepackage{relsize} \usepackage{calc} \usepackage{gensymb} \usepackage{caption} \usepackage{textcomp} \usepackage{epstopdf} \usepackage{subcaption} \usepackage{color} \usepackage{enumerate} \usepackage{enumitem} \usepackage[a4paper,margin=3.5cm,footskip=0.5cm,top=1.8in,bottom=4.5cm]{geometry} \usepackage[font={small}]{caption} \usepackage{titlesec} \usepackage{hyperref} \usepackage{cite} \usepackage{tocbibind} \usepackage{appendix} \usepackage{xcolor} \usepackage{amsthm} \usepackage{chngpage} \usepackage{mathtools} \usepackage[figuresright]{rotating} \setlength\parindent{24pt} \titleclass{\subsubsubsection}{straight}[\subsection] \newcounter{subsubsubsection}[subsubsection] \renewcommand\thesubsubsubsection{\thesubsubsection.\arabic{subsubsubsection}} \renewcommand\theparagraph{\thesubsubsubsection.\arabic{paragraph}} % optional; useful if paragraphs are to be numbered \titleformat{\subsubsubsection} {\normalfont\normalsize\bfseries}{\thesubsubsubsection}{1em}{} \titlespacing*{\subsubsubsection} {0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex} \makeatletter \renewcommand\paragraph{\@startsection{paragraph}{5}{\z@}% {3.25ex \@plus1ex \@minus.2ex}% {-1em}% {\normalfont\normalsize\bfseries}} \renewcommand\subparagraph{\@startsection{subparagraph}{6}{\parindent}% {3.25ex \@plus1ex \@minus .2ex}% {-1em}% {\normalfont\normalsize\bfseries}} \def\toclevel@subsubsubsection{4} \def\toclevel@paragraph{5} \def\toclevel@paragraph{6} \def\l@subsubsubsection{\@dottedtocline{4}{7em}{4em}} \def\l@paragraph{\@dottedtocline{5}{10em}{5em}} \def\l@subparagraph{\@dottedtocline{6}{14em}{6em}} \makeatother \setcounter{secnumdepth}{4} \setcounter{tocdepth}{4} \captionsetup[table]{skip = 12 pt} \newlength{\depthofsumsign} \setlength{\depthofsumsign}{\depthof{$\sum$}} \newlength{\totalheightofsumsign} \newlength{\heightanddepthofargument} \newcommand{\nsum}[1][1.4]{ \mathop{ \raisebox {-#1\depthofsumsign+1\depthofsumsign} {\scalebox {#1} {$\displaystyle\sum$}% } } } \newcommand{\resum}[1]{ \def\s{#1} \mathop{ \mathpalette\resumaux{#1} } } \newcommand{\resumaux}[2]{ \sbox0{$#1#2$} \sbox1{$#1\sum$} \setlength{\heightanddepthofargument}{\wd0+\dp0} \setlength{\totalheightofsumsign}{\wd1+\dp1} \def\quot{\DivideLengths{\heightanddepthofargument}{\totalheightofsumsign}} \nsum[\quot] } % http://tex.stackexchange.com/a/6424/16595 \makeatletter \newcommand*{\DivideLengths}[2]{ \strip@pt\dimexpr\number\numexpr\number\dimexpr#1\relax*65536/\number\dimexpr#2\relax\relax sp\relax } \makeatother \newcommand\varpm{\mathbin{\vcenter{\hbox{% \oalign{\hfil$\scriptstyle+$\hfil\cr \noalign{\kern-.3ex} $\scriptscriptstyle({-})$\cr}% }}}} \newcommand\varmp{\mathbin{\vcenter{\hbox{% \oalign{\hfil$\scriptstyle-$\hfil\cr \noalign{\kern-.3ex} $\scriptscriptstyle({+})$\cr}% }}}} \setlength{\tabcolsep}{8pt} \renewcommand{\arraystretch}{1.5} \pagestyle{fancy} \fancyfoot{} \renewcommand{\footrulewidth}{0pt} \newcommand{\HRule}{\rule{\linewidth}{0.5mm}} \hypersetup{pdfpagemode=UseNone, pdfstartview=FitH, colorlinks=true,urlcolor=red,linkcolor=black,citecolor=black, pdftitle={Default Title, Modify},pdfauthor={Your Name}, pdfkeywords={Modify keywords}} \renewcommand*\rmdefault{lmr} \newcommand{\bb}{\textbf} \newcommand{\ita}{\textit} \newcommand{\tx}{\textrm} \newcommand{\todo}{\textbf{TODO: }} \newcommand*\xbar[1]{% \hbox{% \vbox{% \hrule height 0.5pt % The actual bar \kern0.5ex% % Distance between bar and symbol \hbox{% \kern-0.1em% % Shortening on the left side \ensuremath{#1}% \kern-0.1em% % Shortening on the right side }% }% }% } \renewcommand{\headrulewidth}{0 pt} \begin{document} % ----------------------------------------------------- \begin{titlepage} \selectlanguage{english} \setlength{\headheight}{3 cm} \thispagestyle{fancy} \fancyhead[L]{Header1\\ Header1 Header1 Header1\\ Header1 Header1 Header1 Header1 Header1} \setcounter{page}{0} \pagenumbering{roman} \mbox{}\\[2.5cm] \noindent Name Lastname\\ \noindent {\Large \bfseries Title title title \\title} \mbox{}\\[90 mm] \noindent Document type\\ Place, \today \\ \noindent Supervisor:\,\,\,\,\,\,\,\, Supervisor\\ Advisor:\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, Advisor \\ \selectlanguage{english} \end{titlepage} % -------------------------------------------------- \clearpage \setlength{\headheight}{16pt} \thispagestyle{fancy} \fancyhead[R]{DOCUMENT \\ TYPE} \fancyhead[L]{Header2 \\ Header2 Header2\\Header2 Header2 Header2 \\Header2} \selectlanguage{english} \mbox{}\\[0mm] \enlargethispage{20mm} \begin{center} \begin{tabular}{ |l l| } \hline \bb{Author:} & Name Lastname\\ \hline \bb{Title:} & Title title title\\ \hline \bb{Date:} & \today \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \bb{Pages:}\,\,\, $n+m$\\ \hline \bb{Major:} & Major major major major\\ \bb{Code:} & 1234\\ \hline \bb{Supervisor:} & Supervisor\\ \bb{Advisor:} & Supervisor\\ \hline \multicolumn{2}{|l|}{ \parbox{13.2cm}{ \mbox{}\\[0mm] Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem\\ Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum \\ Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum \\ }} \\ \hline \parbox[t][11 mm][t]{2.7cm}{\bb{Keywords:}} & \parbox[t][16mm][t]{10.0cm}{keyword1, keyword2, keyword3} \\ \hline \bb{Language:} & English \\ \hline \end{tabular} \end{center} %--------------------------------------------------- \clearpage \setlength{\headheight}{16pt} \thispagestyle{fancy} \fancyhead[R]{DOCUMENT\\ TYPE} \fancyhead[L]{Header2 \\ Header2 Header2\\Header2 Header2 Header2 \\Header2} \selectlanguage{english} \mbox{}\\[0mm] \enlargethispage{20mm} \begin{center} \begin{tabular}{ |l l| } \hline \bb{Author:} & Name Lastname\\ \hline \bb{Title:} & Title title title\\ \hline \bb{Date:} & \today \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \bb{Pages:}\,\,\, $n+m$\\ \hline \bb{Major:} & Major major major major\\ \bb{Code:} & 1234\\ \hline \bb{Supervisor:} & Supervisor\\ \bb{Advisor:} & Supervisor\\ \hline \multicolumn{2}{|l|}{ \parbox{13.2cm}{ \mbox{}\\[0mm] Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum \\ Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum \\ Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum }} \\ \hline \parbox[t][11 mm][t]{2.7cm}{\bb{Keywords:}} & \parbox[t][16mm][t]{10.0cm}{keyword1, keyword2, keyword3} \\ \hline \bb{Language:} & language2\\ \hline \end{tabular} \end{center} \selectlanguage{english} %--------------------------------------------------- \clearpage \thispagestyle{plain} \chapter*{Acknowledgements} \label{ch:ackno} Thanks for all to be thanked.\mbox{}\\[2.5cm] \ita{Place, Time time}\\\\\\\\ Author \vspace*{-38.5mm} \setlength{\footskip}{40pt} \addcontentsline{toc}{chapter}{\nameref{ch:ackno}} \thispagestyle{plain} %---------------------------------------------------- \clearpage \thispagestyle{plain} \chapter*{Abbreviations} \label{abbr} \addcontentsline{toc}{chapter}{Abbreviations} \begin{tabular}{cp{0.6\textwidth}} ABBR & Abbreviation explanation\\ ABBR & Abbreviation explanation\\ ABBR & Abbreviation explanation\\ ABBR & Abbreviation explanation\\ ABBR & Abbreviation explanation\\ \end{tabular} %---------------------------------------------------- \clearpage \thispagestyle{plain} \chapter*{List of Symbols} \label{list} \begin{xltabular}{\linewidth}{@{}>{$}r<{$} X @{}} \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \vdots & other symbols with long explanation other symbols with long explanation other symbols with long explanation \\ \sigma^2 & standard deviation\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \alpha & Explanation of the symbol\\ \beta & Explanation of the symbol\\ \gamma & Explanation of the symbol\\ \end{xltabular} \end{document} A: use \usepackage{tabularx} ... \chapter*{List of Symbols} \label{list} \addcontentsline{toc}{chapter}{List of Symbols} \noindent \begin{tabularx}{\linewidth}{@{}cX} $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ ... \end{tabularx} \clearpage \thispagestyle{plain} \noindent \begin{tabularx}{\linewidth}{@{}cX} $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ $symbol$ & Explanation of the symbol\\ ... \end{tabularx} if you need a page break then use package xltabular with the environment of the same name.
[ "stackoverflow", "0037562911.txt" ]
Q: Show all axioms Coq I want to see all axioms which were used by my proof. What are the easiest ways to obtain such information? Which commands or scripts or tools I shall use? I am interested in either all axioms or all used axioms. A: You should use the Print Assumptions foobar. vernacular command, described here
[ "stackoverflow", "0045472727.txt" ]
Q: jQuery Animate - jumps then Having an issue with a div content swap, where I want to animate in content then having it disappear if another element is clicked. I have the content swap working correctly, but it "appears" without the animation. this happens for all elements upon first load. If you click the elements again, then the animation executes properly. You can find my example here: https://jsfiddle.net/aebguh3k/7/ Sample code: $(document).ready(function() { $('#select').on('click', 'a', function() { $('.current').not($(this).closest('a').addClass('current')).removeClass('current'); $('.cselect:visible').hide().animate({ opacity: '0.0' }, "slow"); $('.cselect[id=' + $(this).attr('data-id') + ']').show().animate({ opacity: '1.0' }, "slow"); }); }); How can I fix the code so it animates properly A: The opacity property is not added to your div, until the click handler is triggered. So there is anything that can be animated. adding an initial style will help: https://jsfiddle.net/aebguh3k/8/ CSS: .cselect { opacity: 0; } JS: $('.cselect:first').css({'opacity': '1'});
[ "stackoverflow", "0041806016.txt" ]
Q: Turn off rotation? trying to turn off that user can't change orientation.. I have my view in landscape and it must be in landscaped so I'm doing it this way let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation") And also with this that user can't change rotation private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscapeLeft } private func shouldAutorotate() -> Bool { return false } The problem is that it isn' t working. I have after pushing landscaped but I'm still can rotate it. A: From swift 3 shouldAutorotate and supportedInterfaceOrientations is property not method, so you need to add it like this. override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscapeLeft }
[ "math.stackexchange", "0000182000.txt" ]
Q: Relation between cross-product and outer product If inner products ($V$) are generalisations of dot products ($ \mathbb{R}^n$), then are outer products ($V$) also related to cross-products ($ \mathbb{R}^3$) in some way? A quick search reveals that they are, but yet the outer product of two column vectors in $ \mathbb{R}^3$ is a 3x3 matrix, not another column vector. What's the link? Thanks! A: Cross product is much more related to exterior product which is in fact a far going generalization. Outer product is a matricial description of tensor product of two vectors.
[ "stackoverflow", "0058608012.txt" ]
Q: How should I do to send data between two jsp with a servlet I want to display something from one jsp page in another jsp page by clicking a button. I did it using request.setAttribute request.getAttribute but it doesn't work for me, for some reason the variable I send is null or the page is blank. A: From your original question : When you are doing setAttribute(), its scope is limited to the request when the main page is loading and hence will not be available on the next page as it will be a new request. <%Object product=ptp; request.setAttribute("purchase", ptp.getId()); %> What you can do is, submit this value in URL param as GET or in a form (get/ post) to fetch it on next JSP using request.getParameter(). Or you can use session scope by session.setAttribute() Hope it helps
[ "stackoverflow", "0008319169.txt" ]
Q: How to suppress the "Current Location" callout in map view Tapping the pulsating blue circle representing the userLocation brings up a "Current Location" callout. Is there a way to suppress that? A: There's a property on the annotation view you can change, once the user location has been updated: - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { MKAnnotationView *userLocationView = [mapView viewForAnnotation:userLocation]; userLocationView.canShowCallout = NO; } A: You can set the title to blank to suppress the callout: mapView.userLocation.title = @""; Edit: A more reliable way might be to blank the title in the didUpdateUserLocation delegate method: -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { userLocation.title = @""; } or in viewForAnnotation: - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>) annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) { ((MKUserLocation *)annotation).title = @""; return nil; } ... } Setting the title in the delegate methods lets you be certain you have a real userLocation instance to work with. A: Swift 4 // MARK: - MKMapViewDelegate func mapViewDidFinishLoadingMap(_ mapView: MKMapView) { if let userLocationView = mapView.view(for: mapView.userLocation) { userLocationView.canShowCallout = false } }
[ "askubuntu", "0000744891.txt" ]
Q: How to download a .deb package? This server has a .deb package that I want to download. The issue is, it only lets me download one file at a time from within the package. How can I download just the .deb file to install? A: The deb file has been compressed, I downloaded and extracted the largest archive as follows: wget http://downloadarchive.documentfoundation.org/libreoffice/old/3.5.7.2/deb/x86_64/LibO_3.5.7rc2_Linux_x86-64_install-deb_en-US.tar.gz tar xvf LibO_3.5.7rc2_Linux_x86-64_install-deb_en-US.tar.gz This extraction creates a directory structure: LibO_3.5.7rc2_Linux_x86-64_install-deb_en-US/DEBS and all of the deb packages are in this 'DEBS' folder: andrew@corinth:~/LibO_3.5.7rc2_Linux_x86-64_install-deb_en-US/DEBS$ ls desktop-integration libobasis3.5-base_3.5.7-2_amd64.deb libobasis3.5-binfilter_3.5.7-2_amd64.deb libobasis3.5-calc_3.5.7-2_amd64.deb libobasis3.5-core01_3.5.7-2_amd64.deb libobasis3.5-core02_3.5.7-2_amd64.deb libobasis3.5-core03_3.5.7-2_amd64.deb libobasis3.5-core04_3.5.7-2_amd64.deb libobasis3.5-core05_3.5.7-2_amd64.deb libobasis3.5-core06_3.5.7-2_amd64.deb libobasis3.5-core07_3.5.7-2_amd64.deb libobasis3.5-draw_3.5.7-2_amd64.deb libobasis3.5-en-us_3.5.7-2_amd64.deb libobasis3.5-en-us-base_3.5.7-2_amd64.deb libobasis3.5-en-us-calc_3.5.7-2_amd64.deb libobasis3.5-en-us-math_3.5.7-2_amd64.deb libobasis3.5-en-us-res_3.5.7-2_amd64.deb libobasis3.5-en-us-writer_3.5.7-2_amd64.deb libobasis3.5-extension-beanshell-script-provider_3.5.7-2_amd64.deb libobasis3.5-extension-javascript-script-provider_3.5.7-2_amd64.deb libobasis3.5-extension-mediawiki-publisher_3.5.7-2_amd64.deb libobasis3.5-extension-nlpsolver_3.5.7-2_amd64.deb libobasis3.5-extension-pdf-import_3.5.7-2_amd64.deb libobasis3.5-extension-presentation-minimizer_3.5.7-2_amd64.deb libobasis3.5-extension-presenter-screen_3.5.7-2_amd64.deb libobasis3.5-extension-python-script-provider_3.5.7-2_amd64.deb libobasis3.5-extension-report-builder_3.5.7-2_amd64.deb libobasis3.5-gnome-integration_3.5.7-2_amd64.deb libobasis3.5-graphicfilter_3.5.7-2_amd64.deb libobasis3.5-images_3.5.7-2_amd64.deb libobasis3.5-impress_3.5.7-2_amd64.deb libobasis3.5-javafilter_3.5.7-2_amd64.deb libobasis3.5-kde-integration_3.5.7-2_amd64.deb libobasis3.5-math_3.5.7-2_amd64.deb libobasis3.5-ogltrans_3.5.7-2_amd64.deb libobasis3.5-onlineupdate_3.5.7-2_amd64.deb libobasis3.5-ooofonts_3.5.7-2_amd64.deb libobasis3.5-ooolinguistic_3.5.7-2_amd64.deb libobasis3.5-postgresql-sdbc_3.5.7-2_amd64.deb libobasis3.5-pyuno_3.5.7-2_amd64.deb libobasis3.5-writer_3.5.7-2_amd64.deb libobasis3.5-xsltfilter_3.5.7-2_amd64.deb libreoffice3.5_3.5.7-2_amd64.deb libreoffice3.5-base_3.5.7-2_amd64.deb libreoffice3.5-calc_3.5.7-2_amd64.deb libreoffice3.5-dict-en_3.5.7-2_amd64.deb libreoffice3.5-dict-es_3.5.7-2_amd64.deb libreoffice3.5-dict-fr_3.5.7-2_amd64.deb libreoffice3.5-draw_3.5.7-2_amd64.deb libreoffice3.5-en-us_3.5.7-2_amd64.deb libreoffice3.5-impress_3.5.7-2_amd64.deb libreoffice3.5-math_3.5.7-2_amd64.deb libreoffice3.5-stdlibs_3.5.7-2_amd64.deb libreoffice3.5-ure_3.5.7-2_amd64.deb libreoffice3.5-writer_3.5.7-2_amd64.deb andrew@corinth:~/LibO_3.5.7rc2_Linux_x86-64_install-deb_en-US/DEBS$ And then if you wish you can install all of these from within the DEBS directory by running: sudo dpkg -i *.deb Installing any of these could be an issue depending on: Which version of Ubuntu you are using Which particular deb package you are trying to install Dependencies being the main issue as well as more modern versions being already available / installed from the Ubuntu repository...
[ "stackoverflow", "0046477591.txt" ]
Q: Angular CLI add SASS after the project has been created I have an Angular 4 project created using the Angular CLI. I know that when you are using the Angular CLI you can create a project that uses SASS like this: ng new ProjectName --style=sass My question is: "Can I use the Angular CLI to install SASS after a project has been already created without it?" A: You can set it to style with ng set after installing node-sass npm install node-sass --save-dev ng set defaults.styleExt scss Taken from here: Angular CLI SASS options
[ "stackoverflow", "0021857207.txt" ]
Q: PHP wrong character set I am trying to pull data from a table and output it as a text (RTF) file. The problem is that there are some characters in the content that get mangled. For instance, if I have Spanish content, some of the characters are not recognized and get changed. For example, if I have: 'implementación' the word gets changed to: 'implementación' By using break points, I can see that the string coming from the database is correct, it's only when it gets printed out that the tilde get's changed. Below is my code: header("Content-Type: application/rtf; charset=utf-8;"); header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=".$fileName .".rtf"); header("Content-Transfer-Encoding: binary"); echo $content; Thanks for your help. jason A: Match the output character set with the table's character set or convert the character set from the table with the character set you want to output. Assuming the table uses US-ASCII to store data and we want to output it as UTF-8. $content = iconv( 'US-ASCII', 'UTF-8//IGNORE//TRANSLIT', $content ); echo $content; This will transliterate certain characters EG: € to EUR, and ignore/drop characters that are not known to the output character set. If you are using Latin-1-General encoding in the table try CP850 (AKA: Code Page 850, MSDOS Latin-1) as opposed to US-ASCII. http://us2.php.net/manual/en/function.iconv.php You can optionally cast your encoding from within your query to the table For example with mysql SELECT convert(cast(convert(content using latin1) as binary) using utf8) AS content MySQL - Convert latin1 characters on a UTF8 table into UTF8 This is useful if the data sent to the database was using a different character set than the table. For example sending ASCII or ISO-8859-1 data to a table/column using UTF-8 collation. To find out the tables character encoding try: SHOW CREATE TABLE `tablename`; or How do I see what character set a MySQL database / table / column is? For table encoding: SELECT CCSA.character_set_name FROM information_schema.`TABLES` T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA WHERE CCSA.collation_name = T.table_collation AND T.table_schema = "schemaname" AND T.table_name = "tablename"; For column encoding: SELECT character_set_name FROM information_schema.`COLUMNS` C WHERE table_schema = "schemaname" AND table_name = "tablename" AND column_name = "columnname"; Alternatively you can try changing the charset header in PHP to match the database table's output. header("Content-Type: application/rtf; charset=ISO-8859-1;");
[ "stackoverflow", "0035805530.txt" ]
Q: Unable to connect docker nginx with docker ubuntu I have noticed an issue with docker nginx which is not the case when nginx is running on the host machine (apt-get install). Here is how to reproduce my issue: solution A: 'nc' on container 1, 'nginx' on container 2, 'curl' on host docker stop $(docker ps -aq) docker rm $(docker ps -aq) 'nc' on container 1 docker run -ti --name agitated_stallman ubuntu:14.04 bash nc -l 4545 'nginx' on container 2 LOLPATH=$HOME/testdocker echo $LOLPATH mkdir -p $LOLPATH cd $LOLPATH subl mple.conf . server { listen 80; root /var/www/html; location /roz { proxy_pass http://neocontainer:4545; proxy_set_header Host $host; } } . docker run --link agitated_stallman:neocontainer -v $LOLPATH/mple.conf:/etc/nginx/sites-available/default -p 12345:80 nginx:1.9 'curl' on host sudo apt-get install curl curl http://localhost:12345/roz ERROR response from 'nginx': 2016/03/04 19:59:18 [error] 8#8: *3 open() "/usr/share/nginx/html/roz" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /roz HTTP/1.1", host: "localhost:12345" 172.17.0.1 - - [04/Mar/2016:19:59:18 +0000] "GET /roz HTTP/1.1" 404 169 "-" "curl/7.45.0" "-" solution B: 'nginx' on host, 'nc' on host, 'curl' on host 'nginx' on host sudo apt-get install nginx sudo subl /etc/nginx/sites-available/default . server { listen 80; root /var/www/html; location /roz { proxy_pass http://localhost:4646; proxy_set_header Host $host; } } . sudo service nginx restart 'nc' on host nc -l 4646 'curl' on host sudo apt-get install curl curl http://localhost:80/roz SUCCESS response from 'nc': GET /roz HTTP/1.0 Host: localhost Connection: close User-Agent: curl/7.45.0 Accept: */* A: In short: run nginx container with -v $LOLPATH/mple.conf:/etc/nginx/conf.d/default.conf nginx:1.9 docker image currently uses nginx package from nginx's own repository, not from official debian repository. If you examine that package, you'll find that /etc/nginx/nginx.conf does include only from /etc/nginx/conf.d/*.conf, and that package ships with pre-included /etc/nginx/conf.d/default.conf: server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } # other not important stuff # ... } So your config is not used at all, which explains the open() "/usr/share/nginx/html/roz" failed error. When you install nginx directly on host, you probably use official debian repository, which has different main config file, which in turn does include /etc/nginx/sites-available/*, and your config is actually used.
[ "stackoverflow", "0056713671.txt" ]
Q: Visual Studio Post Build Script Equivalent for Java in IntelliJ I was a C# developer in a .NET based product for a while and we used Visual Studio and post build scripts where provided to do whatever we want to do after we build. Now I have moved on to Java world, and I am using IntelliJ IDEA Community Edition 2019.1.2. When I build project, it complies the java files into class files. Now later I manually run a jar -uvf to update the jar file in the build. (Source and Build aren't directly linked.) Is there anyway to configure the script I run in IntelliJ, so it automatically runs after I build? Following are the links that proved helpless. Most people suggest ant, but the steps they provide simply are not present in IntelliJ, I guess it is due to version mismatch. Build-project-pre-and-post-actions How to run a script after building an artifact VS post build event command line equivalent in IntelliJ IDEA? A: As far as I researched, there is no off the shelf place to copy-paste your script, or link to script file in IntelliJ that could directly run scripts after building the project. So the following steps solves the purpose, but is not as ideal as solution in Visual Studio for .NET projects Step 1 Put the jar update statements in a .sh file (for mac/linux) or .bat file (windows) updateJar.sh cd /path/to/classfiles/ jar -uvf /path/to/jar/file/x.jar package/stucture/ Step 2 Create an ant build file. The below execuatable and args are suitable for mac/linux systems. Please refer ant docs for exec and create correspondingly for windows. build.xml <project default="updateBuild"> <target name="updateBuild"> <exec executable="/bin/bash"> <arg value="/path/to/updateJar.sh" /> </exec> </target> </project> Step 3 Add the build.xml to IntelliJ project. For more details refer here. Step 4 After adding the build.xml, right click the updateBuild target, Select Execute On and then Select After Compilation. Voila. Now whenever you compile, your jar gets updated seamlessly. You can check output by expanding the target in the build messages tab.
[ "math.stackexchange", "0000050368.txt" ]
Q: Analysis of Algorithms: Solving Recursion equations: $\quad T(n)= T(cn)+T(dn)+n$ How can I prove that the solution for the following recursion equation is $\Theta(n)$: $$T(n)= T(cn)+T(dn)+n \text{ for } d,c>0 \text{ and } c+d<1$$ Edit: $cn$ on one side only. What I need to show is that algorithm that works this way it will "waste" linear time of work, depending on $n$ , the amount of values that it will need to work on, I hope I got that clear. A: Since $T(n) > n$, we immediately have $T(N) = \Omega(n)$. To get the desired upper bound, we can apply the Master Theorem (technically, a generalization known as the Akra-Bazzi method). However, since we already know that the answer is $O(n)$ and just need to prove it, a simple induction argument suffices. Let $c+d=1-\epsilon$. Suppose that $T(m) < \alpha m$ for all $m < n$. Then $T(n) < \alpha cn + \alpha dn + n = (c + d)\alpha n + n = (1-\epsilon)\alpha n + n$. We want that $T(n) < \alpha n$. Solving $(1-\epsilon)\alpha n + n < \alpha n$, we see that the inequality holds provided that $\epsilon\alpha > 1$. So $T(n) < \alpha n$ for all $n$, where $\alpha = (1-c-d)^{-1}$.
[ "stackoverflow", "0041077222.txt" ]
Q: Android Studio: 2 XML Files, but App is starting 2nd XML-file instead of 1st one I've made an app that allows a user to login, but everytime I try to run my app, it will automatically display Activity_main.xml (that is a page that if you have login successfully). I want to run my app, but it must display the activity_main.xml (which is the login page) first instead of the activity_main.xml which is now the first page Here is my code: AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mertino11.ourapplication"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".FireApp" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true"> <activity android:name=".MainActivity" android:theme="@style/AppTheme"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name=".AccountActivity" android:theme="@style/AppTheme" /> </application> </manifest> activity_account.xml (XML for user logged in succesfully) <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_account" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.mertino11.ourapplication.AccountActivity"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Account Page" android:ems="10" android:id="@+id/editText" android:textSize="22sp" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:textStyle="normal|bold" android:textAlignment="center" /> </RelativeLayout> activity_main.xml (login page) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:baselineAligned="false"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:ems="10" android:id="@+id/emailField" android:hint="Email" android:paddingTop="20dp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/passwordField" android:hint="Password" android:fontFamily="sans-serif" android:paddingTop="20dp" /> <Button android:text="Login" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/loginBtn" android:paddingTop="20dp" /> </LinearLayout> Java --> Class: AccountActivity (Page when the user logged in successfully) package com.example.mertino11.ourapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class AccountActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account); } } Java --> Class: FireApp (Firebase settings I think) package com.example.mertino11.ourapplication; import android.app.Application; import com.firebase.client.Firebase; /** * Created by Mertino11 on 10-Dec-16. */ public class FireApp extends Application { @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(this); } } Java --> Class: Main Activity (Back-end logging with account) package com.example.mertino11.ourapplication; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { private EditText mEmailField; private EditText mPasswordField; private Button mLoginBtn; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAuth = FirebaseAuth.getInstance(); mEmailField = (EditText) findViewById(R.id.emailField); mPasswordField = (EditText) findViewById(R.id.passwordField); mLoginBtn = (Button) findViewById(R.id.loginBtn); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if(firebaseAuth.getCurrentUser() != null) { startActivity(new Intent(MainActivity.this, AccountActivity.class)); } } }; mLoginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startSignIn(); } }); } @Override protected void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } private void startSignIn() { String email = mEmailField.getText().toString(); String password = mPasswordField.getText().toString(); if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) { Toast.makeText(MainActivity.this, "Fields are empty!", Toast.LENGTH_LONG).show(); } else { mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(!task.isSuccessful()){ Toast.makeText(MainActivity.this, "Sign In Problem!", Toast.LENGTH_LONG).show(); } } }); } } } Logs in Run: 12/10 16:35:26: Launching app $ adb push C:\Users\Mertino11\Downloads\OurApplication\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.mertino11.ourapplication $ adb shell pm install -r "/data/local/tmp/com.example.mertino11.ourapplication" Success $ adb shell am start -n "com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Client not ready yet..Waiting for process to come online Connected to process 2403 on device emulator-5554 W/System: ClassLoader referenced unknown path: /data/app/com.example.mertino11.ourapplication-1/lib/x86 I/InstantRun: Instant Run Runtime started. Android package is com.example.mertino11.ourapplication, real application class is com.example.mertino11.ourapplication.FireApp. [ 12-10 16:35:30.033 1550: 1571 D/ ] HostConnection::get() New Host Connection established 0x89bee200, tid 1571 W/System: ClassLoader referenced unknown path: /data/app/com.example.mertino11.ourapplication-1/lib/x86 W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. W/System: ClassLoader referenced unknown path: /system/priv-app/PrebuiltGmsCore/lib/x86 D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization. W/System: ClassLoader referenced unknown path: W/System: ClassLoader referenced unknown path: /system/priv-app/PrebuiltGmsCore/lib/x86 I/FA: App measurement is starting up, version: 10084 I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE D/FA: Debug-level message logging enabled D/FA: AppMeasurement singleton hash: 174613062 I/art: Background sticky concurrent mark sweep GC freed 21982(2MB) AllocSpace objects, 55(1056KB) LOS objects, 34% free, 7MB/11MB, paused 7.752ms total 131.168ms V/FA: Collection enabled V/FA: App package, google app id: com.example.mertino11.ourapplication, 1:113712880364:android:c60a6cfc3967db90 I/FA: To enable faster debug mode event logging run: adb shell setprop debug.firebase.analytics.app com.example.mertino11.ourapplication V/FA: Registered activity lifecycle callback I/FirebaseInitProvider: FirebaseApp initialization successful V/FA: Using measurement service V/FA: Connecting to remote service W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable V/FA: onActivityCreated V/FA: Using measurement service V/FA: Connection attempt already in progress V/FA: Activity resumed, time: 29161 I/OpenGLRenderer: Initialized EGL, version 1.4 D/OpenGLRenderer: Swap behavior 1 E/EGL_emulation: tid 2587: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH) W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa71b42c0, error=EGL_BAD_MATCH V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 497 V/FA: Using measurement service V/FA: Connection attempt already in progress V/FA: Activity paused, time: 29657 I/Choreographer: Skipped 33 frames! The application may be doing too much work on its main thread. D/FA: Connected to remote service V/FA: Processing queued up service tasks: 3 V/FA: onActivityCreated V/FA: Activity resumed, time: 30137 E/EGL_emulation: tid 2587: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH) W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa71b42c0, error=EGL_BAD_MATCH V/FA: Inactivity, disconnecting from the service W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. V/FA: Session started, time: 39646 I/FA: Tag Manager is not found and thus will not be used D/FA: Logging event (FE): _s, Bundle[{_o=auto, _sc=AccountActivity, _si=-1992202464745463440}] V/FA: Using measurement service V/FA: Connecting to remote service D/FA: Connected to remote service V/FA: Processing queued up service tasks: 1 V/FA: Inactivity, disconnecting from the service Screenshot of my hierachy of the project itself: http://i66.tinypic.com/vor192.png The scenario of the app: Create account firebase Google (manually) Opens app --> Sees login page (where I am stuck at) Logs in with accountdetails of Firebase Goes to AccountActivity page Note: I am a amateur/beginner with AndroidStudio. A: Button logout=(Button) findViewById(R.id.logout) logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseAuth.getInstance().signOut(); startActivity(new Intent(AccountActivity.this,MainActivity.class)); finish(); } }); xml <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="logout" android:id="@+id/logout"/> in AccountActivity.xml
[ "stackoverflow", "0027431563.txt" ]
Q: Print layered html5 canvases I have a page composed of multiple layered canvases, which I would like to turn into one image (and then print). So for one canvas it's simple: capture-html-canvas-as-gif-jpg-png-pdf. So what to do with multiple layers of canvases? The only idea I came up with so far is to create another canvas and paint all the layered canvases into this one with ascending z-order. Will work, but taking a snapshot of the original canvases would be more helpful. A: Combining your canvases into a single "print" canvas is the way to go. BTW, in case you didn't know... context.drawImage(imageSource... will take another canvas as it's imageSource. Therefore, if you need all your canvases intact (uncombined), just create a new in-memory-only canvas and draw all canvases onto that new canvas in z-index order: var printCanvas=document.createElement('canvas'); var printCtx=printCanvas.getContext('2d'); printCtx.drawImage(canvasZIndex0,0,0); printCtx.drawImage(canvasZIndex1,0,0); printCtx.drawImage(canvasZIndex2,0,0); printCtx.drawImage(canvasZIndex3,0,0); var img=new Image(); img.onload=function(){ // print this snapshot image } img.src=printCanvas.toDataURL();
[ "gaming.stackexchange", "0000338155.txt" ]
Q: What does the M counter in Solo Mode mean? In the Solo Mode of Mario Party 6, there is an M counter located just above the coin count. Initially I thought it might track minigame victories, but the counter didn't increase after winning a minigame. What does the M counter mean in Solo Mode? A: I believe it counts collected minigames on the board, factoring in how many Minigames you've collected over your entire career. So if you win a game you haven't collected, the M counter gets incremented and the game can be stolen by Bowser, and so forth. Consider the following gameplay footage in which this video plays with most of the games earned prior to starting a new solo game: Versus this footage where the boards starts with no games earned:
[ "stackoverflow", "0014167059.txt" ]
Q: IP reading and some missing values I am a newbie in R. This time I really need to read a data include time, ip and something like this: 18:00:04.940864 129.63.50.235.53 > 129.63.71.70.1111: udp 107 18:00:04.957456 129.63.80.240.161 > 129.63.152.10.39518: udp 151 18:00:04.958432 129.63.152.10.39518 > 129.63.80.240.161: udp 136 (DF) 18:00:04.963312 217.79.96.182.53 > 129.63.1.1.1564: udp 48 (DF) 18:00:05.000976 129.63.50.235.1028 > 218.232.110.133.53: udp 34 18:00:05.207888 129.63.50.235.1028 > 203.50.0.24.53: udp 32 I began with read.table(file='sample.txt',head=F,'%H:%M:%S',sep='') than I am stuck at that point because there are few types of separation: space, '>' and ': ' Finally is the last vector where could or not have (DF) in there. Could anyone give me an idea to solve this kind of data? Thanks a lot A: Here's a brute-force approach. tt <- read.table(header=FALSE, fill=TRUE, stringsAsFactors=FALSE, text="18:00:04.940864 129.63.50.235.53 > 129.63.71.70.1111: udp 107 18:00:04.957456 129.63.80.240.161 > 129.63.152.10.39518: udp 151 18:00:04.958432 129.63.152.10.39518 > 129.63.80.240.161: udp 136 (DF) 18:00:04.963312 217.79.96.182.53 > 129.63.1.1.1564: udp 48 (DF) 18:00:05.000976 129.63.50.235.1028 > 218.232.110.133.53: udp 34 18:00:05.207888 129.63.50.235.1028 > 203.50.0.24.53: udp 32") last <- apply(tt[-(1:4)], 1, paste, collapse=' ') tt[,5] <- last tt[,4] <- sub(':', '', tt[,4]) tt <- tt[c(1,2,4,5)] > tt ## V1 V2 V4 V5 ## 1 18:00:04.940864 129.63.50.235.53 129.63.71.70.1111 udp 107 ## 2 18:00:04.957456 129.63.80.240.161 129.63.152.10.39518 udp 151 ## 3 18:00:04.958432 129.63.152.10.39518 129.63.80.240.161 udp 136 (DF) ## 4 18:00:04.963312 217.79.96.182.53 129.63.1.1.1564 udp 48 (DF) ## 5 18:00:05.000976 129.63.50.235.1028 218.232.110.133.53 udp 34 ## 6 18:00:05.207888 129.63.50.235.1028 203.50.0.24.53 udp 32
[ "scifi.stackexchange", "0000183555.txt" ]
Q: What happened to The Bulletin’s digital archive? In Season 2 Episode 5 of Daredevil, Ellison allows Karen to look through The Bulletin’s archives in exchange for a story on the Punisher. To Karen’s dismay, all the digital archives were lost. Ellison: All the servers were completely wiped in the incident. Decades, just gone. So we keep hard copies of everything now. What incident is Ellison referring to? How did The Bulletin lose their digital archive? A: I believe it was the events of the first Avengers movie. "The Incident" is referred to several times in the show, and it seems to be referring to when the Chitauri invaded New York.
[ "salesforce.stackexchange", "0000245977.txt" ]
Q: Chart.js - ReferenceErrore : Chart is not defnied I'm using Chart.js inside a Lightning Community app and I'm having trouble creating a simple chart. Here's my script declaration (note that the moment.min.js is required for the Chart.js to work) : <ltng:require scripts="{!join(',', $Resource.BundleResources + '/BundleResources/js/moment.min.js', $Resource.BundleResources + '/BundleResources/js/Chart.min.js')}" afterScriptsLoaded="{!c.init}"/> and here's my rendere javascript file : afterRender : function(component, helper) { this.superAfterRender(); try { var canvas = document.getElementById('networkChart'); var ctx = canvas.getContext('2d'); // below is the standard Chart.js example found in their documentation var youpi = new Chart(ctx, { type: 'bar', data: { labels: ['label1', '2', 'et 3'], data: [1, 2, 3, 4, 5, 6], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); }catch(e){ helper.logError('catched error : ' + e); } } and below is the error the console is giving me : catched error : ReferenceError: Chart is not defined My Chart.min.js is well included, no error on this side. Does anybody knows where I failed ? Thank you ! A: afterRender will be called before ltng:require loads the required scripts. You need to wait until the afterScriptsLoaded method is called (in other words, your init method).
[ "stackoverflow", "0030602898.txt" ]
Q: How can I associate "foreign key" ids of one index to the corresponding data of another index in Elasticsearch using Rails? Situation Elasticsearch has indices "users" and "calls," where users can dial or receive many calls. On the database end, the calls table has user ids that act as foreign keys from the users table. This relationship in Elasticsearch directly correlates to the DBs design. Here is an example Elasticsearch JSON output using Sense: GET /calls/call/23 { "_index": "calls", "_type": "call", "_id": "23", "_version": 2, "found": true, "_source": { "id": 23, "user1_id": 1, //Jack "called" "user2_id": 12, // George "received" "start_time": "2015-05-29T16:01:28.233Z", "end_time": null, "status": "NONE", "reason": null, "created_at": null, "updated_at": null } } This is a rails app, so my issue is when I search for calls by name in the calls view, nothing is found because only the ids (user1_id and user2_id) are stored in the calls index. I essentially need Elasticsearch to return results if searching by names for calls similar to this DB query: select calls.id AS "Call id", users.id AS "User Id", users.name AS "Name" from calls, users where (calls.user1_id=users.id OR calls.user2_id=users.id) AND users.name LIKE '%Jack%'; The above query of course returns all calls made and received by the name searched for, Jack, while comparing the user and call ids. Desired output { "_index": "calls", "_type": "call", "_id": "23", "_version": 2, "found": true, "_source": { "id": 23, "dialer": { "id": 1, "name": "Jack" }, "receiver": { "id": 12, "name": "George" }, "start_time": "2015-04-27T17:29:04.868Z", "end_time": "2015-04-27T17:29:59.198Z", "status": "SUCCESS", "reason": "User hungup", "created_at": null, "updated_at": null } } From what I've gathered when looking into creating new mappings or creating custom search queries in Elasticsearch, I had figured I needed to create the calls index with new source mappings "user1_name" and "user2_name"; then figured Elasticsearch would populate those source mappings accordingly, associating user1_id and user2_id with their names in the corresponding user index. What I've tried I tried a HTTP requests in Sense, which manually creates my desired tree structure, but only for one call item: PUT /calls/call/23 { "id": 23, "dialer": { "id": 1, "name": "Jack" }, "receiver": { "id": 12, "name": "George" }, "start_time": "2015-04-27T17:29:04.868Z", "end_time": "2015-04-27T17:29:59.198Z", "status": "SUCCESS", "reason": "User hungup", "created_at": null, "updated_at": null } I also tried creating aliases in hopes of combining the indices for relationships: POST /_aliases { "actions" : [ { "add" : { "index" : "users", "alias" : "searchcalls" } }, { "add" : { "index" : "calls", "alias" : "searchcalls" } } ] } Also, there's this: http://www.spacevatican.org/2012/6/3/fun-with-elasticsearch-s-children-and-nested-documents/ But there's no way I can be expected to do these things for tens of thousands potentially millions of calls... Question Any direction on how to modify Elasticsearch or my rails code would be much appreciated. I am 100% stuck in the mud here. Not sure if I need to create mappings, do something with ES, or do something else entirely in rails or HOW to do any of it... Simply put, how can I associate user ids in the calls index with the user names that exists in the users index in order that I can have the ability to search for calls by name? I imagine whatever indexing method is required will need to be handled in bulk and stay in sync with the live DB... Thanks! A: After just hammering things out for the past week, I believe I found a solution. After piecing together the massive Elasticsearch doc on Bulk API and Rubydocs, this is what I came up with in rails: Model # elasticsearch custom mapping mappings :dynamic => 'true' do indexes :dialer do indexes :id, :type => 'long' indexes :name, :type => 'string' indexes :email, :type => 'string' end indexes :receiver do indexes :id, :type => 'long' indexes :name, :type => 'string' indexes :email, :type => 'string' end end # customize the index for for relationships def as_indexed_json(options={}) as_json( except: [:user1_id, :user2_id], include: { dialer: { only: [:id, :name, :email]}, receiver: { only: [:id, :name, :email]} } ) end This gives me my desired output, but the problem I am facing now is the import is slow as molasses... This post was helpful, especially the "write a faster import" section, but still slow as molasses. Any comments would still be helpful, thanks. I am open to any and all suggestions!
[ "stackoverflow", "0051250592.txt" ]
Q: Extract a string in R I have the following vector v <- c("feasible", "URE.feasible","RE.β0","RE.β1","RE.β2","URE.β0","URE.β1","URE.β2","URE.SE.β0","URE.SE.β1","URE.SE.β2") I would like to extract only c("URE.β0","URE.β1","URE.β2") so I coded this which(grepl("URE.", v)) but i got more. How can I only get the this c("URE.β0","URE.β1","URE.β2")? A: Use this: grep("^URE\\.β[0-9]+", v) This will give you indices of the matches: [1] 6 7 8 If you want values: grep("^URE\\.β[0-9]+", v, value=TRUE) This produces: [1] "URE.β0" "URE.β1" "URE.β2" With use of grep instead of grepl, you won't need the "which" call. The '^' ensures that only strings beginning with 'URE' are matched, since '^' matches the beginning of a string or a line being matched. Leave out the '+' if only one digit after 'β' needs to be matched.
[ "stackoverflow", "0057536483.txt" ]
Q: How do i increase a number by 1 in every line that contain the number 1 i want it to increase numbers on each number "1" but also repeat the increase two times you can look at my example down below i am trying to delete a bunch of files in my program as i said look down below but if you know how to Directory.Delete(path); without the if (Directory.Exists) and all that it would also be great. cause i rather just type Directory.Delete(path) and if it dont find the folder it will just continue. Sorry for my bad English Everything google sucks if (Directory.Exists(delete[1])) { Directory.Delete(delete[1]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[1])) { Directory.Delete(delete[1]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[1])) { Directory.Delete(delete[1]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[1])) { Directory.Delete(delete[1]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[1])) { Directory.Delete(delete[1]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } to if (Directory.Exists(delete[1])) { Directory.Delete(delete[1]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[2])) { Directory.Delete(delete[2]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[3])) { Directory.Delete(delete[3]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[3])) { Directory.Delete(delete[3]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } if (Directory.Exists(delete[4])) { Directory.Delete(delete[4]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } and so on i showed what i expected over here ^^ A: You want to loop over the array with an iterator variable. Initialize i with your starting point and length to your exclusive ending i (in your example, it's 5). //gets the length of the array int length = sizeof(delete)/sizeof(delete[0]); for(int i=0; i<length; i++){ if (Directory.Exists(delete[i])) { Directory.Delete(delete[i]); Console.WriteLine("You didnt fail"); } else { Console.WriteLine("You failed!"); } }
[ "stackoverflow", "0032866946.txt" ]
Q: C++ a program to calculate the greatest profit This program accepts input of the everyday prices of a good and then calculates the greatest profit. And the list of prices will end with -1. for example, if I input 20,30,10,50,-1 , it means at the first day the good is $20,in the second day is $30,etc. The greatest profit output will be $40 since I could buy it on the third day at $10 and sell it in the fourth day at $50. This is a school assignment and the teacher do not allow me to use array. Now my program is fine except in this case e.g. if I input 20 30 10, the greatest profit will be $(30-10) how could I fix it so if will not store the number after the maximum number e.g. 10 as the minimum number? Or any other codes to fulfil the purpose of my program? #include<iostream> using namespace std; int main() { int c(0), r(0), n1(0), min(0), max(0), l(0), s(0); cout << "Please enter the prices: "; while (n1 != -1) { cin >> n1; if (min == 0 && n1>0) { min = n1; } c++; if (n1 <= 0 && n1 != -1) { cout << "Invalid. Input again. Please make sure it's a positive number!" << endl; r++; } else { if (n1<min && n1 != -1) { min = n1; s++; } if (n1 >= max && (c - r)>(s + 1)) { max = n1; l = c; } cout << c << s + 1 << l << endl; } } cout << max << min; cout << endl << "Largest amount earned: " << (max - min) << endl; return 0; } A: You can simply calculate maximum profit by using the lowest price from now and not in the future. #include <iostream> int main(void) { int lowestPrice = -1; int highestProfit = 0; int price, maxProfit; while (std::cin >> price) { if (price < 0) break; if (lowestPrice < 0 || price < lowestPrice) lowestPrice = price; maxProfit = price - lowestPrice; if (maxProfit > highestProfit) highestProfit = maxProfit; } std::cout << highestProfit << std::endl; return 0; }
[ "stackoverflow", "0050326216.txt" ]
Q: Is using new Function() unsafe in all instances? I'm working on a project that creates a new function, then returns an evaluated template string. My code goes like this: var myString = "${hello}" var myFunc = new Function("hello", 'return `' + myString + '`') document.getElementById("tdiv").innerHTML = myFunc("whassup") It works perfectly, as you can see on my JSFiddle: https://jsfiddle.net/nebrelbug/28c7hfm8/. However, is this a security risk? Functions automatically have strict use, so it couldn't access variables other than those I pass in. I fail to see how this would impact security at all. If it is a security risk, please explain why. If not, will most security evaluators like 'npm audit' or Github mark it as one? Thanks! A: Many things said to be "risky" are not inherently security risks by themselves, they're just potentially security risks if implemented improperly. This is one of those cases. You could have a script like const foo = 'foo'; const bar = eval('foo'); This code, exactly as is with nothing else, is obviously not a security risk, but you can't necessarily count on security evaluators to completely accurately verify whether how you're implementing something is actually safe or not - they use programmed heuristics, rather than a human security expert examining your code for holes. As such, using eval and its relatives like new Function are more closely correlated with insecure code. In my snippet, just as with your code, even if it's not a security risk, it's still a very inelegant way of achieving your goal. Try to find a better way of achieving it. For example: var myString = "foo ${hello} bar"; function myFunc(replaceHelloWith) { return myString.replace(/\$\{hello\}/g, replaceHelloWith); } console.log(myFunc("whassup"));
[ "academia.stackexchange", "0000088350.txt" ]
Q: Should I sleep less to achieve my thesis targets? I am doing my Masters (thesis-based) in Computer Engineering in Canada. I started my research in September 2015 and it is now the end of April in 2017 but I haven't done ANY significant research. It is very distressing and I definitely will need extra time to finish my research and graduate. I meet with my professor and we both decide on what I need to do and a deadline is set for specific tasks. The initial stages of these tasks mainly involve installing software on my lab system which has the hardware I need for my research. I always run into problems during these installation processes and I end up spending more time than necessary JUST to have the necessary tools needed to do my project. By the time I get started with my work and do anything meaningful, the deadline arrives and the tasks remain incomplete. My professor is frustrated by my lack of concrete results but despite that, he is encouraging and believes in my abilities. I also think I can publish at least one conference paper before I graduate. However, I am wasting my potential and my expertise by not meeting set deadlines. I know I can get things done but apparently, I am too slow in getting to where I want to be. I feel that setting aside a set amount of time each day (6 hours or so) is not always effective in meeting goals. Should I just give up sleep (and definitely my leisure time) to meet my goals? I am afraid that it will impact my health and my concentration and negatively impact the quality of my work. Should I simply come to terms with the fact that given my capabilities, I will need to sleep less to meet my goals? EDIT: I also work as a TA and a good amount of time also goes towards preparing for labs and marking students' papers. A: Reducing sleep may work for a day or two. However, after that, sleep debt accumulates, and sleep deprivation will lead to a reduction in productivity. Sleep is essential for your physical health, and in particular, it is essential for mental functioning. You may find it better to view sleep as a form of "work time". The cognitive structures you have about your thesis will be refined and pruned while you sleep. You'll make novel connections while you sleep. Sleep will also enable you to have the mental energy to engage in focused activity on the thesis. In particular, the kind of deep creative thinking required to analyse data and write a thesis is helped greatly by being well-rested. Sleep also helps ensure that the work you do is directed towards your goals. Thus, allocating enough time to sleep so that you are well-rested is essential to overall academic productivity. So in general, if you are looking to maximise productivity in the medium-term (i.e., from a week or two to perhaps a month or two), then look at things other than sleep and thesis-time that can be trimmed. If possible, remove all other work commitments (i.e., no tutoring, RA work, consulting, etc.). Other work consumes largely the same set of limited mental and time resources that you have available each week. If possible, reduce non-work commitments. Also, in the medium term, many people do pull back from social and leisure activities a little bit. But in the longer term, you want to think about a balance to your life that truly works for you. I also think that incorporating at least a moderate amount of physical exercise is also important. A: Having less sleep would do potentially more harm than good. Quite simply, you are less likely to be able to work to capacity if you are tired and worn out and this is very likely to have a detrimental effect on your studies and on your health in the medium to long term at least - you could end up becoming very resentful towards your work, which would compound the problems you are facing now. There have been a considerable amount of research investigating the link between amount of sleep and academic performance. An example is the article Causes and consequences of sleepiness among college students (Hershner and Chervin, 2014), where they state: The consequences of sleep deprivation and daytime sleepiness are especially problematic to college students and can result in lower grade point averages, increased risk of academic failure, compromised learning, impaired mood, and increased risk of motor vehicle accidents. Instead of reducing your sleep, you need to ensure that you maintain your sleep duration and patterns, as well as eating well, exercising regularly and occasionally giving yourself some 'time off'. Look for other areas that time can be gained (without harming your studies, health or work, of course). Talk with your professor about these issues as well, particularly about the time spent on installations and as a TA.
[ "stackoverflow", "0010197279.txt" ]
Q: Two questions: should I do client-side or server-side in terms of validation? Also, how would I verify that no textbox is blank/invalid... ...with jquery/javascript? I want to check and make sure that a value has been entered and that it's a number. First - Is it a best practice to do validation on the client-side, server-side, or both? Is this something that should be validated twice or is checking on the client-side enough? Second - If client-side validation is the best way to go about this, how could I do this with javascript/jquery? I assume that for the button that's clicked, I would assign its onclientclick equal to a javascript function. A: 1) Validation should, at minumum be done on the server side. Both is even better. 2) If you wanted to do easy validation, you would simply attach to either a button click event, or better even, the form submit event. $('form').submit(function() { // Do My Validation // return false if invalid, true otherwise }); A: You need to do both, and you should use jQuery Validate for the client-side.
[ "workplace.stackexchange", "0000151328.txt" ]
Q: Can I put my business signature on my personal email? In other words, include my title and the name of my employer in my personal email signature in my personal email. A: You can, but I wouldn't advise it, for the following reason. Every last email you send with that information reflects on the company In other words, if you compose an email that offends someone, and it gets back to your employer, you are out of luck. It is far too much of a risk to use in anything other than professional correspondence. A: It's a bad idea. It would cause confusion. There are two identities: your personal one, and your work one. These should be kept separate. If you start sending emails like this and somebody notices that the signature doesn't match the email domain, it will damage both your reputation and your company. I would myself take this as impersonating somebody else and potential scam attempt.
[ "stackoverflow", "0060874332.txt" ]
Q: Django redirecting to a wrong url when i click submit on my form it goes to ../register/register/ where as my expectation is that it should go to ../register This is my main project urls.py urlpatterns = [ path('participants/', include('participants.urls')), path('admin/', admin.site.urls), ] This is my application urls.py urlpatterns = [ path('register/', views.register, name="register") ] This is my views function def register(request): if request.method == "POST": username = request.POST['username'] # email = request.POST['email'] password = request.POST['pass'] print(username, password) user = User.objects.create_user(username=username, password=password) user.save() return redirect('register') else: return render(request, 'register.html') A: You can try adding namespaces to your urls Main project urls.py urlpatterns = [ path('participants/', include('participants.urls', namespace='participants')), path('admin/', admin.site.urls), ] Application urls.py app_name = 'participants' urlpatterns = [ path('register/', views.register, name="register") ] View def register(request): if request.method == "POST": ... return redirect('participants:register')
[ "stackoverflow", "0027323919.txt" ]
Q: Array index out of bounds - 2d to 1d I am working with the algs4 8-puzzle program presented by Princeton. I am getting an array index out of bounds exception in my second for loop. Does anyone see the issue that is throwing this exception? My board class + relevant method looks like this: public class Board { private final int[][] blocks; private final int N; // construct a board from an N-by-N array of blocks // (where blocks[i][j] = block in row i, column j) public Board(int[][] blocks){ N = blocks.length; this.blocks = new int[N][]; for (int i=0; i<N; i++){ this.blocks[i] = Arrays.copyOf(blocks[i], N); } } // board dimension N public int dimension(){ return this.N; } //is the board solvable? public boolean isSolvable(){ int inversions = 0; List<Integer> convert = new ArrayList<>(); // convert 2d to 1d for (int i = 0; i < blocks.length; i++){ for (int j = 0; j < blocks[i].length; j++){ convert.add(blocks[i][j]); } } for (int i = 0; i < blocks.length; i++){ //counts the number of inversions if (convert.get(i) < convert.get(i-1)){ //ARRAYINDEXOUTOFBOUNDS -1 inversions++; } } if (inversions % 2 == 0){ return true; //even } return false; //odd } A: convert.get(i-1) is out of bounds when i==0. You should probably change the start index of your loop : for (int i = 1; i < blocks.length; i++){ //counts the number of inversions if (convert.get(i) < convert.get(i-1)){ inversions++; } }
[ "stackoverflow", "0039931299.txt" ]
Q: Unable to upload image despite successful submission via HTML form I have a custom PHP website hosted on a Plesk(Windows Hosting Server of Godaddy) When I submit the form, all of the values get updated, but the image does not get updated. This is the error shown on the page PHP Warning: move_uploaded_file(../../../uploads/channels/3.jpg): failed to open stream: Permission denied in G:\PleskVhosts\dramatainment.com\httpdocs\dashboard\admin\actions\update_queries.php on line 50 PHP Warning: move_uploaded_file(): Unable to move 'C:\Windows\Temp\php5E2E.tmp' to '../../../uploads/channels/3.jpg' in G:\PleskVhosts\dramatainment.com\httpdocs\dashboard\admin\actions\update_queries.php on line 50 I am using the code that I got from w3schools.com here is the link to that script http://www.w3schools.com/php/php_file_upload.asp Any help would be greatly appreciated. A: Give write permission for destination folder to which you are moving image file.
[ "stackoverflow", "0007011859.txt" ]
Q: ASP.NET Server-side datetime problem I came across an issue that I'm not sure how to resolve. I developed a web application which makes use of DateTime.UtcNow. After testing on my local machine and everything worked fine, I deployed the application to the server. The server is flipping the month and day, so instead of it being August 10th, it says it is October 8th. This must be a regional thing, but I don't want to force a specific format. What's the best solution for this? EDIT: I think it might be because I'm converting the datetimes into strings. How should I represent them as a string depending on the machine? A: When displaying the DateTime, format it with a specific culture. myDateTime.ToString(CultureInfo.InvariantCulture); myDateTime.ToString(new CultureInfo("en-GB")); myDateTime.ToString(new CultureInfo("en-US")); I also suggest reading up on standard and custom date and time format strings.
[ "stackoverflow", "0009875946.txt" ]
Q: How do I limit the number of records shown in an XML feed in asp.net? I'm trying to limit the number of records from an XML feed that are passed through to an asp.net repeater. There are hundreds of "records" and I want to limit the repeater to 4. Any help is appreciated. Thanks! My code behind: protected void XMLsource() { string URLString = "http://ExternalSite.com/xmlfeed.asp"; XmlDataSource x = new XmlDataSource(); x.DataFile = URLString; x.XPath = String.Format(@"root/mainNode"); xPathRepeater.DataSource = x; xPathRepeater.DataBind(); } And my front-end code: <asp:Repeater ID="xPathRepeater" runat="server"> <ItemTemplate> <li> <h1><%#XPath ("title") %></h1> </li> </ItemTemplate> </asp:Repeater> A: xPathRepeater.DataSource = x.Data.Take(4); xPathRepeater.DataBind();
[ "math.stackexchange", "0002275204.txt" ]
Q: Question regarding validity of $\partial A = \partial(\mathbb{X} \verb!\!A) $ for a Hausdorff topology Let $\mathbb{X}$ be a topological Hausdorff space. Then for $A \subset \mathbb{X}$ it holds that $\partial A = \partial(\mathbb{X} \verb!\!A) $, where $\partial A$ i.e. is the set of boundary points for $A$. The material I have claims that this equality holds. However, I have a difficult time validating it. Here's how my material goes about with the proof: $x \in \partial A \implies \forall N \in V(x) : N \cap(\mathbb{X} \verb!\!A) \neq \emptyset \implies x \in \partial (\mathbb{X} \verb!\! A)$ Where $V(x)$ is the set of all neighborhoods of $x$. I can perhaps see how $\exists x \in \partial A :x \in \partial (\mathbb{X} \verb!\! A) $ would make sense, but a straight up equality? I.e., let's say that $\mathbb{X}$ is a topology on a space in the interval $[1,10]$. Then let's say $A=\verb!{! x : x \in [4,6] \verb!}!$. This would give us: $(\mathbb{X} \verb!\!A) = \verb!{! x : x \in [1,4) \cup(6,10] \verb!}! $ However, $\partial A = \partial(\mathbb{X} \verb!\!A) $ would not hold since $\partial A = \verb!{! 4,6 \verb!}!$ and $\partial(\mathbb{X} \verb!\!A) =\verb!{! 1,4,6,10 \verb!}!$. Any help is appreciated. Also, please don't hesitate to correct me if I have done something incorrect. Best regards, kasp9201. A: By definition (well, one of the equivalent definitions), the boundary of $A$ is the set of points $x$ in $X$ such that every neighbourhood of $x$ intersects $A$ as well as its complement. This definition is clearly symmetrical with respect to $A$ vs $X\setminus A$, and you need no separation axioms for that. In your example, $1$ and $10$ are not on the boundary of $X\setminus A$: a neighbourhood of $1$ (in $X$), for example, is a set containing an interval of the form $[1,b)$ for some $b<10$. For example, $[1,3)$ is a neighbourhood of $1$ disjoint from $A$ (which is the complement of $X\setminus A$).
[ "stackoverflow", "0004965123.txt" ]
Q: Open a webpage in flex application How can I open a web (example www.cnn.com) in a Flex application? A: I understand that you are trying to open an url in the default system browser.Please try this. var urlRequest:URLRequest = new URLRequest("http://www.adobe.com/"); //To open in a new tab navigateToURL(urlRequest,_blank); //To open on top of the same page navigateToURL(urlRequest,_top); If you are looking to open an url within a Flex application you check here
[ "stackoverflow", "0006233581.txt" ]
Q: jquery writing unobtrusive javascript help I have the following code in jquery. $(function() { $('.test').click(function() { alert('this is a test'); }); }); I realize that this is unobtrusive, but I would like to try and make it even more unobtrusive by doing something like this. $(function() { $('.test').submitAlert(); *and place the alert message right here. }); Then I would be able to call the alert message on different classes without having to retype the code. Could somebody please show how to do this to me with jquery please? A: You could wrap your code into a plugin: (function($) { $.fn.submitAlert = function(text) { this.bind("click", function() { alert(text); }); } })(jQuery); Usage: $(".test").submitAlert("hello world"); Here's a working example: http://jsfiddle.net/andrewwhitaker/UGsHR/1/
[ "stackoverflow", "0025451452.txt" ]
Q: Use inline Request.QueryString to build url Not sure if I'm asking this right, but I have this: <a href="mypage.aspx?id=<% Request.QueryString["id"].ToString(); %>&sec=map"> Map </a> But it doesn't add the ID to the url query string. Not sure what to do cause I really don't want to have to make a bunch of literals to build this on code side. The url I get is: mypage.aspx?id=&sec=map A: You need an = after the <% otherwise the value is not written out. You will then need to remove the semi-colon as well: <a href="mypage.aspx?id=<%= Request.QueryString["id"].ToString() %>&sec=map"> Map </a> See this question for more details on the various meanings of <%.
[ "stats.stackexchange", "0000314017.txt" ]
Q: Is there such a thing as similarities between parametric and nonparametric statistics? Is there such a thing as similarities between parametric and nonparametric statistics? I've been doing a research on the subject, spoiler alert: I'm a noob on this. So far, I've been able to find lots of information about the differences between the two, but nothing about the similarities, except for this: Differences & Similarities between Parametric & Non-Parametric Statistics .. but the article never touches the subject of similarities. Can anyone throw me some light on the subject? Thanks. EDIT: May I politely ask why was my question downvoted? I've done my research (as best as my abilities and understanding of the subject have allowed me to), I've searched on the site, I've found similarly written questions (and getting answered without any issues), I've read the tour and help pages, so I'd love a heads up so I can keep up the quality of the content on the StackExchange sites. Thanks. A: Their general similarity is in their approach. Most non-parametric methods are rank methods in some form. Nonparametric methods are, generally, optimal methods of dealing with a sample reduced to ranks from raw data. The logic behind the testing is the same, but the information set is different. Their similarity is in the logic of their construction.
[ "stackoverflow", "0046308990.txt" ]
Q: How to change color of default style for progressbar in Qt How I can change green tint in default QProgressbar style, without changing other default gradients and effects (a little noticeable "flow white chunk" effect): Default QProgressbar style . I was tried to set new combination of background colors for QProgressBar::chunk:horizontal using qlineargradient, but I did not succeed to keep mentioned effect with any of such stylesheets. A: Possibly try to update StyleSheet with timer like this: mRunner = 0.1; QTimer *mTimer = new QTimer(this); connect(mTimer, SIGNAL(timeout()), this, SLOT(updateProgress())); mTimer->start(40); and method should change gradient for each new step: void MainWindow::updateProgress() { QString lStyle = QString("QProgressBar::chunk {background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:%1 white, stop:1 #b4b4b4);}").arg(mRunner); ui->progressBar->setStyleSheet(lStyle); mRunner += 0.01; if (mRunner > 1) { mRunner = 0.1; } }
[ "stackoverflow", "0060897504.txt" ]
Q: Task not executing in tests with Robolectric I've got problems testing the result of FirebaseVisionTextRecognizer.processImage() My Android app takes the outcome of that function and tries to interpret it in a special context. Different types of images should be treated differently with a customized parser. So I thought that an automated test of these classes would be the right approach. Robolectric sounds like the right framework for this use case, but I'm not really sure. @Rule public TestRule rule = new InstantTaskExecutorRule(); private static int number = 0; @Test public void testTask() { Bitmap testBitmap = BitmapFactory.decodeFile( "src/test/testImages/img1.jpg" ); FirebaseApp.initializeApp( ApplicationProvider.getApplicationContext() ); FirebaseVisionImage visionImage = FirebaseVisionImage.fromBitmap( testBitmap ); FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance().getCloudTextRecognizer(); Task<FirebaseVisionText> result = detector.processImage( visionImage ) .addOnSuccessListener( visionText -> { number = 1; System.out.println( "Success!" ); } ) .addOnFailureListener( e -> { number = 2; System.err.println( "Failed…" ); } ); // nothing of this block works ShadowApplication.runBackgroundTasks(); shadowOf( getMainLooper() ).idle(); shadowOf( getMainLooper() ).runToEndOfTasks(); Robolectric.flushBackgroundThreadScheduler(); Thread t = new Thread( () -> { try { // Comment this out to see that it runs forever // Tasks.await( result ); } catch( Exception e ) { e.printStackTrace(); } } ); t.start(); try { t.join(); } catch( InterruptedException e ) { e.printStackTrace(); } assertThat( number == 1 ).isTrue(); } Nothing is printed, and if you comment out the command that says you want to wait until the task is finished, you wait forever (>2h). I suspect it has something to do with the files the library has to download the first time it is used, but I'm not sure if it is caused by something in the ml-vision kit or in the Robolectric framework. Thank you for any advice on how to fix this problem or for suggestions for other setups where I don't need this. A: Yeah, the textRecognizer depends on the model to be downloaded via Google Play Services. It will be hard to test the pipeline involving model in robolectric test. You will need to mock at some level to make your unit test work to test your own code.
[ "stackoverflow", "0044168756.txt" ]
Q: Compute average of grouped data.frame using dplyr and tidyr I'm just learning R and trying to find ways to modify my grouped data.frame in order to get a mean of a variable value (x+y/2), and standard deviation (sd) sqrt((x^2+y^2)/2) of cohesive observations. Other (equal) variables (sequence, value1) should not change. I used subset() and rowMeans(), but I wonder if there is a nicer way using dplyr and tidyr (probably using a nested dataframe?) My test data.frame looks like: id location value sd sequence value1 "anon1" "nose" 5 0.2 "a" 1 "anon2" "body" 4 0.4 "a" 2 "anon3" "left_arm" 3 0.3 "a" 3 "anon3" "right_arm" 5 0.6 "a" 3 "anon4" "head" 4 0.3 "a" 4 "anon5" "left_leg" 2 0.2 "a" 5 "anon5" "right_leg" 1 0.1 "a" 5 dput output of my test data.frame: myData <- structure(list(ï..id = structure(c(1L, 2L, 3L, 3L, 4L, 5L, 5L ), .Label = c("anon1", "anon2", "anon3", "anon4", "anon5"), class = "factor"), location = structure(c(5L, 1L, 3L, 6L, 2L, 4L, 7L), .Label = c("body", "head", "left_arm", "left_leg", "nose", "right_arm", "right_leg" ), class = "factor"), value = c(5L, 4L, 3L, 5L, 4L, 2L, 1L ), sd = c(0.2, 0.4, 0.3, 0.6, 0.3, 0.2, 0.1), sequence = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "a", class = "factor"), value1 = c(1L, 2L, 3L, 3L, 4L, 5L, 5L)), .Names = c("ï..id", "location", "value", "sd", "sequence", "value1"), class = "data.frame", row.names = c(NA, -7L)) how it should look: id location value sd sequence value1 "anon1" "nose" 5 0.2 "a" 1 "anon2" "body" 4 0.4 "a" 2 "anon3" "arm" 4 0.47 "a" 3 "anon4" "head" 4 0.3 "a" 4 "anon5" "leg" 1.5 0.15 "a" 5 A: dplyr's group_by and summarise will help, with some support from gsub for the string variable: library(dplyr) myData %>% group_by(id) %>% summarise( location = gsub(".*_", "", location[1]), value = mean(value), sd = mean(sd), sequence = sequence[1], value1 = value1[1] ) #> # A tibble: 5 × 6 #> id location value sd sequence value1 #> <fctr> <chr> <dbl> <dbl> <fctr> <int> #> 1 anon1 nose 5.0 0.20 a 1 #> 2 anon2 body 4.0 0.40 a 2 #> 3 anon3 arm 4.0 0.45 a 3 #> 4 anon4 head 4.0 0.30 a 4 #> 5 anon5 leg 1.5 0.15 a 5 Or if id, sequence, and value1 match across all cases: myData %>% group_by(id, sequence, value1) %>% summarise( location = gsub(".*_", "", location[1]), value = mean(value), sd = mean(sd)) #> Source: local data frame [5 x 6] #> Groups: id, sequence [?] #> #> id sequence value1 location value sd #> <fctr> <fctr> <int> <chr> <dbl> <dbl> #> 1 anon1 a 1 nose 5.0 0.20 #> 2 anon2 a 2 body 4.0 0.40 #> 3 anon3 a 3 arm 4.0 0.45 #> 4 anon4 a 4 head 4.0 0.30 #> 5 anon5 a 5 leg 1.5 0.15
[ "stackoverflow", "0012386699.txt" ]
Q: Sending the unique phone id as an email I try to create an app that allows the user to register himself for my service. The problem is that it is very important that i can limit each user to a very single account i figured out I could probably do this with the Phone unique id and the windows live id i also figured out how to get These within the app , but now my problem is how to get them to me! Can anyone help me on how to send the phone id with the desired username to my email address ? Thank you EDIT I use this code to get the needed values public static class ExtendedPropertyHelper { private static readonly int ANIDLength = 32; private static readonly int ANIDOffset = 2; public static string GetManufacturer() { string result = string.Empty; object manufacturer; if (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out manufacturer)) result = manufacturer.ToString(); return result; } //Note: to get a result requires ID_CAP_IDENTITY_DEVICE // to be added to the capabilities of the WMAppManifest // this will then warn users in marketplace public static byte[] GetDeviceUniqueID() { byte[] result = null; object uniqueId; if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId)) result = (byte[])uniqueId; return result; } // NOTE: to get a result requires ID_CAP_IDENTITY_USER // to be added to the capabilities of the WMAppManifest // this will then warn users in marketplace public static string GetWindowsLiveAnonymousID() { string result = string.Empty; object anid; if (UserExtendedProperties.TryGetValue("ANID", out anid)) { if (anid != null && anid.ToString().Length >= (ANIDLength + ANIDOffset)) { result = anid.ToString().Substring(ANIDOffset, ANIDLength); } } return result; } } Now i need to store thes in variables ( what i cant really get to work ) and then send them to my php script which extracts them in addition to this i need to ask the user to enter his email address and include this in the POST too , can you help? A: You can get DeviceExtendedProperties.DeviceUniqueId from Microsoft.Phone.Info namespace. Don't forget to declare in WMAppManifest.xml like this: <Capabilities> <Capability Name="ID_CAP_IDENTITY_DEVICE"/> <Capability Name="ID_CAP_IDENTITY_USER"/> </Capabilities> Link to msdn here Then, you can send this id to your e-mail: var emailComposeTask = new EmailComposeTask { To = "your-email@domiain.com", Subject = "Test Message using EmailComposeTask", Body = deviceId }; emailComposeTask.Show(); But this will open an-email client, and I don't thik that user will be so kind to send you an email. So, you'd better send a POST request to your server private void Button_Click(object sender, RoutedEventArgs e) { //collect all data you need: var deviceId = Convert.ToBase64String(ExtendedPropertyHelper.GetDeviceUniqueID()); var userName = ExtendedPropertyHelper.GetWindowsLiveAnonymousID(); var manufatcurer = ExtendedPropertyHelper.GetManufacturer(); //create request string //[see the explanation on MSDN][2] var requestUrl = string .Format("http://myPageUrlAddress.com/script.aspx?deviceid={0}&user={1}&manufacturer={2}", deviceId, userName, manufatcurer); System.Uri myUri = new System.Uri(requestUrl); //create a request instance HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; //and it will be sent. //Also you need to create GetRequestStreamCallback method to //handle server responce. myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest); } //this method is empty. You can show tha dialog box about successful sending. public void GetRequestStreamCallback(IAsyncResult result) { ; } What about e-mail - just create a TextBox on the same Page, and save user input to a variable.
[ "math.stackexchange", "0000709370.txt" ]
Q: What is the Hessian of Frobenius norm As we know that every norm is convex, and if a function is convex w.r.t. the input variable, then corresponding Hessian should be positive semidefinite. When I try to find the Hessian of Frobenius norm, I can't obtain expected result. I compute the Hessian as follows I first compute the first order derivative: $\frac{\partial \||X\||_F^2}{\partial X} = 2X$, and I refer to the Other matrix derivatives section in wiki http://en.wikipedia.org/wiki/Matrix_calculus to compute the $\frac{\partial 2X}{\partial X}$. However, it seems that if I use that formula, I won't get desired result. Hope someone could tell me what is wrong with my derivation. Thanks very much. A: More generally, consider $n\times n$ real matrices $A,X$ and the function $f:X\rightarrow ||AX||^2=trace(AXX^TA^T)$. Then its derivative is $D_Xf:H\rightarrow 2trace(X^TA^TAH)$. moreover its Hessian is $Hess_X(f):(H,K)\rightarrow 2trace(K^TA^TAH)$, a symmetric bilinear form that does not depend on $X$. Let $(E_{i,j})$ be the canonical basis of $M_n$. Then, if $j\not=l$, then $Hess_X(f)(E_{i,j},E_{k,l})=0$ and $Hess_X(f)(E_{i,j},E_{k,j})=2u_{i,k}$ where $u_{i,j}$ is the $(i,j)$ entry of $A^TA$. Let $vec(U)$ denotes the vectorization of a $n\times n$ matrix $U$, formed by stacking the rows (resp. the columns) of $U$ into a single column vector. Then the $n^2\times n^2$ symmetric matrix associated to $Hess_X(f)$ is $2A^TA\otimes I_n$ (resp. $2I_n\otimes A^TA$). cf.: http://en.wikipedia.org/wiki/Kronecker_product The eigenvalues $(\lambda_i)_i$ of $A^TA$ are non-negative. The eigenvalues of $2A^TA\otimes I_n$ and $2I_n\otimes A^TA$ are $(2\lambda_i)_i$, $n$ times each ; hopefully, $Hess_X(f)$ is sym. non-negative (semidefinite). In particular, if $A=I_n$, then $Hess_X(f)$ is associated to the matrix $2I_n\otimes I_n=2I_{n^2}$ as 127 wrote above. EDIT: Charles, that you write is the gradient $\nabla_X(f)=2A^TAX$. The gradient is defined from the matrix scalar product $(U,V)=trace(U^TV)$ by the formula $(\nabla_X(f),H)=D_Xf(H)$. We conclude by identification. A: When working with the Frobenius norm, we can stack the columns of $X$ into a single vector $\widehat X\in \mathbb R^{n^2}$ and take the norm of that. This simplifies the computation: the gradient is $2\widehat X$ and the Hessian is $2I$ where $I$ is the identity matrix acting on $\mathbb R^{n^2}$; i.e., the identity matrix of size $n^2\times n^2$. If you insist on matrix notation for $X$, then notice that the derivative of $X\mapsto 2X$ with respect to $X$ does not naturally fit in a matrix form; matrix-by-matrix derivatives are absent from the table in the wiki article you mentioned. Notice that we could also talk about the derivative of a vector with respect to a matrix, or any of the other unfilled cells in our table. However, these derivatives are most naturally organized in a tensor of rank higher than 2, so that they do not fit neatly into a matrix You would need a tensor of order 4 to express the Hessian in this case.
[ "meta.askubuntu", "0000007704.txt" ]
Q: Who owns Ask Ubuntu? Just out of curiosity, who owns Ask Ubuntu? Canonical or Stack Exchange ? Previously it was said that Canonical helped to make this site and also assisted in designs but there were no Ubuntu links at the top. Now every link of Ubuntu.com appears in the navbar at top, so I thought of asking. A: Stack Exchange. There's a trademark arrangement and yes, there are design considerations influenced from Canonical, but it's very much still a Stack Exchange venture. A: I don't think we can say that "someone owns Ask Ubuntu". The system and the engine that runs this site is provided and maintained by Stack Exchange whereas all the content and contribution of members is licensed under cc-wiki. This site has come into existence by a democratic process and the strength of every Stack Exchange site is its users and members. I don't think we can say that the site is owned by Stack Exchange. But they are the maintainers of the engine and act as trustees to ensure that the site is run properly. Stack Exchange derives its revenues through this model, so well-run sites definitely help them creating goodwill. Whereas, Ask Ubuntu is also regarded as an Official Support channel for all things Ubuntu. And Ubuntu involves the whole community around Ubuntu. So, once again this is not owned by someone. Basically, I think each and every site in Stack Exchange network is not owned by anyone. Stack Exchange is at the core of every site, but they are the maintainers of the engine - I wouldn't regard them as the owners of the site (because of the fact that the strength of the SE model is its members). What I consider is that the community owns Ask Ubuntu (and every other SE site). PS: The above is just my opinion without going into technicalities and the legal stuff.
[ "stackoverflow", "0022998957.txt" ]
Q: PostgreSQL select master records and display details columns for specific record First I must apologize for bad topic text, but I don't have any better idea. Maybe because of that, I didn't find solution when searching the web. I have 2 tables: master and details who of course has foreign key to master. I would like to get all rows and all fields from master and fields from details for specific record (let's say order of some column) for every row in master. I tried like this: SELECT master.id, master.title, temp2.master_id, temp2.datetime, temp2.title_details FROM master LEFT JOIN (SELECT master_id, datetime, title AS title_details FROM details ORDER BY datetime DESC) temp2 ON temp2.master_id=master.id //and this: SELECT master.id, master.title, (SELECT master_id, datetime, title AS title_details FROM details WHERE master.id=details.master_id ORDER BY datetime DESC) FROM master //but of course: subquery must return only one column But this is not working. Example what I want to do: Master: id title 1 test 2 blab 3 something Details: id master_id datetime title 1 1 2004-... t: 1.1 2 1 2005-... t: 2.1 3 1 2006-... t: 3.1 4 2 2004-... t: 4.2 5 2 2005-... t: 5.2 6 3 2006-... t: 6.3 Expected output: id title datetime title_details 1 test 2006-... t: 3.1 2 blab 2005-... t: 5.2 3 something 2006-... t: 6.3 Because it is hard for me to explain what I need, here is the PHP code (from head) what I don't want to do: $q = Database::$DB->prepare("SELECT * FROM master"); $q2 = Database::$DB->prepare("SELECT * FROM details WHERE master_id=? ORDER BY datetime DESC LIMIT 1"); $rows = $q->execute(); foreach ($rows as $row) { $q2->execute($row->id); $row->AdditionalFields = $q2->fetch(); } In other words, I don't want to iterate through all master rows and select data for specific ONE record (last - ORDER BY datetime) in details. I tried all different UNIONs, JOINS and SUBQUERIES, but without success. EDITED (comment on different answers): The actual queries are: SELECT DISTINCT ON (todo_topics.id) todo_topics.id, todo_topics.user_id, users.username AS author, todo_topics.title, todo_topics.datetime_created, todo_topics.version, todo_topics.todo_status_id, todo_statuses.icon_image, todo_topics.version_status_changed, todo_posts.text, u.username AS last_poster, todo_posts.user_id as last_poster_id FROM todo_topics LEFT JOIN todo_statuses ON todo_statuses.id = todo_topics.todo_status_id LEFT JOIN users ON users.id = todo_topics.user_id LEFT JOIN todo_posts ON todo_topics.id=todo_posts.todo_topic_id LEFT JOIN users u ON u.id = todo_posts.user_id ORDER BY todo_topics.id, todo_posts.datetime_created DESC "Total runtime: 0.863 ms" SELECT todo_topics.id, todo_topics.user_id, users.username AS author, todo_topics.title, todo_topics.datetime_created, todo_topics.version, todo_topics.todo_status_id, todo_statuses.icon_image, todo_topics.version_status_changed, todo_posts.text, u.username AS last_poster, todo_posts.user_id as last_poster_id FROM todo_topics LEFT JOIN todo_statuses ON todo_statuses.id = todo_topics.todo_status_id LEFT JOIN users ON users.id = todo_topics.user_id INNER JOIN ( SELECT *, ROW_NUMBER() OVER (PARTITION BY todo_topic_id ORDER BY datetime_created DESC) AS ordinal FROM todo_posts ) AS todo_posts ON todo_posts.todo_topic_id = todo_topics.id LEFT JOIN users u ON u.id = todo_posts.user_id WHERE todo_posts.ordinal = 1 "Total runtime: 1.281 ms" SELECT todo_topics.id, todo_topics.user_id, users.username AS author, todo_topics.title, todo_topics.datetime_created, todo_topics.version, todo_topics.todo_status_id, todo_statuses.icon_image, todo_topics.version_status_changed, todo_posts.text, u.username AS last_poster, todo_posts.user_id as last_poster_id FROM todo_topics LEFT JOIN todo_statuses ON todo_statuses.id = todo_topics.todo_status_id LEFT JOIN users ON users.id = todo_topics.user_id INNER JOIN ( SELECT todo_topic_id, MAX(datetime_created) AS max_datetime FROM todo_posts GROUP BY todo_topic_id ) AS details_lookup ON details_lookup.todo_topic_id = todo_topics.id INNER JOIN todo_posts ON todo_posts.todo_topic_id = details_lookup.todo_topic_id AND todo_posts.datetime_created = details_lookup.max_datetime LEFT JOIN users u ON u.id = todo_posts.user_id "Total runtime: 1.143 ms" If someone want to know what this time means for specific hardware: The database is experimental (a few records in each table - < 100) running on Windows 7 localhost, Intel I7 3,4GHz, 16GB ram, PostgreSQL 9.3.4 (default installation) A: Simpler with DISTINCT ON: SELECT DISTINCT ON (m.id) m.*, d.datetime, d.title AS title_details FROM master m LEFT JOIN details d ON d.master_id = m.id ORDER BY m.id, d.datetime DESC; Assuming master.id to be the primary key and details.datetime to be NOT NULL. Detailed explanation: Select first row in each GROUP BY group? Careful if datetime can be NULL. You probably want NULLS LAST in that case.
[ "stackoverflow", "0009390341.txt" ]
Q: can I decrypt an encrypted data if I have input and output and the method but dont have the key? This is a security question, What if I give to the user: a sample input before encrypting a sample output after encrypting the encryption method but I did not provide the correct key for the encryption method, would it be easily that the user can find the encryption key? Thanks in advance. A: Not easy, no. It does make cracking the encyption easier though. You have confirmed the exact logic for producing the encrypted string, and given the attacker an example to test with.
[ "english.stackexchange", "0000492158.txt" ]
Q: Is there any such thing as noun pronoun proximity? I have read of Concord (or noun-verb agreement) and was wondering if, is as I have been told, there is a similar grammar rule for noun-pronoun agreement/proximity. When there's a sentence where two nouns are given and a pronoun used, to which noun will the pronoun be assigned? Carol visited Mary. Mary is the lady living next door. She had barely eaten that day. Or Carol visited Mary. Mary lives next door. She had barely eaten that day. Are the above sentences even grammatical? Assuming they are, I am tempted, in the first example, to assign the pronoun to the subject in the preceding sentence, but I'm not absolutely certain because I've heard that the pronoun(just as in noun-verb agreement) should be assigned to the noun closest. Carol and Mary had been best friends for years. Until she got sick. To who does the pronoun refer? Why? Is there any such rule as alluded? A: The name of the linguistic principle that governs how pronouns are resolved to entities mentioned in the discourse is: anaphora resolution. Not all languages are identical in anaphora resolution, but the simplest rule is mostly universal, the closest preceding noun that matches number, gender, person, etc. Exceptions tend to start from this. (as to a literal answer to your question, no, there is no name for this rule. But 'anaphora resolution' is what you're talking about, it's the name for what any such rule is trying to do.
[ "stackoverflow", "0050770638.txt" ]
Q: Extract json response to shell variable using jq I have a sample json response as shown below which i am trying to parse using jq in shell script.[{"id":1,"notes":"Demo1\nDemo2"}] This is the command through which I am trying to access notes in the shell script. value=($(curl $URL | jq -r '.[].notes')) When I echo "$value" I only get Demo1. How to get the exact value: Demo1\nDemo2 ? A: To clarify, there is no backslash or n in the notes field. \n is JSON's way of encoding a literal linefeed, so the value you should be expecting is: Demo1 Demo2 The issue you're seeing is because you have split the value on whitespace and created an array. Each value can be accessed by index: $ cat myscript data='[{"id":1,"notes":"Demo1\nDemo2"}]' value=($(printf '%s' "$data" | jq -r '.[].notes')) echo "The first value was ${value[0]} and the second ${value[1]}" $ bash myscript The first value was Demo1 and the second Demo2 To instead get it as a simple string, remove the parens from value=(..): $ cat myscript2 data='[{"id":1,"notes":"Demo1\nDemo2"}]' value=$(printf '%s' "$data" | jq -r '.[].notes') echo "$value" $ bash myscript2 Demo1 Demo2
[ "stackoverflow", "0053910692.txt" ]
Q: How to join two tables but not to repeat rows in mysql I am facing one issue for getting data. I am new in Mysql. Firstly i will show my table structure order_products id user_id product_id product_name 1 1 10 Jacket1 2 1 10 Jacket2 order_products_sizes id order_product_id size qty 1 1 S 56 2 1 M 36 3 1 XL 36 4 1 2XL 56 5 2 S 32 6 2 M 28 7 2 XL 28 8 2 2XL 32 9 2 3XL 69 My expected Output:- product_name S M XL 2XL 3XL JACKET1 56 36 36 56 JACKET2 32 28 28 32 69 for first row 3xl would be empty beacuse there is no size available in order_product_sizes Actually i am using join but when i use join the rows are repeating because of joining two table that is actual behavior of joins. I have tries so far:- SELECT order_products.product_name, CASE WHEN order_product_sizes.order_product_id = order_products.id AND order_product_sizes.size = 'L' THEN order_product_sizes.qty END AS L from order_products join order_product_sizes on order_products_sizes.order_product_id = order_products.id; A: You can try below - using conditional aggregation SELECT order_products.product_name, max(CASE WHEN order_product_sizes.size = 'S' THEN order_product_sizes.qty END) AS S, max(CASE WHEN order_product_sizes.size = 'M' THEN order_product_sizes.qty END) AS M, max(CASE WHEN order_product_sizes.size = 'XL' THEN order_product_sizes.qty END) AS XL, max(CASE WHEN order_product_sizes.size = '2XL' THEN order_product_sizes.qty END) AS '2XL', max(CASE WHEN order_product_sizes.size = '3XL' THEN order_product_sizes.qty END) AS '3XL' from order_products join order_products_sizes on order_products_sizes.order_product_id = order_products.id group by order_products_sizes.order_product_id
[ "space.stackexchange", "0000028393.txt" ]
Q: Why does only SpaceX release every stage of rocket launch for the public viewing? What I mean is SpaceX telecast every stage of rocket launch. But in NASA and ISRO, they just telecast rocket ignition launch. ISRO and NASA never does this thing why so? A: Largely because SpaceX has had to prove itself as an independent contractor and as a company. This article from 2011 was typical of the then-unproved SpaceX launch systems My main concern in raising these issues was that NASA not become overly dependent on an unproven launch provider -- one that only achieved its first launch success 32 months ago, but now says it will soon be ready to loft U.S. astronauts into orbit. And here, it compares SpaceX to United Launch Alliance(ULA), which had far fewer launch failures under its belt Musk's enthusiasm is infectious and inspiring, but SpaceX's performance to date doesn't measure up to the rhetoric. SpaceX has only mounted seven launches since its inception, three of which were catastrophic failures. By way of comparison. Lockheed Martin's family of Atlas boosters has seen 97 consecutive launches without a single failure. The United Launch Alliance in which traditional providers Lockheed Martin and Boeing are partnered to offer both Atlas and Delta launch vehicles has had 50 successful launches in a row. Showing live launches helped head off criticism that NASA was wasting its time and money on a private company with no launch history SpaceX was not able to deliver on its promises (i.e. solid launches and stage 1 recovery) By contrast, neither Lockheed Martin, nor Boeing, (the two jointly own ULA) are wholly reliant on rocket launches to sustain their companies. They have long-term commitments to launch rockets as well. As such, NASA doesn't have much reason to focus on live launches. ISRO is government funded. It doesn't have to prove itself to continue funding (it's a national interest that they build a successful rocket program), which might explain why they have had more failures of late. India shows no signs of letting that slow down their entry into the launch vehicle market. A: I don't think it has much to do with convincing NASA or other potential clients at all. After all they are going to get more information directly from SpaceX than you can get from watching a video of the launch and will know how a launch went even without the video stream of the launch. No I think it has more to do with Musk's personality in general and their ultimate goal of getting to Mars. Getting a colony going on Mars requires a couple things. A way to get there and enough people who want to and can afford to go. SpaceX is trying to build a way to get there and make it cheap enough that people can actually afford it so if they accomplish both those then you just need people who want to go. Getting people excited about space now will help with having people who want to go in 5/10/15/20 years or whenever they actually get BFR going to Mars. I'm sure some people would say Musk is a glory hound or loves the lime light but I don't think that's actually the case. I think he's simply a true believer in what he is doing and enthusiastic so wants to share his excitement. I know it has rekindled my excitement about space and has gotten my son excited about it. He built his own FH out of legos after watching the launch but he was a little disappointed it didn't have a RUD.
[ "stackoverflow", "0004396203.txt" ]
Q: How to fire event from button inside datagrid in silverlight and MVVM I have button at first column in datagrid. I am using MVVM and try to bind Command to Command in ViewModel but when I click button in each row, it don't work (It don't call Command in ViewModel) but if I move that button out of datagrid it's working properly. How can I fire event from button inside datagrid in MVVM? Update 1: XAML's code is: <datagrid:DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <Button x:Name="button" Content="View" Margin="5" DataContext="{StaticResource XDataContext}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:InvokeCommandAction Command="{Binding ViewOrganizationCommand}" CommandParameter="{Binding ElementName=dtgOrganizations, Path=SelectedItem}" /> </i:EventTrigger> </i:Interaction.Triggers> </Button> </StackPanel> </DataTemplate> </datagrid:DataGridTemplateColumn.CellTemplate> ViewModel's code is: public ViewModelCommand ViewOrganizationCommand { get; set; } A: I solved this problem by use EventToCommand behavior in MVVMLight Toolkit
[ "stackoverflow", "0048753948.txt" ]
Q: how to display unaccumulated variables in python? I'm doing an assignment that requires me to display a menu, then prompt the customer to pick a rose type and an amount of chosen rose. I have an accumulating variable to accept and be used for the final transaction calculations. But how do I get it to display the unaccumulated/inputted variable and price whenever a customer selects to order more roses? elif roseTypeOrdered == 'r' or roseTypeOrdered == 'R': numRedRosesOrdered += int(input("How many red roses would you like to order?")) totalPrice += numRedRosesOrdered * STEM_RED_ROSE_PRICE print("You have selected {amount:.0f} red roses for a price of ${price:.2f}" .format(amount=numRedRosesOrdered, price=totalPrice)) # Make sure you have a check to see if the input only Y or N transactionActive = input("Would you like to order more roses? (Y-yes, N-no)") if transactionActive == 'N' or transactionActive == 'n': break As is, if I input R, 4, Y (You have selected 4 red roses for $8.00) then R, 4, N (You have selected 8 red roses for $24.00). Red roses are $2.00 each. A: This happens because each time through the loop you are adding the running total of roses numRedRosesOrdered to totalPrice, which itself is already a running total. Change numRedRosesOrdered to: numRedRosesOrdered = int(input("How many red roses would you like to order?")) ...and then have a separate variable, say totalNumRedRoses that you define like: totalNumRedRoses += numRedRosesOrdered This is what you'll use in your summary print: print("You have selected {amount:.0f} red roses for a price of ${price:.2f}" .format(amount = totalNumRedRoses , price = totalPrice))
[ "stackoverflow", "0022077562.txt" ]
Q: Extra spacing on CSS Menu I'm having a weird problem with my CSS menu. There is a huge space above the links. I tried everything from removing all the margin and padding settings from the css and still nothing. The only way I can remove the extra spacing is to delete all the li. Can anyone see what I'm doing wrong? http://jsfiddle.net/3dB7v/ <div id="test_nav"> <div id="test_subnav"> <ul id="test_ul"> <li><a href="#" target="">Test 1</a></li> <li><a href="#" target="">Test 2</a></li> </ul> </div> <asp:panel id="pnlUpdateDate" cssclass="UpdateDate" runat="server">Last Update: 11-26-2013</asp:panel> </div #test_nav { text-align: left; padding: 5px; border: 1px dashed blue; } #pnlUpdateDate { width: 200px; border: 1px dashed blue; } #test_subnav { float: right; position: relative; z-index: 1000; padding: 0; border: 1px solid red; } #test_ul li { position: relative; list-style: none; margin: 0; padding: 0; z-index: 1001; b1order: 1px dashed orange; } #test_ul li ul { margin-left: 0; padding: 0; } #test_ul > li { float: left; padding: 3px; /* padding-top: 3px; padding-bottom: 3px; */ margin: 0 2px 0 0; } #test_ul > li > a, #test_ul > li > span { display: block; padding: 4px 4px 4px 4px; margin: 0 3px 0 3px; font-size: 14px; font-weight: bold; color: black; text-decoration: none; } #test_ul > li > span { cursor: default; } #test_ul > li:hover > a, #test_ul > li.active > a { color: Red; } #test_ul > li:hover > a:active { color: #3B96B6; } #test_ul > li:hover > span { color: #3B96B6; } A: That space belongs to the default margins of the ul#test_ul element applied by the useragent. You should reset the default stylesheet applied by user agent on the list element, as follows: ul#test_ul { padding: 0; margin: 0; } You can refer to this answer for further details: User agents apply some default styles to the HTML elements. For instance they apply a top and bottom margin on the <p>, <ul>, ... elements. As Google Chrome sets -webkit-margin-before: 1em; and -webkit-margin-after: 1em;. Working Demo It's better to reset user agent stylesheet before any author stylesheet to prevent unexpected issues.
[ "stackoverflow", "0006223800.txt" ]
Q: node.js and browser code reuse: importing constants into modules I have some constants in JavaScript that I'd like to reuse in several files while saving typing, reducing bugs from mistyping, keeping runtime performance high, and being useful on either the node.js server scripts or on the client web browser scripts. example: const cAPPLE = 17; const cPEAR = 23; const cGRAPE = 38; ...(some later js file)... for...if (deliciousness[i][cAPPLE] > 45) ... Here are some things I could do: copy/paste const list to top of each file where used. Oh, Yuck. I'd rather not. This is compatible with keeping the constant names short and simple. It violates DRY and invites all sorts of awful bugs if anything in the list changes. constant list ---> const.js on browser, this is FINE ... script gets fed in by the html file and works fine. but on node.js, the require mechanism changes the constant names, interfering with code reuse and requiring more typing, because of how require works.... AFAIK This doesn't work, by design, in node.js, for any const.js without using globals: require('./const.js'); for...if...deliciousness[i][cAPPLE] > 45 ...; This is the node.js way: (... const.js ....) exports.APPLE = 17; (... dependency.js ... ) var C = require('./const.js'); for...if...deliciousness[i][C.APPLE] > 45..... so I would either have to have two files of constants, one for the node.js requires and one for the browser, or I have to go with something further down the list... 3 make the constants properties of an object to be imported ... still needs two files... since the node.js way of importing doesn't match the browser. Also makes the names longer and probably takes a little more time to do the lookups which as I've hinted may occur in loops. 4 External constant list, internal adapter.... read the external constants, however stored, into internal structure in each file instead of trying to use the external list directly const.js exports.cAPPLE = 17 browser.js const cAPPLE = exports.cAPPLE; ...code requiring cAPPLE... node.js CONST = require(./const.js) const cAPPLE = CONST.cAPPLE; ...code requiring cAPPLE... This requires a one-time-hit per file to write the code to extract the constants back out, and so would duplicate a bunch of code over and over in a slightly more evolved cut and paste. It does allows the code requiring cAPPLE to continue to work based on use of short named constants Are there any other solutions, perhaps a more experienced JavaScripter might know, that I might be overlooking? A: module.exports = Object.create({},{ "foo": { value:"bar", writable:false, enumerable:true } }); Properties are not writable. Works in strict mode unlike "const". A: I would just make them global keys: ...(module consts.js)... global.APPLE = 17; global.PEAR = 23; global.GRAPE = 38; ...(some later js file)... var C = require('./const.js'); for (var i = 0; i < something.length; i++) { if (deliciousness[i][global.APPLE] > 45) { blah(); } } They wouldn't be enforced constants, but if you stick to the ALL_CAPS naming convention for constants it should be apparent that they shouldn't be altered. And you should be able to reuse the same file for the browser if you include it and use it like so: var global = {}; <script src="const.js"></script> <script> if (someVar > global.GRAPE) { doStuff(); } </script>
[ "stackoverflow", "0034802001.txt" ]
Q: ReferenceError: db is not defined when i try to GET data from server i develop a new project for my school and i try to fetch some data from my database but i ecounter that error in my terminal: ReferenceError: db is not defined here are my files from my project: server.js var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var morgan = require('morgan'); var mongoose = require('mongoose'); var passport = require('passport'); var config = require('./config/database'); // get db config file var User = require('./app/models/user'); // get the mongoose model var Products = require('./app/models/products'); //get the mongoose model var port = process.env.PORT || 8080; var jwt = require('jwt-simple'); // get our request parameters app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // log to console app.use(morgan('dev')); // Use the passport package in our application app.use(passport.initialize()); // demo Route (GET http://localhost:8080) app.get('/', function(req, res) { res.send('The API is at http://localhost:' + port + '/api'); }); // connect to database mongoose.connect(config.database); // pass passport for configuration require('./config/passport')(passport); // bundle our routes var apiRoutes = express.Router(); // create a new user account (POST http://localhost:8080/api/signup) apiRoutes.post('/signup', function(req, res) { if (!req.body.name || !req.body.password || !req.body.email) { res.json({success: false, msg: 'Please pass name and password and email.'}); } else { var newUser = new User({ name: req.body.name, password: req.body.password, email: req.body.email }); // save the user newUser.save(function(err) { if (err) { return res.json({success: false, msg: 'Username already exists.'}); } res.json({success: true, msg: 'Successful created new user.'}); }); } }); // route to authenticate a user (POST http://localhost:8080/api/authenticate) apiRoutes.post('/authenticate', function(req, res) { User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.send({success: false, msg: 'Authentication failed. User not found.'}); } else { // check if password matches user.comparePassword(req.body.password, function (err, isMatch) { if (isMatch && !err) { // if user is found and password is right create a token var token = jwt.encode(user, config.secret); // return the information including token as JSON res.json({success: true, token: 'JWT ' + token}); } else { res.send({success: false, msg: 'Authentication failed. Wrong password.'}); } }); } }); }); // create a new Product (POST http://localhost:8080/api/productsignup) apiRoutes.post('/productsignup', function(req, res) { if (!req.body.name || !req.body.serialnumber) { res.json({success: false, msg: 'Please pass name and serial number.'}); } else { var newProducts = new Products({ name: req.body.name, serialnumber: req.body.serialnumber }); // save the Product newProducts.save(function(err) { if (err) { return res.json({success: false, msg: 'Product already exists.'}); } res.json({success: true, msg: 'Successful created new Product.'}); }); } }); apiRoutes.get('/productinfo' , function(req, res, next) { db.products.find(); if (err) return next(err); res.json(post); }); // route to a restricted info (GET http://localhost:8080/api/memberinfo) apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) { var token = getToken(req.headers); if (token) { var decoded = jwt.decode(token, config.secret); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'}); } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); getToken = function (headers) { if (headers && headers.authorization) { var parted = headers.authorization.split(' '); if (parted.length === 2) { return parted[1]; } else { return null; } } else { return null; } }; // connect the api routes under /api/* app.use('/api', apiRoutes); module.exports = apiRoutes; // Start the server app.listen(port); console.log('http://localhost:' + port); and database.js module.exports = { 'secret': 'di.ionio.gr', 'database': 'mongodb://localhost/firstapp' }; package.json: { "name": "firstapp", "main": "server.js", "dependencies": { "bcrypt": "^0.8.5", "body-parser": "~1.9.2", "express": "~4.9.8", "jwt-simple": "^0.3.1", "mongoose": "~4.2.4", "mongodb" : "~1.2.5", "morgan": "~1.5.0", "passport": "^0.3.0", "passport-jwt": "^1.2.1" } } A: Because db is not defined and you don't need it just use the model "products", just change this apiRoutes.get('/productinfo' , function(req, res, next) { db.products.find(); if (err) return next(err); res.json(post); }); To this apiRoutes.get('/productinfo' , function(req, res, next) { products.find( function (err, result) { if (err) return console.error(err); res.json(result); }); });
[ "gis.stackexchange", "0000212509.txt" ]
Q: What is Diffrent Between Version & Replica In ArcGIS Geodatabase I know Versioning allows multiple editors to alter the same data in an enterprise or workgroup geodatabase without duplicating data and Geodatabase replica allows creates copies of data across two or more geodatabases such that changes to the data may be synchronized. I am not really getting the point here! aren't they same? can someone please let me know what is exactly the use of Replica? A: Versioning is for editing in a multi-user environment. Replication is for replicating your data in a multi-database environment. They are two very different things. In a multi-user environment the versioning is used to enable handling of conflicts where two (or more) editors may have edited the same feature. It gives the abililty to choose the correct edit when pushing those changes back to the default live version - what everyone else sees. Versions are not a copy of the data, rather the database keeps track of edits (creation, edit, deletion) and when these edits are posted, they are reconciled and updated in the default live version. Replication is used to copy your data out to other databases - these may be in other locations, or just on the other side of a firewall. If users need to edit features in a replica then usually versioning is used to handle those edits, particularly as edits may also be coming in from other locations. In our office we use both replication and versioning. Versioning because we have 10-20 users in the organisation that edit features across hundreds of feature classes. Replication because we push all our data through to a cloud server environment which is then made available on the web or in apps over the internet. Some editing also takes place via these apps, and are replicated back to our internal server environment. See An overview of versioning Working with geodatabase replicas Both versioning and replication require ArcGIS Standard or Advanced licenses.
[ "gaming.stackexchange", "0000229375.txt" ]
Q: Accidentally sold the Troopa pin. How do I get it back? So I accidentally sold the Troopa pin while playing with emulator on PS3. Is there any way I can get it back on the same run? Maybe buy it back from a seller or something? A: No. The Troopa Pin, like many other items in the game, can only ever be acquired once. And there's no way to buy items back that you've sold. If you lost it, it's gone for good.
[ "ell.stackexchange", "0000118624.txt" ]
Q: Meaning of 'gave' in "What a great feeling that gave me" This is a passage from my English exercise book: After spending a day at the beach, I stopped to buy a snack on my way home. But when I searched for my wallet, it wasn’t there. I checked my other pockets, and the car and then headed back to look at the beach. My driver’s license, my ID card – my mind was racing through all the things I had lost and I felt rotten. A search of the beach and parking lot proved fruitless, so I headed home. I tried to forget it because there was nothing I could do, but I was mad at myself for losing it. After dinner when I was watching TV and trying to forget, the phone rang and a voice asked: “Did you lose a wallet? I found it on the beach.” What a great feeling that gave me – not only for my luck, but also for my faith in all humanity! I guess the meaning of the phrase "what a great feeling that gave me" is "what a great feeling that / which I had". I don't really understand the meaning of the word 'gave' in the sentence. A great feeling gave me what (What did a great feeling give me)? It seems like the word 'gave' might have a special meaning when it goes with 'feeling'. Could you please explain this special meaning in this context? A: In this situation, I believe "that" is part of the reason the phrase isn't making sense to you. "What a great feeling that gave me..." could be rewritten as "What a good feeling the stranger's kindness gave me..." "That" is a demonstrative pronoun for "the stranger's kindness" (or "the caller's good deed" or any similar phrasing). "Gave" makes sense because it helps to specify what caused the good feeling. Think of it in this case as a synonym for "caused" or "contributed," not "gifted." It works with things that aren't "feelings." "When the teacher told me that I passed the very difficult test, that gave me a feeling of relief!" "When Bob said the project wasn't due for another two days, that gave me a chance to check it over again." "Susan had come down with a cold. That gave Alice an excuse to go visit."
[ "stackoverflow", "0042592803.txt" ]
Q: Data structure: Top K ordered dictionary keys by value I have a very large dictionary with entries of the form {(Tuple) : [int, int]}. For example, dict = {(1.0, 2.1):[2,3], (2.0, 3.1):[1,4],...} that cannot fit in memory. I'm only interested in the top K values in this dictionary sorted by the first element in each key's value. If there a data structure that would allow me to keep only the largest K key-value pairs? As an example, I only want 3 values in my dictionary. I can put in the following key-value pairs; (1.0, 2.1):[2,3], (2.0, 3.1):[1,4], (3.1, 4.2):[8,0], (4.3, 4.1):[1,1] and my dictionary would be: (3.1, 4.2):[8,0], (1.0, 2.1):[2,3], (2.0, 3.1):[1,4] (in case of key-value pairs with the same first element, the second element will be checked and the largest key-value pair based on the second element will be kept) A: import heapq class OnlyKDict(object): def __init__(self,K,key=lambda x:x): self.data = [] self.dictionary = {} self.key=key # Lambda function for the comparator self.K = K # How many values to keep in dictionary def push(self,item): heapq.heappush(self.data,(self.key(item),item)) self.dictionary[item[0]]=item[1] if len(self.data)>self.K: #Size greater than k? pop minimum from heap and dict. item = self.pop() #This ensure only k largest are there. self.dictionary.pop(item[0],None) def pop(self): return heapq.heappop(self.data)[1] def __getitem__(self,key): return self.dictionary[key] def __setitem__(self,key,value): if self.dictionary.has_key(key): self.dictionary[key] = value #If key present update value else: self.push((key,value)) ##Else push key and value as a tuple h = OnlyKDict(8,lambda x:x[0][1] if x[0][1]==x[0][0] else x[0][0]) ##Compare 2nd value if both equal else compare 1st value only. for i in xrange(10): h[(i,i)] = [i,i] print h.dictionary Output: {(5, 5): [5, 5], (6, 6): [6, 6], (4, 4): [4, 4], (7, 7): [7, 7], (9, 9): [9, 9], (8, 8): [8, 8], (2, 2): [2, 2], (3, 3): [3, 3]} You can see how only the top 8 values are stored here. Major stuff taken from heapq with custom compare predicate. What we do is create our custom heap class which takes a key parameter where we specify on what value to sort. The next is whenever this size is greater than 8 we pop the minimum item. This ensures we always have only the max 8 values.
[ "stackoverflow", "0042371144.txt" ]
Q: Can I use md-select and have one option select multiple options? I have the following small sample: <md-select ng-model="selectedYears" multiple> <md-option>10 Years</md-option> <md-option value="2016"> <md-option value="2015"> <!--- more options --> </md-select> What I want is when the user selects the option that I labeled with "10 Years" above, the equivalent of the following should happen (instead of selecting the option) $scope.selectedYears = [2016, 2015/*, ... */]; A: You could put change event on your select so that whenever there is 10 years have been selected that time you could last 10 years manually. Also you have to change value to ng-value so that value should be consider as of number type instead of string. Markup <md-select ng-model="selectedYears" multiple ng-change="yearChanged(selectedYears)"> <md-option ng-value="10">10 Years</md-option> <md-option ng-value="2016">2016</md-option> <md-option ng-value="2015">2015</md-option> <md-option ng-value="2014">2014</md-option> <md-option ng-value="2013">2013</md-option> <md-option ng-value="2012">2012</md-option> <md-option ng-value="2011">2011</md-option> <md-option ng-value="2010">2010</md-option> <md-option ng-value="2009">2009</md-option> <md-option ng-value="2008">2008</md-option> </md-select> </md-select> Forked Pen
[ "stackoverflow", "0022279429.txt" ]
Q: iOS: Parsing dictionaries from a string into NSMutableDictionary / NSMutableArray Is there a fast way to parse dictionaries in iOS from a sting, with the format: property1: value1 property2: [ property3: value3 ; property4: [property5: value5] ] property6: "and so on" The string would contain something like: NSString *str = @"property1: value1 property2: [ property3: value3 ; property4: [property5: value5]] property6: "and so on" "; and would generate a root NSMutableDictionary / NSMutableArray element, containing additional NSMutableDictionary / NSMutableArray elements Thanks in advance A: why not using json format ? replace this with this [ { ] } ; , and you will be able to use jsonparser : NSJSONSerialization
[ "stackoverflow", "0034882972.txt" ]
Q: dlang compare types: cannot use '==' with types I have the following line in my code: static if (typeof(val) == string) { It is not compiling and returning the error Error: incompatible types for ((string) == (string)): cannot use '==' with types. What is the correct way to check the type of a variable? A: The correct way to do it is to use an is expression around it: is(A == b) like this: static if (is(typeof(val) == string)) {
[ "stackoverflow", "0054429533.txt" ]
Q: Manually downloading JAR from Google Maven I'm trying to manually download some JAR files from Google Maven. Following official documentation doesn't seem to work. For example: I'm able to download POM from URL: https://dl.google.com/dl/android/maven2/androidx/test/rules/1.1.0/rules-1.1.0.pom But I get 404 when trying to download JAR from URL: https://dl.google.com/dl/android/maven2/androidx/test/rules/1.1.0/rules-1.1.0.jar Am I doing something wrong? A: This is because the library is not a jar but an aar (Android Archive). Try https://dl.google.com/dl/android/maven2/androidx/test/rules/1.1.0/rules-1.1.0.aar And it will work. Edit: You can determine this from the <packaging> tag in the pom file: <?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>androidx.test</groupId> <artifactId>rules</artifactId> <version>1.1.0</version> <packaging>aar</packaging>
[ "stackoverflow", "0047833296.txt" ]
Q: Pack HTML5 + Javascript files in .exe I would like to pack my files (html, javascript) in .exe files. The question is - is there any program I can "load" browser in desktop windows? If I provided not many infos I can add them, just want to know if that is possible. A: As mentioned, you can use something like electron to build your web app into a native app. You could also look into making a Progressive Web App (PWA) as one of the design aspects is to make these available offline. Those are two great solutions. A third potential is it should be possible to minify and merge all your js/html/css into a single html file, that just sits on the users' desktop that they can 'visit' at any time. Out of those three I would highly recommend using a PWA. It will give you the best of all worlds.
[ "stackoverflow", "0004043527.txt" ]
Q: Need code for addition of 2 numbers I am having the numbers follows taken as strings My actual number is 1234567890123456789 from this i have to separate it as s=12 s1=6789 s3=3456789012345 remaining as i said I would like to add as follows 11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows 4613579012345 Any help please A: public static string CombineNumbers(string number1, string number2) { int length = number1.Length > number2.Length ? number1.Length : number2.Length; string returnValue = string.Empty; for (int i = 0; i < length; i++) { int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1)); int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1)); int sum = n1 + n2; returnValue += sum < 10 ? sum : sum - 10; } return returnValue; }
[ "rpg.stackexchange", "0000090140.txt" ]
Q: Can a single casting of Dispel Magic dispel every creature conjured by a Conjure Animals spell? Yesterday in a game, my character cast Conjure Animals and summoned 8 wolves†. On the baddies' turn, one cleric was about to cast Dispel Magic, but the DM changed his mind, deciding that the 8 wolves could not be considered a single magical effect. Personally, I agree with this, but I'm wondering if that stands up to the rules: Can a single casting of Dispel Magic dispel every conjured creature from one spell at once? † I'm aware of the debate over who picks the animals; my DM ruled that I could pick. A: No, it only ends the spell on a single target We can extrapolate an answer based on how dispel magic interacts with spells like bless: From the Sage Advice Compendium: If dispel magic targets the magical effect from bless cast by a cleric, does it remove the effect on all the targets? Dispel magic ends a spell on one target. It doesn’t end the same spell on other targets. Since the conjure spells actually bring creatures into the Prime Material plane and in essence holds them there, a dispel magic will only end the magic on a single creature; the rest would still have the magic to keep them present. A: No, dispel magic works on each creature independently. Here is an excerpt from the Sage Advice Compendium: [...] a spell like conjure woodland beings has a non-instantaneous duration, which means its creations can be ended by dispel magic and they temporarily disappear within an antimagic field. Only the creatures summoned who happen in to an antimagic field disappear, not all 8 if you happen to target just one. I have to imagine this holds true for dispel magic as well, though the wording is open to interpretation. It would be pretty nasty if an increasingly powerful spell could just be rendered completely useless with a single casting of dispel magic. A: I no longer agree with my answer but instead with the one presented above by Slagmoth, but leave it here for you to read and make your own decision: My argument is that yes casting a Dispel Magic on one of the creatures ends the whole spell. Conjure Animals: 3rd-level conjuration You summon fey spirits that take the form of beasts and appear in unoccupied spaces that you can see within range. Each beast is also considered fey, and it disappears when it drops to 0 hit points or when the spell ends. Conjure animals is a 3rd level spell that summons a number of fey spirits in the form of beasts and when it ends all the animals disappear together. Therefore it is a single magical effect, no matter how far apart the animals get, or how far from the caster they get. For instance the spell ends when the caster loses concentration and all the animals disappear as one. It is a single magical effect. This is a key point. Dispel magic: Choose one creature, object, or magical effect within range. Any spell of 3rd level or lower on the target ends. The key point is that, as with any spell, if any part of a target is in range of a Dispel Magic you can target it. Therefore if you can cast a Dispel Magic on any one of the fey spirits that are there because of the conjuration spell, you have targeted the magical effect, the spell ends and all the creatures disappear as one. Targeting the caster does not end the spell as they are not part of the magical effect nor do they have the spell "on" them, despite the need for their concentration.
[ "stackoverflow", "0014792888.txt" ]
Q: Get Latitude,Longtitude by a stable marker? I have to make an application with a marker on the center of a srceen and by moving the map and not the marker get lat,lon of the point that the marker shows. I have search the internet for something like Drag Marker but I am not sure if this is what I need.Any Solution? A: In your mapActivity wrtie this. Location l = new Location(); // Location class will be used to calculate distance moved by map TimerTask tm; GeoPoint oldCenterOfMap, newCenteOfMap; // On your on resume method of activity do oldCenterOfMap = mapView.getMapCenter(); Handler mHandler = new Handler(); int isTouched = 0; MapView mapview = (MapView) findViewById(R.id.yourmapview_from_xml); mapView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { newCenteOfMap = mapView.getMapCenter(); if (mapchanged(oldCenterOfMap, newCenteOfMap)) { isTouched++; // Here is what would you do when you lift your finger fromt he map***** newCenteOfMap =mapView.getMapCenter()); if (isTouched >= 1) { if (isTouched > 1) { mHandler.removeCallbacks(tm_circle); isTouched = 1; } mHandler.postDelayed(tm_circle, 1200); } } if (!mapchanged(oldCenterOfMap, newCenteOfMap)) mHandler.removeCallbacks(tm_circle); } return false; } }); tm_circle = new TimerTask() { @Override public void run() { isTouched = 0; // here is what you do after you touched a map moved after 1.2 seconds oldCenterOfMap = mapView.getMapCenter(); } }; public boolean mapchanged(GeoPoint oldCenter, GeoPoint newCenter) { String distance = l.CalclauteDistance(oldCenter.getLongitudeE6() / 1E6, oldCenter.getLatitudeE6() / 1E6, newCenter.getLongitudeE6() / 1E6, newCenter.getLatitudeE6() / 1E6); if (Double.valueOf(distance) == 0.0) return false; else return true; } Previous code would keep the track of the map movement. Next code will respond in case of map movement. In the comments present in the code above ( // here is what you do after you touched a map moved after 1.2 seconds AND // Here is what would you do when you lift your finger fromt he map*****) follow the instruction on my answer on another post. Here Adding multiple overlays on mapview dynamically Edit public String CalclauteDistance(double long1, double lat1, double long2, double lat2) { String Result; Point p1 = new Point(long1, lat1); Point p2 = new Point(long2, lat2); Result = p1.distanceTo(p2) + ""; return Result; } Here is the function (CalclauteDistance) from location class.
[ "stackoverflow", "0063154914.txt" ]
Q: label not fully on page I'm having a small problem with a hover aria label I made with HTML/CSS. As you can see in the picture below, the title is not fully shown on the page. When the sentence is too long, I want the rest of the sentence shown on a new line so you can still read it. Can someone help? span:hover { position: relative; } span[aria-label]:hover:after { content: attr(aria-label); font-size: 13px; padding: 6px 8px; position: absolute; font-weight: normal; left: 20px; top: 100%; white-space: nowrap; color: #000; border: 1px solid #00adf6; background: #FFF; } <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <span aria-label="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc consequat diam nec ullamcorper dapibus. Sed nunc odio, accumsan id pellentesque in, interdum quis metus."><i class="fa fa-info info-btn"></i></span> Adding a width or max-width didn't work. The first problem is now solved. But now I have the following problem: Other text is going over it. I want the aria-label to be on the foreground. A: You need to remove white-space: nowrap; add display:block for showing it properly or you can use div tag instead if span span:hover { position: relative; display: block; /*added*/ } span[aria-label]:hover:after { content: attr(aria-label); font-size: 13px; padding: 6px 8px; position: absolute; font-weight: normal; left: 20px; top: 100%; color: #000; border: 1px solid #00adf6; background: #FFF; } <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <span aria-label="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc consequat diam nec ullamcorper dapibus. Sed nunc odio, accumsan id pellentesque in, interdum quis metus."><i class="fa fa-info info-btn"></i></span>
[ "tex.stackexchange", "0000419510.txt" ]
Q: execute R code in latex file imported from separate R file My personal objective in this Rnotebook revolution where typesetting and number crunching cohabitate is to keep R files separate from latex and as little polluted by markdown as possible and only in the form of R comments, like with javadoc for example or even perlpod. And in that I have succeeded so far by producing readable R-reports with minimal markdown safely confined within comment fences. Then from an R cli session one can do: library(rmarkdown); render('afile.R'). Now I am trying to typeset with latex and crunch with R. But again: try to keep R and latex files separate. So instead of following what many naive examples on the net do (and end up in hell when files grow): \documentclass[12pt]{article} \begin{document} Hello I am latex <<echo=F>>= cat('and I am R and 1+1 is ', 1+1) x1 <- runif(1000,1,2) hist(x1,breaks=10) @ \end{document} Ideally, I would like to do this: \documentclass[12pt]{article} \begin{document} Hello I am latex and following is my R script: \input{crunch.R} \end{document} where crunch.R is: cat('and I am R and 1+1 is ', 1+1) x1 <- runif(1000,1,2) hist(x1,breaks=10) Unfortunately this does not work because the input is not enclosed in <<>>= and @. But neither does this crunch.R work (additionally the file can not be processed by R correctly): <<>>= cat('and I am R and 1+1 is ', 1+1) x1 <- runif(1000,1,2) hist(x1,breaks=10) @ Nor this latex file: \documentclass[12pt]{article} \begin{document} Hello I am latex and following is my R script: <<>>= \input{crunch.R} @ \end{document} for obvious reasons. What I need is a special \inputR{filename.R} latex command which will take care of inserting the tags <<>>= and @. Any idea where to find this command or how to write it? A: You can load external chunks using read_chunk and then execute them later. This simplifies the source document and allows you to keep code external. See Code Externalization. So assume your R code is called Rcode.R This has an R comment line with the label of the code to be used in your .Rnw file, in this example the label is external-code. It looks like this: # ---- external-code ---- cat('and I am R and 1+1 is ', 1+1) x1 <- runif(1000,1,2) hist(x1,breaks=10) Now we have the following .Rnw file. Notice that this first reads the code, and then executes it separately. The code is referred to using the label defined in the Rcode.R file. \documentclass[12pt]{article} \begin{document} Hello I am latex <<external-code, cache=FALSE,echo=F>>= read_chunk('Rcode.R') @ <<external-code,echo=F>>= @ \end{document} You get the following output:
[ "math.stackexchange", "0002991245.txt" ]
Q: What the mass matrix represents? I'm having a really hard time understanding the concept behind the mass matrix in the discretization of PDEs (I get the stiffness one, but not this one), also I know that is related to the identity (like the identity "moved"). Can someone make light on this doubts ? Thank you EDIT: Since I have not put any background on it, generally speaking could someone explain the difference between mass matrix and stiffness matrix ? Like, why in a lot of examples there is only the stiffness matrix and not the mass matrix ? When we need it ? A: Given a base $\{b_j\}$ of some discrete subspace $V_h\subset V$ where $V$ is usually some Sobolev space on a domain $\Omega$, the mass matrix is the matrix $M=(m_{j,k})$ with $$m_{j,k}=\int_\Omega b_j(x)b_k(x)\,dx.$$ It can be considered as the discrete version of the $L_2(\Omega)$ inner product on $V_h$. Edit: Consider the simple problem: find $u\in V_h$ (with $V_h=\mathrm{span}\{b_j:j=1,\ldots,n\}$ as before) such that $$u_h=f$$ for some given function $f\in L_2(\Omega)$. Of course for $f\notin V_h$ we there is no solution in strong sense. But we can go over to the weak form. To this end we multiply with testfunctions $v_h$ and integrate to find the variational formulation $$\int_\Omega u_h(x) v_h(x)\, dx=\int_\Omega f(x) v_h(x)\, dx,\quad\forall v_h\in V_h$$ Now plug in $u_h=\sum_{j=1}^n \alpha_j b_j$ and all basis functions $b_j$ for $v_h$ and you end up with $$M \alpha=F,$$ with $\alpha=(\alpha_1,\ldots,\alpha_n)^T$, $F=(f_1,\ldots,f_n)^T$ and $$f_j=\int_\Omega b_j(x)f(x)\,dx.$$ Thus, the mass matrix appears naturally when you want to approximate a given function $f$ in a discrete space. The stiffness matrix consists of entries $$s_{j,k}=\int_\Omega\nabla b_j(x)\cdot\nabla b_k(x)\,dx.$$ It is the discrete version of the $H^1(\Omega)$ semi-norm. These matrices appear in finite element discretizations of PDEs. For example a discretization of Poisson's equation with homogenous Neumann boundary data and right hand side $f$ i.e. \begin{align} -\Delta u(x)&=f(x),&x&\in\Omega\\ \frac{\partial u}{\partial n}(x)&=0,&x&\in\partial\Omega\\ \end{align} would be $$S\alpha=F$$ with $\alpha,F$ as before.
[ "math.stackexchange", "0000688374.txt" ]
Q: Moving a distance at a position vector I have a problem set in which the problem states from vector $a = 4i+3j+8k$ move lets say $2$ metres in the direction of the vector $r = 1i + 2j +5k$. What is your final position? I know how to add vetors and however I am not sure how to deal with it when they you must move a certain number of meters in the direction of another vector. Must I multiply the vector by the $2$? Thanks. A: Assuming you are always dealing in meters, then you need to normalize the vector $\mathbf{r}$ and multiply it by $2$. Then normalized vector is found by $$\mathbf{n}=\frac{\mathbf{r}}{||\mathbf{r}||}$$ Where $||\mathbf{r}||=\sqrt{1^2+2^2+5^2}$. Normalizing the vector gives you the unit vector in the direction of $\mathbf{r}$ . Then you add $\mathbf{a}+\mathbf{r}$.
[ "chemistry.stackexchange", "0000075347.txt" ]
Q: Long-term storage of Ascorbic Acid mixed with Sodium Bicarbonate Every day I mix two parts of ascorbic acid powder with 1 part of sodium bicarbonate powder and place the resulting powder into an airtight container. I have noticed that if the resulting powder is mixed with water within 30-60 minutes, it fizzles indicating the release of carbon dioxide as a byproduct of the acid-base reaction. However, if I leave it untouched (within a dry and airtight container) for 6 to 8 hours, it hardens. If I crush it (so it turns into powder again) and mix it with water, it no longer fizzles. My questions are: Why does it harden and no longer fizzles if mixed with water after a few hours? Does the acid-base reaction take place even without adding any liquids to the mixed powder? Most importantly, does the reaction that causes the hardening and absence of fizzling cause any kind of degradation (e.g., oxidation) to the ascorbic acid? In other words, can I mix ascorbic acid with sodium bicarbonate (both in powder form), store the resulting powder in an airtight container and consume over a few months? Would that diminish the efficacy of the Vitamin C in any way? Thank you in advance. Update: I have bought sodium bicarbonate from a different manufacturer and now after mixing it with ascorbic acid, nothing happens until water is added. It can sit for 24+ hours, without hardening and it will still fizz when mixed with water. I suspect the sodium bicarbonate from the previous manufacturer was slightly moist and this one is completely dry. A: The reason that your solid mixture is clumping and hardening inside your airtight container is that the reaction between the two compounds is producing water as follows: $$\ce{C6H8O6 + NaHCO3 <=> NaC6H7O6 + CO2 + H2O}$$ where $\ce{C6H8O6}$ is ascorbic acid. This reaction proceeds rapidly in the presence of excess water, which allows the reacting species to dissolve and thus have ready access to each other. This results in the observed fizzing from the release of carbon dioxide. In the solid phase, the initial reaction is limited to the surfaces of the particles coming into contact with each other. As the reaction proceeds, the once purely solid material becomes wet via the acid-base reaction producing water, and the remaining materials can somewhat dissolve, facilitating migration of the reacting species so that on a timescale of hours all of your material has reacted. Regarding the stability of storing the solid mixture vs. storing the solids separately, you are probably better off storing them separately until use. Both ascorbic acid and sodium ascorbate are susceptible to being oxidized by long-term exposure to air. Although water itself shouldn't act as an oxidant here, it could facilitate reaction with oxygen in the air in a similar manner in which it facilitates the acid-base reaction, as discussed above. A: The sodium bicarbonate (a base) is reacting with the ascorbic acid to form sodium ascorbate and carbon dioxide, as well as water. The carbon dioxide is responsible for the fizzing you note when you dissolve the mixture in water. When you mix the two solids, the reaction is relatively slow, since the reaction must take place at the interface of the two solids; however, it appears that allowing it to sit overnight is ample time. The hardening is probably due to the release of water, which causes to solid to aggregate; the solid will no longer bubble in water as it has already reacted and released its carbon dioxide. As for the fate of the ascorbic acid, the sodium salt is stable, and will be converted back to the free acid in the presence of another acid. Just don't expect it to fizz.
[ "sitecore.stackexchange", "0000003186.txt" ]
Q: No contact created in MongoDB when session is closed 8.2 update 0. I have changed session to be 1 minute instead of the default 20 minutes. When I log into the site, in incognito, surf around and close the browser. No contact is ever created in the Mongo analytics database. When I look in the logs, there is nothing before or after the profile is created to identify any issues. I have installed a profile viewer and can verify that a profile is being created and has custom facets. I just can get it to write the contact to Mongo when the session is closed. I have tried several different browers on and off server. A: I know you have already found the exact solution for your particular case. Still, I'm going to list the steps I normally take when troubleshooting data saving issues in xDB. Hopefully, this can help others in the future. Ensure the analytics connection string is set up properly in the ConnectionStrings.config. Make sure that you have a valid xDB license. You can see the list of available licenses in the Control Panel > Administration > Installed licenses. "Sitecore.xDB.base" should be present there. Make sure that xDB and its tracking subsystem are enabled. The settings Xdb.Enabled and Xdb.Tracking.Enabled should be set to true when you open this page: /sitecore/admin/ShowConfig.aspx. The configuration file Sitecore.Analytics.Tracking.Database.config should be enabled. Enable tracking on your site definition by setting enableTracking to true for your site in the <sites> section. Try making several page requests instead of just one before letting the session expire. Ensure that all of your layout pages contain the VisitorIdentification control in the <head> section. In MVC layouts, use @Html.Sitecore().VisitorIdentification(); in ASP.NET WebForms layouts, use <sc:VisitorIdentification runat="server" />. Try disabling robot detection by setting both Analytics.Robots.IgnoreRobots and Analytics.AutoDetectBots to false. The original values for these settings are located in the Sitecore.Analytics.Tracking.config. If interactions are saved after this, it means your visitors were recognized as robots. If nothing helps, go through the steps listed in the article Troubleshooting xDB data issues. A: Ensure the VisitorIdentification code is available on the layout. @Html.Sitecore().VisitorIdentification() Also, if it helps, the contact creation logic is executed in the below pipeline processor: <ensureSessionContext> ... <processor type="Sitecore.Analytics.Pipelines.EnsureSessionContext.CreateContact, Sitecore.Analytics"> <ContactManager ref="tracking/contactManager" /> </processor> ... </ensureSessionContext>
[ "stackoverflow", "0022263643.txt" ]
Q: Anonymous (?) initialization of a struct passed as an argument in C++03 Say, I have struct Foo { char a; char b; }; void bar(Foo foo); What's the most succinct way to initialize a struct and pass it to the function? Ideally I would like to write something like bar(Foo = {'a','b'}); What if Foo was a union? UPD: My sincere apologies, the question was supposed to be in relation to C++03 only. Also, in this particular case, going away from POD is to be avoided (the code is for embedded system, ergo shorter bytecode is sought after). vonbrand, thanks for the C++11 answer. A: In C++ 11 you can write: bar({'a', 'b'}); or: bar(Foo{'a', 'b'}); (see Stroustup's C++11 FAQ. g++-4.8.2 accepts this without complaints only if you give it -std=c++11, clang++-3.3 gives an error unless -std=c++11
[ "stackoverflow", "0012049351.txt" ]
Q: while posting json to webapi error occured : Origin null is not allowed by Access-Control-Allow-Origin Am trying to post json data to the server. am using visual studio 2012 RC and windowsazure for hosting the web application . On posting am getting the following errors : OPTIONS http://*.azurewebsites.net/api/Child 405 (Method Not Allowed) jquery-1.7.1.js:8102 XMLHttpRequest cannot load http://*.azurewebsites.net/api/Child. Origin null is not allowed by Access-Control-Allow-Origin. My client side code is : function PostChild() { var Chld = {}; Chld.Child_FirstName = $("#Child_FirstName").val(); Chld.Child_LastName = $("#Child_LastName").val(); Chld.Child_Age = $("#Child_Age").val(); var createurl = "http://*.azurewebsites.net/api/Child"; $.ajax({ type: "POST", url: createurl, contentType: "application/json; charset=utf-8", data: JSON.stringify(Chld), statusCode: { 200: function () { $("#txtmsg").val("done"); alert('Success'); } }, error: function (res) { alert('Error'); $("#txtmsg").val("error" + " " + res.status + " " + res.statusText); } }); } My server side code is : public HttpResponseMessage PostChild(Child child) { if (ModelState.IsValid) { db.Children.Add(child); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, child); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = child.ChildID })); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } Help me please Thanks, A: The errors was due to CORS (Cross Origin Resource sharing). By default, a web page cannot make calls to services (APIs) on a domain other than the one where the page came from. This is a security measure to avoid cross-site forgery attacks and all. To solve it follow this tutorial: http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx
[ "stackoverflow", "0028676945.txt" ]
Q: Building Sencha Touch app with Cordova - [You may not have the required environment or OS to build this project] error I am trying to build a sencha touch 2.4 application for Android using the sencha cmd "sencha app build native" and I am getting an error that I can't solve. "You may not have the required environment or OS to build this project" I am working on Win7, using sencha touch 2.4 and sencha cmd v5.1. I downloaded the Android sdk (API 19) using the Android SDK Manager. This is the command output: D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA>sencha app build native Sencha Cmd v5.1.1.39 [INF] Processing Build Descriptor : native [INF] Loading app json manifest... [INF] Concatenating output to file D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/build/temp/production/GeoMapTematicPA/sencha-compiler/cmd-packages.js [INF] writing content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] Appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/bootstrap.json [WRN] C1014: callParent has no target (me.callParent in Ext.dataview.DataView.onAfterRender) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\dataview \DataView.js:892 [WRN] C1014: callParent has no target (this.callParent in Ext.Decorator.setDisabled) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\Decorator.js:157 [WRN] C1014: callParent has no target (this.callParent in Ext.data.ArrayStore.loadData) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\data\ArrayStore.js:64 [WRN] C1014: callParent has no target (this.callParent in Ext.fx.animation.Wipe.getData) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\fx\animation\Wipe.js:119:7 [INF] merging 0 input resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www\resources [INF] merged 0 resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www\resources [INF] merging 87 input resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www [INF] merged 0 resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www [INF] executing compass using system installed ruby runtime identical ../css/app.css [INF] Copying page resources to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www [INF] Writing content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/microloader.js [INF] Appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/microloader.js [INF] Building output markup to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/index.html [INF] Writing content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/index.html [INF] [Cordova] Attempting Cordova Build for platforms "android" [INF] [shellscript] [INF] [shellscript] D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova>cordova build android [INF] [shellscript] Running command: D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\platforms\android\cordova\build.bat [INF] [shellscript] events.js:85 [INF] [shellscript] throw er; // Unhandled '''error''' event [INF] [shellscript] ^ [INF] [shellscript] Error: spawn cmd ENOENT [INF] [shellscript] at exports._errnoException (util.js:746:11) [INF] [shellscript] at Process.ChildProcess._handle.onexit (child_process.js:1046:32) [INF] [shellscript] at child_process.js:1137:20 [INF] [shellscript] at process._tickCallback (node.js:355:11) [INF] [shellscript] ERROR building one of the platforms: Error: D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\platfrms\android\cordova\build.bat: Command failed with exit code 1 [INF] [shellscript] You may not have the required environment or OS to build this project Thanks in advance, any help would be really appreciated. A: As suggested here, Cordova / Ionic build error (sometimes): don't have required environment, what to do is Copy and paste this "%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\" to the enviroment variables Path.
[ "stackoverflow", "0033425488.txt" ]
Q: ServiceLoader doesn't load implementation I really did a lot of research before asking this, it seems like I'm missing something. I try to implement a ServiceLoader and therefore made an example class: the code is simple: testInterface.java package com.test; public interface testInterface { void test(); } testImpl.java package com.test; public class testImpl implements testInterface { @Override public void test() { System.out.println("test"); } } Main.java package com.test; import java.util.ServiceLoader; public class Main { public static void main(String[] args) { ServiceLoader<testInterface> serviceLoader = ServiceLoader.load(testInterface.class); serviceLoader.iterator().next().test(); } } com.test.testInterface com.test.testImpl I keep getting a NoSuchElementException at the iterator part which means that the implementation was not loaded. Thanks in advance. A: Put your META-INF/services/ into resources/ and add it to the Eclipse project as a source folder. It will be automatically included in the JAR file when you compile.
[ "meta.stackexchange", "0000055199.txt" ]
Q: Why didn't I get the bounty? This thread had a bounty of 150 on it ... How to add statusbar correctly? My answer was accepted a day or so before the bounty finished and I note the user has lost the reputation. On the other hand I never received the bounty. Why is that? A: The implementation has changed a bit to better accommodate careless bounty owners. :) If ... the bounty was started by the question owner the question owner accepts an answer during the bounty period the bounty award period expires without an explicit award ... then we assume the question owner liked your answer when they accepted it, and it gets the full amount of the bounty at time of bounty expiration. A: Because OP didn't click +150 icon under it, and you don't have +2 upvotes to get half bounty. Bounty rules changed, and accepting an answer does not automatically award bounty anymore.
[ "stackoverflow", "0062939073.txt" ]
Q: How to change language in Request (GET) URL? I am trying this code however still unable to change the language of the URL. from requests import get url = 'https://www.fincaraiz.com.co/apartamento-apartaestudio/arriendo/bogota/' headers = {"Accept-Language": "en-US,en;q=0.5"} params = dict(lang='en-US,en;q=0.5') response = get(url, headers = headers, params= params) print(response.text[:500]) titles = [] for a in html_soup.findAll('div', id = 'divAdverts'): for x in html_soup.findAll(class_ = 'h2-grid'): title = x.text.replace("\r", "").replace("\n", "").strip() titles.append(title) titles Output ['Local en Itaguí - Santamaría', 'Casa en Sopó - Vereda Comuneros', 'Apartamento en Santa Marta - Bello Horizonte', 'Apartamento en Funza - Zuame', 'Casa en Bogotá - Centro Comercial Titán Plaza', 'Apartamento en Cali - Los Cristales', 'Apartamento en Itaguí - Suramerica', 'Casa en Palmira - Barrio Contiguo A Las Flores', 'Apartamento en Cali - La Hacienda', 'Casa en Bogotá - Marsella', 'Casa en Medellín - La Castellana', 'Casa en Villavicencio - Quintas De San Fernando', 'Apartamento en Santa Marta - Playa Salguero', 'Casa Campestre en Rionegro - La Mosquita', 'Casa Campestre en Jamundí - La Morada', 'Casa en Envigado - Loma De Las Brujas', 'Casa Campestre en El Retiro - Los Salados'] Does anyone know how can I change the language of the URL? Tried everything A: I am only giving example for particular field title, you may extend it to other fields, you may face issue like being blocked by google for number of concurrent request while using this library as it is not official one. Also you must consider to see the Note written in the documentation https://pypi.org/project/googletrans/ from requests import get from bs4 import BeautifulSoup from googletrans import Translator translator = Translator() url = 'https://www.fincaraiz.com.co/apartamento-apartaestudio/arriendo/bogota/' headers = {"Accept-Language": "en-US,en;q=0.5"} params = dict(lang='en-US,en;q=0.5') response = get(url, headers = headers, params= params) titles = [] html_soup = BeautifulSoup(response.text, 'html.parser') for a in html_soup.findAll('div', id = 'divAdverts'): for x in html_soup.findAll(class_ = 'h2-grid'): title = x.text.replace("\r", "").replace("\n", "").strip() titles.append(title) english_titles=[] english_translations= translator.translate(titles) for trans in english_translations: english_titles.append(trans.text) print(english_titles) Since you are scraping from spanish language to english language you can specify parameters in translator.translate(titles,src="es",dest="en")
[ "physics.stackexchange", "0000011763.txt" ]
Q: How does dynamic casimir effect generate correlated photons? There is a recent paper on arxiv receiving lot of acclaim http://arxiv.org/abs/1105.4714 The authors experimentally show that moving a mirror of a cavity at high speeds produces light from high vacuum. The usual doubts about the experimental techniques seem to be very clearly addressed and reviewed (as per Fred Capasso's comments) http://www.nature.com/news/2011/110603/full/news.2011.346.html) My question is: Can someone explain how correlated/squeezed photons are generated in this process? I can get a feel for how a moving mirror can generate real photons by imparting energy to the vacuum (correct me if this is not consistent with the detailed theory). But, I don't see how photons are generated in pairs. Could someone describe the parametric process happening here? A: Ref [19] in the arXiv paper, C. M. Caves and B. L. Schumaker, Phys Rev A 31, 3068 (1985), gives a clean description of a parametric amplifier as the prototype of a two-photon device, at the bottom of its second page: In a [parametric amplifier], an intense laser beam at frequency $2\Omega$ —the pump beam— illuminates a suitable nonlinear medium. The nonlinearity couples the pump beam to other modes of the electromagnetic field in such a way that a pump photon at frequency $2\Omega$ can be annihilated to create "signal" and "idler" photons at frequencies $\Omega\pm\epsilon$ and, conversely, signal and idler photons can be annihilated to create a pump photon. One way to think of the present situation would be as a dual of this description. That is, the medium, the Josephson junction, oscillates at a pump frequency $2\Omega$, and interacts nonlinearly with the vacuum state. From the arXiv paper itself, there is a clear parallel, Quantum theory allows us to make more detailed predictions than just that photons will simply be produced. If the boundary is driven sinusoidally at an angular frequency $\omega_d = 2\pi f_d$, then it is predicted that photons will be produced in pairs such that their frequencies, $\omega_1$ and $\omega_2$, sum to the drive frequency, i.e., we expect $\omega_d = \omega_1 + \omega_2$. One of the comments on the Nature News page, Edward Schaefer at 2011-06-06 12:39:04 PM, makes a point that I think is worth highlighting, that "The mirror transfers some of its own energy to the virtual photons to make them real."
[ "linguistics.meta.stackexchange", "0000001836.txt" ]
Q: What's going on with the Russian etymology questions? Recently there's been a spate of questions asking about Russian etymologies. Each question seems to come from a new user who never posts again, but all the questions are basically in the same format. What's going on with this? And is it something we should do something about? A: This must be a single person who asks low-quality questions which get downvoted, and this triggers an automatic question ban. Numerous fake accounts are needed to evade that ban. The Mods should check the cross-IP activity and, if it confirms that these accounts are sockpuppet accounts, burn them with fire. A: Yes, probably there is a need for taking some measures. As a moderator of Русский язык, I am quite acquainted with the situation as these questions had at first been presented on our site until I closed them all. It is difficult to understand why the person who is asking them uses different accounts here because on Русский язык he uses a single profile. I recommended local moderators to pay attention to all these fake accounts controlled by the man in question, but it seems that this was fruitless. Well, concerning the reason I used to close the questions like 'Does Russian пушка share the same root with English porch?' is Please provide the phonetic laws you used to consider these words cognate. Otherwise, we cannot help you. Maybe you should try something similar to it? A: I've re-opened a couple of the questions asked by those possible sockpuppets, not because I appreciate these machine-gun etymology questions, but because the reason given is usually "off-topic: Language-specific grammar and usage questions are off-topic unless primarily concerned with linguistics rather than usage". These questions are primarily about etymology, which is definitely part of linguistics, and they are generally about the relatedness of words in at least two languages, so I think it's a bad precedent to consistently close them on those grounds: well thought-out (or even half-well thought-out) etymology questions should be allowed in my opinion, and I guess the reason this closing reason is chosen is that they are allowed as there isn't a closing reason that is actually appropriate. It's possible to vote for closing a question as "other" and then add a comment. Some comments have mentioned there seems to be an almost complete lack of research behind this question (and I'd say the poster is basically picking pairs of random words that sound vaguely similar and just asking ahead), so maybe people who want the questions closed should simply give a reason of this sort. Does it even make sense to close them in the first place, though? If the questions are on-topic and would generally be appropriate for the site, except for the fact they're machine-gun questions of an identical type that show no prior research and are posted by apparent sockpuppets, then to me, it makes more sense to downvote the questions to death, and hopefully manage to ban the sockpuppets.
[ "electronics.stackexchange", "0000074579.txt" ]
Q: What exactly is a Flash emulator, and how does it work? I read about a flash emulator. Can someone tell me what exactly a flash emulator is, and explain how it works? Is it synonymous with an in-circuit emulator? A: A Flash Emulator is used in a system that normally keeps its program code in a FLASH memory chip. The emulator is a small piece of hardware that substitutes in place of the normal FLASH memory chip in a way to disable the normal FLASH and stands in place of its functionality. Sometimes the normal FLASH chip is unplugged and the emulator plugs into the chip socket. Other times the target board will have a special connector to which the emulator attaches. The act of plugging in the emulator disables the normal FLASH and enables then emulator. A third common type is connecting the emulator via a chip clip that clamps over the FLASH chip on the target board. If the emulator is to pretend to be the FLASH to the board under test it has to supply memory that can contains program code for the processor on the board. This memory is usually in the form of RAM inside the adapter that has glue hardware between it and the FLASH interface to convert the normal FLASH read/write interface protocol to that required to access this RAM. In this manner the processor on the target board can fetch and execute code that is contained in RAM of the emulator. The RAM from the emulator is also dual ported to a host accessible interface so that the RAM contents can be loaded. The host is often a PC type computer with cross compiler, assembler and linker tools that is capable of producing program images for the target MCU. The host computer then accesses the Flash emulator so that the code can be executed and tested on the target MCU. The interface between the host computer and the emulator may be a variety of different types including parallel port, USB, serial, or Ethernet. USB interfaces are in common use today. These days in the embedded MCU world the use of actual Flash Emulators as described is becoming quite uncommon. Almost all mainstream MCUs have onboard FLASH memory and built in debug harware that allows remotely loading the FLASH. The debug hardware is the used to permit testing of the code as it executes. The debug interface to the MCU is a specialized set of pins that connect to a special downloader/debug pod. The host computer is normally connected to this debug pod via USB or Ethernet and special dedicated software on the host is used to do the FLASH programming and operate the debug interface in the target MCU.
[ "stackoverflow", "0018702169.txt" ]
Q: Java, Float.parseFloat(), System.out.printf() inconsistency Consider the following code in Java : String input = "33.3"; float num = Float.parseFloat(input); System.out.printf("num: %f\n",num); Why is the output of the code above num: 33.299999 ? Shouldn't it be num: 33.300000 ? I would really appreciate it if someone can explain this to me. A: You're a victim of floating-point error. In base 2, 33.3 is technically a repeating binary(similar to a repeating decimal), as when written as m/n with m and n being integers and gcd(m,n)=1, the prime factors of n are not a subset of the prime factors of 2. This also means that it cannot be written as the sum of a finite number of terms m*(2^n) where m and n are integers. A similar example happens with 7/6 in base 10. _ 1.16 becomes 1.16666667 which is then read literally, and is not equal to 7/6. A: Don't use float if you can avoid it. The problem here is that %f is treating it as a double when it doesn't have that precision String input = "33.3"; double num = Double.parseDouble(input); System.out.printf("num: %f\n",num); prints 33.300000 This occurs because 33.3f != 33.3 as float has less precision. To see the actual values you can use BigDecimal which covers the actual value precisely. System.out.println("33.3f = " + new BigDecimal(33.3f)); System.out.println("33.3 = " + new BigDecimal(33.3)); prints 33.3f = 33.299999237060546875 33.3 = 33.2999999999999971578290569595992565155029296875 As you can see the true value represented is slightly too small in both cases. In the case of how %f it shows 6 decimal places even though float is not accurate to 8 decimal places in total. double is accurate to 15-16 decimal places and so you won't see an error unless the value is much larger. e.g. one trillion or more.
[ "stackoverflow", "0017966446.txt" ]
Q: reading standard output via read function instead of fread I would like my program to read the standard output produced by another application. I am aware that I can use popen to do that and use fread to read that output. Do you know whether is possible to use read (and possibly open)? I am working in LINUX with C/C++ A: You can get a file descriptor for read() by calling int fd = fileno(fp) for the FILE *fp you have got from popen(). But be aware that you must not mix calling read() and fread()! EDIT If you want to avoid popen(), you have to use pipe(), fork(), exec..() and dup2() like it's done here
[ "pt.stackoverflow", "0000327968.txt" ]
Q: Como pegar o primeiro caractere de uma String e torná-lo maiúsculo armazenando em uma variável? String user,newUser,newPassword, password, resposta, user1,pass1; user = "admin"; password = "123"; Console.WriteLine("LOGIN\n"); body: Console.WriteLine("Ja possui login?"); resposta = Console.ReadLine(); /* gostaria de fazer com que a resposta acima lida pelo programa seja convertida para um unico caractere maiusculo para quando fizer a comparação não precisar colocar varias || dentro da condição. */ if (resposta.Equals("N")) { Console.Write("Digite novo usuario: \n"); newUser = Console.ReadLine(); Console.Write("Digite nova senha: \n"); newPassword = Console.ReadLine(); Console.WriteLine("Criado com sucesso!\nAgora faça Login!"); goto body; } else if (resposta.Equals("S")) { Console.Write("Digite usuario: \n"); user1 = Console.ReadLine(); if (user1.Equals(user)) { Console.Write("Digite a senha: \n"); pass1 = Console.ReadLine(); if (pass1.Equals(password)) { Console.WriteLine("Logado com Sucesso!"); } else { Console.WriteLine("Senha incorreta, tente novamente:"); goto body; } } else { Console.WriteLine("Usuario incorreto, tente novamente!"); goto body; } } Console.Read(); A: var c = char.ToUpper(texto[0]); Coloquei no GitHub para referência futura. Documentação. Mas antes de usar isso, apague todo seu código e comece de novo, desta vez escreva um código sem goto e com os recursos do C#. Tem outros erros, mas esses são urgentes. Sugiro aprender por outros meios.
[ "stackoverflow", "0023500766.txt" ]
Q: BASH - extract integer from logfile with sed I've got the following logfile and I'd like to extract the number of dropped packets (in the following example the number is 0): ITGDec version 2.8.1 (r1023) Compile-time options: bursty multiport ---------------------------------------------------------- Flow number: 1 From 192.168.1.2:0 To 192.168.1.2:8999 ---------------------------------------------------------- Total time = 2.990811 s Total packets = 590 Minimum delay = 0.000033 s Maximum delay = 0.000169 s Average delay = 0.000083 s Average jitter = 0.000010 s Delay standard deviation = 0.000016 s Bytes received = 241900 Average bitrate = 647.048576 Kbit/s Average packet rate = 197.270907 pkt/s Packets dropped = 0 (0.00 %) Average loss-burst size = 0.000000 pkt ---------------------------------------------------------- __________________________________________________________ **************** TOTAL RESULTS ****************** __________________________________________________________ Number of flows = 1 Total time = 2.990811 s Total packets = 590 Minimum delay = 0.000033 s Maximum delay = 0.000169 s Average delay = 0.000083 s Average jitter = 0.000010 s Delay standard deviation = 0.000016 s Bytes received = 241900 Average bitrate = 647.048576 Kbit/s Average packet rate = 197.270907 pkt/s Packets dropped = 0 (0.00 %) Average loss-burst size = 0 pkt Error lines = 0 ---------------------------------------------------------- I'm trying with the following command: cat logfile | grep -m 1 dropped | sed -n 's/.*=\([0-9]*\) (.*/\1/p' but nothing gets printed. Thank you EDIT: I just wanted to tell you that the "Dropped packets" line gets printed in the following way in the code of the program: printf("Packets dropped = %13lu (%3.2lf %%)\n", (long unsigned int) 0, (double) 0); A: Aside from the problem in your sed expression (that it doesn't allow space after =), you don't really need a pipeline here. grep would suffice: grep -m 1 -oP 'dropped\s*=\s*\K\d+' logfile You could have fixed your sed expression by permitting space after the =: sed -n 's/.*= *\([0-9]*\) (.*/\1/p'
[ "stackoverflow", "0014322236.txt" ]
Q: Making TileOverlays transparent I'm currently working on a App that uses a custom TileSource to display data on Google Maps. I get those data in form of *.png images, and I'm using the URLTileProvider. Everything is working well, but I'm now trying to make the TileLayer transparent, or at least, partly. The goal is, that the layer is visible but the underlying Google Maps still shines through. Somehow I'm stuck, as I do not know how to achieve this. I did not find a way to fully implement a custom TileProvider, it seems one can only extend URLTileProvider Serverside imagemanipulation is not possible, as the data is given There are no options to make a TileOverlay transparent? (alpha, opacity, transparency) I'd be very helpful if someone could hint me in the right direction, or tell me whether the Google Maps API V2 for Android really does not support this feature. A: At this moment it is not possible to specify transparency for TileOverlay in android maps sdk v2. Unfortunately setTransparency(float) method is available for GroundOverlay only.. The only way to do this - is to implement your own TileProvider and change png 'on-the-fly' to change alpha channel.