text
stringlengths
64
81.1k
meta
dict
Q: Dynamic input parameter instead of in Spring for a class How can I get rid of the constructor-args in the spring-config.xml bean mapping and supply the value dynamically or from the String args[] parameter form the main method for the BattingStats class? I have the following Player class package com.scorer.game; public class Player { private BattingStats battingStats; public BattingStats getBattingStats() { return battingStats; } public void setBattingStats(BattingStats battingStats) { this.battingStats = battingStats; } @Override public String toString() { return "Player{" + "runs scored=" + battingStats.getRunsScored() + " balls faced=" + battingStats.getBallsFaced() + " strike rate=" + battingStats.getStrikeRate() + '}'; } } and class BattingStats as follows: package com.scorer.game; public class BattingStats { private Integer battingPosition; private Integer ballsFaced; private Integer runsScored; private Integer fours; private Integer sixes; private Boolean isNotOut; private Boolean isRightHand; private Float strikeRate; public BattingStats(Integer battingPosition, Integer ballsFaced, Integer runsScored, Integer fours, Integer sixes, Boolean isNotOut, Boolean isRightHand) { this.battingPosition = battingPosition; this.ballsFaced = ballsFaced; this.runsScored = runsScored; this.fours = fours; this.sixes = sixes; this.isNotOut = isNotOut; this.isRightHand = isRightHand; this.strikeRate = (float)(((float)runsScored/(float)ballsFaced)*100); } public static BattingStats getInstance(Integer battingPosition, Integer ballsFaced, Integer runsScored, Integer fours, Integer sixes, Boolean isNotOut, Boolean isRightHand) { return new BattingStats(battingPosition, ballsFaced, runsScored, fours, sixes, isNotOut, isRightHand); } public Integer getBattingPosition() { return battingPosition; } public Integer getBallsFaced() { return ballsFaced; } public Integer getRunsScored() { return runsScored; } public Integer getFours() { return fours; } public Integer getSixes() { return sixes; } public Boolean getIsNotOut() { return isNotOut; } public Boolean getIsRightHand() { return isRightHand; } public Float getStrikeRate() { return strikeRate; } public void setBattingPosition(Integer battingPosition) { this.battingPosition = battingPosition; } public void setBallsFaced(Integer ballsFaced) { this.ballsFaced = ballsFaced; } public void setRunsScored(Integer runsScored) { this.runsScored = runsScored; } public void setFours(Integer fours) { this.fours = fours; } public void setSixes(Integer sixes) { this.sixes = sixes; } public void setIsNotOut(Boolean isNotOut) { this.isNotOut = isNotOut; } public void setIsRightHand(Boolean isRightHand) { this.isRightHand = isRightHand; } public void setStrikeRate(Float strikeRate) { this.strikeRate = strikeRate; } } and the main class ass follows: package com.scorer.app; import com.scorer.game.BattingStats; import com.scorer.game.Player; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String args[]) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); BattingStats battingStats = (BattingStats)context.getBean("battingStats"); Player player = (Player)context.getBean("player"); System.out.println(player.toString()); } } the spring-confix.xml is as follows <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="player" class="com.scorer.game.Player" > <property name="battingStats" ref="battingStats"></property> </bean> <bean id="battingStats" class="com.scorer.game.BattingStats"> <constructor-arg type="java.lang.Integer" name="battingPosition" value = "1"></constructor-arg> <constructor-arg type="java.lang.Integer" name="ballsFaced" value = "101"></constructor-arg> <constructor-arg name ="runsScored" value = "52"></constructor-arg> <constructor-arg name ="fours" value = "100"></constructor-arg> <constructor-arg name ="sixes" value = "100"></constructor-arg> <constructor-arg name ="isNotOut" value = "true"></constructor-arg> <constructor-arg name ="isRightHand" value = "true"></constructor-arg> </bean> </beans> A: You can use @Configuration annotation to construct your beans using Java instead of XML, enabling you to dynamically calculate whatever variables you need to pass into bean constructors. package com.example; import java.net.URI; import java.net.URISyntaxException; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.scorer.game.BattingStats; @Configuration public abstract class DatabaseConfiguration { @Bean public BasicDataSource createDataSource() throws URISyntaxException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setUrl(dbUrl); basicDataSource.setUsername(username); basicDataSource.setPassword(password); basicDataSource.setTestOnBorrow(true); basicDataSource.setTestOnReturn(true); basicDataSource.setTestWhileIdle(true); basicDataSource.setTimeBetweenEvictionRunsMillis(1800000); basicDataSource.setNumTestsPerEvictionRun(3); basicDataSource.setMinEvictableIdleTimeMillis(1800000); basicDataSource.setValidationQuery("SELECT version();"); return basicDataSource; } @Bean(name = "persistenceXmlLocation") public String persistenceXmlLocation() { return "classpath:META-INF/persistence.xml"; } /* --------- UPDATE ---------------- */ @Bean public BattingStats battingStats() { Integer battingPosition = methodForDynamicallyCalculatingBattingPosition(); // call the rest of your "dynamic" methods here return new BattingStats(battingPosition, /* the rest of your dynamic arguments go here */); } }
{ "pile_set_name": "StackExchange" }
Q: There is something wrong with my Python code involve the replace function I was creating a function about replacing multiple part of a string with multiple number but for some reason, the output is not what i expected. from pyprimes import isprime def prime_replace(x, l = []): lst = [] string = str(x) for n in range(10): for i in l: string = string.replace(string[i], str(n)) lst.append(int(string)) return lst print prime_replace(x = 56243, l = [2, 3]) The output of this function is a list [56003, 56113, 56223, 56333, 56444, 56555, 66666, 77777, 88888, 99999] but what i wanted is [56003, 56113, 56223, 56333, 56443, 56553, 56663, 56773, 56883, 56993] Can someone help me with this and tell me what went wrong, thank you. A: You're modifying the original string, and replace is replacing "all occurrences" Here's part of a print out for how it's generating the output you see: ... string is now 56333 replacing 3 with 3 string is now 56333 replacing 3 with 4 string is now 56444 ... You can see that we successfully got 56333 like you wanted, but then you wanted to replace str[2] (actual value: 3) with str(n) (actual value: 4), which replaced all occurrences of 3 One workaround for this specific scenario is to make a copy of your string: def prime_replace(x, l = []): lst = [] string = str(x) for n in range(10): newstr = string for i in l: newstr = newstr.replace(string[i], str(n)) lst.append(int(newstr)) return lst print prime_replace(x = 56243, l = [2, 3]) Output: [56003, 56113, 56223, 56333, 56443, 56553, 56663, 56773, 56883, 56993] Demo (not recommended) However, replace may not be the best choice since it will replace all occurrences of the "oldstring" with the "newstring". It looks like what you're really trying to do is to change string at indices in l to be the next value in range(10), we can do this through indexing and appending: def prime_replace(x, l = []): lst = [] string = str(x) for n in range(10): newstr = string for i in l: newstr = newstr[0:i]+str(n)+newstr[i+1:]; lst.append(int(newstr)) return lst Demo (better)
{ "pile_set_name": "StackExchange" }
Q: Using querySelector exclude elements whose id's include a spesific string I want to get results whose id does not include a string (let's say it's is "test") <ul class="numberlist"> <li id="test1" style="display:none"> <div></div> </li> <li> <a>one</a> </li> <li> <a>two</a> </li> <li> <a>three</a> </li> <li id="test2" style="display:none"> <div></div> </li> <li> <a>four</a> </li> <li id="test" style="display:none"> </div></div> </li> </ul> As I said I want to exclude which has id that includes string test. How can I achieve it? I can get the list of <li>'s by writing document.querySelectorAll('ul.numberList') But I want to exclude some of them by their id's. A: You can use attribute contains selector with :not() pseudo-class selector document.querySelectorAll('ul.numberlist li:not([id*="test"])') console.log(document.querySelectorAll('ul.numberlist li:not([id*="test"])').length) <ul class="numberlist"> <li id="test1" style="display:none"> <div></div> </li> <li> <a>one</a> </li> <li> <a>two</a> </li> <li> <a>three</a> </li> <li id="test2" style="display:none"> <div></div> </li> <li> <a>four</a> </li> <li id="test" style="display:none"> <div></div> </li> </ul> FYI : document.querySelectorAll('ul.numberList') , doesn't get all li element, instead which gets all ul with class numberList. To get all li inside use selector as ul.numberList li. Also in your html class name is numberlist not numberList.
{ "pile_set_name": "StackExchange" }
Q: In cross validation, higher the value of k, lesser the training data for this formula? Is it right to say that smaller the value of k in cross validation based on the following formula, more the number of records in test data/smaller the number of records in training data. According to me, these are the proportions of train and test data depending on the value of k for the following formula. x.train = x.shuffle[which(1:nrow(x.shuffle)%%folds != i%%folds), ] x.test = x.shuffle[which(1:nrow(x.shuffle)%%folds == i%%folds), ] Proportion of train and test data depending on the value of k At k==10, train:test = 9:1, ie, traindata = 90%, testdata = 10% At k== 9, train:test = 8:1 At k== 8, train:test = 7:1 At k== 7, train:test = 6:1 At k== 6, train:test = 5:1 At k== 5, train:test = 4:1, ie, traindata = 80%, testdata = 20% At k== 4, train:test = 3:1 At k== 3, train:test = 2:1 At k== 2, train:test = 1:1, ie, traindata = 50%, testdata = 50% At k== 1, train:test = 0:1, ie, traindata = 0%, testdata = 100% A: Yes, you can say that (and your train/test ratios are also correct). Although, $k=1$ doesn't really make sense. The most common choice is $k=10$ (paper reference [PDF]).
{ "pile_set_name": "StackExchange" }
Q: Sending signals to PC over wifi I need a microcontroller that would send statuses of it's input pins (around 5 of them, they can be 0 or 1) to a PC over wifi. I thought of using arduino, but I don't know what would I need to make it able to send data over wifi? Some wifi module? And would that be a good combination? This is a part of a device which is going to be on the hand, so it needs to be small and battery powered. (It should send statuses of it's pins at speed of around 15 times a second, and I'll need it to have one output pin set to 1, so I could send that signal to input pins) And since arduino is a bit bigger in size than I would like and it's made for much more advanced stuff I'm not sure if it would be the best choice. So can anyone tell me what kind of microcontroller do I need and how to use wifi with it? (I have some experience with arduino, but not with using wifi or other form of remote communication with electronics. If something about the question is unclear please ask in the comments. Thanks) A: For establishing a communication between a computer and an MCU I strongly suggest you to use Texas Instrument's CC3000 Wi-Fi chip with an Arduino (Easiest way to accomplish what you need). Adafruit and SparkFun introduced breakout* and shield** versions of the Wi-Fi chip. It is easy to use, just connect the wires and start communicating. There is a strong library support of these products. Either of it can be found in relevant websites. You can send http requests to arduino or you can get http requests from arduino using these libraries. There are a lot of examples, sketches of this product. One of them is Wi-Fi weather station. Check the video, I believe this is what you want to accomplish. *Adafruit's breakout *SparkFun's breakout **Adafruit's shield **SparkFun's shield A: Arduino is a good starting point. There is a WiFi Shield available. Your question, "What kind of microcontroller do I need?" is too broad. There are literally hundreds if not thousands of microcontrollers that you could potentially use. So how do you go about selecting one? First, there are many manufacturers such as Microchip (PIC), Freescale, Atmel (AVR), etc. Selecting one is largely preference, but also highly dependent on support, price, reputation, available tools/software, feature offerings, etc. PIC and AVR are, for example, very popular platforms for 8- to 32-bit microcontrollers. The Arduino Uno is based on the Atmel ATmega328 8-bit microcontroller. Let's say you pick AVR after becoming familiar with Arduino as a starter platform. (This is what I did.) Atmel has a microcontroller selector which gives you a parametric selection matrix to help you narrow down choices. The available microcontrollers are quite numerous, and some are purpose-made with specific applications in mind, such as portable music players, automotive applications, touch-based devices, and so on. Using the selector, you can filter by such properties as memory size, pin count, CPU speed and type, temperature range, included timers and interrupts, external oscillator support, etc. From what you've explained of your application, you are simply reading the state of five input pins and need to send that to a PC over a wireless (presumably ethernet) network at a rate of 15 Hz. The minimum requirement for that would be, obviously, at least 5 I/O pins, plus a way to connect to another component to send the data. SPI and I2C are common interface types, requiring two to four pins, depending on configuration. The WiFi Shield for Arduino that I mentioned earlier uses SPI to connect to the Arduino. In the case of the WiFi Shield, all of the processing required for handling TCP/IP, encryption, and so on, is built into the board. If you decide to design and build your own microcontroller-based device, you could potentially find WiFi modules designed to "plug and play" with a microcontroller via SPI, or select individual components and create your own WiFi implementation. Personally, that would be a daunting task, especially if you're not familiar with microcontroller basics. This site is not suited for product recommendations, but I can at least tell you to look for "WLAN Modules" or "WiFi Modules" at your favorite electronics component vendor. You can use their search tools to find modules that suit your needs, including the connection type you intend to use with your microcontroller. If you're doing a one-off, or just getting started in learning, I would definitely recommend picking up an Arduino and the WiFi Shield. There is a lot of support for it, most of the difficult work has already been done, and there's even an Arduino StackExchange site.
{ "pile_set_name": "StackExchange" }
Q: Recurse for object if exists in JQ I have the following structure: { "hits": [ { "_index": "main" }, { "_index": "main", "accordions": [ { "id": "1", "accordionBody": "body1", "accordionInnerButtonTexts": [ "button11", "button12" ] }, { "id": "2", "accordionBody": "body2", "accordionInnerButtonTexts": [ "button21", "button22" ] } ] } ] } I want to get to this structure: { "index": "main" } { "index": "main", "accordions": [ { "id": "1", "accordionBody": "body1", "accordionInnerButtonTexts": [ "button11", "button12" ] }, { "id": "2", "accordionBody": "body2", "accordionInnerButtonTexts": [ "button21", "button22" ] } ] } Which means that I always want to include the _index-field as index, and I want to include the whole accordions-list IF IT EXISTS in the object. Here is my attempt: .hits[] | {index: ._index, accordions: recurse(.accordions[]?)} It does not produce what I want: { "index": "main", "accordions": { "_index": "main" } } { "index": "main", "accordions": { "_index": "main", "accordions": [ { "id": "1", "accordionBody": "body1", "accordionInnerButtonTexts": [ "button11", "button12" ] }, { "id": "2", "accordionBody": "body2", "accordionInnerButtonTexts": [ "button21", "button22" ] } ] } } { "index": "main", "accordions": { "id": "1", "accordionBody": "body1", "accordionInnerButtonTexts": [ "button11", "button12" ] } } { "index": "main", "accordions": { "id": "2", "accordionBody": "body2", "accordionInnerButtonTexts": [ "button21", "button22" ] } } It seems to create a list of all different permutations given by mixing the objects. This is not what I want. What is the correct jq command, and what is my mistake? A: The problem as stated does not require any recursion. Using your attempt as a model, one could in fact simply write: .hits[] | {index: ._index} + (if has("accordions") then {accordions} else {} end) Or, with quite different semantics: .hits[] | {index: ._index} + . | del(._index)
{ "pile_set_name": "StackExchange" }
Q: How to save 2 data from SQL into 2 different PHP variables? I'm fetching data from 2 tables with one common column and and the query is returning values as expected. How to save these two values "Normal" and "Normal" gotten from "disease" and "cases" column, into 2 different variables in PHP? This is my query: SELECT healthdb.disease, criminaldb.cases FROM criminaldb NATURAL JOIN healthdb WHERE aadharnos = {$aadharnos}; The output was: How to save this text "Normal" in PHP variable {$case} and other value, "Normal" in another PHP variable {$disea} so that I can compare them within if condition for my next part of my code A: You can use fetch-assoc so you will have all the data return from the SQL query in PHP variable. Consider the following: $query = "SELECT healthdb.disease, criminaldb.cases FROM criminaldb NATURAL JOIN healthdb WHERE aadharnos = $aadharnos;"; $results = $connectToDb->query($query); while($row = $results->fetch_assoc()){ print_r($row); //here you can access the row data returned and save your data in local variable $crim = $row["cases"]; $dis = $row["disease"]; if($crim == "Normal" AND $dis == "Normal) { // or you can just do: if($row["cases"] == "Normal" AND $row["disease"] == "Normal) { //some code } }
{ "pile_set_name": "StackExchange" }
Q: How to get the value of a disabled text field in jsp I am having a dropdown box and a 5 textfields( all disabled). I am entering data into textfield by using javascript, from the dropdown(what ever value is present in the dropdown, goes into the text fields). Now, when the submit button is clicked, I want to get the value from this text field in the action class(java). On testing, I was getting "null" [getParameterValues("textfieldname") is what I have done]. When I removed the disabled, I was getting the value. So, how can I get the value while the disabled, is applied to the text field ? A: Instead of disable them make them readonly. <input type="text" name="nameOfTextField" readonly="readonly" />
{ "pile_set_name": "StackExchange" }
Q: How to reset/restore to original spawn I am trying to mock spawn process using mock-spawn module. The subsequent test are failing since I am not able to restore the mock. I tried with mySpawn.resotre() but there is no such function. I checked the code still not able to figure it out. Can anyone please help me on this. A: I had similar requirement, this is the comment from mock-spawn contributor You can simply require('child_process').spawn if you need the original back. If you have overridden that, you should save the original before and reset the child_process spawn property to the saved original. Ref: https://github.com/gotwarlost/mock-spawn/issues/13#issuecomment-342589086
{ "pile_set_name": "StackExchange" }
Q: Remove User search limit per month PDO::MYSQL How can I have PHP remove a users limit every month I have this code to increment a users search limit and if they reach their limit $search = $db->prepare("SELECT `searched` FROM `search` WHERE `user_id` =:user_id"); $search->bindValue(':user_id', $vbulletin->userinfo['userid'], PDO::PARAM_INT); $search->execute(); $result = $search->fetch(PDO::FETCH_ASSOC); if ($result['searched'] >= 100){ exit('You have reached your search limit for this month.<br>'); } $addsearch = $db->prepare("UPDATE `evomap`.`search` SET `searched` = :searched + 1 WHERE `search`.`id` =:user_id;"); $addsearch->bindValue(':user_id', $vbulletin->userinfo['userid'], PDO::PARAM_INT); $addsearch->bindValue(':searched', $result['searched'], PDO::PARAM_STR); $addsearch->execute(); /* page i want to execute if user has no reached limit */ A: You might better have a column with a month timestamp, being set to a date, when user has reached 100 searches, then checking if current month != timestamp. But you can also try MySQL events. Something like: DELIMITER $$ CREATE EVENT search_removal ON SCHEDULE EVERY MONTH DO BEGIN UPDATE search SET searched = 0; END; $$;
{ "pile_set_name": "StackExchange" }
Q: Is there a way to get a non-node result from MSXML XPath evaluator? I understand that the name of selectNode/selectSingleNode methods actually suggests that they are designed to return a node, however maybe there is some other way or a setting available to enable XPath evaluator to return data of other types (that are also valid XPath results) oDocument.selectSingleNode("'1'"); throws an error "Expression does not return a DOM node" I want to query oDocument.selectSingleNode("concat(@day, '-', @month, '-', @year") and get a result (that is possible with standard DOM XPath API). Indeed I can query for nodes and then traverse them with DOM, however this would be way to inefficient. A: selectSingleNode() and selectNodes() select nodes identified by an XPath expression. Their return values are of type IXMLDOMNode and IXMLDOMNodeList, respectively. Nothing else can be returned. Expressions that do not return a node set (but otherwise are valid XPath expressions) will result in an error.
{ "pile_set_name": "StackExchange" }
Q: Steamer with single vent instead of bottom holes My family has owned a stainless steel steamer for a long time with a single raised vent to let steam into the upper compartment. It's great because there's no way for food to get into the bottom compartment so it (mostly) never has to be washed. It only ever contains water. I really want to buy one of these but the only steamers I can find for sale have a perforated bottom in the upper compartment. Does anyone know where I can buy one or if any company still manufactures these? A: I have a stainless steel steamer/juicer similar to the one picture w/o perforation. It has a tube that dispels the juice into any container you choose right from the middle pan as it extracts. I purchased mine from Amazon and it is a product of Cook N Home.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use a value from a result to union another result into the previous resultset? So let's say that I have a table, BMST. I use this query to find a result set: SELECT PARENT, CHILD, LEVEL, QTY FROM BMST WHERE PARENT = '111' In the result set are PARENT part numbers, as well as CHILD part numbers such as: PARENT | CHILD | LEVEL | QTY ----------------------------- 111 | 222 | 0 | 2 111 | 333 | 0 | 1 111 | 444 | 0 | 1 The table gives information on all the CHILD parts that are used to make the PARENT part, as well as the QUANTITY of CHILD parts used in each PARENT part. The LEVEL column has a value of '0' because part '111' is the origin part that we care about. We do not care if part '111' is a CHILD part to another larger PARENT part. It is possible for CHILD parts to be PARENT parts as well if they are made up of smaller CHILD parts. For example, this query: SELECT PARENT, CHILD, LEVEL, QTY FROM BMST WHERE PARENT = '222' would return: PARENT | CHILD | LEVEL | QTY ----------------------------- 222 | 555 | 1 | 1 222 | 666 | 1 | 1 222 | 777 | 1 | 1 The LEVEL value in this new table is '1' because the part '222' is a CHILD part of a LEVEL = '0' PARENT part. Going even further, the CHILD parts of part '222' could have CHILD parts themselves, so that a similar query for part '777' would return: PARENT | CHILD | LEVEL | QTY ----------------------------- 777 | 999 | 2 | 2 My question is, would it be possible to create a query that would return the first result set, and then check all of the CHILD part values within that result set to see if those have any CHILD parts, and then checks the resulting CHILD parts for even more CHILD parts, etc. until there are no more CHILD parts, and then UNION those that do into the first result set so it looks like: PARENT | CHILD | LEVEL | QTY ----------------------------- 111 | 222 | 0 | 2 222 | 555 | 1 | 1 222 | 777 | 1 | 1 777 | 999 | 2 | 2 222 | 888 | 1 | 1 111 | 333 | 0 | 1 111 | 444 | 0 | 1 The LEVEL value needs to increment for every step deeper that the query goes, and the end result set should show every single part that goes into the requested PARENT part. Is there a way to do all of this in SQL? Or do I have to use VB6 or another program to iterate through the loops? Any and all feedback is appreciated. A: To do what you want you will need something called recursion. Ofcourse, you can parse it line by line (with T-SQL, or with VB, or whatever language you are comfortable in), however, this problem (recursion) is very easy to solve with something called Common Table Expressions or CTE. With a CTE you are able to union against your result, so a PARENT-CHILD relation where the CHILD can be a PARENT is solveable in this case. I have created this script to show you how. First i populate some Temp tables, after that i am querying using the CTE if object_id('tempdb..#BMST') is not null begin drop table #BMST end create table #BMST ( PARENT varchar(5) , CHILD varchar(5) , LEVEL varchar(5) , QTY varchar(5) ) insert into #BMST select '111', '222', 0, 2 union all select '111', '333', 0, 1 union all select '111', '444', 0, 1 union all select '222', '555', 1, 1 union all select '222', '666', 1, 1 union all select '222', '777', 1, 1 union all select '777', '999', 2, 2 Blow is the CTE. A Common Table Expression always has to be the first statement, so a semicolon is used for that. After that a with xxx as () construction starts. The results is a fictional name and can be anything. (In this example i used a new colom SECONDLEVEL to show you the new level) ;with results as ( select * , 0 as SECONDLEVEL from #BMST b union all select b.* , r.SECONDLEVEL + 1 as SECONDLEVEL from #BMST b inner join results r on r.CHILD = b.PARENT and b.LEVEL > r.LEVEL ) select * from results As you can see, i am using an UNION ALL operator. The top part is querying the #temp table, and it the bottom part it is using that to join to results that are already fetched. And that's it. You have recursion now.
{ "pile_set_name": "StackExchange" }
Q: DQ currents of BLDC I am trying to apply FOC scheme with SVPWM for controlling a BLDC and comparing the resuls with trapezoidal commutation. I have my BLDC model and it is working correctly with trapezoidal commutation. My sign convention is positive speed CCW and when the motor is turning CCW, stators are located as A-B-C, stator A is located at electrical 0 degree. When i drive the motor with trapezoidal commutation i am measuring the phase currents and applying the DQ transformation to measured currents. When i apply the transformation i can see that trapezoidal commutation forces D current to stay as close as to zero, however Q has negative value under this sign convention. The thing that i am trying to understand is if i force D current to be zero in FOC (as it suggested in all papers), Q current supposed to have negative reference for positive speed but in the suggested FOC schemes, Q reference is generated with speed reference and has positive sign for positive speed references. When i apply the FOC scheme it simply does not work because of this problem, Q goes negative for positive set points whereas controller tries to drive Q to a positive value. A: Nice show. Your Clarke/Park seem to work properly. You have almost zero Id and almost constant Iq with ripples, which is normal if you run in six-step commutation. From my intuition, you have wrong current measurements. Everything behaves as the phasor diagram is flipped, that means that Ia = -Ia, I =-Ib, Ic = -Ic. Could be current sensor swapped, or the opamp measuring configuration.
{ "pile_set_name": "StackExchange" }
Q: Solve RTL children ordering in Chrome In the following MWE, a span and a div are placed inside an RTL div, and their order is swapped in Firefox but not in Chrome (no idea what it shows in IE...). <html> <body> <div dir="rtl"> <span id="empty-span"></span> <div>This is arabic!</div> </div> <script> var anchorEl = document.getElementById('empty-span'); var anchorRect = anchorEl.getBoundingClientRect(); console.log(anchorRect); </script> </body> </html> Firefox places the span to the right of the div, while Chrome keeps it to the left. (The exact value shown in the console depends on your screen size.) Firefox: ClientRect {left: 700, right: 700, ...} Chrome: ClientRect {left: 8, right: 8, ...} I need the Firefox behavior, because the span is the target of a tooltip that should be placed near the text. I'm fairly new to web development, so what is the best approach: use another type of hidden element to anchor the tooltip, place the span differently depending on the browser, or what? Just for clarity, there's no dir="rtl" attribute in fact, but the problem shows in Arabic and Hebrew locales. I just used it so people won't need to change their default language to reproduce. A: In my opinion, handling of the dir attribute isn't especially well specified, which could explain why different browsers handle your situation differently. I'm guessing that since your <span> element is empty, and since it is retaining its default display property of inline, it no defined dimensions on the page. Chrome is optimizing by simply not bothering to apply the rtl formatting to it. When you change the display property to inline-block, you're giving the <span> a height and width, albeit 0. Chrome is "smart" enough to optimize when the element has no height and width defined, but it doesn't go the extra step of optimizing when the element has a defined height and width of 0. That's just a guess, though. FWIW, I've found the CSS direction property to be more reliable than the dir attribute.
{ "pile_set_name": "StackExchange" }
Q: Creating object in C++ I am new to C++. Here's my problem. I declare bus, stepper as private instances in the h file: class Motor_control { public: ... private: IICBus bus ; IICStepper stepper ; IICStepper stepper_r ; IICStepper stepper_l ; }; And then initiate them in the constructor Motor_control::Motor_control(){ IICBus bus ("/dev/i2c-2",0,""); IICStepper stepper (bus,0x00, "Global addr"); IICStepper stepper_r (bus,0x6e, "Stepper Modul"); IICStepper stepper_l (bus,0x66, "Stepper Modul"); } IICStepper was declared in .cpp: IICStepper::IICStepper(IICBus& bus, int addr, const string& name) : IICBase(bus,addr, name) { } in cpp and in .h: class IICStepper : public IICBase { public: IICStepper(IICBus& bus, int addr, const std::string& name); virtual ~IICStepper(){}; ...} It compalins ../src/Motor_control.h:15: error: no matching function for call to 'IICStepper::IICStepper()' ../src/Stepper.h:41: note: candidates are: IICStepper::IICStepper(IICBus&, int, const std::string&) ../src/Stepper.h:38: note: IICStepper::IICStepper(const IICStepper&) ../src/Motor_control.h:15: error: no matching function for call to 'IICBus::IICBus()' ../src/Bus.h:28: note: candidates are: IICBus::IICBus(const std::string&, int, const std::string&) ../src/Bus.h:17: note: IICBus::IICBus(const IICBus&) ../src/Motor_control.h:15: error: no matching function for call to 'IICStepper::IICStepper()' ../src/Stepper.h:41: note: candidates are: IICStepper::IICStepper(IICBus&, int, const std::string&) ../src/Stepper.h:38: note: IICStepper::IICStepper(const IICStepper&) ../src/Motor_control.h:15: error: no matching function for call to 'IICStepper::IICStepper()' ../src/Stepper.h:41: note: candidates are: IICStepper::IICStepper(IICBus&, int, const std::string&) ../src/Stepper.h:38: note: IICStepper::IICStepper(const IICStepper&) ../src/Motor_control.h:15: error: no matching function for call to 'IICStepper::IICStepper()' ../src/Stepper.h:41: note: candidates are: IICStepper::IICStepper(IICBus&, int, const std::string&) ../src/Stepper.h:38: note: IICStepper::IICStepper(const IICStepper&) A: Before the constructor body enters, all user types are initialized. Because you don't have default constructors for IICStepper, you'll get the errors. You need to use initializer lists: Motor_control::Motor_control() : bus("/dev/i2c-2", 0, ""), stepper(bus, 0, "Global addr"), stepper_r(bus, 0x6e, "Stepper Modul"), stepper_l(bus, 0x66, "Stepper Modul") { } Your version not only doesn't initialize the members, it creates new temporary objects which you never use afterwards.
{ "pile_set_name": "StackExchange" }
Q: CSS to rotate an image/icon(spinner) in IE11 Css to convert an icon/image into spinner add following properties to the class of that icon/image .spinner{ -webkit-animation: load3 1.4s infinite linear; animation: load3 1.4s infinite linear; -ms-transform: translateZ(0); transform: translateZ(0); } A: add this to your CSS and you'll have a rotating image @keyframes load3 { from { -ms-transform: rotate(0deg); -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } to { -ms-transform: rotate(360deg); -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } }
{ "pile_set_name": "StackExchange" }
Q: Rapidshare premium download (c#) Is there a way to download a file using a rapidshare premium account with c# or java? A: RapidShare has an API you might want to look into.
{ "pile_set_name": "StackExchange" }
Q: How to check if QSpinBox value changed by keyboard or buttons(mouse wheel) I need to set spinbox value to one of 1, 10, 100, 1000, 10000 if value changed by spinbox buttons or mouse wheel or up or down keys. But if value changed by keyboard I need other behavior. Here is my code for buttons, mouse wheel, up and down keys. void Dlg::onValueChanged(int value) { if (value > _value) value = (value - 1) * 10; value = log10(value); value = _Pow_int(10, value); _ui->spinBoxs->setValue(_value = value); } How can I make other behavior for value changing by keyboard? A: In this case I think you will have create your custom spinbox derived from QSpinBox. And you will need to reimplement at least the following functions: virtual void keyPressEvent( QKeyEvent* event ); virtual void wheelEvent( QWheelEvent* event ); with your specification.
{ "pile_set_name": "StackExchange" }
Q: Why is a (non-)degenerate semiconductor called (non-)degenerate? In a non-degenerate semiconductor with (Ec-Ef) > 4kT separation, Maxwell-Boltzmann distribution can be used for simplification. I do not get why the term non-degenerate is used in this context? Degeneracy refers to multiple states having equal energies. Does the term degeneracy have different meanings in different contexts? Points where different bands cross are also referred to as degenerate points. At high dopings, dopants also form a band which can interact with the semiconductor bands. Is this interaction (band crossing) causing the degeneracy leading to a the term degenerate semiconductor? Can someone shed some light on this concept of degeneracy? Thanks A: When used in reference to a semiconductor, the term "degenerate" means that it is doped so much that the material has metallic properties such as a Fermi surface and high electrical conductivity. To be strictly correct, it is more appropiate to say that the semiconductor "has degenerate electron statistics" when said statistics are only appropiately described by a Fermi-Dirac distribution at thermal equilibrium, which is the case when the semiconductor is highly doped. However, the phrase "degenerate semiconductor" is considered acceptable shorthand for the term "semiconductor with degenerate electron statistics". Evidently, this concept of degeneracy is different from the degeneracy of energy states, in which the term is also often used in solid-state physics. However, the degeneracy of the energy of the eigenstates of a Hamiltonian is just an instance of a broader mathematical concept of degeneracy, which applies when multiple members of a set share a common characteristic, such as the value of their energy. Off the top of my head, a classical system of coupled harmonic oscillators may have degenerate oscillation modes, sharing a common frequency. Propagating electromagnetic modes in a waveguide can be said to be degenerate if they have the same propagation constant. The concept of degenerate electron bands, as you say, is then that of two different bands which share states with common Bloch wave vector (up to the addition of a reciprocal lattice vector) and energy. This concept is clearly different from that of the degeneracy of the electron statistics of a doped semiconductor, which, again, qualifies if Fermi-Dirac statistics are necessary to describe the occupation of electronic states in thermal equilibrium.
{ "pile_set_name": "StackExchange" }
Q: How to do in-code bindings on Windows Phone 8 I'm trying to do in-code binding on Windows Phone 8, like in the question "How to do CreateBindingSet() on Windows Phone?" How to do CreateBindingSet() on Windows Phone? I think I have done the steps as suggested by Stuart, but I keep getting exception error or output error "MvxBind:Warning: 9,86 Failed to create target binding for binding _update for TextUpdate" In Droid it works very well, so what am I doing wrong, missing or don't see? Any suggestions? I have the following setup in the Phone part. Setup.cs: using Cirrious.CrossCore.Platform; using Cirrious.MvvmCross.BindingEx.WindowsShared; using Cirrious.MvvmCross.ViewModels; using Cirrious.MvvmCross.WindowsPhone.Platform; using Microsoft.Phone.Controls; namespace DCS.Phone { public class Setup : MvxPhoneSetup { public Setup(PhoneApplicationFrame rootFrame) : base(rootFrame) { } protected override IMvxApplication CreateApp() { return new Core.App(); } protected override IMvxTrace CreateDebugTrace() { return new DebugTrace(); } protected override void InitializeLastChance() { base.InitializeLastChance(); var builder = new MvxWindowsBindingBuilder(); builder.DoRegistration(); } } } ServerView.xaml: <views:MvxPhonePage x:Class="DCS.Phone.Views.ServerView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:views="clr-namespace:Cirrious.MvvmCross.WindowsPhone.Views;assembly=Cirrious.MvvmCross.WindowsPhone" xmlns:converters="clr-namespace:DCS.Phone.Converters" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" mc:Ignorable="d" shell:SystemTray.IsVisible="True"> <!--LayoutRoot is the root grid where all page content is placed--> <Grid x:Name="LayoutRoot" Background="Transparent"> <!--used as dummy bool to call Update callback through converter --> <CheckBox x:Name ="DummyUpdated" Height ="0" Width ="0" Content="" Visibility="Visible" IsChecked="{Binding TextUpdate, Converter={StaticResource Update }, ConverterParameter=ServerView}"></CheckBox> <ScrollViewer x:Name="ScrollView" Height="760" Width ="480" VerticalAlignment="Top"> <Canvas x:Name="View" Top="0" Left="0" Margin ="0" Background="Transparent" Height="Auto" Width ="Auto"/> </ScrollViewer> </Grid> </views:MvxPhonePage> ServerView.xaml.cs: using System.Windows; using Cirrious.MvvmCross.Binding.BindingContext; using Cirrious.MvvmCross.WindowsPhone.Views; using DCS.Core; using DCS.Core.ViewModels; using DCS.Phone.Controls; namespace DCS.Phone.Views { public partial class ServerView : MvxPhonePage,IMvxBindingContextOwner { private bool _isUpdating; private bool _update; private DcsText _text; private DcsInput _input; private DcsList _list; private DcsButton _button; public IMvxBindingContext BindingContext { get; set; } public ServerView(){ InitializeComponent(); BindingContext = new MvxBindingContext(); Loaded += new RoutedEventHandler(MainPage_Loaded); } private void MainPage_Loaded(object sender, RoutedEventArgs e){ CreateControls(); } private void CreateControls() { //User controls _text = new DcsText(View); _input = new DcsInput(View, View, DummyUpdated); _list = new DcsList(View); _button = new DcsButton(View); //Bindings var set = this.CreateBindingSet<ServerView, ServerViewModel>(); set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); for (int i = 0; i < Constants.MaxButton; i++){ set.Bind(_button.Button[i]).To(vm => vm.ButtonCommand).CommandParameter(i); } set.Apply(); AppTrace.Trace(string.Format("OnCreate Finish")); } protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){ base.OnNavigatedTo(e); BindingContext.DataContext = this.ViewModel; } } } I get the following errors when I try to do set.Apply(); Exception at set.Apply(); var set = this.CreateBindingSet<ServerView, ServerViewModel>(); for (int i = 0; i < Constants.MaxButton; i++){ set.Bind(_button.Button[i]).To(vm => vm.ButtonCommand).CommandParameter(i); } set.Apply(); System.NullReferenceException was unhandled by user code HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=Cirrious.MvvmCross.BindingEx.WindowsPhone StackTrace: at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxDependencyPropertyExtensionMethods.EnsureIsDependencyPropertyName(String& dependencyPropertyName) at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxDependencyPropertyExtensionMethods.FindDependencyPropertyInfo(Type type, String dependencyPropertyName) at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxDependencyPropertyExtensionMethods.FindDependencyProperty(Type type, String name) at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxBinding.MvxWindowsTargetBindingFactoryRegistry.TryCreatePropertyDependencyBasedBinding(Object target, String targetName, IMvxTargetBinding& binding) at Cirrious.MvvmCross.BindingEx.WindowsShared.MvxBinding.MvxWindowsTargetBindingFactoryRegistry.TryCreateReflectionBasedBinding(Object target, String targetName, IMvxTargetBinding& binding) at Cirrious.MvvmCross.Binding.Bindings.Target.Construction.MvxTargetBindingFactoryRegistry.CreateBinding(Object target, String targetName) at Cirrious.MvvmCross.Binding.Bindings.MvxFullBinding.CreateTargetBinding(Object target) at Cirrious.MvvmCross.Binding.Bindings.MvxFullBinding..ctor(MvxBindingRequest bindingRequest) at Cirrious.MvvmCross.Binding.Binders.MvxFromTextBinder.BindSingle(MvxBindingRequest bindingRequest) at Cirrious.MvvmCross.Binding.Binders.MvxFromTextBinder.<>c__DisplayClass1.<Bind>b__0(MvxBindingDescription description) at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at Cirrious.MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.AddBindings(IMvxBindingContextOwner view, IEnumerable`1 bindings, Object clearKey) at Cirrious.MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.AddBindings(IMvxBindingContextOwner view, Object target, IEnumerable`1 bindingDescriptions, Object clearKey) at Cirrious.MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.AddBinding(IMvxBindingContextOwner view, Object target, MvxBindingDescription bindingDescription, Object clearKey) at Cirrious.MvvmCross.Binding.BindingContext.MvxBaseFluentBindingDescription`1.Apply() at Cirrious.MvvmCross.Binding.BindingContext.MvxFluentBindingDescriptionSet`2.Apply() at DCS.Phone.Views.ServerView.CreateControls() at DCS.Phone.Views.ServerView.MainPage_Loaded(Object sender, RoutedEventArgs e) at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName) InnerException: Output at set.Apply(); var set = this.CreateBindingSet<ServerView, ServerViewModel>(); set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); set.Apply(); MvxBind:Warning: 9,86 Failed to create target binding for binding _update for TextUpdate Just to clerify. set.Bind(this).For(v => v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); gave the warning on set.Apply() MvxBind:Warning: 9,86 Failed to create target binding for binding _update for TextUpdate Using the public bool Update did solve the set.Apply() problem, but I don't get the binding. In Droid all these are working set.Bind(this).For("_update").To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); set.Bind("_update").To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); set.Bind(this).For(v=>v._update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); set.Bind(this).For(v=>v.Update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); set.Bind("Update").To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); set.Bind(_button.Button[i]).To(vm => vm.ButtonCommand).CommandParameter(i); gave the exception: A: Looking at the stack trace, the code is failing on: https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.BindingEx.WindowsPhone/MvxDependencyPropertyExtensionMethods.cs#L113 private static void EnsureIsDependencyPropertyName(ref string dependencyPropertyName) { if (!dependencyPropertyName.EndsWith("Property")) dependencyPropertyName += "Property"; } So this would suggest that the dependencyPropertyName name being passed to the method is null. My guess is that this is because _update is not a property and not public. MvvmCross binding works on properties - and .Net security forces it to only work with public (although you could use internal with a little assembly:InternalsVisibleTo code). Try replacing _update with a public property with both get and set access - e.g.: public bool Update { get { return _update; } set { _update = value; /* do something with the new value? */ } } with: set.Bind(this).For(v => v.Update).To(vm => vm.TextUpdate).OneWay().WithConversion("Update", this); Aside: In non-Windows binding this problem would result in a much nicer error message - Empty binding target passed to MvxTargetBindingFactoryRegistry from https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding/Bindings/Target/Construction/MvxTargetBindingFactoryRegistry.cs#L34 - will put on the todo list for Windows too.
{ "pile_set_name": "StackExchange" }
Q: listen for any div that goes from display: none to display:block Is there any way to listen for elements being shown or hidden? I would like categorically to--whenever an element goes from hidden to shown--put focus on the first input element within the newly shown element I thought of attaching a click event to everything and putting it at the top of the document, thinking that would trigger before anything and I could track whether the clicked element's next("div") (or something) would have a css display property of none, then setting a small timeout, then setting the focus, but I get undefined when I try to access that CSS property $("html").on("click", "body", function(){ alert($(this).next("div").css("display")); //undefined }); Is there a way to do this? A: You can try something like this (it’s kind of a hack). If you monkey-patch the css/show/hide/toggle prototypes in jQuery, you can test if the element changes it’s :hidden attribute after a "tick" (I used 4ms). If it does, it has changed it’s visibility. This might not work as expected for animations etc, but should work fine otherwise. DEMO: http://jsfiddle.net/Bh6dA/ $.each(['show','hide','css','toggle'], function(i, fn) { var o = $.fn[fn]; $.fn[fn] = function() { this.each(function() { var $this = $(this), isHidden = $this.is(':hidden'); setTimeout(function() { if( isHidden !== $this.is(':hidden') ) { $this.trigger('showhide', isHidden); } },4); }); return o.apply(this, arguments); }; }) Now, just listen for the showhide event: $('div').on('showhide', function(e, visible) { if ( visible ) { $(this).find('input:first').focus(); } }); Tada! PS: I love monkeypatching
{ "pile_set_name": "StackExchange" }
Q: How to remove a file from Git Pull Request I have a pull request opened where I have some project.lock.json files which I do not want to merge while merging my branch to main branch. Is there a way to remove thos project.lock.json files from my Pull Request? A: Please do let me know if there is a better way of doing this. This is the workaround I have found. list remote branches git branch -va checkout the PR branch git checkout origin pr_branch overwrite pr_branch's file with other_branch's file git checkout other_branch -- ./path/to/file commit changes git commit -m "overwrite with other_branch's" push your changes git push origin pr_branch A: You need to remove file, commit changes and make next push to your branch. If you want leave file in your branch, but not to merge it to main branch, you can delete it in one commit, then add again in another. Git allows you manually accept certain commits using git-cherry-pick. You can accept each commit except that in which you have added this file again.
{ "pile_set_name": "StackExchange" }
Q: What does it mean? A record deal? And hating on somebody? Some people started hating on my friend when she got a record deal. A record deal? what kind of a deal is it? Does the word "hating" mean envious? A: In this context, a record deal could mean one of two things: It could refer to a recording contract, where a performing artist signs a contract with a record label, also known as a recording studio. For example: Beyonce signed a new record deal with Arista. Her new album will be released next year. Or, it could refer to a deal that sets a new record (for something like salary) in any industry; for example, it would make your friend the highest-paid athlete in the history of her sport. Rousey signed a record deal that will pay her 40 million dollars over the next five years. There is no way to tell which your sentence means without surrounding context, which is why we often exhort users to provide context when they ask questions here on ELL. And, yes, I would guess the word "hating" here refers to being envious.
{ "pile_set_name": "StackExchange" }
Q: Take an unknown format string and return a UTF-8 string The following two strings are different in format but identical in data: str1 = '\xd7\x91\xd7\xa8\xd7\xa7' str2 = u'\u05d1\u05e8\u05e7' I need to implement the following function: Take a string in either one of the formats above as input Return the equivalent string in the first format as output I know that I can encode a string from the second format into the first format. But how do I determine that the input string is indeed given in the second format? A: For Python 3.x, the right thing to do would probably be to try to call encode. (For 3.5+, this will hopefully be as simple as try s.encode('utf-8') except AttributeError: s.) But for 2.x, the encode will succeed even on str1—by first decoding the UTF-8 string as ASCII (or whatever sys.getdefaultencoding() returns) so it can re-encode it, so you definitely don't want that. When there is no way to safely EAFP, you have no choice but to LBYL. So: if isinstance(s, unicode): return s.encode('utf-8') else: return s Note that I'm using isinstance here, not calling type and comparing. As PEP 8 says: Object type comparisons should always use isinstance() instead of comparing types directly. Why? Because instances of subtypes (subclasses, classes registered with ABCs, etc.) are, by definition, supposed to always count as instances of their supertypes. There are some rare cases where you explicitly need to break that rule, in which case type comparisons are what you want. But otherwise, don't use them.
{ "pile_set_name": "StackExchange" }
Q: iOS - Passing LaunchOptions to a sub-method Im trying to add an asyncronous lookup for Push Notifications and I'm having a problem passing launchOptions to the*@selector. Can you please tell me what I need to change? - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { /* Operation Queue init (autorelease) */ NSOperationQueue *queue = [NSOperationQueue new]; /* Create NSInvocationOperation to call loadDataWithOperation, passing in nil */ NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(setupPushNotifications) object:launchOptions]; [queue addOperation:operation]; /* Add the operation to the queue */ [operation release]; } and -(void)setupPushNotifications:(NSDictionary *)launchOptions { //Init Airship launch options NSMutableDictionary *takeOffOptions = [[[NSMutableDictionary alloc] init] autorelease]; [takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey]; // Create Airship singleton that's used to talk to Urban Airship servers. // Please populate AirshipConfig.plist with your info from http://go.urbanairship.com [UAirship takeOff:takeOffOptions]; NSLog(@"Registering for Notifications"); // Register for notifications [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; } A: change NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(setupPushNotifications) object:launchOptions]; to NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(setupPushNotifications:) object:launchOptions];
{ "pile_set_name": "StackExchange" }
Q: Can you get the filename of the jsp file using a taglib in the taglib code Is it possible to get the filename of the jsp file that uses a taglib from the java code? I.e. public int doStartTag() throws JspException { try { String xxx = pageContext.? Where xxx would get the filename of the jsp file (which of course could be a nested include file) br /B A: It's not possible to get the name of the JSP file simply because at this point it has been compiled and you're dealing with compiled version rather than source JSP file. You can get the name of the class JSP has been compiled into via pageContext.getPage().getClass().getName(); and try to derive the JSP name from it but the naming scheme differs between JSP containers.
{ "pile_set_name": "StackExchange" }
Q: How to bind web service in jquery easy ui CRUD DataGrid I am developing an website in c# asp.net using jQuery EasyUI CRUD datagrid. But i need to replace the .php files with my web service to bind the datagrid as in the following snippet.Please suggest me a way to do so. <table id="dg" title="My Users" style="width:700px;height:250px" toolbar="#toolbar" pagination="true" idField="id" rownumbers="true" fitColumns="true" singleSelect="true"> <thead> <tr> <th field="firstname" width="50" editor="{type:'validatebox',options:{required:true}}">First Name</th> <th field="lastname" width="50" editor="{type:'validatebox',options:{required:true}}">Last Name</th> <th field="phone" width="50" editor="text">Phone</th> <th field="email" width="50" editor="{type:'validatebox',options:{validType:'email'}}">Email</th> </tr> </thead> </table> <script type="text/javascript"> $(function(){ $('#dg').edatagrid({ url: 'get_users.php', saveUrl: 'save_user.php', updateUrl: 'update_user.php', destroyUrl: 'destroy_user.php' }); }); </script> A: You can use jQuery Ajax, with jTemplate. $.ajax({ url: "Your webservice path", type: "POST", data: "JSON formated data to pass in the webservice", contentType: "application/json; charset=utf-8", dataType: "json", cache: false, success: function (data) { //You can further use jTemplate to output the data. }, error: function (data) { } }); The following link shows a simple example for jTemplate: http://www.codeproject.com/Articles/45759/jQuery-jTemplates-Grid
{ "pile_set_name": "StackExchange" }
Q: What is C#.net meaning in conjuction with terms like Javascript, HTML5, CSS etc? I recently got an offer for a traineeship for C#.NET. However before being allowed in the traineeship I need to make a small program which displays my programming skills in "C#.net". I don't know what to do now. I've downloaded visual studio 2015 and when I open it I see lots of stuff like console application/windows application etc and even .asp.net applications for web. In the traineeship document terms are used like " Object Oriëntated, Object Orientated Analysis and Design, UML, Database Design, SQL, XML, Scrum, Javascript, HTML5 CSS3, jQuery, Ajax, Design Pattern (MVC) and WCF. I don't have a clue where to start! If they wanted ASP websites they could've explicated this right? Should I make them a keygen music mp3 player in a console application? Srs please help. I got 1 week for this. A: Usually when asked to perform such task with as vague description as possible, the recruiters want to see your creativity and general knowledge of the technology. You don't have write another Windows system, so it's entirely up to you on what you decide to write. Just make sure it will work and it will follow general coding guidelines and it should be okay :)
{ "pile_set_name": "StackExchange" }
Q: HTML 5 input range-thumb disappeared after updating Chrome to version-49 I've themed HTML5 input range-thumb in one of my Client website using pseudo classes :after and :before and using the -webkit- prefix. And it was displaying all fine until I updated my Chrome browser (Desktop, Windows 7) to Version 49.0.2623.87 m. Can anyone please suggest, what has changed here? Thanks! Here is the css I used for Chrome: input.thickness { -webkit-appearance: none; float: left; width: 72%; margin-right: 20px; margin-top: 8px; margin-left: 0 /*for firefox*/; padding: 0 /*for IE*/; } input.thickness:focus::-webkit-slider-runnable-track { outline: none; } input.thickness::-webkit-slider-runnable-track { width: 100%; height: 8px; background-color: #2f9de2; border-radius: 4px; } input.thickness::-webkit-slider-thumb { -webkit-appearance: none; position: relative; background: transparent; width: 22px; height: 12px; margin-top: 8px; } input.thickness::-webkit-slider-thumb:after, input.thickness::-webkit-slider-thumb:before { bottom: 0; left: 0; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; } input.thickness::-webkit-slider-thumb:after { border-color: rgba(136, 183, 213, 0); border-bottom-color: #2f9de2; border-width: 10px; } input.thickness::-webkit-slider-thumb:before { border-color: rgba(194, 225, 245, 0); border-bottom-color: #2f9de2; border-width: 10px; } <input class="thickness" type="range" min="0" max="100" value="50" /> A: This is intentional. It's also on par with Gecko's behaviour.
{ "pile_set_name": "StackExchange" }
Q: How to put debug point I've a php file calling another php file which sometimes calls another php file to execute some actions (all through ajax). What I use to do was to echo at different points to know upto where the codes are executing properly. But with this approach, I can keep echo-ing. So how do I know upto where my code is executing?? Is there a tool for Google Chrome browser to detect it?? A: In your web browser, click the wrench icon, then "Tools", then "Developer tools". You can debug and step through JavaScript, you can see a timeline of requests with the request and response headers and bodies fully inspectable, etc. You should be able to debug all your AJAX request without any additional software/plugins.
{ "pile_set_name": "StackExchange" }
Q: Find matching strings in table column Oracle 10g I am trying to search a varchar2 column in a table for matching strings using the value in another column. The column being searched allows free form text and allows words and numbers of different lengths. I want to find a string that is not part of a larger string of text and numbers. Example: 1234a should match "Invoice #1234a" but not "Invoice #1234a567" Steps Taken: I have tried Regexp_Like(table2.Searched_Field,table1.Invoice) but get many false hits when the invoice number has a number sequence that can be found in other invoice numbers. A: Suggestions: Match only at end: REGEXP_LIKE(table2.Searched_Field, table1.Invoice || '$') Match exactly: table2.Searched_Field = 'Invoice #' || table1.Invoice Match only at end with LIKE: table2.Searched_Field LIKE '%' || table1.Invoice
{ "pile_set_name": "StackExchange" }
Q: Append to closest div class (multiple divs with same class on page) I'm trying to append content into the closest div class with name ".infoCatcher", but as of now it is appending to all divs with that class on the page. How do I append this to the closest div? I have this: $(document).on('click', '.btnMoreInfo', function () { $('.item').closest('div').find('.infoCatcher').append('<div class="moreInfo info">' + '</div>'); }); And HTML: <ul> <li> <button class='btnMoreInfo'>More</button> <div class='infoCatcher'></div> </li> <li> <button class='btnMoreInfo'>More</button> <div class='infoCatcher'></div> </li> <li> <button class='btnMoreInfo'>More</button> <div class='infoCatcher'></div> </li> <li> <button class='btnMoreInfo'>More</button> <div class='infoCatcher'></div> </li> <li> <button class='btnMoreInfo'>More</button> <div class='infoCatcher'></div> </li> </ul> Thankful for help! A: Try .siblings. Converted your code to fiddle. Working version is here $(document).ready(function(){ $(document).on('click', '.btnMoreInfo', function (e) { alert('Yes'); $(e.target).siblings(".infoCatcher").append('<div class="moreInfo info">More Content..' + '</div>'); }); });
{ "pile_set_name": "StackExchange" }
Q: HttpClient java.net.UnknownHostException exception when the CURL command passes I am trying to use httpclient to make make a call to Jenkins to get a list of jobs. When I run my code, I get an UnknownHostException. I tried to make the same request using curl and I was able to get the result. I am not sure how to interpret this. void nwe() throws ClientProtocolException, IOException { HttpHost target = new HttpHost("https://<JENKINS_URL>/api"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpGet httpGet = new HttpGet("/json"); httpGet.setHeader("Content-type", "application/json"); BasicScheme basicAuth = new BasicScheme(); HttpClientContext localContext = HttpClientContext.create(); CloseableHttpResponse response1 = httpclient.execute(target, httpGet, localContext); System.out.println(response1.getStatusLine()); } The CURL command on the same URL gives me the expected output Thanks, Amar A: Read the JavaDoc for HttpHost: Parameters: hostname - the hostname (IP or DNS name) So you should use just (omit the protocol and context): HttpHost target = new HttpHost( "<JENKINS_URL>" ); and then HttpGet the /api/json part. Cheers,
{ "pile_set_name": "StackExchange" }
Q: Generate XML from a class with JAVA I asked this question before: Generate XML from a class I want to do this with Java. Is it possible to do the same with Java via attributes? or is there a framework i can use for this purpose as well. A: XStream will allow you to represent any class as an XML. You can check here for an example. A: JAXB could be what you want. It's fairly common. You just add some annotations to your properties and any instance of that class can be serialized/deserialized to XML.
{ "pile_set_name": "StackExchange" }
Q: How to create DNS records for my VPS first of all I should mention that I'm fairly new to the world of DNS. I've purchased a VPS plan and I'm trying to run a web server and also a custom mail server (postfix and dovecot combination), which turns out to be a real pain. I'm aware of the fact that I can make my life easier by using Google App services but nonetheless I want to be able to do it myself. I'm stuck with so called DNS records and as far as my understanding goes I should first of all create an A record for my mail.mydomain.com and afterwards a MX record, am I right? I checked every option my hosting provider provides, but unfortunately I couldn't find anything. If I run: nslookup -q=mx mydomain.com it gives me: Non-authoritative answer: mydomain.com mail exchanger = 10 mail.mydomain.com and for "Authoritative answers" I get nothing. So first question: "'Authoritative answers' are answers from mydomain.com itself and to be able to give such answers I should run my own DNS Name Server and have so called 'zones file' in which I have these records setup, am I right?". And following question would be: "to be able to do it I should have 'bind' software package installed, right?". Another question: "if haven't done any of it how come I get 'Non-authoritative answer' for my MX query? Does it mean I already have one MX record from my service provider?". And the last question would be, since it is for a custom mail server and if you are familiar with it: "could you tell me why do I have to have a reversed domain record (I think it is called PTR) in order to avoid my mail get landed in spam folder?" A: You got Non-authoritative answer because you did not query records from name servers of the domain, and the results may contain IPs. This result is similar as yours. $ nslookup -q=mx google.com Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: google.com mail exchanger = 30 alt2.aspmx.l.google.com. google.com mail exchanger = 20 alt1.aspmx.l.google.com. google.com mail exchanger = 40 alt3.aspmx.l.google.com. google.com mail exchanger = 50 alt4.aspmx.l.google.com. google.com mail exchanger = 10 aspmx.l.google.com. Authoritative answers can be found from: alt3.aspmx.l.google.com internet address = 173.194.204.26 alt4.aspmx.l.google.com internet address = 74.125.141.26 alt2.aspmx.l.google.com internet address = 173.194.219.27 aspmx.l.google.com internet address = 74.125.25.26 alt1.aspmx.l.google.com internet address = 74.125.193.27 So we can find name servers of the targeted domain. $ nslookup -q=ns google.com Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: google.com nameserver = ns3.google.com. google.com nameserver = ns1.google.com. google.com nameserver = ns2.google.com. google.com nameserver = ns4.google.com. Authoritative answers can be found from: ns3.google.com internet address = 216.239.36.10 ns2.google.com internet address = 216.239.34.10 ns1.google.com internet address = 216.239.32.10 ns4.google.com internet address = 216.239.38.10 Then we can get authoritative answer. $ nslookup -q=mx google.com ns1.google.com Server: ns1.google.com Address: 216.239.32.10#53 google.com mail exchanger = 40 alt3.aspmx.l.google.com. google.com mail exchanger = 10 aspmx.l.google.com. google.com mail exchanger = 30 alt2.aspmx.l.google.com. google.com mail exchanger = 50 alt4.aspmx.l.google.com. google.com mail exchanger = 20 alt1.aspmx.l.google.com. As the sample you posted, you can confirm if mail.mydomain.com has pointed to a IP ( so called A record ), and mail related services maight be OK if there are correct MX & A records. You should find out name servers of your domain before you maintain the DNS records. I guess your service provider ( or someone else ) have set up MX record of your domain, you may get more answers from your service provider.
{ "pile_set_name": "StackExchange" }
Q: Looping within a regular expression can regex able to find a patter to this? {{foo.bar1.bar2.bar3}} where in the groups would be $1 = foo $2 = bar1 $3 = bar2 $4 = bar3 and so on.. it would be like re-doing the expression over and over again until it fails to get a match. the current expression i am working on is (?:\{{2})([\w]+).([\w]+)(?:\}{2}) Here's a link from regexr. http://regexr.com?3203h -- ok I guess i didn't explain well what I'm trying to achieve here. let's say I am trying to replace all .barX inside a {{foo . . . }} my expected results should be $foo->bar1->bar2->bar3 A: This should work, assuming no braces are allowed within the match: preg_match_all( '%(?<= # Assert that the previous character(s) are either \{\{ # {{ | # or \. # . ) # End of lookbehind [^{}.]* # Match any number of characters besides braces/dots. (?= # Assert that the following regex can be matched here: (?: # Try to match \. # a dot, followed by [^{}]* # any number of characters except braces )? # optionally \}\} # Match }} ) # End of lookahead%x', $subject, $result, PREG_PATTERN_ORDER); $result = $result[0];
{ "pile_set_name": "StackExchange" }
Q: Does a list_iterator garbage collect its consumed values? Suppose I have li = iter([1,2,3,4]). Will the garbage collector drop the references to inaccessible element when I do next(li). And what about deque, will elements in di = iter(deque([1,2,3,4])) be collectable once consumed. If not, does a native data structure in Python implement such behaviour. A: https://github.com/python/cpython/blob/bb86bf4c4eaa30b1f5192dab9f389ce0bb61114d/Objects/iterobject.c A reference to the list is held until you iterate to the end of the sequence. You can see this in the iternext function. The deque is here and has no special iterator. https://github.com/python/cpython/blob/master/Modules/_collectionsmodule.c You can create your own class and define __iter__ and __next__ to do what you want. Something like this class CList(list): def __init__(self, lst): self.lst = lst def __iter__(self): return self def __next__(self): if len(self.lst) == 0: raise StopIteration item = self.lst[0] del self.lst[0] return item def __len__(self): return len(self.lst) l = CList([1,2,3,4]) for item in l: print( len(l) )
{ "pile_set_name": "StackExchange" }
Q: Is a Python closure a good replacement for `__all__`? Is it a good idea to use a closure instead of __all__ to limit the names exposed by a Python module? This would prevent programmers from accidentally using the wrong name for a module (import urllib; urllib.os.getlogin()) as well as avoiding "from x import *" namespace pollution as __all__. def _init_module(): global foo import bar def foo(): return bar.baz.operation() class Quux(bar.baz.Splort): pass _init_module(); del _init_module vs. the same module using __all__: __all__ = ['foo'] import bar def foo(): return bar.baz.operation() class Quux(bar.baz.Splort): pass Functions could just adopt this style to avoid polluting the module namespace: def foo(): import bar bar.baz.operation() This might be helpful for a large package that wants to help users distinguish its API from the package's use of its and other modules' API during interactive introspection. On the other hand, maybe IPython should simply distinguish names in __all__ during tab completion, and more users should use an IDE that allows them to jump between files to see the definition of each name. A: I am a fan of writing code that is absolutely as brain-dead simple as it can be. __all__ is a feature of Python, added explicitly to solve the problem of limiting what names are made visible by a module. When you use it, people immediately understand what you are doing with it. Your closure trick is very nonstandard, and if I encountered it, I would not immediately understand it. You would need to put in a long comment to explain it, and then you would need to put in another long comment to explain why you did it that way instead of using __all__. EDIT: Now that I understand the problem a little better, here is an alternate answer. In Python it is considered good practice to prefix private names with an underscore in a module. If you do from the_module_name import * you will get all the names that do not start with an underscore. So, rather than the closure trick, I would prefer to see correct use of the initial-underscore idiom. Note that if you use the initial underscore names, you don't even need to use __all__. A: The problem with from x import * is that it can hide NameErrors which makes trivial bugs hard to track down. "namespace pollution" means adding stuff to the namespace that you have no idea where it came from. Which is kind of what your closure does too. Plus it might confuse IDEs, outlines, pylint and the like. Using the "wrong" name for a module is not a real problem either. Module objects are the same from wherever you import them. If the "wrong" name disappears (after a update) it should be clear why and motivate the programmer to do it properly next time. But it doesn't cause bugs.
{ "pile_set_name": "StackExchange" }
Q: Control RaspberryPI 3 via Serial/GPIO So I'm working on a bit of a little project with a PI for work. I'm making the PI into a little portable NAS where i can connect it to a network and on boot, it will email me its IP Address (if it gets one). In the case where the network is static, i want to have a way to connect to my PI's terminal and configure a static IP without the need of connecting the PI to a display and mouse and keyboard etc. I want to connect to my PI via Putty and get to the console. I followed this tutorial on enabling the /dev/ttyS0 port which is the GPIO on pins 14 and 15. And from my understanding, this should allow me to do what i want but not sure what the next step is to connect the PI to my PC so i can Putty into it. I was looking at GPIO to USB or something, but unsure what to use. Anyone done this before or similar and knows what i should get to achieve what i want? Many thanks! A: You need an USB to TTL cable. TTL indicates 3.3 V compatibility. "Normal" USB to RS-232 cables work with higher voltages and can damage the Pi. Example USB to TTL cable : https://www.adafruit.com/product/954
{ "pile_set_name": "StackExchange" }
Q: What frameworks are available in ASP.NET Core (ASP.NET 5) applications? I have seen various frameworks targeted in project.json files, using names such as netcore50, dotnet, dnx451, net45, and others. The documentation for the "framework" section project.json does not (yet) specify how to use this section for different frameworks. What frameworks are available and what name should be used in project.json to target each? A: UPDATE 3 Full list see Target Frameworks. The most common TFMs ASP.NET app developers need to know are: netcoreappx.y = An application that targets .NET Core x.y (e.g. netcoreapp1.0 = .NET Core 1.0) netstandardx.y = A library that targets .NET Standard x.y. (e.g. netstandard2.0 = .NET Standard 2.0). .NET Standard libraries can work on desktop .NET, Windows Phone, Mono, and others. net4xy = A library or console app that targets desktop .NET Framework 4.x.y (e.g. net452 or net46) UPDATE 2 (Dec 9, 2015) Somewhat official docs are now available from dotnet. See .NET Platform Standard → Nuget For libraries targeting multiple platforms that adhere to the .NET Standard, these TFMs (target framework monikers) are available.~ UPDATE (Aug 12, 2015) This Nuget blog post shows additional TFMs available for nuget. It also explains the dotnet TFM. Original response Although this is not official documentation, this blog post by Oren Novotny has an excellent table showing the different target framework monikers.
{ "pile_set_name": "StackExchange" }
Q: String Formatting: what is the width for the e format? My IronPython console gives the following: >>> "%9.2e" % 1.236 '1.24e+00' >>> "%10.2e" % 1.236 ' 1.24e+00' >>> The total characters in the output do not seem to correspond to 9 or 10 respectively. A: This is a know bug with IronPython; the width is not handled correctly when using the %<width>e format. CPython handles the width as expected; e.g. '%9.2e' % 1.236 produces a string of length 9. You could try using the format() function instead, if you are lucky it doesn't reuse the same code: format(1.236, '9.2e')
{ "pile_set_name": "StackExchange" }
Q: OpenCV cvtColor CV_BGR2HSV CV_32FC3 Saturation Range I'm trying to build histograms for materials in OpenCV 3.2 but am confused by the HSV ranges--they don't seem to match the documentation, or I am approaching it wrong. // cv::Mat bgrPhoto contains a test image cv::Mat3f hsvPhoto; bgrPhoto.convertTo(hsvPhoto, CV_32FC3); cv::cvtColor(hsvPhoto, hsvPhoto, CV_BGR2HSV, CV_32FC3); std::vector<cv::Mat1f> hsvChannels; cv::split(hsvPhoto, hsvChannels); // Documentation [0.0, 1.0]: measured here Hue to 360.0, Sat to 1.0, Val to 255.0 double minHue, maxHue, minSat, maxSat, minVal, maxVal; cv::minMaxIdx(hsvChannels[0], &minHue, &maxHue, 0, 0); cv::minMaxIdx(hsvChannels[1], &minSat, &maxSat, 0, 0); cv::minMaxIdx(hsvChannels[2], &minVal, &maxVal, 0, 0); A: When you converted your image from 8-bit to 32-bit, you haven't scaled your values from [0, 255] to [0, 1]. convertTo() simply converts the types; it doesn't rescale the values by default. This is affecting your output since, from the docs for color conversion from BGR to HSV, V simply gets set to max(B, G, R) (which will be a max of numbers going up to 255). You'll notice that in the docs for cvtColor() it says for 8-bit and 16-bit images, they are scaled to fit the [0, 1] range; but not for float images. However, the H channels and S channels still get scaled to the correct ranges because they use V to scale the image. When you do bgrPhoto.convertTo(hsvPhoto, CV_32FC3) you need to divide by 255 to set the values into [0, 1]. If you check out the docs for convertTo() you'll notice a third positional argument can be set which is a scale factor. Simply using bgrPhoto.convertTo(hsvPhoto, CV_32FC3, 1.0/255.0) will, as the documentation states, scale every pixel value by that factor. Also, Miki's point in the comment on the OP totally slipped by me but it was a great catch; check the docs for cvtColor(); the fourth argument is an argument for number of destination channels, not dtype, so cv::cvtColor(hsvPhoto, hsvPhoto, CV_BGR2HSV) is what you want.
{ "pile_set_name": "StackExchange" }
Q: Using the AngularJS require option to call into another directive I was just reading here about accessing one directive's controller from within another directive via the require option: http://jasonmore.net/angular-js-directives-difference-controller-link/ The directive droppable and dashboard declarations in on my view - on two different divs: <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-lg-12" data-droppable drop="handleDrop"> <div id="dash" dashboard="dashboardOptions" class="dashboard-container"></div> </div> </div> However I can't seem to get it to work. My dashboardCtrl param below is NULL. Here in my droppable directive, I use the REQUIRE option: .directive('droppable', function () { return { scope: { drop: '&', }, //****************** dashboard directive is optionally requested ************ require: '?dashboard', link: function (scope, element, attributes, dashboardCtrl) { el.addEventListener('drop', function (e) { if (e.preventDefault) { e.preventDefault(); } this.classList.remove('over'); var item = document.getElementById(e.dataTransfer.getData('Text')); this.appendChild(item.cloneNode(true)); // *** CALL INTO THE dashboardCtrl controller *** dashboardCtrl.addWidgetInternal(); return false; }, false); } } }); and the dashboard directive : angular.module('ui.dashboard') .directive('dashboard', ['WidgetModel', 'WidgetDefCollection', '$modal', 'DashboardState', '$log', function (WidgetModel, WidgetDefCollection, $modal, DashboardState, $log) { return { restrict: 'A', templateUrl: function (element, attr) { return attr.templateUrl ? attr.templateUrl : 'app/shared/template/dashboard.html'; }, scope: true, controller: ['$scope', '$attrs', function (scope, attrs) { // ommitted for brevity }], link: function (scope) { scope.addWidgetInternal = function (event, widgetDef) { event.preventDefault(); scope.addWidget(widgetDef); }; }; } }]); However, my dashboardCtrl parameter is NULL. Please help me to figure out how to use require. I actually need to call the addWidget() function, which is within the link option; but I suppose I can copy or move that into the controller option. thank you ! Bob A: Here is an example of "parent" directive dashboard requiring droppable, and communication between the two making use of require and passing dashboardCtrl Here is a good article to see directive to directive communication Fiddle example also built from your previous question JSFiddle app.directive('droppable', [function () { return { restrict: 'A', require: 'dashboard', link: function (scope, elem, attrs, dashboardCtrl) { dashboardCtrl.controllerSpecificFunction('hello from child directive!'); scope.addWidgetInternal = function(message) { console.log(message); } } } }]); app.directive('dashboard', [function () { return { restrict: 'A', controller: function ($scope) { $scope.handleDrop = function(message) { $scope.addWidgetInternal(message) } this.controllerSpecificFunction = function(message) { console.log(message); } } } }]); Edit Based on discussion, here is a solution for what I currently understand the problem to be Parent directive dashboard optionally requires child directive droppable and there needs to be communication between the two <div dashboard> <button id="dash" droppable ng-click="handleDrop($event)">Handle Drop</button> </div> app.directive('droppable', [function () { return { restrict: 'A', require: '^?dashboard', link: function (scope, elem, attrs, dashboardCtrl) { scope.handleDrop = function($event) { dashboardCtrl.addWidgetInternal($event); } } } }]); app.directive('dashboard', [function () { return { restrict: 'A', controller: function ($scope) { this.addWidgetInternal = function($event) { console.log($event); } } } }]); Updated JSFiddle
{ "pile_set_name": "StackExchange" }
Q: PHP: Text Area echo in form won't echo during validation Currently I have a form that goes through validation, and echo statement that are entered and returned errors on what needs to be filled in. My commenting area is within a tag. It throws the error when it's empty. But when it's filled and other areas are empty, it DOES NOT echo the previously entered text. I view another question that claims to have an answer. Previous I was using:<?php echo $_POST['email']; ?> in my value result. The "answer" said to replace value with and htmlentities() as such: <?php echo htmlentities($comments, ENT_COMPAT,'ISO-8859-1', true);?> However, that did not work either. I want the comments to echo, when text is entered, but other areas still need info. HTML form text area: <textarea name="comments" maxlength="500" rows="10" cols="10" placeholder="Please enter your comments here..." value="<?php echo htmlentities($_POST['comments'], ENT_COMPAT,'ISO-8859-1', true);?>"></textarea> PHP (not sure if needed here in this answer): <?php if(!empty($_POST)){ $POST = filter_post($_POST); $invoice = array_splice($POST,3,1); $MSG = check_empty($POST); if(!array_filter($MSG)){ $POST['invoice'] = $invoice['invoice']; if(send_mail($POST)){ $MSG[] = "Email Success"; } else{ $MSG[] = "Email Failed"; } } } function filter_post($POST){ $keys = array('name','phone','email','invoice','comments'); $POST = array_intersect_key($POST, array_flip($keys)); $POST = array_map('strip_tags', $POST); return($POST); } function check_empty($POST){ foreach($POST as $key => $value){ if(empty($value)){ $MSG[] = "You need to fill out the $key section"; } } return($MSG); } function send_mail($POST){ extract($POST); $to = 'jordan@jordandavis.work'; $sbj = 'New Question For Se7en Service!'; $msg = "Name: $name \n Phone: $phone \n Email: $email \n Invoice #: $invoice \n Comments: $comments"; $headers = "From: $email"; return(mail($to, $sbj, $msg, $headers)); } function output_errors($MSG){ return '<ul><li>' . implode('</li><li>', $MSG) . '</li></ul>'; } ?> Link to question with answer that didn't work for me. A: <textarea> element does not have a value attribute. The 'value' is set between the opening/closing tags -> <textarea name="comments" maxlength="500" rows="10" cols="10" placeholder="Please enter your comments here..."> <?php echo htmlentities($_POST['comments'], ENT_COMPAT,'ISO-8859-1', true);?> </textarea> http://www.w3.org/TR/html401/interact/forms.html#h-17.7 or http://www.w3.org/TR/html-markup/textarea.html
{ "pile_set_name": "StackExchange" }
Q: Create tuples of (lemma, NER type) in python , Nlp problem I wrote the code below, and I made a dictionary for it, but I want Create tuples of (lemma, NER type) and Collect counts over the tuples I dont know how to do it? can you pls help me? NER type means name entity recognition text = """ Seville. Summers in the flamboyant Andalucían capital often nudge 40C, but spring is a delight, with the parks in bloom and the scent of orange blossom and jasmine in the air. And in Semana Santa (Holy Week, 14-20 April) the streets come alive with floats and processions. There is also the raucous annual Feria de Abril – a week-long fiesta of parades, flamenco and partying long into the night (4-11 May; expect higher hotel prices if you visit then). Seville is a romantic and energetic place, with sights aplenty, from the Unesco-listed cathedral – the largest Gothic cathedral in the world – to the beautiful Alcázar royal palace. But days here are best spent simply wandering the medieval streets of Santa Cruz and along the river to La Real Maestranza, Spain’s most spectacular bullring. Seville is the birthplace of tapas and perfect for a foodie break – join a tapas tour (try devoursevillefoodtours.com), or stop at the countless bars for a glass of sherry with local jamón ibérico (check out Bar Las Teresas in Santa Cruz or historic Casa Morales in Constitución). Great food markets include the Feria, the oldest, and the wooden, futuristic-looking Metropol Parasol. Nightlife is, unsurprisingly, late and lively. For flamenco, try one of the peñas, or flamenco social clubs – Torres Macarena on C/Torrijano, perhaps – with bars open across town until the early hours. Book it: In an atmospheric 18th-century house, the Hospes Casa del Rey de Baeza is a lovely place to stay in lively Santa Cruz. Doubles from £133 room only, hospes.com Trieste. """ doc = nlp(text).ents en = [(entity.text, entity.label_) for entity in doc] en #entities #The list stored in variable entities is has type list[list[tuple[str, str]]], #from pprint import pprint pprint(en) sum(filter(None, entities), []) from collections import defaultdict type2entities = defaultdict(list) for entity, entity_type in sum(filter(None, entities), []): type2entities[entity_type].append(entity) from pprint import pprint pprint(type2entities) A: I hope the following code snippets solve your problem. import spacy # Load English tokenizer, tagger, parser, NER and word vectors nlp = spacy.load("en_core_web_sm") text = ("Seville. Summers in the flamboyant Andalucían capital often nudge 40C, but spring is a delight, with the parks in bloom and the scent of orange blossom and jasmine in the air. And in Semana Santa (Holy Week, 14-20 April) the streets come alive with floats and processions. There is also the raucous annual Feria de Abril – a week-long fiesta of parades, flamenco and partying long into the night (4-11 May; expect higher hotel prices if you visit then). Seville is a romantic and energetic place, with sights aplenty, from the Unesco-listed cathedral – the largest Gothic cathedral in the world – to the beautiful Alcázar royal palace. But days here are best spent simply wandering the medieval streets of Santa Cruz and along the river to La Real Maestranza, Spain’s most spectacular bullring. Seville is the birthplace of tapas and perfect for a foodie break – join a tapas tour (try devoursevillefoodtours.com), or stop at the countless bars for a glass of sherry with local jamón ibérico (check out Bar Las Teresas in Santa Cruz or historic Casa Morales in Constitución). Great food markets include the Feria, the oldest, and the wooden, futuristic-looking Metropol Parasol. Nightlife is, unsurprisingly, late and lively. For flamenco, try one of the peñas, or flamenco social clubs – Torres Macarena on C/Torrijano, perhaps – with bars open across town until the early hours. Book it: In an atmospheric 18th-century house, the Hospes Casa del Rey de Baeza is a lovely place to stay in lively Santa Cruz. Doubles from £133 room only, hospes.com Trieste.") doc = nlp(text) lemma_ner_list = [] for entity in doc.ents: lemma_ner_list.append((entity.lemma_, entity.label_)) # print list of lemma ner tuples print(lemma_ner_list) # print count of tuples print(len(lemma_ner_list))
{ "pile_set_name": "StackExchange" }
Q: How do I make main a friend of my class from within a library? Please see my first attempt at answering this . I neglected to tell the whole story before in an attempt to simplify things. Turns out my example works! Sorry. The whole story is that this is a library the contains a class in one file and the main in another file, all linked into my library. The library is providing the basis for a Process Framework, which is why the main is in the library and not the process. Below is a stripped down version of what I have. pf.hpp using namespace std; namespace MyNamespace { class ProcessManager { public: friend int main(int argc, char** argv); private: void test(); }; }; pf.cpp #include "pf.h" namespace MyNamespace { ProcessManager::test() { cout << "My friend has accessed my member" << endl; } }; pfmain.cpp #include "pf.hpp" int main(int argc, char** argv) { ProcessManager pm; pm.test(); } Note that this fails on the compilation of the library What I have tried is: Moving the friend all over the place Making the friend reference to main use global scope (e.g. ::main) Making friend and main declarations use global scope What am I missing? Thanks! A: Just declare the main outside the MyNamespace and specify global namespace :: in friend statement //in header file of ProcessManager //your pf.h int main(int argc, char** argv); namespace MyNamespace { class ProcessManager { public: friend int ::main(int argc, char** argv); private: void test(); }; };
{ "pile_set_name": "StackExchange" }
Q: How to get list of layers from geoserver Is it possible to get a list of all the layers served by geoserver? I.e. is there some specific url request to send that does this? A: The capabilities links on the geoserver home page each list layers served via various services: the WMS capabilities lists layers that support requests for tiled images the WFS capabilities lists layers that support requests for vector data the WCS capabilities lists layers that support raster queries A sample WMS request would look like this: http://demo.opengeo.org/geoserver/wms?request=GetCapabilities&service=WMS&version=1.0.0 A: So just for completeness, here's an example of how to get a list/array of layers: var formatter = new OpenLayers.Format.WMSCapabilities(); var endpoint = "path/to/wms/endpoint"; var layers = []; // async call to geoserver (I'm using angular) $http.get(endpoint + 'request=GetCapabilities'). success(function(data, status, headers, config) { // use the tool to parse the data var response = (formatter.read(data)); // this object contains all the GetCapabilities data var capability = response.capability; // I want a list of names to use in my queries for(var i = 0; i < capability.layers.length; i ++){ layers.push(capability.layers[i].name); } }). error(function(data, status, headers, config) { alert("terrible error logging.."); });
{ "pile_set_name": "StackExchange" }
Q: Encapsulated Group by or conditional aggregation in Vertica DB I have the following table in a Vertica DB: +---------+-------+ | Readout | Event | +---------+-------+ | 1 | A | | 1 | B | | 1 | A | | 2 | B | | 2 | A | +---------+-------+ I would like to group each readout and count the frequency of the events, resulting in a table like this: +---------+----------------+----------------+-----------------+ | Readout | Count(Readout) | Count(Event A) | Count (Event B) | +---------+----------------+----------------+-----------------+ | 1 | 3 | 2 | 1 | | 2 | 2 | 1 | 1 | +---------+----------------+----------------+-----------------+ I am sure there is an easy GROUP BY command, but I can't wrap my head around it. A: You want conditional aggregation: select readout, count(*), sum(case when event = 'A' then 1 else 0 end) as num_a, sum(case when event = 'B' then 1 else 0 end) as num_b from t group by readout;
{ "pile_set_name": "StackExchange" }
Q: load overflow topmost address on x86 What would happen when an unaligned load overflows the topmost address on x86? For example, what would happen when loading a 4-byte integer at address 0xfffffffe on 32-bit x86 processor? Of course, the topmost page (0xfffff000-0xffffffff) is mapped to some physical memory and the page is readable/writable, and the current loading program is in operating system kernel in Ring0. You can assume that loading 4-byte at 0xfffffffc is legal for simplicity. Will such loading generate a page-fault? A: It would generate a general protection (#GP) fault due to the limit checking in segments. The processor checks the segment limit when data is accessed with DS segment register which is usual case. The default segment limit of DS segment register is [0,0xffffffff). The processor causes a general-protection exception any time an attempt is made to access the following addresses in a segment: A byte at an offset greater than the effective limit A word at an offset greater than the (effective-limit – 1) A doubleword at an offset greater than the (effective-limit – 3) A quadword at an offset greater than the (effective-limit – 7) According to the Intel x86 spec, "explicitly unaligned" accesses (regardless of whether they're at the edge of your address space) can also cause general protection faults for AVX, FME, VEX, or SSE instructions. Interestingly, the lowest and highest addresses are not the only boundaries in your address space where this could happen. More boundaries show up in x86_64 address spaces, where there is a sparse / unaddressable space in the middle which your processor can't use (because this way processor manufacturers can cut down the number of bits required for many processor internals -- after all, nobody is using a full 64 bit address space yet).
{ "pile_set_name": "StackExchange" }
Q: Xcode code completion, search through whole method name Is there any way to have Xcode's code completion search the whole method name for the characters I start typing? For example if I start typing [self con I want things like navigationController to show up, whereas now I have to type [self nav to see that. A: If you're currently in a file, you can click on the jump bar and start typing: No, that's not a leak of the official app. EDIT Now I see you are talking about in-code-writing code completion. No, there isn't a way to do that - imagine how annoying it would be when you type [self a and every single method with an a in the name shows up. Wouldn't be fun.
{ "pile_set_name": "StackExchange" }
Q: Gson deserialisation result is null for one type I'm getting a response which consists of two types of objects : Pagination and a List of ArtistSearch. The model I'm using for the deserialization is : public class ArtistSearchResults { List<ArtistSearch> artistSearchList; Pagination pagination; // getters and setters... } And I deserialize here : Gson gson = new Gson(); ArtistSearchResults results = gson.fromJson(response.toString(), ArtistSearchResults.class); List<ArtistSearch> artistSearchList = results.getArtistSearchList(); Pagination pagination = results.getPagination(); Log.i(TAG, "onSuccess Pagination size == " + pagination.getItems() ); Log.i(TAG, "onSuccess RESULTS size == " + artistSearchList.get(0).getTitle() ); and although I get correctly the response for the Pagination object I'm always getting null for the artistSearchList. I'm not getting any error messages so I'm not sure where the error is. The kind of results I'm getting looks like this : 07-10 06:11:06.726 6954-6954/jb.ti.discogsball I/SEARCHHANDLER: onSuccess Search-Artist response = {"pagination":{"per_page":5,"pages":3,"page":1,"urls":{"last":"https:\/\/api.discogs.com\/database\/search?q=savage+republic&per_page=5&type=artist&page=3","next":"https:\/\/api.discogs.com\/database\/search?q=savage+republic&per_page=5&type=artist&page=2"},"items":14},"results": [{"thumb":"https:\/\/api-img.discogs.com\/RAHE1vqHWb1xwPUv5y2Q1v5g4Yo=\/150x150\/smart\/filters:strip_icc():format(jpeg):mode_rgb():quality(40)\/discogs-images\/A-121133-1262786660.jpeg.jpg","title":"Savage Republic","uri":"\/artist\/121133-Savage-Republic","resource_url":"https:\/\/api.discogs.com\/artists\/121133","type":"artist","id":121133},{"thumb":"https:\/\/api-img.discogs.com\/GYkPyAYZEcFM0bzyjnBple7P3Yw=\/150x150\/smart\/filters:strip_icc():format(jpeg):mode_rgb():quality(40)\/discogs-images\/A-307086-1160815350.jpeg.jpg","title":"Bruce Licher","uri":"\/artist\/307086-Bruce-Licher","resource_url":"https:\/\/api.discogs.com\/artists\/307086","type":"artist","id":307086},{"thumb":"https:\/\/api-img.discogs.com\/XHvbh885CZ2uTcq7WT3ph0n0gMs=\/150x150\/smart\/filters:strip_icc():format(jpeg):mode_rgb():quality(40)\/discogs-images\/A-71224-1334785233.jpeg.jpg","title":"Medicine (2)","uri":"\/artist\/71224-Medicine-2","resource_url":"https:\/\/api.discogs.com\/artists\/71224","type":"artist","id":71224},{"thumb":"","title":"Val Haller","uri":"\/artist\/492425-Val-Haller","resource_url":"https:\/\/api.discogs.com\/artists\/492425","type":"artist","id":492425},{"thumb":"","title":"Ramona Clarke","uri":"\/artist\/1957827-Ramona-Clarke","resource_url":"https:\/\/api.discogs.com\/artists\/1957827","type":"artist","id":1957827}]} 07-10 06:11:06.732 6954-6954/jb.ti.discogsball I/SEARCHHANDLER: onSuccess Pagination size == 14 and as you can see I get a value for the Pagination object but I get a NPE for the artistSearchList. The model I'm using for ArtistSearch is : public class ArtistSearch { int id; String title; String type; String resource_url; String uri; String thumb; // getters and setters ... This is the text from the response that parses to null : "results":[{"thumb":"https://api-img.discogs.com/RAHE1vqHWb1xwPUv5y2Q1v5g4Yo=/150x150/smart/filters:strip_icc():format(jpeg):mode_rgb():quality(40)/discogs-images/A-121133-1262786660.jpeg.jpg","title":"Savage Republic","uri":"/artist/121133-Savage-Republic","resource_url":"https://api.discogs.com/artists/121133","type":"artist","id":121133},{"thumb":"https://api-img.discogs.com/GYkPyAYZEcFM0bzyjnBple7P3Yw=/150x150/smart/filters:strip_icc():format(jpeg):mode_rgb():quality(40)/discogs-images/A-307086-1160815350.jpeg.jpg","title":"Bruce Licher","uri":"/artist/307086-Bruce-Licher","resource_url":"https://api.discogs.com/artists/307086","type":"artist","id":307086},{"thumb":"https://api-img.discogs.com/XHvbh885CZ2uTcq7WT3ph0n0gMs=/150x150/smart/filters:strip_icc():format(jpeg):mode_rgb():quality(40)/discogs-images/A-71224-1334785233.jpeg.jpg","title":"Medicine (2)","uri":"/artist/71224-Medicine-2","resource_url":"https://api.discogs.com/artists/71224","type":"artist","id":71224},{"thumb":"","title":"Val Haller","uri":"/artist/492425-Val-Haller","resource_url":"https://api.discogs.com/artists/492425","type":"artist","id":492425},{"thumb":"","title":"Ramona Clarke","uri":"/artist/1957827-Ramona-Clarke","resource_url":"https://api.discogs.com/artists/1957827","type":"artist","id":1957827}] A: Could you please replace the following variable declaration in ArtistSearchResults.java: private List<ArtistSearch> artistSearchList; by this: @SerializedName("results") private List<ArtistSearch> artistSearchList; and see the results?
{ "pile_set_name": "StackExchange" }
Q: Searching with Hash in Perl I am using a hash containing 5000 items to match words in a sentence, it so occurs that when I match for eg: if($hash{$word}){Do Something} sometimes it happens that the period occurs in the word and even if it is a match the presence of period results in a non-match. Can anything be done to ignore any punctuations when matching with hashes? A: You would have to redefine the words you look up to exclude the punctuation, remembering that you might or might not want to eliminate all punctuation (for example, you might want to keep dashes and apostrophes - but not single quotes). The crude technique - not recognizing any punctuation is: $key = $word; $key ~= s/\W//g; # Any non-word characters are removed if (defined $hash{$key}) { DoSomething; } You can refine the substitute command to meet your needs. But the only way to make sure that the hash keys match is to make sure that the hashed key matches - so you need to be consistent with what you supply.
{ "pile_set_name": "StackExchange" }
Q: Possible to compare date strings in mongodb? I have a collection that contains documents with a date attribute like so: { title: "whatever", created: ISODate("2013-05-27T03:36:50Z") } I would like to select records that were created on a certain day. I was hoping I could use toDateString() and compare the values but when I do a search like the one below: db.myCollection.find({ 'created.toDateString()': new Date('05/27/2013').toDateString() }).pretty() But this does not work. Is there any way to do what I am attempting above? A: If you want to select records then use a date range: db.collection.find({ created: { "$gte": new Date("2013-05-27"), "$lt": new Date("2013-05-28") } }) And that selects all the contained hours, minutes etc, falling between the two dates. So you should be trying to use the date values and not coerce into strings. If you want this for doing aggregation or otherwise need the results in a day only format then do this using $project and the date operators: db.collection.aggregate([ // Still match on the normal date forms, this time whole month { "$match": { created: { "$gte": new Date("2013-05-01"), "$lt": new Date("2013-05-31") } }}, // Project the date { "$project": { "date": { "year" : { "$year" : "$created" }, "month" : { "$month" : "$created" }, "day": : { "$dayOfMonth": "$created" } }, "title": 1 }}, // Group on day and title { "$group": { "_id": { "date" : "$date", "title" : "$title" }, "count": { "$sum": 1 } }}, // Sort by date { "$sort": { "_id.date.year": 1, "_id.date.month": 1, "_id.date.day": 1, }}, // Project nicer dates and document { "$project": { "_id": 0, "date": { "$concat": [ { "$substr": [ "$_id.date.year", 0, 4 ] }, "-", { "$substr": [ "$_id.date.month", 0, 2 ] }, "-", { "$substr": [ "$_id.date.day", 0, 2 ] } ]}, "title": "$_id.title", "count": 1 }} ])
{ "pile_set_name": "StackExchange" }
Q: Identifying from which method it is coming I have two methods both returning the view: public function method1() { return ('view1'); } and public function method2() { return ('view1'); } In the view i want to edit some changes regarding from which method it is coming: Something like this in view1: @if(coming form method1) { This is coming from method1, } @endif How can this be acheived? Currently i'm just making two separate views for so minor change. A: Why not add a flag in method public function method1() { $flag = 'method1'; return ('view1', compact('flag')); } public function method2() { $flag = 'method2'; return ('view1', compact('flag')); } and in the view check for the flag @if ($flag == 'method1') This is coming from method1 @elseif ($flag == 'method2') This is coming from method2 @endif
{ "pile_set_name": "StackExchange" }
Q: Why is there no "encoding" attribute in a string got by "IXMLDocument.SaveToXML" method? I use NewXMLDocument() to produce an XML document of my data. There is a SaveToXML() method to save the document to an XML-formatted string variable. The problem is that the XML string does not contain an "encoding" attribute in the head tag. But, if we save the XML document to a file with the SaveToFile() method, the "encoding" attribute will exist in it. Here is my code: var XML: IXMLDocument; RootNode, CurNode: IXMLNode; XmlString: string; begin XML := NewXMLDocument; XML.Encoding := 'utf-8'; XML.Options := [doNodeAutoIndent]; RootNode := XML.AddChild('XML'); CurNode := RootNode.AddChild('List'); CurNode := CertList.AddChild('Item'); CurNode.Text := 'bla-bla-bla'; ... XMl.SaveToXML(XmlString); // <<--- no "encoding" attribute here XMl.SaveToFile('my-list.xml'); XMl := nil; end; Is there a way to make the SaveToXML() method add the "encoding" attribute? A: You need to use the overload method IXMLDocument.SaveToXML(var XML: UTF8String). That will encode the xml to UTF-8 and add the encoding attribute in the xml header. Declare your XmlString as UTF8String to get the desired result. When you declare XmlString as string like you did, which is UTF-16 (Unicode) in Delphi 2009+, you actually call SaveToXML(var XML: DOMString). The DOMString is defined as UnicodeString. By default, variables declared as type string are UnicodeString. The output xml is UTF-16 and the encoding attribute is omitted.
{ "pile_set_name": "StackExchange" }
Q: Why use geometric algebra and not differential forms? This is somewhat similar to Are Clifford algebras and differential forms equivalent frameworks for differential geometry?, but I want to restrict discussion to $\mathbb{R}^n$, not arbitrary manifolds. Moreover, I am interested specifically in whether $$(\text{differential forms on }\mathbb{R}^n\text{ + a notion of inner product defined on them}) \simeq \text{geometric algebra over }\mathbb{R}^n$$ where the isomorphism is as Clifford algebras. (I.e., is geometric algebra just the description of the algebraic properties of differential forms when endowed with a suitable notion of inner product?) 1. Is any geometric algebra over $\mathbb{R}^n$ isomorphic to the exterior algebra over $\mathbb{R}^n$ in the following senses: as a vector space? (Should be yes.) as an exterior algebra? (Obviously they are not isomorphic as Clifford algebras unless our quadratic form is the zero quadratic form.) Since the basis of the geometric algebra (as a vector space) is the same (or at least isomorphic to) the basis of the exterior algebra over $\mathbb{R}^n$, the answer seems to be yes. Also because the standard embedding of any geometric algebra over $\mathbb{R}^n$ into the tensor algebra over $\mathbb{R}^n$ always "piggybacks" on the embedding of the exterior algebra over $\mathbb{R}^n$, see this MathOverflow question. 2. Are differential forms the standard construction of an object satisfying the algebraic properties of the exterior algebra over $\mathbb{R}^n$? 3. Does the answers to 1. and 2. being yes imply that the part in yellow is true? EDIT: It seems like the only problem might be that differential forms are covariant tensors, whereas I imagine that multivectors are generally assumed to be contravariant. However, distinguishing between co- and contravariant tensors is a standard issue in tensor analysis, so this doesn't really seem like an important issue to me. Assuming that I am reading this correctly, it seems like the elementary construction of the geometric algebra with respect to the standard inner product over $\mathbb{R}^n$ given by Alan MacDonald here is exactly just the exterior algebra over $\mathbb{R}^n$ with inner product. David Hestenes seems to try and explain some of this somewhat here and here, although I don't quite understand what he is getting at. (Also his claim in the first document that matrix algebra is subsumed by geometric algebra seems completely false, since he only addresses those aspects which relate to alternating tensors.) A: This seems to be best answered by Lounesto's paper "Marcel Riesz's Work on Clifford Algebras" (see here or here). In what follows: $\bigwedge V=$ the exterior algebra over $V$ $C\ell(Q)=$ the Clifford (geometric) algebra over $V$ w.r.t. the quadratic form $Q$ Note in particular that we always have $C\ell(0)=\bigwedge V$, $0$ being the degenerate quadratic form. On p. 221, Professor Lounesto discusses, given a non-degenerate quadratic form $Q$, how to define an "inner product" (contraction $\rfloor$) on the exterior algebra $\bigwedge V$. On p. 223, Professor Lounesto discusses how to extend the inner product (by combining it with the wedge product of the exterior algebra) to produce a Clifford/geometric product on $\bigwedge V$, which makes $\bigwedge V$ isomorphic to $C\ell(Q)$ (the Clifford algebra w.r.t. the quadratic form $Q$). One can also go the other way around, as M. Riesz originally did in 1958 (see section 1.3, beginning on p. 230, "Riesz's Introduction of an Exterior Product in $C\ell(Q)$ "), and use the Clifford product to define a notion of exterior product which makes $C\ell(Q)$ isomorphic to $\bigwedge V$. In other words, we do indeed have: (exterior algebra over $\mathbb{R}^n +$ inner product) $\simeq$ geometric algebra over $\mathbb{R}^n$ One should note that $\bigwedge \mathbb{R}^n$, the exterior algebra over $\mathbb{R}^n$, consists of alternating contravariant tensors of rank $k$ over $\mathbb{R}^n$. However, differential forms are alternating covariant tensors of rank $k$ over $\mathbb{R}^n$. So in general they behave differently. Nevertheless, an inner product on $V$ gives a linear isomorphism between any vector space $V$ and its dual $V^*$ to argue that covariant tensors of rank $k$ and contravariant tensors of rank $k$ are "similar". (Mixed variance tensors complicate things somewhat further, but are not relevant to this question.) Thus, differential forms are "similar" to $\bigwedge \mathbb{R}^n$ (since they are essentially $\bigwedge (\mathbb{R}^n)^*$). Also, we can just as easily construct a Clifford algebra from $\bigwedge V$ as from $\bigwedge V^*$, so we can extend differential forms to "covariant geometric algebras" by introducing an inner product based on a quadratic form $Q$. So, perhaps less convincingly, we also do have (at least in an algebraic sense): (differential forms + inner product) $\simeq$ "covariant geometric algebra" over $\mathbb{R}^n$ It is also worth noting that, according to Professor Lounesto on p. 218, Elie Cartan also studied Clifford algebras, in addition to introducing the modern notions of differential form and exterior derivative. So it is not all too surprising that they should actually be related to one another. In fact, thinking about (covariant) geometric algebra in terms of "differential forms + inner product", while using the geometric intuition afforded by geometric algebra, actually makes the ideas behind differential forms much more clear. See for example here. I'm only beginning to process all of the implications, but as an example, a $k-$blade represents a $k-$dimensional subspace, and its Hodge dual is the differential form of rank $n-k$ which represents its orthogonal complement. The reason why orthogonal complements are represented in the dual space is because the inner product between two vectors can also be defined as the product of a vector and a covector (w.r.t. our choice of non-degenerate quadratic form $Q$). All of this should be generalizable from $\mathbb{R}^n$ to the tangent and cotangent spaces of arbitrary smooth manifolds, unless I am missing something. This is especially the case for Riemannian manifolds, where we also get a non-degenerate quadratic form for each (co)tangent space for free. (Which raises the question of why David Hestenes wants us to throw out smooth manifolds in favor of vector manifolds, a topic for future research.) As to the answer to "why use geometric algebra and not differential forms", for now my answer is: Use the tensor algebras over $\mathbb{R}^n$ and $(\mathbb{R}^n)^*$, while appreciating the special properties of their exterior sub-algebras and remembering that, given our favorite quadratic form $Q$, we can always introduce an additional notion of "contraction" or "inner product" to make them into Clifford (geometric) algebras. Hyping geometric algebra alone misses the importance of linear duals and arbitrary tensors. Likewise, focusing on differential forms alone seems like a good way to do differential geometry without geometric intuition (i.e. with a mathematical lobotomy). Sensible minds may disagree. Note: There are a lot of differences in the theory in the case that the base field is $\mathbb{F}_2$. To some extent we should expect this, since in that case we don't even have "alternating = anti-symmetric". In particular, we don't have bivectors for fields of characteristic two, and defining/identifying a grading of the Clifford algebra via an isomorphism with the exterior algebra is impossible (at least if I am interpreting Professor Lounesto's paper correctly). In any case, when I say "geometric algebra", I essentially mean "Clifford algebras of vector spaces with base field the real numbers", so the exceptions thrown up in the case that the characteristic equals 2 don't really matter for the purposes of this question; we are dealing exclusively with characteristic 0, although generalizations are possible. A: I just want to point out that GA can be used to make covariant multivectors (or differential forms) on $\mathbb R^n$ without forcing a metric onto it. In other words, the distinction between vectors and covectors (or between $\mathbb R^n$ and its dual) can be maintained. This is done with a pseudo-Euclidean space $\mathbb R^{n,n}$. Take an orthonormal set of spacelike vectors $\{\sigma_i\}$ (which square to ${^+}1$) and timelike vectors $\{\tau_i\}$ (which square to ${^-}1$). Define null vectors $$\Big\{\nu_i=\frac{\sigma_i+\tau_i}{\sqrt2}\Big\}$$ $$\Big\{\mu_i=\frac{\sigma_i-\tau_i}{\sqrt2}\Big\};$$ they're null because $${\nu_i}^2=\frac{{\sigma_i}^2+2\sigma_i\cdot\tau_i+{\tau_i}^2}{2}=\frac{(1)+2(0)+({^-}1)}{2}=0$$ $${\mu_i}^2=\frac{{\sigma_i}^2-2\sigma_i\cdot\tau_i+{\tau_i}^2}{2}=\frac{(1)-2(0)+({^-}1)}{2}=0.$$ More generally, $$\nu_i\cdot\nu_j=\frac{\sigma_i\cdot\sigma_j+\sigma_i\cdot\tau_j+\tau_i\cdot\sigma_j+\tau_i\cdot\tau_j}{2}=\frac{(\delta_{i,j})+0+0+({^-}\delta_{i,j})}{2}=0$$ and $$\mu_i\cdot\mu_j=0.$$ So the spaces spanned by $\{\nu_i\}$ or $\{\mu_i\}$ each have degenerate quadratic forms. But the dot product between them is non-degenerate: $$\nu_i\cdot\mu_i=\frac{\sigma_i\cdot\sigma_i-\sigma_i\cdot\tau_i+\tau_i\cdot\sigma_i-\tau_i\cdot\tau_i}{2}=\frac{(1)-0+0-({^-}1)}{2}=1$$ $$\nu_i\cdot\mu_j=\frac{\sigma_i\cdot\sigma_j-\sigma_i\cdot\tau_j+\tau_i\cdot\sigma_j-\tau_i\cdot\tau_j}{2}=\frac{(\delta_{i,j})-0+0-({^-}\delta_{i,j})}{2}=\delta_{i,j}$$ Of course, we could have just started with the definition that $\mu_i\cdot\nu_j=\delta_{i,j}=\nu_i\cdot\mu_j$, and $\nu_i\cdot\nu_j=0=\mu_i\cdot\mu_j$, instead of going through "spacetime". The space $V$ will be generated by $\{\nu_i\}$, and its dual $V^*$ by $\{\mu_i=\nu^i\}$. You can take the dot product of something in $V^*$ with something in $V$, which will be a differential 1-form. You can make contravariant multivectors from wedge products of things in $V$, and covariant multivectors from wedge products of things in $V^*$. You can also take the wedge product of something in $V^*$ with something in $V$. $$\mu_i\wedge\nu_i=\frac{\sigma_i\wedge\sigma_i+\sigma_i\wedge\tau_i-\tau_i\wedge\sigma_i-\tau_i\wedge\tau_i}{2}=\frac{0+\sigma_i\tau_i-\tau_i\sigma_i-0}{2}=\sigma_i\wedge\tau_i$$ $$\mu_i\wedge\nu_j=\frac{\sigma_i\sigma_j+\sigma_i\tau_j-\tau_i\sigma_j-\tau_i\tau_j}{2},\quad i\neq j$$ What does this mean? ...I suppose it could be a matrix (a mixed variance tensor)! A matrix can be defined as a bivector: $$M = \sum_{i,j} M^i\!_j\;\nu_i\wedge\mu_j = \sum_{i,j} M^i\!_j\;\nu_i\wedge\nu^j$$ where each $M^i_j$ is a scalar. Note that $(\nu_i\wedge\mu_j)\neq{^-}(\nu_j\wedge\mu_i)$, so $M$ is not necessarily antisymmetric. The corresponding linear function $f:V\to V$ is (with $\cdot$ the "fat dot product") $$f(x) = M\cdot x = \frac{Mx-xM}{2}$$ $$= \sum_{i,j} M^i_j(\nu_i\wedge\mu_j)\cdot\sum_k x^k\nu_k$$ $$= \sum_{i,j,k} M^i_jx^k\frac{\nu_i\mu_j-\mu_j\nu_i}{2}\cdot\nu_k$$ $$= \sum_{i,j,k} M^i_jx^k\frac{(\nu_i\mu_j)\nu_k-\nu_k(\nu_i\mu_j)-(\mu_j\nu_i)\nu_k+\nu_k(\mu_j\nu_i)}{4}$$ (the $\nu$'s anticommute because their dot product is zero:) $$= \sum_{i,j,k} M^i_jx^k\frac{\nu_i\mu_j\nu_k+\nu_i\nu_k\mu_j+\mu_j\nu_k\nu_i+\nu_k\mu_j\nu_i}{4}$$ $$= \sum_{i,j,k} M^i_jx^k\frac{\nu_i(\mu_j\nu_k+\nu_k\mu_j)+(\mu_j\nu_k+\nu_k\mu_j)\nu_i}{4}$$ $$= \sum_{i,j,k} M^i_jx^k\frac{\nu_i(\mu_j\cdot\nu_k)+(\mu_j\cdot\nu_k)\nu_i}{2}$$ $$= \sum_{i,j,k} M^i_jx^k\frac{\nu_i(\delta_{j,k})+(\delta_{j,k})\nu_i}{2}$$ $$= \sum_{i,j,k} M^i_jx^k\big(\delta_{j,k}\nu_i\big)$$ $$= \sum_{i,j} M^i_jx^j\nu_i$$ This agrees with the conventional definition of matrix multiplication. In fact, it even works for non-square matrices; the above calculations work the same if the $\nu_i$'s on the left in $M$ are basis vectors for a different space. A bonus is that it also works for a non-degenerate quadratic form; the calculations don't rely on ${\mu_i}^2=0$, nor ${\nu_i}^2=0$, but only on $\nu_i$ being orthogonal to $\nu_k$, and $\mu_j$ being reciprocal to $\nu_k$. So you could instead have $\mu_j$ (the right factors in $M$) be in the same space as $\nu_k$ (the generators of $x$), and $\nu_i$ (the left factors in $M$) in a different space. A downside is that it won't map a non-degenerate space to itself. I admit that this is worse than the standard matrix algebra; the dot product is not invertible, nor associative. Still, it's good to have this connection between the different algebras. And it's interesting to think of a matrix as a bivector that "rotates" a vector through the dual space and back to a different point in the original space (or a new space). Speaking of matrix transformations, I should discuss the underlying principle for "contra/co variance": that the basis vectors may vary. We want to be able to take any (invertible) linear transformation of the null space $V$, and expect that the opposite transformation applies to $V^*$. Arbitrary linear transformations of the external $\mathbb R^{n,n}$ will not preserve $V$; the transformed $\nu_i$ may not be null. It suffices to consider transformations that preserve the dot product on $\mathbb R^{n,n}$. One obvious type is the hyperbolic rotation $$\sigma_1\mapsto\sigma_1\cosh\phi+\tau_1\sinh\phi={\sigma_1}'$$ $$\tau_1\mapsto\sigma_1\sinh\phi+\tau_1\cosh\phi={\tau_1}'$$ $$\sigma_2={\sigma_2}',\quad\sigma_3={\sigma_3}',\quad\cdots$$ $$\tau_2={\tau_2}',\quad\tau_3={\tau_3}',\quad\cdots$$ (or, more compactly, $x\mapsto\exp(-\sigma_1\tau_1\phi/2)x\exp(\sigma_1\tau_1\phi/2)$ ). The induced transformation of the null vectors is $${\nu_1}'=\frac{{\sigma_1}'+{\tau_1}'}{\sqrt2}=\exp(\phi)\nu_1$$ $${\mu_1}'=\frac{{\sigma_1}'-{\tau_1}'}{\sqrt2}=\exp(-\phi)\mu_1$$ $${\nu_2}'=\nu_2,\quad{\nu_3}'=\nu_3,\quad\cdots$$ $${\mu_2}'=\mu_2,\quad{\mu_3}'=\mu_3,\quad\cdots$$ The vector $\nu_1$ is multiplied by some positive number $e^\phi$, and the covector $\mu_1$ is divided by the same number. The dot product is still ${\mu_1}'\cdot{\nu_1}'=1$. You can get a negative multiplier for $\nu_1$ simply by the inversion $\sigma_1\mapsto{^-}\sigma_1,\quad\tau_1\mapsto{^-}\tau_1$; this will also negate $\mu_1$. The result is that you can multiply $\nu_1$ by any non-zero Real number, and $\mu_1$ will be divided by the same number. Of course, this only varies one basis vector in one direction. You could try to rotate the vectors, but a simple rotation in a $\sigma_i\sigma_j$ plane will mix $V$ and $V^*$ together. This problem is solved by an isoclinic rotation in $\sigma_i\sigma_j$ and $\tau_i\tau_j$, which causes the same rotation in $\nu_i\nu_j$ and $\mu_i\mu_j$ (while keeping them separate). Combine these stretches, reflections, and rotations, and you can generate any invertible linear transformation on $V$, all while maintaining the degeneracy ${\nu_i}^2=0$ and the duality $\mu_i\cdot\nu_j=\delta_{i,j}$. This shows that $V$ and $V^*$ do have the correct "variance". See also Hestenes' Tutorial, page 5 ("Quadratic forms vs contractions").
{ "pile_set_name": "StackExchange" }
Q: How to add set elements to a string in python how would I add set elements to a string in python? I tried: sett = set(['1', '0']) elements = '' for i in sett: elements.join(i) but no dice. when I print elements the string is empty. help A: I believe you want this: s = set(['1', '2']) asString = ''.join(s) Be aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them.
{ "pile_set_name": "StackExchange" }
Q: How to flatten tables using LINQ I've this query: var usersByBranch = (from u in _db.VRT_User join urb in _db.VRT_UserRoleBranch on u.UserId equals urb.UserId join r in _db.VRT_Role on urb.RoleId equals r.RoleId where branches.Contains(urb.BranchId) select new UserRoleBranchModel { UserId = u.UserId, BranchId = urb.BranchId, RoleId = urb.RoleId, RoleName = r.RoleName }); In this query, for the same userId, the roleId (1-4) and RoleName with the same BranchId are returned separately. I'd like to flatten the rows, so that a row with the same userId contains all the RoleId and RoleName within the same BranchId. Your help is greatly appreciated. A: Not sure what you mean by contains, but you can't use the same UserRoleBranchModel to hold multiple roles, so an anonymous object will do the job: var usersByBranch = (from u in _db.VRT_User join urb in _db.VRT_UserRoleBranch on u.UserId equals urb.UserId join r in _db.VRT_Role on urb.RoleId equals r.RoleId where branches.Contains(urb.BranchId) group r by new { urb.UserId, urb.BranchId } into rg select new { UserId = rg.Key.UserId, BranchId = rg.Key.BranchId, Roles = rg.Select(r => r) });
{ "pile_set_name": "StackExchange" }
Q: LoadImage() with variable path? How do I get LoadImage(); to work with a variable file path? I have the desired file path in the variable bg, and I'm calling the function like so: bmp = LoadImage(hInst,bg,IMAGE_BITMAP,640,480,LR_LOADFROMFILE); Yet bmp does not render any image when used with: BitBlt(hDC,0,0,640,480,memDC,0,0,SRCCOPY); If I can't use LoadImage();, what equivalent is there that can handle non-constant file names? [EDIT] Apparently, the error was caused by another bit of code, and not the LoadImage() function. Disragerd. A: It seems to be the timer. The documentation about the SetTimer function says that the second parameter (nIDEvent) must be a nonzero value. So, I imagine your timer is never firing, the execmain() function is never called, and so your bg string is never set. When you replace bg by a string literal, it works, because the WM_PAINT message does not depend on the timer, it is always called at least once when the window is created.
{ "pile_set_name": "StackExchange" }
Q: Satz mit den meisten aufeinanderfolgenden Verben Es geht um Sätze mit aufeinanderfolgenden Verben ohne andere Wortarten oder Satzzeichen dazwischen. Beispiele (Länge der längsten Verbfolge in Klammern): Ich schreibe einen Brief (1) Ich habe einen Brief schreiben müssen (2) Der Brief muss geschrieben werden (3) Der Brief hätte geschrieben werden müssen (4) Ein Bekannter meinte, dass es nicht möglich sei, einen korrekten Satz mit mehr als vier aufeinanderfolgenden Verben zu formulieren, aber nach einiger Zeit ist mir ein Satz mit fünf eingefallen: Er war nicht so blöd, wie man hätte geneigt sein können anzunehmen. Ist das auch mit mehr als fünf Verben möglich? Ich habe jetzt eine Weile darüber nachgedacht, aber mir ist kein anderer Satz mit fünf oder mehr aufeinanderfolgenden Verben eingefallen. A: Man kann im Grunde alle verfügbaren Modalverben aneinanderreihen, auch wenn pro hinzugefügten Modalverb es immer aufwendiger wird, einen Sitz im Leben für einen solchen Satz zu finden. Aber unmöglich ist es nicht. Ich hätte das Honigglas nicht auslecken dürfen. Ich hätte das Honigglas nicht auslecken wollen sollen. [...] Ich hätte das Honigglas nicht auslecken wollen sollen können dürfen müssen mögen. Nun kann man aber auch die Modalverben mehrfach einsetzen: Ich hätte das Honigglas nicht auslecken dürfen dürfen. Sprich: Es wäre besser gewesen, Autoritätsperson 1 hätte es Autoritätsperson 2 nicht gestattet, mir zu gestatten, das Honigglas auszulecken. A: Ohne Partizipien (also nur finite und infinite Verbformen) können Konstruktionen mit Verben der Wahrnehmung (zB sehen, hören) manchmal viele aufeinanderfolgenden Infinitivformen enthalten. Ein Zitat aus "Der Prozess" von Franz Kafka: Als ich mich ein Weilchen wieder so ruhig verhalten hatte, dass man die Fliegen an der Wand hätte können gehen hören, vernahm ich, dass... Ich bin aber eher der Meinung, dass die Reihenfolge in diesem Fall eher unidiomatisch ist. Hätte gehen hören können fände ich besser. Man kann sich auch locker eine realistische Situation vorstellen, wo noch ein Modalverb dazu kommt, ohne dass es zu schräg klingt, und noch verständlich wäre, bspw.: Es war im Raum so leise, dass man ihn eigentlich hätte atmen hören können sollen. A: Man kann deinen Beispielsatz einfach erweitern: Er war nicht so blöd, wie man hätte geneigt gewesen sein können anzunehmen.
{ "pile_set_name": "StackExchange" }
Q: How to send C++ console params to C# DLL I need to send two numbers entered as parameters or requested by C++ console to a library in C#. Manually the code is: BSTR thing_to_send = ::SysAllocString(L"10 20"); How can I create a variable of type BSTR using the values of the parameters indicated by the console or by two variables of type integer or string. I need to concatenate the values using a space between them, for example: string Num1 = 30; string Num2 = 40; string dataToSend = Num1 + " " + Num2; or string Num1 = argv[1]; string Num2 = argv[2]; string dataToSend dataToSend += Num1 + " "; dataToSend += Num2; How I can convert dataToSend to BSTR valid variable to send with: HRESULT hResult = obj->GetTheThing(dataToSend, &returned_thing);? What I have tried: In each page that I have reviewed other types of values of origin for the transformation are indicated, with explicit values of chain like being "Cade to convert" but not with the use of variables as it is in this case The code I need to solve is: BSTR thing_to_send = ::SysAllocString(L"10 20"); BSTR returned_thing; BimObjectTest_CSharp::_TheClassPtr obj(__uuidof(BimObjectTest_CSharp::TheClass)); HRESULT hResult = obj->GetTheThing(thing_to_send, &returned_thing); the literal L "10 20" must be replaced by the parameters of the console or by two variables requested via the console, note the space between the values! BSTR thing_to_send should contain, for example, argv[1] + " " + argv[2]! A: Here is a function CombineStrings, that combines two _TSTRINGs to BSTR with space between them. There is also a main function that show how to call it with console arguments. BSTR CombineStrings(_TCHAR* arg1, _TCHAR* arg2) { long len1 = wcsnlen_s(arg1, 100); long len2 = wcsnlen_s(arg2, 100); BSTR result = SysAllocStringLen(NULL, len1 + len2 + 1); memcpy(result, arg1, len1 * sizeof(OLECHAR)); memcpy(result + len1, L" ", 1 * sizeof(OLECHAR)); memcpy(result + len1 + 1, arg2, len2 * sizeof(OLECHAR)); result[len1 + len2 + 1] = NULL; // contains "firstarg<empty>secondarg" return result; } int _tmain(int argc, _TCHAR* argv[]) { if (argc < 3) { // two arguments required. return -1; } BSTR combinedStr = CombineStrings(argv[1], argv[2]); BSTR returned_thing; HRESULT hResult = obj->GetTheThing(combinedStr, &returned_thing); SysFreeString(combinedStr); return 0; }
{ "pile_set_name": "StackExchange" }
Q: Why doesn't `FOO=42 echo "$FOO"` print 42 in Bash? I'm confused by this behaviour: $ FOO=42 echo "$FOO" $ FOO=42 && echo "$FOO" 42 I'm accustomed to using VARNAME=value cmd to specify environment variables for other commands, so I was surprised to discover it doesn't work when cmd is echo. This might have something to do with echo being a Bash built-in. Is this the case? If so, is using && the best way to specify environment variables for Bash built-ins? Update: && is no good, as it results in the environment variables being set permanently, which I'm trying to avoid. A: It doesn't matter that echo is a built-in. The reason is that variables on the command line are evaluated before executing the command, they're not evaluated by the command. You could get the result you want with: FOO=42 bash -c 'echo "$FOO"' This starts a new shell to execute echo $foo. Since the argument to bash is in single quotes, the variable is not replaced by the original shell. A: The replacement happens before the command is executed: $FOO is replaced with its current value. echo "" is executed with $FOO set to 42. Try: FOO=42 sh -c 'echo "$FOO"'
{ "pile_set_name": "StackExchange" }
Q: Does this code not follow or violate prototype pattern in any way? Instead of getting clone object and modifying attributes, I have first modified attributes of the object and then returned its clone. Is there any difference rule-wise and performance-wise? Also, any other suggestions regarding the design would be great. Thanks. public class Category implements Cloneable { private int id; private String title; private int totalGames; // getters and setters public Category clone() { try { return (Category)super.clone(); } catch(CloneNotSupportedException ex) { return null; } } } public class CategoryCache { private static Category category = new Category(0, null, 0); private CategoryCache() { } public static Category getCategory(int id, String title, int totalGames) { category.setId(id); category.setTitle(title); category.setTotalGames(totalGames); return category; } } while (<100 times>) { Category category = CategoryCache.getCategory(<var1>, <var2>, <var3>).clone(); arlCategory.add(category); // add to arraylist } A: Indeed more than a pattern, Prototype is a work around for increasing performance in Java. The basic thing we need to understand is 'we need Prototype whenever we think that direct creation looks costly, hence we are using a clone of an existing one rather than newly creation. So primarily we replace the creation (new()) with someExistingObject.clone(). So it doesn't matter whether you are changing the attributes before/after cloning, you have achieved the ultimate goal. So the results will be same. The only difference in your way is, the object you are using for cloning purpose (which you are using again and again) most probably will be a dedicated one only for cloning process, and can not perform any other work.
{ "pile_set_name": "StackExchange" }
Q: NGINX SSL Forward Proxy Config I know that NGINX is not supposed to be used as a forward proxy but I have a requirement to do so ... Anyway, obviously it is not to hard to get http to work as a forward proxy but issues arise when trying to configure https. I generated some self signed certs and then try to connect to https://www.google.com and it gives me the error ERR_TUNNEL_CONNECTION_FAILED. The issue has to do with my certs somehow but I have no idea how to fix the issue. Does anyone know how to achieve this functionality ? Here is my config server { listen 443 ssl; root /data/www; ssl on; ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/certs/server.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { resolver 8.8.8.8; proxy_pass https://$http_host$uri$is_args$args; } } A: The reason NGINX does not support HTTPS forward proxying is because it doesn't support the CONNECT method. However, if you are interested in using it as a HTTPS forwarding proxy you can use the ngx_http_proxy_connect_module
{ "pile_set_name": "StackExchange" }
Q: global/inner variable conflict? (python) Sorry for the stupid question, I'm a newbie programmer. But can anyone tell me why the following program behaves this way? def lol(a): a=[] a.append(1) return a Now when I do k = [2, 3] lol(k) It returns 1, but k is still unchanged? Why? Thanks a lot! A: In lol(a), the line a=[] binds a to a new list. After this line, a is no longer bounded to the same list than k. So what you're actually modifying in your function is a new list, not the list that you received in argument. For further information, see the docs. If you want k to be [1], then you could write something like this instead: def lol(a): a[:] = [1] return a k = [2, 3] lol(k) # now k is equal to [1]
{ "pile_set_name": "StackExchange" }
Q: WinForm - draw resizing frame using a single-pixel border In a Windows Form with a Resizing Frame, the frame border draws with a raised 3-D look. I'd like it to draw with a flat single pixel border in a color of my choosing. Is this possible without having to owner draw the whole form? A: You could try something like this: Point lastPoint = Point.Empty; Panel leftResizer = new Panel(); leftResizer.Cursor = System.Windows.Forms.Cursors.SizeWE; leftResizer.Dock = System.Windows.Forms.DockStyle.Left; leftResizer.Size = new System.Drawing.Size(1, 100); leftResizer.MouseDown += delegate(object sender, MouseEventArgs e) { lastPoint = leftResizer.PointToScreen(e.Location); leftResizer.Capture = true; } leftResizer.MouseMove += delegate(object sender, MouseEventArgs e) { if (lastPoint != Point.Empty) { Point newPoint = leftResizer.PointToScreen(e.Location); Location = new Point(Location.X + (newPoint.X - lastPoint.X), Location.Y); Width = Math.Max(MinimumSize.Width, Width - (newPoint.X - lastPoint.X)); lastPoint = newPoint; } } leftResizer.MouseUp += delegate (object sender, MouseEventArgs e) { lastPoint = Point.Empty; leftResizer.Capture = false; } form.BorderStyle = BorderStyle.None; form.Add(leftResizer);
{ "pile_set_name": "StackExchange" }
Q: Linux cron job fails to execute part of script which works in shell I'm having a problem with a script that writes to a log file during a backup procedure. Tested perfectly when called from the root shell, but fails when run from the cron demon. Backup is done over a series of partitions and the on-site admin will rotate the drives in the top dock weekly. In order to know where the most recent backup is located I've included the following lines sudo hdparm -I /dev/sdb | grep 'Model Number' sudo hdparm -I /dev/sdb | grep 'Serial Number' I've tried this with a >> /batch/backup.log and without. When the bash script is run from the command line, it works beautifully. But when the crontab calls the script the output from these lines is blank. crontab entry: 00 00 * * * /batch/backup.bat >> /batch/backup.log I have no idea why other than the possibility that cron can't handle the pipe or the grep or something. I have isolated the lines in a test.bat but they remain blank. The backup script uses the hdparm to spin down the drive at the end, but now I wonder if that's not working properly either if cron can't handle hdparm. A: That is probably because hdparm is not in the PATH when the script is executed through cron. Although less likely, same might apply to grep as well. Try replacing hdparm with /full/path/to/hdparm in your script.
{ "pile_set_name": "StackExchange" }
Q: how to format a number in mIRC? My remote script gets a variable with a number formatted like 4365271385. I would like the script to send a message with the variable in it formatted like 4.365.271.385. I searched the internet and the help file, but i couldn't find it. Sometimes the number is in the thousands, sometimes in the billions. How to do this? Can't be hard, can it? A: It is indeed not very hard. Use $bytes, in your case $bytes(4365271385,bd) b parameter: Comma-formats the number for bytes. d parameter: Returns the value whilst retaining decimal point values. You don't need this if you're only working with whole integers. But it's handy to have. More at http://en.wikichip.org/wiki/mirc/identifiers/$bytes
{ "pile_set_name": "StackExchange" }
Q: Android UI Mathematics required for the implementation Can someone tell me what would be the math required for moving around the small ball in the bar(meter) according to the touch motion.... I needed a clear idea on the logic.. A: The logic depends on how you want to model the interaction between the finger and the ball. Is it moving through a fluid, like a ball bearing? A gravitational field? Do you want it to decelerate as if under the influence of friction from the sides of the bar? Or do you want to simply have the ball track the finger, without fancy damping of the motion? My point is that the "logic" can be pretty complicated, depending on how you decide to model it. I'd recommend looking for something canned in JavaScript before coding it yourself.
{ "pile_set_name": "StackExchange" }
Q: WPF Group Items in ComboBox programmatically (Creating Data Templates in Code) I need to group my Items in a Combobox like this. [Category] - Item - Item [Category2] - Item - Item I found an working answer here, but my comboboxes are created dynamically by User Action. Is it possible to fill the Combobox like this programmatically? The Items I want to display are ModuleCategoryViewControl's : public class ClassNameController { public string Name { get; set; } public System.Type ObjectType { get; set; } public ClassNameController(string name, Type objectType) { this.Name = name; this.ObjectType = objectType; } public override string ToString() { return Name; } } class ModuleCategoryViewControl : ClassNameController { public string Category { get; set; } public ModuleCategoryViewControl(string name, string category, Type objectType) : base(name, objectType) { this.Category = category; } } They should group by Category and displayed by Name A: Is it possible to fill the Combobox like this programmatically? The sample code on the link you supplied does fill the ComboBox programmatically so it's unclear what your issue really is. If you add items dynamically at runtime you should replace the List<ModuleCategoryViewControl> with an ObservableCollection<ModuleCategoryViewControl>. Please refer to the following sample code. Window.xaml.cs: public partial class MainWindow : Window { readonly ObservableCollection<ModuleCategoryViewControl> items = new ObservableCollection<ModuleCategoryViewControl>(); public MainWindow() { InitializeComponent(); items.Add(new ModuleCategoryViewControl("Item2", "A", typeof(int))); items.Add(new ModuleCategoryViewControl("Item2", "A", typeof(int))); items.Add(new ModuleCategoryViewControl("Item3", "A", typeof(int))); items.Add(new ModuleCategoryViewControl("Item4", "B", typeof(int))); items.Add(new ModuleCategoryViewControl("Item5", "B", typeof(int))); ListCollectionView lcv = new ListCollectionView(items); lcv.GroupDescriptions.Add(new PropertyGroupDescription("Category")); comboBox.ItemsSource = lcv; } private void Button_Click(object sender, RoutedEventArgs e) { items.Add(new ModuleCategoryViewControl("Item6", "A", typeof(int))); items.Add(new ModuleCategoryViewControl("Item7", "C", typeof(int))); } } Window.xaml: <StackPanel x:Name="sp"> <ComboBox x:Name="comboBox"> <ComboBox.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </GroupStyle.HeaderTemplate> </GroupStyle> </ComboBox.GroupStyle> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> <Button Content="Add Item" Click="Button_Click" /> </StackPanel> If you want to create the DataTemplates programmatically you could use the XamlReader.Parse method: ComboBox cmb = new ComboBox(); cmb.GroupStyle.Add(System.Windows.Markup.XamlReader.Parse("<GroupStyle xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><GroupStyle.HeaderTemplate><DataTemplate><TextBlock Text=\"{Binding Name}\"/></DataTemplate></GroupStyle.HeaderTemplate></GroupStyle>") as GroupStyle); cmb.ItemTemplate = System.Windows.Markup.XamlReader.Parse("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><TextBlock Text=\"{Binding Name}\"/></DataTemplate>") as DataTemplate; cmb.ItemsSource = lcv; sp.Children.Add(cmb);
{ "pile_set_name": "StackExchange" }
Q: My iOS app isn't requesting iAds I recently released my first app on the app store (August 5, 2014 release). When I was testing the app the test iAds seemed to never go away. Now, the actual app available on the app store isn't displaying any ads. I have read similar question, where iAds didn't work at first, but everyone says they started working after a little bit. However, mine seems unique in that it made six impressions right after it was first downloaded (6 requests, 6 impressions), but it hasn't done anything since. Is this a programming error and that's why my requests are low, or is this common for iAds on new apps? Thanks. Oh, and I added ads using the method shown in this video https://www.youtube.com/watch?v=u5XcVnHCQ0w The app uses Sprite Kit and was designed for iOS 7.0. There is only one view controller and it only displays banner ads. The app also uses Game Center if that is of any importance. A: iAd takes a few days to look at new apps and then approves those for the iAd network. It is normal that you will have to wait a little bit.
{ "pile_set_name": "StackExchange" }
Q: Show HyperLinks in Gridview I have an XML file and it contains data about products,and the most interesting data is a url that takes user to the page of thah product.I have successfully extracted urls from that XML file into XmlNodeList and then I put them into DataTable so these urls can be displayed in ASPxGridview.But these urls are shown as text and are not clickable.How to convert the text into HyperLinks?Thanks in advance! A: You are looking for a HyperLinkField: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlinkfield.aspx You'd bind the url to the DataNagivateUrlFields property. Edit with code example: <asp:gridview id="gv1" autogeneratecolumns="true" runat="server"> <columns> <asp:hyperlinkfield text="View Product" DataNavigateUrlFields="url" /> </columns> </asp:gridview>
{ "pile_set_name": "StackExchange" }
Q: Are there any tutorials on version 10 notebook templating and report generation? Are there missing docs? Bug introduced in 10.0 and persisting through 10.2 or later I am trying to understand the new templating in version 10. While there is a general documentation page with links to docs for each new function, so far I am unable to find any report generation worked examples of what a user may do after they open File > New > Template Notebook. Additionally when I press the help button on the template notebook it seems there is documentation missing: When you type "ReportGeneration" in the docs this is what you get: Templates were first introduced in the Finance Platform -- which is essentially a version of Mathematica with a few other functions. Rather than have report generation functions without any coherent description of how a user can start from scratch and make a template and an automated report, the Finance Platform has a wealth of material, including a tour: ...detailed extensive documentation: ...a specific palette that contains links to the tour, the extensive documentation and a video: All of this stuff is missing from my OS X version 10. Is it present in Windows? A: Confirmed bug by WRI tech support A: John Fultz gave a great talk about the templating system at the European Wolfram Technology Conference in 2014 - http://www.wolfram.com/events/technology-conference-eu/2014/presentations/Fultz_ReportGeneration.nb As requested, here's a video of John doing madlibs http://www.wolfram.com/broadcast/video.php?sx=Report%20Generation&v=1096 A: Maybe they renamed it. You should search the help for "AutomatedReports" this will bring you to guide/AutomatedReports. Or on the web: AutomatedReports. Some small examples and more details are presented at Automated Report Generation and the links therein.
{ "pile_set_name": "StackExchange" }
Q: jQuery changing font family and font size I am trying to change font family and font size of the text that appears in a textarea and a container by choosing the font from the list, font size should be fixed. I am also trying to change color of the background when a font is picked. That is my code: <script type="text/javascript"> function changeFont(_name) { document.body.style.fontFamily = _name; document.textarea = _name; } </script> </head> <body style="font-family"> <form id="myform"> <input type="text" /> <button>erase</button> <select id="fs" onchange="changeFont(this.value);"> <option value="arial">Arial</option> <option value="verdana">Verdana</option> <option value="impact">Impact</option> <option value="'ms comic sans'">MS Comic Sans</option> </select> <div align="left"> <textarea style="resize: none;" id="mytextarea" cols="25" rows="3" readonly="readonly" wrap="on"> Textarea </textarea> <div id='container'> <div id='float'> <p>This is a container</p> </div> </form> </body> When I try it in the browser the font family does not change in the text area. It only changes in the container. I also do now know how to set a new font size and background for the container and the textarea when the font family is picked. I will appreciate any help guys! A: Full working solution : HTML: <form id="myform"> <button>erase</button> <select id="fs"> <option value="Arial">Arial</option> <option value="Verdana ">Verdana </option> <option value="Impact ">Impact </option> <option value="Comic Sans MS">Comic Sans MS</option> </select> <select id="size"> <option value="7">7</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> </form> <br/> <textarea class="changeMe">Text into textarea</textarea> <div id="container" class="changeMe"> <div id="float"> <p> Text into container </p> </div> </div> jQuery: $("#fs").change(function() { //alert($(this).val()); $('.changeMe').css("font-family", $(this).val()); }); $("#size").change(function() { $('.changeMe').css("font-size", $(this).val() + "px"); }); Fiddle here: http://jsfiddle.net/AaT9b/ A: In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class. don't know if that's an option in your case though.
{ "pile_set_name": "StackExchange" }
Q: Use cases between interface implementations I know two ways to use an Interface. public interface MyInterface { void myMethod(); } Approach: Using implements: public class MyClass implements MyInterface { @Override myMethod(){} } I'm using an Interface this way most of the time, if the interface is a contract like: MyInterface foo = new MyClass(); Now I can control MyClass with the provided methods of the Interface. This is also nice for collections. If there are some classes which implements MyInterface I have a common thread: List<MyInterface> list = new ArrayList<MyInterface>(); Approach: Using it as an anonymous class: public class MyClass { public MyInterface myInterface = new MyInterface(){ @Override public void myMethod(){} }; } This approach I'm using for callbacks with dependcy injection like this: public class MyOtherClass { public MyInterface myInterface; // Using setter injection here public void setInterface(MyInterface interface){ myInterface = interface; } } MyOtherClass is calling myInterface.myMethod() where it is appropriate. A callback can be realized with the first approach by using the this pointer too. Now I would like to know which approach should be used for a callback and why? I have seen both and I don't know where the real benefit is. As I see it, that's the only difference where I can choose between the first and second approach. If I'm wrong here please tell me another difference. I'm asking this to be able to select the proper tool for different situations. In addition I would like to know another situation but a callback, where I can use the second approach. A: The choice of using a named or an anonymous interface implementation depends on several things: Are you planning to reuse some of the logic in the implementation? - If the answer is "yes", use the first approach; otherwise, use the second approach. Do you need to implement complex logic with lots of external interactions? - If the answer is "yes", use the first approach; otherwise, use the second approach. Does your interface have multiple methods, some of which may meaningfully do nothing? - If the answer is "yes", use the first approach, or make a "default" class with all implementations doing nothing; otherwise, use the second approach. In the end, the biggest difference between these two approaches is mostly non-technical: it has to do with readability of your resultant code. After all, anonymous classes are a little more than "syntactic sugar" - you can perfectly implement your system with only named classes. If you think that a named implementation reads better, use the first approach; if you think that an anonymous one works better, use the second approach.
{ "pile_set_name": "StackExchange" }
Q: why does new Integer(i).hashCode() return i? I want to know why new Integer(i).hashCode() or new Long(i).hashCode() returns i but when hashCode() is invoked by some other object say new Double(345).hashCode(), it returns a random number. Why? A: Because the int value of an Integer perfectly satisfies and fully complies with the general contract of Object.hashCode(): The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. In short: The hash codes for 2 objects must be the same if equals() returns true and should be (but not required) different if equals() returns false. Also by the declaration of Object.hashCode() it must be an int. Ideally the hash code should depend on all the data that is hashed. Hash code of Long Long has to map 8 bytes to 4 bytes (size of an int). Current implementation of Long.hashCode() will only return i if it fits into an int, else it will be XOR'ed with the upper 32 bits (4 bytes): return (int)(value ^ (value >>> 32)); Hash code of Double Obviously the double value of a Double does not qualify for this. Double also has to map 8 bytes to 4 bytes. Double.hashCode() will return a seemingly random value because floating point numbers (float and double) are not stored "nicely" (e.g. 2's complement like int or long) in the bytes that are reserved for them but using IEEE 754 binary floating point standard and so mapping those 8 bytes to 4 (this is exactly what the implementation does) will not be a meaningful number as an int which uses 2's complement representation. long bits = doubleToLongBits(value); return (int)(bits ^ (bits >>> 32)); A: A value of an integer is a good enough hash because it is just as unique as the unique integer number itself. A double has to be hashed in some different manner because the hash here has to be an integer. A: Becase the implementation say it: Returns a hash code for this Integer. Returns:a hash code value for this object, equal to the primitive int value represented by this Integer object. 707 708 public int hashCode() { 709 return value; 710 }
{ "pile_set_name": "StackExchange" }
Q: mySQL stored procedural with variable method, query and limit Hello I'm quite new to mySQL and I'm trying to write a stored procedure. I've searched on the internet to questions alike this one but I couldn't find any results for this. I'm trying to make search function for my webapplication where you can search in the database for results, yet there are different methods to search on (By name, last name, adres, etc). The query should also have a limit in results (1, 5, 10, 20). My idea was something like this: CREATE PROCEDURE SelectTopResults @query varchar(60), @method varchar(20), @limited int(3) AS SELECT * FROM customer WHERE @method = %@query% LIMIT @limited GO; This doesn't run. Is this idea of the procedure correct? And how should I fix it then? Or is there another better way to do this? Thanks in advance. Edit: This is to be accessed with PHP. My idea was to write a code that basically does: $sql = 'EXEC SelectTopResults @method = ?, @query = ?, @limited = ?;' Edit 2: Solved, thanks a lot! :) For those interested in the code: DELIMITER // CREATE PROCEDURE selectTopResults(IN col varchar(64), IN limited int(3), searchquery varchar(60)) BEGIN SET @s = CONCAT("SELECT * FROM customer WHERE ",col," LIKE '%",searchquery,"%' LIMIT ",limited); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; END // DELIMITER ; Also works with wildcards and can be called upon with: CALL selectTopResults('column_name', 5, 'query'); whereby 5 is the limit A: Welcome to the forum. You've got it a bit wrong - there is something about stored procedures in the MySQL manual, but I can never find it in the first attempt. Luckily, there are many tutorials, if you search for them in google, bing or whatever. Try this, for example: https://www.mysqltutorial.org/introduction-to-sql-stored-procedures.aspx So, to get your procedure to work: DELIMITER $$ CREATE PROCEDURE SelectTopResults ( query varchar(60), method varchar(20), limited int(3) ) BEGIN ... END$$ DELIMITER ; It is normal to use the DELIMITER statement to change what signifies the end of a statement - otherwise, you are going to get error messages when you type in the statements that go into the procedure. Next, you need round brackets around your parameters and no @ before their names. You may wonder why I break the parameter list out over several lines; this is just my style - I feel it makes it easier to read where the parameters start and end. Finally, about your SELECT statement: SELECT * FROM customer WHERE @method = %@query% LIMIT @limited I'm not sure what you are trying here - firstly, you need to loose the @s - that is for variables you set with SET, I believe (I'm writing from memory, as I am not near my manuals), not for variables and parameters in a procedure or function. But more importantly, you can't use the parameter method as the name of a table column - for that you need to construct the SELECT as a string and execute. This is called 'dynamic SQL', as far as I recall; I think you can do this in MySQL, but I am not sure without looking it up. I hope this helps, and hopefully somebody with more immediate knowledge can help you better.
{ "pile_set_name": "StackExchange" }
Q: Condition when I do not have a file in my list My script: #!/bin/bash NOW=$(date +"%Y%m%d%t%H%M%S") # Pour chaque dossiers "log" trouvé. for folder in $(find . -name "*log*" -type d ) do : # Pour chaque dossier log contenant des fichiers ".log" vieux de +30jours. tar czf archive-log.$NOW.tar.gz $(find $folder -name "*.log" -mtime +30) # On supprime les anciens fichiers de log rm $(find $folder -name "*.log" -mtime +30) done my question is: What test do I find out if I have files to be archived or not ? Thx A: If you want to skip the case in which there are no files to archive, this can help you: if [ ! -z $(find $folder -name "*.log" -mtime +30) ] then tar czf archive-log.$NOW.tar.gz $(find $folder -name "*.log" -mtime +30) rm $(find $folder -name "*.log" -mtime +30) else echo "there are no files to archive" fi The syntax if [ -z "string" ] checks if a string is empty or not. Negating it, if [ ! -z $(find...) ] we check if the result returns results or not.
{ "pile_set_name": "StackExchange" }
Q: How to Disable JButton I want my JButton to be Disabled until all of the fields has inputs. package Grade; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GradeGUI extends JFrame { private JLabel quizL,exerL,partL,partLL,examL,finalSL,totalIL,totalL,blankL,blankL2,blankL3,blankL4,blankL5,blankL6,blankL7,blankL8; private JTextField quizTF,exerTF,examTF,partTF,quizTF1,exerTF1,examTF1,total1,total2,total3,total4,totalF,letterTF; private JButton calculateB,exitB; private CalculateButtonHandler cbHandler; private ExitButtonHandler exitHandler; public GradeGUI(){ blankL8=new JLabel(""); blankL7=new JLabel(""); blankL6=new JLabel(""); blankL5=new JLabel(""); blankL4=new JLabel(""); blankL3=new JLabel(""); blankL2=new JLabel(""); blankL=new JLabel(""); partLL=new JLabel(""); quizL=new JLabel("Quiz: "); exerL=new JLabel("Exercise: "); partL=new JLabel("Participation: "); examL=new JLabel("Exams: "); finalSL=new JLabel("Final Score"); totalIL=new JLabel("Total # of Items"); totalL=new JLabel("Final Score"); letterTF=new JTextField(25); quizTF=new JTextField(25); exerTF=new JTextField(25); examTF=new JTextField(25); partTF=new JTextField(25); quizTF1=new JTextField(25); exerTF1=new JTextField(25); examTF1=new JTextField(25); total1=new JTextField(25); total2=new JTextField(25); total3=new JTextField(25); total4=new JTextField(25); totalF=new JTextField(25); total1.setEditable(false); total2.setEditable(false); total3.setEditable(false); total4.setEditable(false); totalF.setEditable(false); letterTF.setEditable(false); calculateB=new JButton("Calculate"); exitB=new JButton("Exit"); calculateB=new JButton("Calculate"); cbHandler= new CalculateButtonHandler(); calculateB.addActionListener(cbHandler); exitB=new JButton("Exit"); exitHandler= new ExitButtonHandler(); exitB.addActionListener(exitHandler); setTitle("Grade Calculator"); Container p = getContentPane(); p.setLayout(new GridLayout(6,5)); p.add(blankL); p.add(finalSL); p.add(totalIL); p.add(totalL); p.add(blankL4); p.add(quizL); p.add(quizTF); p.add(quizTF1); p.add(total1); p.add(blankL5); p.add(exerL); p.add(exerTF); p.add(exerTF1); p.add(total2); p.add(blankL6); p.add(partL); p.add(partTF); p.add(blankL2); p.add(total3); p.add(blankL7); p.add(examL); p.add(examTF); p.add(examTF1); p.add(total4); p.add(blankL8); p.add(blankL3); p.add(calculateB); p.add(exitB); p.add(totalF); p.add(letterTF); setSize(500,400); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private class CalculateButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ try{ double quiz,exam,exer,part,quizT,examT,exerT; double total11,total22,total33,total44,totalFf; double quizTT,examTT,partTT,exerTT; quiz=Integer.parseInt(quizTF.getText()); exam=Integer.parseInt(examTF.getText()); exer=Integer.parseInt(exerTF.getText()); part=Integer.parseInt(partTF.getText()); quizT=Integer.parseInt(quizTF1.getText()); examT=Integer.parseInt(examTF1.getText()); exerT=Integer.parseInt(exerTF1.getText()); quizTT=((quiz/quizT)*100)*0.20; examTT=((exam/examT)*100)*0.30; partTT=part*0.10; exerTT=((exer/exerT)*100)*0.40; total1.setText(""+quizTT); total2.setText(""+examTT); total3.setText(""+partTT); total4.setText(""+exerTT); total11=Double.parseDouble(total1.getText()); total22=Double.parseDouble(total2.getText()); total33=Double.parseDouble(total3.getText()); total44=Double.parseDouble(total4.getText()); totalFf=total11+total22+total33+total44; totalF.setText(""+totalFf); if(totalFf>=95){ letterTF.setText("A"); }else if(totalFf>=90){ letterTF.setText("B"); }else if(totalFf>=85){ letterTF.setText("C"); }else if(totalFf>=80){ letterTF.setText("D"); }else if(totalFf>=75){ letterTF.setText("E"); }else{ letterTF.setText("F"); } }catch(Exception s){ JOptionPane.showMessageDialog(null,"Please Try Again!!","ERROR",JOptionPane.ERROR_MESSAGE); } } } private class ExitButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ System.exit(0); } } public static void main(String[]args){ GradeGUI a=new GradeGUI(); } } A: Using the JTextField class's addCaretListener method, you can check for changes in each text field. When characters are typed into a text field, the caret's position will change, and a javax.swing.event.CaretEvent will be fired, which you can use to check if each text field is empty or not; based on this, you can then set your button to be enabled or disabled. For example: quizTF.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent ev) { calculateB.setEnabled(!quizTF.getText().isEmpty() && !exerTF.getText().isEmpty() && ...); } }); // code here Personally, I would place all your JTextField objects in an ArrayList or something similar so you can loop through and perform operations on them and it won't be tedious writing so much code.
{ "pile_set_name": "StackExchange" }
Q: How can I make the SpeechSynthesizer speak through a particular device? I am new to the Speech Recognition, so please excuse me if the question is very basic level. My application captures what I speak through my microphone. I have written some responses using my c# code for every command I say and the SpeechSynthesizer does this without any issues using the code mentioned below. But I want the SpeechSynthesizer to respond back through my laptop speaker, rather than my default input device (my microphone). Is it doable? The code I am currently using is given below. I am looking for something which can get all the playback devices available and then select and speak back using my speaker. public void SpeakTheText(string text) { SpeechInput = text; SpeechSynthesizer _synthesizer = new SpeechSynthesizer(); _synthesizer.SelectVoiceByHints(VoiceGender.Male); _synthesizer.SetOutputToDefaultAudioDevice();//Microphone _synthesizer.SpeakAsync(SpeechInput); } A: You could use the System.Media.SoundPlayer class to output the audio from a stream. See this example from MSDN public void SpeakTheText(string text) { // Initialize a new instance of the speech synthesizer. using (SpeechSynthesizer synth = new SpeechSynthesizer()) using (MemoryStream streamAudio = new MemoryStream()) { // Create a SoundPlayer instance to play the output audio file. System.Media.SoundPlayer m_SoundPlayer = new System.Media.SoundPlayer(); // Set voice to male synth.SelectVoiceByHints(VoiceGender.Male); // Configure the synthesizer to output to an audio stream. synth.SetOutputToWaveStream(streamAudio); // Speak a phrase. synth.Speak(text); streamAudio.Position = 0; m_SoundPlayer.Stream = streamAudio; m_SoundPlayer.Play(); // Set the synthesizer output to null to release the stream. synth.SetOutputToNull(); // Insert code to persist or process the stream contents here. } } I'm not sure if SoundPlayer can specify an output device, but it should output using your default output device.
{ "pile_set_name": "StackExchange" }
Q: how to carry a graphics card arround if I dont have anti static bag I want to carry a graphics card to a friends place. The Card is old and I don't have the original packaging. I know that best way to carry it will be in an anti-static polybag and I tried hard to get one at local stores without any luck. I tried looking for them online but they come as a bunch and cost does not suit the purpose. Is there any other way to safely do this? I got my hands on some packaging foam from a PC which looks like conductive black foam, will wrapping the card in it will make it safe? A: Carefully wrap it in aluminium foil ensuring that you touch the foil and card all the time while wrapping until wrapped. Do the same when unwrapping and keep hold of the card and touch whatever target system with your other hand (to equalize any potential differences) before inserting the card.
{ "pile_set_name": "StackExchange" }
Q: How to determine the confidence of a neural network prediction? To illustrate my question, suppose that I have a training set where the input has a degree of noise but the output does not, for example; # Training data [1.02, 1.95, 2.01, 3.06] : [1.0] [2.03, 4.11, 5.92, 8.00] : [2.0] [10.01, 11.02, 11.96, 12.04] : [1.0] [2.99, 6.06, 9.01, 12.10] : [3.0] here the output is the gradient of the input array if it were noiseless (not the actual gradient). After training the network, the output should look something like this for a given input. # Expected Output [1.01, 1.96, 2.00, 3.06] : 95% confidence interval of [0.97, 1.03] [2.03, 4.11, 3.89, 3.51] : 95% confidence interval of [2.30, 4.12] My question is how can a neural network be created such that it will return a predicted value and a measure of confidence, such as a variance or confidence interval? A: It sounds like you are looking for a prediction-interval, i.e., an interval that contains a prespecified percentage of future realizations. (Look at the tag wikis for prediction-interval and confidence-interval for the difference.) Your best bet is likely to work directly with NN architectures that do not output single point predictions, but entire predictive distributions. You can then directly extract desired prediction intervals (or mean, or median point predictions) from these distributions. I and others have been arguing that predictive distributions are much more useful than point predictions, but to be honest, I have not yet seen a lot of work on predictive distributions with neural nets, although I have been keeping my eyes open. This paper sounds like it might be useful. You might want to search a bit, perhaps also using other keywords like "forecast distributions" or "predictive densities" and such. That said, you might want to look into Michael Feindt's NeuroBayes algorithm, which uses a Bayesian approach to forecast predictive densities. A: I'm not sure you can compute a confidence interval for a single prediction, but you can indeed compute a confidence interval for error rate of the whole dataset (you can generalize for accuracy and whatever other measure you are assessing). If $e$ is your error rate while classifying some data $S$ of size $n$, a 95% confidence interval for your error rate is given by: $$ e \pm 1.96\sqrt{\frac{e\,(1-e)}{n}}$$. (see "Machine Learning" book from Tom Mitchell, chapter 5.) EDIT Guess I should state a more general case, which is: $$ e \pm z_N\sqrt{\frac{e\,(1-e)}{n}},$$ where common choices for $z_N$ are listed in the following table: confidence level 80% 90% 95% 98% 99% values of zN 1.28 1.64 1.96 2.33 2.58 A: Prediction intervals (PI) in non parametric regression & classification problems, such as neural nets, SVMs, random forests, etc. are difficult to construct. I'd love to hear other opinions on this. However, as far as I know, Conformal Prediction (CP) is the only principled method for building calibrated PI for prediction in nonparametric regression and classification problems. For a tutorial on CP, see Shfer & Vovk (2008), J. Machine Learning Research 9, 371-421 [pdf]
{ "pile_set_name": "StackExchange" }
Q: Heroku-like services for Scala? I love Heroku but I would prefer to develop in Scala rather than Ruby on Rails. Does anyone know of any services like Heroku that work with Scala? UPDATE: Heroku now officially supports Scala - see answers below for links A: As of October 3rd 2011, Heroku officially supports Scala, Akka and sbt. http://blog.heroku.com/archives/2011/10/3/scala/ A: Update Heroku has just announced support for Java. Update 2 Heroku has just announced support for Scala Also Check out Amazon Elastic Beanstalk. To deploy Java applications using Elastic Beanstalk, you simply: Create your application as you normally would using any editor or IDE (e.g. Eclipse). Package your deployable code into a standard Java Web Application Archive (WAR file). Upload your WAR file to Elastic Beanstalk using the AWS Management Console, the AWS Toolkit for Eclipse, the web service APIs, or the Command Line Tools. Deploy your application. Behind the scenes, Elastic Beanstalk handles the provisioning of a load balancer and the deployment of your WAR file to one or more EC2 instances running the Apache Tomcat application server. Within a few minutes you will be able to access your application at a customized URL (e.g. http://myapp.elasticbeanstalk.com/). Once an application is running, Elastic Beanstalk provides several management features such as: Easily deploy new application versions to running environments (or rollback to a previous version). Access built-in CloudWatch monitoring metrics such as average CPU utilization, request count, and average latency. Receive e-mail notifications through Amazon Simple Notification Service when application health changes or application servers are added or removed. Access Tomcat server log files without needing to login to the application servers. Quickly restart the application servers on all EC2 instances with a single command. Another strong contender is Cloud Foundry. One of the nice features of Cloud Foundry is the ability to have a local version of "the cloud" running on your laptop so you can deploy and test offline.
{ "pile_set_name": "StackExchange" }
Q: Looking for large GML files containing vector polygon data I have few vector data files with 500 to 700 MB GML files. But I am looking for files larger than these preferably 1 GB, 2 GB. It would be helpful if somebody can provide some pointers regarding the place to find such files. Note: I need to test polygon overlay over large data sets, so the two layers that I need should be intersecting. A: You can try some of the CanVec data, available here. Some of those files range from 4 MB to 50GB, depending on the one you choose.
{ "pile_set_name": "StackExchange" }
Q: Как сделать, чтобы String str = любому значению из массива? нужно чтобы String str = любому значению из массива, чтобы можно было написать public static void say() { Scanner in = new Scanner(System.in); Random random = new Random(); String str = in.nextLine(); switch(str) { case("Привет"): System.out.println(HELLO[random.nextInt(HELLO.length)]);break; case("Привет!"): System.out.println(HELLO[random.nextInt(HELLO.length)]);break; case("привет"): System.out.println(HELLO[random.nextInt(HELLO.length)]);break; } say(); нужно чтобы по несколько раз не писать case и не писать повторно Sout. A: Наверное Вам нужно что то подобное: Scanner in = new Scanner(System.in); Random random = new Random(); String str = in.nextLine(); Map<String, String[]> db = new HashMap<>(); String[] hellos = new String[]{"Привет", "Алоха"}; String[] helloAnswers = new String[]{"Здравствуй", "Добрых вечеров!"}; for (String hello : hellos) { db.put(hello, helloAnswers); } String[] goodbyes = new String[]{"Пока", "Прощай"}; String[] goodbyeAnswers = new String[]{"До свидания", "Ну пока"}; for (String goodbye: goodbyes) { db.put(goodbye, goodbyeAnswers); } if (db.containsKey(str)) { String[] answers = db.get(str); System.out.println(answers[random.nextInt(answers.length)]); } PS: могут быть ошибки, писано с телефона...
{ "pile_set_name": "StackExchange" }
Q: What is the proper way to fill a form with multiple data fields? I have been asked to create a vb.net WinForms app that automates the creation of this spreadsheet: Obviously, creating that spreadsheet manually is a back breaking task. I am very comfortable writing SQL to pull each individual field of data, however I've got to believe that there is a better way. Such a method would require 144 queries !! I've considered creating a form with individual labels for each field, or using a gridview. Either would be acceptable to the end user, but I'm really not sure how I would write a query to produce a dataset that look like the end product anyway. I'm not asking anyone to write any code for me, what I'm asking for help with is the concept of how I should attack this task. Here is a query that I wrote which returns the fields for Business Unit #1 for the first week on the spreadsheet. I don't think it helps much, but I'm adding it to show that I've put some effort into this. DECLARE @WeekEnding AS DATE DECLARE @DIV AS INT SET @WeekEnding = '11/13/2015' SET @DIV = 20 -- A/R downpayments OPCH SELECT SUM(OPCH.DocTotal - OPCH.VatSum - OPCH.TotalExpns) AS 'ARDownPaymentInvoice' FROM OPCH LEFT JOIN INV1 ON OPCH.DocEntry = INV1.DocEntry AND INV1.VisOrder = 0 LEFT JOIN OITM ON INV1.ItemCode = OITM.ItemCode LEFT JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod LEFT JOIN OACT AS CurrCode (NOLOCK) ON OITB.RevenuesAc = CurrCode.AcctCode WHERE DATEPART(WEEK, OPCH.DocDate) = DATEPART(WEEK, @WeekEnding) AND YEAR(OPCH.DocDate) = YEAR(@WeekEnding) AND CurrCode.Segment_4 = @DIV -- Credits ORIN SELECT SUM(ORIN.DocTotal - ORIN.VatSum - ORIN.TotalExpns) * -1 AS 'Credit' FROM ORIN LEFT JOIN INV1 ON ORIN.DocEntry = INV1.DocEntry AND INV1.VisOrder = 0 LEFT JOIN OITM ON INV1.ItemCode = OITM.ItemCode LEFT JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod LEFT JOIN OACT AS CurrCode (NOLOCK) ON OITB.RevenuesAc = CurrCode.AcctCode WHERE DATEPART(WEEK, ORIN.DocDate) = DATEPART(WEEK, @WeekEnding) AND YEAR(ORIN.DocDate) = YEAR(@WeekEnding) AND CurrCode.Segment_4 = @DIV --Invoices SELECT SUM(OINV.DocTotal - OINV.VatSum - OINV.TotalExpns) AS 'Invoice' FROM OINV LEFT JOIN INV1 ON OINV.DocEntry = INV1.DocEntry AND INV1.VisOrder = 0 LEFT JOIN OITM ON INV1.ItemCode = OITM.ItemCode LEFT JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod LEFT JOIN OACT AS CurrCode (NOLOCK) ON OITB.RevenuesAc = CurrCode.AcctCode WHERE DATEPART(WEEK, OINV.DocDate) = DATEPART(WEEK, @WeekEnding) AND YEAR(OINV.DocDate) = YEAR(@WeekEnding) AND CurrCode.Segment_4 = @DIV` Thanks for any ideas. A: One way to achieve this: CREATE TABLE #tmpData (column1 varchar(50), column2 varchar(50), column3 varchar(50), column4 varchar(50), column5 varchar(50), column6 varchar(50), column7 varchar(50), column8 varchar(50), column9 varchar(50), column10 varchar(50), column11 varchar(50), column12 varchar(50)) Then you could insert a row displaying the dates of each column INSERT INTO #tmpData --Write your select query here for filling in all the dates Then you would insert the data for each line item in the rows. INSERT INTO #tmpdata SELECT 'Business Unit 1', -- insert remaining column data here
{ "pile_set_name": "StackExchange" }
Q: How to use lower_bound to insert value into sorted vector I have a vector of pointer to class A which I want to keep sorted by int key using STL. To do this I defined an operator < in class A bool operator< (const A &lhs, const A &rhs){ return (lhs.key < rhs.key); }; and in my insert function it looks like vector<A*>::iterator it = lower_bound(vec.begin(), vec.end(), element); vec.insert(it, element); I expect lower_bound to return first place where the new element can be placed, but it does not work. Inserting A objects with keys 0,1,2,3 will result in vector in incorrect order (2,3,1,0). Why is that ? Probably I could also use comparator for this object: compare function for upper_bound / lower_bound but what's wrong with my code? A: From your example, you're using a vector of pointers: std::vector<A*>. Hence, you need to define a comparison for pointers which you pass in to std::lower_bound: bool less_A_pointer (const A* lhs, const A* rhs) { return (lhs->key < rhs->key); } auto it = std::lower_bound(vec.begin(), vec.end(), element, less_A_pointer); //... Of course, the question is why are you using pointers in the first place - just store A objects unless you really need to. If you do need to store pointers, look into std::shared_ptr which will handle this for you: std::vector<std::shared_ptr<A>> v; std::shared_ptr<A> element(new A(...)); auto it = std::lower_bound(v.begin(), v.end(), element); //Will work properly You can also use a lambda instead of having to write a free function: auto it = std::lower_bound(v.begin(), v.end(), [](const A* lhs, const A* rhs) { return lhs->key < rhs->key; });
{ "pile_set_name": "StackExchange" }
Q: Access: generating a .DOC file cannot be opened on an iDevice I am generating a .DOC file in an old access-VBA application using the typical GetObject("", Word.Document) strategy. I can open this .doc just fine in windows, however I cannot open it on an iPad\iPhone. The strange thing is, if I open this .doc in MS word, save it again as a .doc, I can then open it on an iPad. What do I have to do to ensure that this .doc gets saved as something that isn't "an invalid format" on an idevice? Any ideas? EDIT 1: I Found some code that looks like: DoCmd.OutputTo ...,..., "Rich Text Format",... and am wondering if this is correct? EDIT 2: What I am seeing is DoCmd.OutputTo as a RTF is what the iDevices do not seem to like. Any other way to go about doing this? A: This is because you are actually saving the file in RTF (Rich Text Format), but giving it a .DOC extension. MS Word can figure out the difference, but the iPad cannot. To get the file to open on both devices, give the document a .RTF extension instead of .DOC.
{ "pile_set_name": "StackExchange" }
Q: Running the XCode 3.1 application in XCode 4.1? I am new developer on iPhone. My problem is that I have installed the XCode 4.1 after changed the settings in the edit project settings it shows XCode 3.1 is missing so if any one know about it give me solution to solve the problem. A: you should set the base SDK version in project settings and Target settings as well. you should check if you have specified the base SDK at both places. Best of luck.
{ "pile_set_name": "StackExchange" }
Q: How to access drives other than C: in Ubuntu on Windows In the Windows Subsystem for Linux, I can access the C: drive as /mnt/c. How can I access other drive letters, such as optical discs and network mounts? They do not show up under /mnt for me. A: How can I access other drive letters, such as optical discs and network mounts? At the moment there are limitations on what drives are mounted: In order for a drive to show up under /mnt/ it must meet the following criteria: The drive must be a fixed drive The drive must be formatted to NTFS. This has been raised as an issue: Drives other than C: are not mounted in /mnt #1079. It is still marked as "Open".
{ "pile_set_name": "StackExchange" }
Q: Is there a way to change what Pepper says in Autonomous Life? I would like to change what Pepper the robot says when it is in "default mode", i.e. without having any application launched; thus enabling it to answer some questions the manufacturer didn't include, or to change its answer. I have already tried —to no avail— looking for a solution on Aldebaran's documentation, google researches proved fruitless too. The kind of questions that the robot can be asked are here: http://doc.aldebaran.com/2-5/family/pepper_user_guide/basic_channel_conversation_pep.html it doesn't say how to change the content though. I'm basically expecting the robot to be able to deliver some information without needing to get into application; I'm aware that there are collaborative speeches but this isn't what I am looking for. A: Option 1: You can find the dialoges from Pepper at: /data/home/nao/.local/share/PackageManager/apps/dialog_* e.g. /data/home/nao/.local/share/PackageManager/apps/dialog_goodbye/dlg_goodbye/dlg_goodbye_enu.top You could edit or extend those. Option 2: You could copy the content, edit them as you like and merge it into your own dialog. But you would have to "get into application". If you just want to add something to the default dialoges. Then you could activate your own custom topic in default mode. Given your topic file is named myTopic.top and is placed in /data/home/nao/: import naoqi from naoqi import ALProxy ald = ALProxy("ALDialog", "pepper.local", 9559) myTopic = ald.loadTopic("/data/home/nao/myTopic.top") ald.activateTopic(myTopic) ald.getLoadedTopics("English") Then your custom topic should be listed among the other topics activated in defaut mode. Option 3: Make your own application with your own dialog and just activate all the other topics too.
{ "pile_set_name": "StackExchange" }
Q: New tag should require more privilege I am a relatively new user in Ask Ubuntu site, which is a subsite of the Stack Exchange network. After participating in the Questions and answers in the AU site for a while, I see that, the "tags" are very important in this site. (It is also very important on all SE sites). I often see and feel that, Moderators and Community members have a hard time deleting tags, which were created by users (without having good knowledge about the importance of tags). I also experienced a situation where a user trying to delete ubuntu-netbook tag, created a new one as ubuntu-n accidentally and was unaware of this new tag. (We are requested to delete that tag, because that is no longer important). So, I feel that, tag creation should not be that easy and should go through some approval by moderators before being used in the system. That's why I am proposing this request. We can apply to the system one or more of these methods to prevent unimportant tags being created. We can increase the required reputation level from 300 to 2000. It is now 300 New tags should go through moderator approval before being used. The user can still type a new tag name, but that new tag will only appear in the question after moderator approval I want to hear from community members about this particular request. A: 300 is quite a high enough limit honestly. I mean, if you reach 300 rep, it means you did participate in the community and the site itself (at least a bit). 2K seems like too much for me. Tags are important — yes — but a wrong tag might not create so many problems, and in any case, not that many problems to justify a 2K limit privilege. Another thing: apart from the fact that moderators already have quite a few duties to take care of, adding this one wouldn't have that much effect. Consider that a tag, in order to survive, must be used. If you create a tag and nobody else uses it, the system will purge it. So it's not like a wrong tag is a scar forever. It'll be seen sooner or later, either by the system or by the community: no need for exclusive moderator action.
{ "pile_set_name": "StackExchange" }
Q: how to add opencv to a gui QT application? I created a new widget gui application in QT . and in order to using opencv , I added INCLUDEPATH and LIBS to my projects as following : QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = testqt4 TEMPLATE = app SOURCES += main.cpp\ widget.cpp INCLUDEPATH += C:/opencv/build/include LIBS += -LC:\opencv\build\x64\vc12\lib -lopencv_world310d HEADERS += widget.h FORMS += widget.ui and I included my desired opencv headers as following : #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> .... but when I builded the project I encountered with this error : can anyone help me to fix this error ? thank you . A: Are you using qt creator? It will not update your makefile once you changed your .pro file. Right click on the project folder in Projects view and click "Run qmake" should fix it.
{ "pile_set_name": "StackExchange" }
Q: Thomas-Wigner rotation of a stick directly from the Lorentz Transformation I'm trying to better understand Thomas-Wigner rotation. I understand how to calculate it for the case of a perpendicular pair of boosts. But I also want to see the rotation more directly. The effect is purely kinematic. It's all within the Lorentz Transformation (LT). It's therefore possible to see the rotation using a pair of LT boosts on some suitable histories. I'm not seeing the correct outcome when I do this. Is my algorithm (below) correct? Notation used here involves three frames: K boosted along the X-axis to K'. then a second boost along the Y-axis of K' to K''. I examine the histories of the endpoints of a stick. the stick is stationary in K'', and it lies along the X''-axis in K'' I get the histories (worldlines) of the end-points of the stick (simple, because the stick is stationary in K'') I then reverse-boost from K'' to K' to K. (I call this reverse because the usual direction is from K to K' to K'') in K, I find two events, one on each history, that are at the same coordinate-time in K. This is a time-slice across the two histories. A time-slice is needed whenever you need to measure spatial geometry. I take the difference between the two events, to get a displacement 4-vector in K, whose ct-component is 0 this displacement 4-vector gives me the geometry of the stick as seen in K I infer the angle of the stick with respect to the X-axis in K It doesn't work. I see rotation and contraction of the stick. The rotation is in the right direction, but it's way too big. Example data: boost 1 [Y,-0.6c] boost2 [X,-0.8c] length of the stick in K: 0.76837 (length is 1.0 in K'') Rotation of the stick from time-slice of histories in K: -38.6598 degrees Thomas-Wigner angle calculated directly from a formula: -18.92464 degrees The formula is $\tan \theta = - (\gamma1 * \gamma2 * \beta1 * \beta2)/(\gamma1 + \gamma2$) (Although you should concentrate on the algorithm stated above, the actual code is here, if it helps.) A: The algorithm is correct in that it shows the geometry of the stick in frame K. But the geometry of the stick is affected not only by Thomas-Wigner rotation, but also by the regular flattening (length contraction) that happens with all boosts. So there are two effects here, not one. The first is the spatial flattening (length contraction) that happens with all boosts, of course. Spatial flattening changes not only lengths, but angles and shapes. In the present case, it changes the orientation of the stick. The second effect is the Thomas-Wigner rotation. The result I have from the algorithm stated above reflects both of these effects (in the position of the stick as measured in K). (All angles in degrees. All measurements in the K frame.) A:Equivalent-boost direction: 24.2277 from the X-axis. B:Angle of the stick from manual calc in code : 38.6598 from the X-axis A+B: angle of stick: 62.8875 from the direction of equivalent-boost C:Thomas-Wigner rotation from a formula: 18.9246 from the X-axis D: flattening (length contraction) of (A + C) from a formula: 62.8875 from the direction of equivalent-boost (same as above) So it seems to all agree, when the two effects are taken into account. The formula for the change in orientation of a stick (used in D) is: $\tan \theta' = \gamma * \tan \theta$
{ "pile_set_name": "StackExchange" }
Q: Error converting data type nvarchar to bigint -when joining two differnet data types I am trying to join two tables. Table1.Column1 where column 1 is a BIGInt. On Table2.Column2 where column 2 is Nvarchar. Here is what I am running Select HspId, CMSid, Cast(CMSId as nvarchar) From Q2IMSSiteHistory2015old inner Join HSP on HSP.CMSid = Q2IMSSiteHistory2015old.POS I am getting the following Error: Error converting data type nvarchar to bigint. Even if I do not cast anything I get the same error. A: Cast the join. Select HspId, CMSid, Cast(CMSId as nvarchar) From Q2IMSSiteHistory2015old inner Join HSP on CAST(HSP.CMSid as nvarchar) = Q2IMSSiteHistory2015old.POS
{ "pile_set_name": "StackExchange" }
Q: Frequent blow outs in the same location I keep getting blow outs in my front tube and always in the same location: right next to the valve stem. The blow outs look like: On this same tube, there is wear on exactly the other side of the valve stem. I have checked the tire and the wheel and there doesn't appear to be anything sharp enough there. What can cause this? I suspect it's something that I'm doing. I'm tired of buying new tubes, as I hear these flats cannot be patched. If it matters, it's a presta valve and I usually inflate to 110 psi, the maximum. A: Check inside the rim at the point where the punctures occur. Is the rim tape intact? Does a spoke push through when weight is placed on the bike? One of my friends had a problem like this, and it turned out that when he sat on the bike his weight caused the end of a spoke to push through the rim and puncture his tyre. A: A few things come to mind: Using a presta tube on a rim designed for schraeder valves. This would cause wear around the valve stem. See "Can I usea a presta tube in a schraeder rim?" for more details. Worn out rim tape near the valve. Does the tape look worn? Is there some nasty edge or burr under the tape that's getting through? Try replacing the rim tape or doubling it up in the area where you're getting the flats. Tubes getting nicked when you install them. When replacing your front tube, do you put the valve stem in first or last? (first is better) Is it possible that the tube is getting pinched against the rim edge when putting the tire back on? A: The picture of your blow-out doesn't show up for me, so I'm guessing a bit based on your description. Do you use the little nut that comes with the tube and threads down the stem of the presta valve? Typically, you'd thread this nut on and screw it down to the rim after installing and inflating the tube. The nut provides a bit of support for the vavle stem against the rim. If you are using this nut, you may be overtightening it. The symptoms if this is the case will be the valve stem separating from the tube where it joins the tube. If this sounds like your problem, I'd suggest you either don't fit the nut or you only fit the nut after you've inflated the tube in the tyre, and that you make sure you don't tighten the nut too tight.
{ "pile_set_name": "StackExchange" }
Q: App service plan pricing details This is the details required to fill for App Service plan section What should we enter for the number of instances while entering the details of the App service plan. How is the number of instances determined. suppose a Web App Bot i depolyed in azure using a free account does not use any Virtual Machine..then does it mean the web apps do not need any Virtual Machines even when moved to production also. When i check the Virtual Machines tab in the Azure portal https://portal.azure.com/ it says no virtual Machines to display. A: The Azure VM is where your web app run. So whatever plan you choose, there's at least one VM instance hosting your web app. How is the number of instances determined. The number of instance is determined by two factors. Pricing tier of your App service plan. It decides the maximum of instance you can use. For Free or Shared pricing tier, web apps run on the same VM with apps belonged to other customers, you only need to input 1 if you want to calculate. Your need. For pricing tier Basic+ (Basic, Standard, Premium), you possess more than one dedicated VM instance(You can check the explicit number in portal or here). Thus you can set the instance number from 1 to Maximum mentioned above, according to your requirement. When i check the Virtual Machines tab in the Azure portal, it says no virtual Machines to display. Virtual Machines tab shows the VM resource you create explicitly, while the VM hosting your web app is managed by Azure automatically. Thus you can't see them.
{ "pile_set_name": "StackExchange" }
Q: Calling method from a generic wildcard reference the following code is reduced to the essentials for the question: public class GenericTest { private interface CopyInterface<T extends CopyInterface<T>> { public void copyFrom(T source); } public void testMethod() { CopyInterface<?> target; CopyInterface<?> source; target.copyFrom(source); } } This leads to the following compiler error message: The method copyFrom(capture#1-of ?) in the type GenericTest.CopyInterface is not applicable for the arguments (GenericTest.CopyInterface) GenericTest.java /ACAF/src/de/tmasoft/acaftest/attributes line 14 Java Problem When I use the raw type for the variable target, I just get a raw-type warning. Is there a way to get this compiled without using a raw-type? A: You have to make your testMethod() generic and declare that source and target are of the same type: public <T extends CopyInterface<T>> void testMethod() { T target = ...; //initialize the variable T source = ...; //initialize the variable target.copyFrom(source); }
{ "pile_set_name": "StackExchange" }
Q: WIndows 10 UWP - How can I determine if a Key press is a letter or number? Windows 10 UWP: Example: On UWP grid, a button1.content = 1 and a textbox. Using mouse to press button1.content, 1 is shown in the textbox.text. How to simulate numeric keypad (1) and 1 is shown in the textbox.text? A: You can use TextBlock.Text to set the text to TextBlock. If you want to know the key press, you should add KeyDown in Grid <Grid KeyDown="Grid_OnKeyDown"></Grid> And add the following code private void Grid_OnKeyDown(object sender, KeyEventArgs e) { var str = e.Key.ToString(); if (char.IsDigit(str[0])) { //is digit } // is letter } You can use TextBlock.Text = xx to set the TextBlock.
{ "pile_set_name": "StackExchange" }