text
stringlengths
64
89.7k
meta
dict
Q: Problema con ejercicio de ajedrez en java El objetivo del programa es imprimir un tablero de ajedrez, con casillas B (blancas) y N (negras), pedir una fila y una columna y establecer un alfil ahí. Hasta aquí todo bien, pero el problema viene cuando hay que modificar el tablero con asteriscos en las casillas donde se pueda mover el alfil (en diagonal): B * B N B * B N N B * B * B N B B N B A B N B N N B * B * B N B B * B N B * B N * B N B N B * B B N B N B N B * N B N B N B N B El profesor se ha saltado este problema, entonces recurro a este foro. ¿Cómo lo plantearíais? Código: int posicion=8*(fila-1)+columna; for(int i=1;i<=64;i++) { if(i%2!=0){ if(i==posicion){ System.out.print("A "); continue; } System.out.print("B "); }else{ if(i==posicion){ System.out.print("A "); continue; } System.out.print("N "); } if(i%8==0){ System.out.println(); } } No he dado matrices todavía. Gracias [EDIT] Sólo valen movimientos válidos, de acuerdo con el movimiento real del alfil. A: Si quieres que tu alfil se coloque en la posición [x1 ; y1], entonces tienes que completar con asteriscos todas las posiciones [x2 ; y2] que cumplan con la condición de que: X1 != X2 y Y1 != Y2 | X1 - X2 | = | Y1 - Y2 | Creo que el siguiente código puede ayudarte: public static int mod(int x) { return (x < 0)?-x:x; } int x, y; //Posicion del alfil for(int i=1;i<=8;i++) { for(int j=1;j<=8;j++) if(i == x && j == y) System.out.print("A "); else if(mod(i - x) == mod(j - y)) System.out.print("* "); else if((i + j) % 2 == 0) System.out.println("B "); else System.out.println("N "); System.out.println(); }
{ "pile_set_name": "StackExchange" }
Q: Expand label/cell size based on text size in UITableView Swift I am new to iOS development. I have a problem with my cell sizing. I am not using Auto-Laylout feature. My current TableView cell looks something like this. I want to make the label size which is selected in the image to be extended dynamically based on the text content of that Label. Thanks in advance. A: i think the swift version like below, it calculates nearer values not the exact height, for example class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var messageArray:[String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background", "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.", " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.", "Whale&W", "Rcokey", "Punch", "See & Dive"] } in the above we have an array which contains string of different length func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell; if(cell == nil) { cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "CELL") cell?.selectionStyle = UITableViewCellSelectionStyle.none } cell?.textLabel.font = UIFont.systemFontOfSize(15.0) cell?.textLabel.sizeToFit() cell?.textLabel.text = messageArray[indexPath.row] cell?.textLabel.numberOfLines = 0 return cell!; } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row]) return height + 70.0 } func calculateHeight(inString:String) -> CGFloat { let messageString = inString let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)] let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes) let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) let requredSize:CGRect = rect return requredSize.height } try it in a new project just add the tableview and set its datasource and delegate and past the code above and run the result will be like below A: Try to override methods: override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } Complete solution: In iOS 8, Apple introduces a new feature for UITableView known as Self Sizing Cells. Prior to iOS 8, if you displayed dynamic content in table view with varied row, you need to calculate the row height on your own. In summary, here are the steps to implement when using self sizing cells: • Add auto layout constraints in your prototype cell • Specify the estimatedRowHeight of your table view • Set the rowHeight of your table view to UITableViewAutomaticDimension Expressing last two points in code, its look like: tableView.estimatedRowHeight = 43.0; tableView.rowHeight = UITableViewAutomaticDimension You should add it in viewDidLoad method. With just two lines of code, you instruct the table view to calculate the cell’s size matching its content and render it dynamically. This self sizing cell feature should save you tons of code and time. In Attributes Inspector of your UILabel, change Lines value to 0, so label will automatically adjust the number of lines to fit the content. Please note that first point is required and remember that you cannot use self sizing cell without applying auto layout. If you are note familiar with auto layout, please read this, it will be enough: https://developer.apple.com/library/mac/recipes/xcode_help-IB_auto_layout/chapters/pin-constraints.html Or, easier way to set auto layout, but maybe not be what you exactly expected is to clear all of your constraints, go to Resolve Auto Layout Issues and for All Views click on Reset to Suggested Constraints.
{ "pile_set_name": "StackExchange" }
Q: how can I change the "get" and "set" on a Model Property? Currently I have a DateTime property for a model. I am using the telerik MVC framwork but I am using a DateTime property and the editor column for this property is auto-generated so there is no code which controls it in my View or Controller. On Telerik's website there are instructions on how to set the default date time for a date time picker but this picker isn't initiated anywhere because it is in a column. The problem is I want to set the DateTime to be the current date and time if it isn't already specified. Currently, the code for the model looks like this: public DateTime CreatedDate { get; set;} I want it to do something more like this: public DateTime CreatedDate { get { if (QuestionID != 0) { return this.CreatedDate; } else { return DateTime.Now; } } set { CreatedDate = value; } } this way it will return the DateTime that is stored for this Question if the ID exists. If you are creating a new Question, it gets the current DateTime. The problem is here with the Set. When I try to load up a screen, set get's a Stack Overflow. I'm really unfamilular with this kind of code, so I have no idea how to work with it. Before we were not working with the model, and instead using JQuery to get the CreatedDate's data and set it to the current date time. The issue with that is when you go to the "picker" part of the date time, it goes to the default date time rather than the current one. this is why I want to set it through the Model, View, or Controller, and not with Jquery. Let me know if you can help me understand Gets and Sets in the model! A: You need to have a private property you are using behind the scenes. private DateTime _createdDate; public DateTime CreatedDate { get { if (QuestionID != 0) { return _createdDate; } else { return DateTime.Now; } } set { _createdDate = value; } } You are getting an overflow because you are doing something like this currently: CreatedDate = 1/1/2012; ...which then calls CreatedDate = 1/1/2012; ...which then calls CreatedDate = 1/1/2012 ..You get the point (it is continuously setting itself until the stack overflows) Auto implemented properties ({get;set;}) actually use a private variable behind the scenes. If you were to look at the IL, then you would see that it actually breaks that simple {get;set;} into a getter/setter based on a generated private variable. They are just a type of "compiler magic" to cut down on boilerplate code of having to create a private variable when there is no real logic in the getter/setter. If you have logic, then you need to implement this private variable yourself.
{ "pile_set_name": "StackExchange" }
Q: Where to put rewards in IInAppBillingService method? I have this method for IInAppBillingService: if (sku.equals(inappid)) { Bundle buyIntentBundle = mservice.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); if (buyIntentBundle.getInt("RESPONSE_CODE") == 0) { PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); * long starsLong = Menu.sharedPref.getLong("stars", 0L); SharedPreferences.Editor editor = Menu.sharedPref.edit(); editor.putLong("stars", starsLong + stele); editor.commit(); * } } but even if the user will cancel the payment, the award will be stack in the sharedPreferences. Where I should put the part with STARS for the award can stack only if the user pay (in which method, or what condition should i put)? Thanks! A: I found it. it's onActivityResult method from the Activity class. Here you can put the condition if (resultCode == RESULT_OK) and this is called only when the user pay for your item.
{ "pile_set_name": "StackExchange" }
Q: Does the d8 shell's console.log support format specifiers? d8 is a minimal shell for running JavaScript programs using V8. Does the implementation of console.log in d8 support format specifiers/characters? I tried to use a format specifier, and it printed the specifier and the variable value (as shown below). d8> for (i = 0; i < 10; i++) {console.log('Number is %d', i);} Number is %d 0 Number is %d 1 Number is %d 2 Number is %d 3 Number is %d 4 Number is %d 5 Number is %d 6 Number is %d 7 Number is %d 8 Number is %d 9 undefined I see a similar question here: https://github.com/nodejs/node/issues/10292 ... Any insight would be helpful. A: As you can see from your experiment, d8 does not support format specifiers. It wouldn't want to support anything that's not legal JavaScript. Speaking of which: JavaScript has "template literals" since a while. So without placing any requirements on d8 or console.log, anywhere you have strings you can do: let i = 42; console.log(`Number is ${i}`); let just_a_string = `1 + 2 = ${1+2}`; console.log(just_a_string); console.assert(just_a_string === "1 + 2 == 3"); If you were hoping for more advanced formatting, like C-style %5d, AFAIK you'll have to build that yourself. If you're interested in floating-point numbers, .toFixed and .toPrecision might be helpful.
{ "pile_set_name": "StackExchange" }
Q: When I must log out user if I use Specflow and Selenium (BDD) I have started to use Specflow, Selenium and PageObject pattern for testing. I would like to make scenarios independent of each other, but when I start running my test features, I see that my user is not anonymous after the first scenario. When should I log out the test user? Before each scenario? After each scenario? Can specflow and selenium drop state after each scenario? Must I call page.Logout() every time? A: I would say that you should log out, when it's relevant to the test case. Say you log in to SO and test posting a new question, then write an answer and add two comments to each. Logging in and out between each step would be a big hassle and no user would do that in the real world. Thus just log in at the start of the test scenario and log out when you're finished with it. Another example would be doing each of the above steps as different users, then it would be a necessity to log in/log out at every step. This applies in the bigger picture as well, if you have multiple scenarios that require a logged in user, but don't depend on any of that user's information, may as well just log in once before running all of them and then log out. Specflow and Selenium don't hold the state, it's the system you're testing that does it. For instance if your session is stored in cookies, you could clear said cookies and that would in effect log you out. But this is not testing the system as the end user is meant to use it, so it's just cutting corners and testing different area of system (authorization of unauthenticated users) and thus doesn't really correlate very well to the real world case. Just use the log out button/link on the page, since you're writing browser based tests. A: I think you should make your test feature wise or module wise. if you consider all the processes in a feature and according to the flow, you will only need to logout in the end. If you make module wise, after a process you can logout each time and login again at the new module.
{ "pile_set_name": "StackExchange" }
Q: How to get image from Google static map API I use this code to generate static images from Google API, but I have too many requests, so sometimes I get overuse from Google. string latlng = location.Latitude + "," + location.Longitude; string path = "http://maps.googleapis.com/maps/api/staticmap?center=" + latlng + "&zoom=16&size=200x200&maptype=roadmap&markers=color:blue%7Clabel:S%7C" + latlng + "&sensor=false"; Is it possible to call this from C# to generate and save images? I can't find way to get an image object. A: using (WebClient wc = new WebClient()) { wc.DownloadFile(url, @"c:\temp\img.png"); }
{ "pile_set_name": "StackExchange" }
Q: Disable the Cache Busting in Dynamically Linked External Javascript Files? When loading content through AJAX which contains an externally linked Javascript file or when using jQuery.getScript() function call, the linked Javascript files are appended with a cache busting parameter, which prevents the file from being cached by the browser. So, instead of writ­ing some­thing like <script src="/js/foo.js">, it writes some­thing like <script src="/js/foo.js?_=ts2477874287">, caus­ing the script to be loaded fresh each time. Is there a way to disable this and have the file cached when it's loaded? A: I don't know about getScript, but cache is a parameter you can set in a .ajax() parameter map. It's false by default for scripts but you can flip it to true. Once false, it won't append a cache-busting query string. [updated per comment]
{ "pile_set_name": "StackExchange" }
Q: drawing predict line on an R graph I have a time series data: output of x data frame: Date vol 1990 12 1991 13 1992 15 1994 18 1995 20 1996 35 I am trying to plot this data and predict 4 year ahead as below: plot(x$Date, x$vol, col="blue") x.lm<-lm(x$Vol ~ x$Date) x.pre<-predict(x.lm, n.ahead=4) abline(x.pre, col="red") I get this error: Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : invalid a=, b= specification can anybody tell me what I am doing wrong? A: You capitalized "Vol" in x.lm<-lm(x$Vol ~ x$Date). Try x.lm<-lm(x$vol ~ x$Date) Also, you're not going to be able to pass the value of predict() into abline like that without some extra modification. Since you're not doing any sophisticated prediction, but really just wanting to plot the linear fit, you could plot the line using abline(x.lm, col="red") If you separate your variables and then use the newdata parameter in predict, you should be able to get the actual predictions. That would probably be the cleanest way to do it. For instance: y <- x$vol x <- x$Date x.lm <- lm(y~x) predict(x.lm, data.frame(x=1997:2000)) This will return the predictions for 1997 - 2000. I believe the "x" in data.frame(x=1997:2000) must match the variable you put into lm() as your x variable. In your case, that has a dollar sign accessor, which makes the whole thing a bit more complex. I'd just take the approach above and rename the x component fed into your lm() function as a valid variable name which can be referenced later.
{ "pile_set_name": "StackExchange" }
Q: Does anyone recognise this Taylor series expansion of an exp-like function? Does anyone recognise this Taylor series expansion? It is similar to that of $\exp(x)$, but not quite: $$ 1 - \frac{1}{2!}x + \frac{1}{3!}x^2 - \frac{1}{4!}x^3 + \frac{1}{5!}x^4 - \frac{1}{6!}x^5 + \ldots $$ Is this a well-known function? Thank you very much in advance. A: \begin{align*} S(x)&=1-\dfrac{1}{2!}x+\dfrac{1}{3!}x^{2}-\cdots\\ &=\dfrac{1}{x}\left(x-\dfrac{1}{2!}x^{2}+\dfrac{1}{3!}x^{3}-\cdots\right)\\ &=-\dfrac{1}{x}\left(-x+\dfrac{1}{2!}x^{2}-\dfrac{1}{3!}x^{3}+\cdots\right)\\ &=-\dfrac{1}{x}(e^{-x}-1). \end{align*} And define $S(0)=1$.
{ "pile_set_name": "StackExchange" }
Q: awk - finding numbers from file Can you explain me this command please? awk '/^$/{flag=""} /Input-Output in F Format/{flag=1;next} flag && ($0 ~ /^[0-9]/ || $0 ~ /^ [0-9]+/) && ($0 !~ /[2][89]/ && $0 !~ /[3][01]/){printf("%.06f\n%.06f\n",$5,$6)}' 'Input-Output in F Format' is a string in file Thank you A: Print the 5th and 6th numerical fields in lines that begin with a digit or a space followed by multiple digits but do not contain any of 28,29,30 or 31, and occur between a line containing “Input-Output in F Format” and an empty line. I wonder how hard it would be to write an awk2english translator.... /^$/{flag=“"} -- when there is a blank line, clear the flag. /Input-Output in F Format/{flag=1;next} -- when long string, set flag and skip other rules (next) flag && .... -- when flag is set, perform the numeric rules. ($0 ~ /^[0-9]/ || $0 ~ /^ [0-9]+/) -- line begins with a digit, or a space followed by multiple digits ($0 !~ /[2][89]/ && $0 !~ /[3][01]/) -- line does not contain 28,29,30 or 31. With respect to your file in 53800568: awk '/^[0-9 ][0-9]+[ \t]/ && NF == 6 { printf("%f\n", $5); }' Worked for me.
{ "pile_set_name": "StackExchange" }
Q: How to modify a token in a text file? I have 3 config files with a token like "[DBPASSWORD]" that I'd like to modify from my "build" task wiht Phing. I didn't find a task that performs what I need and before writing my own task for this I'd like to know if anyone has a better solution. Thanks! A: To answer to my own question, I finally did it like this. My conf file has this tokens: user: %%dbUser%% password: %%dbPassword%% I had to copy this file, config.yml.dist to config.yml, and change the tokens, so I did this: <copy file="./config.yml.dist" tofile="./config.yml"> <filterchain> <replacetokens begintoken="%%" endtoken="%%"> <token key="dbUser" value="myUser" /> <token key="dbPassword" value="myPassword" /> </replacetokens> </filterchain> </copy> And thats it.
{ "pile_set_name": "StackExchange" }
Q: Low power reliable motion state sensor for car I am looking for a sensor to reliably determine the state of motion of a car (passenger, van, forklift, tractor). I will not disclose the nature of the project at this time but a similar sensor system could be used to activate a log of travel hours or send a GPS position report on arrival and departure from a destination. First priority is low power, it must trigger a micro-controller (in deep sleep) only on motion start and stop, my complete system will operate on 2 or 3 coin cells for long periods (not wired to the vehicle, relocatable, cheap). Second priority is 0% false detection of motion at the cost of response time. Response time of half minute is optimal, 5 minutes is about the limit. I require a signal edge on the state change from stationary to in-motion and vice versa and knowledge of which state the car is in. I have considered trembler switches using springs, ball bearings, conductive liquids (not Hg). Also magnetic field vector sensor to determine rotation of vehicle, might not detect short movements. An accelerometer to sense motion might false on loading activities. Passive sensors could interrupt from motion. Magnetic and acceleration sensors would need to be polled (every 30 seconds) to determine if changes have occurred. An alternative would be to use a combination with the trembler switch triggering the other sensor to confirm movement and avoid false motion event. Changes in engine or ignition status, ambient lighting, noise level, occupancy, loading, unloading, construction site proximity must not cause false motion state. Also intermittent motion in a parking garage, fuel queue, traffic lights or traffic jam should maintain a reliable motion detection. My current idea is to have a sensitive trembler switch with asymmetrical filtering and long time hysteresis to change. Are there standard sensors types that are used for this or that would provide me with a simple output I could condition? A: As you have hinted in your question, an accelerometer with a 30 second poll interval would probably be the lowest power solution. Tilt switches and piezoelectric sensors aren't going to be sensitive enough to the kind of motion that you are trying to detect. The uC would power off the accelerometer, sleep for 30s, then wake, power on the accelerometer and take a reading. If there is any motion at that instant then you run a more thorough algorithm for a few seconds before deciding whether to mark the vehicle as moving or not, then go back to sleep. As for 'standard sensors', probably not as your problem is specific. But a search for low power accelerometers results in the ADXL362 which takes 1.8uA, runs off a wide range of voltages and has SPI so can easily be connected to a uC.
{ "pile_set_name": "StackExchange" }
Q: how to read links from a list with beautifulsoup? I have a list with lots of links and I want to scrape them with beautifulsoup in Python 3 links is my list and it contains hundreds of urls. I have tried this code to scrape them all, but it's not working for some reason links= ['http://www.nuforc.org/webreports/ndxe201904.html', 'http://www.nuforc.org/webreports/ndxe201903.html', 'http://www.nuforc.org/webreports/ndxe201902.html', 'http://www.nuforc.org/webreports/ndxe201901.html', 'http://www.nuforc.org/webreports/ndxe201812.html', 'http://www.nuforc.org/webreports/ndxe201811.html',...] raw = urlopen(i in links).read() ufos_doc = BeautifulSoup(raw, "html.parser") A: raw should be a list containing the data of each web-page. For each entry in raw, parse it and create a soup object. You can store each soup object in a list (I called it soups): links= ['http://www.nuforc.org/webreports/ndxe201904.html', 'http://www.nuforc.org/webreports/ndxe201903.html', 'http://www.nuforc.org/webreports/ndxe201902.html', 'http://www.nuforc.org/webreports/ndxe201901.html', 'http://www.nuforc.org/webreports/ndxe201812.html', 'http://www.nuforc.org/webreports/ndxe201811.html'] raw = [urlopen(i).read() for i in links] soups = [] for page in raw: soups.append(BeautifulSoup(page,'html.parser')) You can then access eg. the soup object for the first link with soups[0]. Also, for fetching the response of each URL, consider using the requests module instead of urllib. See this post.
{ "pile_set_name": "StackExchange" }
Q: Converting python float to bytes I want to convert a Python float into a byte array, encoding it as a 32 bit little-endian IEEE floating point number, in order to write it to a binary file. What is the modern Pythonic way to do that in Python 3? For ints I can do my_int.to_bytes(4,'little'), but there is no to_bytes method for floats. It's even better if I can do this in one shot for every float in a numpy array (with dtype numpy.float32). But note that I need to get it as a byte array, not just write the array to a file immediately. There are some similar-sounding questions, but they seem mostly to be about getting the hex digits, not writing to a binary file. A: With the right dtype you can write the array's data buffer to a bytestring or to a binary file: In [449]: x = np.arange(4., dtype='<f4') In [450]: x Out[450]: array([0., 1., 2., 3.], dtype=float32) In [451]: txt = x.tostring() In [452]: txt Out[452]: b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@' In [453]: x.tofile('test') In [455]: np.fromfile('test','<f4') Out[455]: array([0., 1., 2., 3.], dtype=float32) In [459]: with open('test','br') as f: print(f.read()) b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@' Change endedness: In [460]: x.astype('>f4').tostring() Out[460]: b'\x00\x00\x00\x00?\x80\x00\x00@\x00\x00\x00@@\x00\x00'
{ "pile_set_name": "StackExchange" }
Q: How to equivalent to ps -ef in Windows 10 I have looked online, and have not found anything that would accomplish what I want to do. I am looking for a command with output equivalent to "ps -ef" of Linux so I can find out the process id associated with an executable I created myself. I want to do this so can attach the GDB debugger to it. I am doing this on a windows 10 machine. I found out about get-process in powershell, but the output does not show me the name of the executable like ps command does. Can anyone help? I am trying to follow these procedures. Here is the type of output I am after: B$ ps -ef ... user 17809 16492 7 21:28 pts/1 00:00:00 java JNITest user 17821 14042 4 21:28 pts/2 00:00:00 bash user 17845 17821 0 21:28 pts/2 00:00:00 ps -ef Thanks. You were both right. I had to look for "java". A: Use powershell rather than the typical cmd prompt. Just type powershell to open up a term. Then in powershell type Get-Process to list all processes. To get a specific process do Get-Process -Id 99. Of course 99 would be your PID.
{ "pile_set_name": "StackExchange" }
Q: Triggering an action after text input after stopping writing? I've been working on a visual force search page and have run into an issue. I have a text input section to search for the name of a record. However, it updates every time any letter is input. I want it to only search after the user has stopped typing. I found this post regarding this exact issue. However, as I'm fairly new to coding (especially with js), I can't seem to figure out how to trigger my action using the js code found in the other post. Thanks for you help! Here is my VF page code: <apex:page controller="CorpGovSearchController" sidebar="false"> <c:LoadingBox /> <apex:form id="myForm"> <apex:pageMessages id="errors" /> <apex:pageBlock title="Agreement Search" mode="edit"> <table width="100%" border="0"> <tr> <td width="200" valign="top"> <apex:pageBlock title="Filters" mode="edit" id="criteria"> <script type="text/javascript"> var oldG; var oldAP; var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); $('#name').keyup(function() { delay(function (){ }, 1000 ); }); function doSearch() { if(document.getElementById("{!$Component.geography}").value=='' || document.getElementById("{!$Component.subgeography}").value=='__' || document.getElementById("{!$Component.geography}").value!=oldG){ document.getElementById("{!$Component.subgeography}").value=''; } if(document.getElementById("{!$Component.agmtPurpose}").value=='' || document.getElementById("{!$Component.agmtCategory}").value=='__' || document.getElementById("{!$Component.agmtPurpose}").value!=oldAP){ document.getElementById("{!$Component.agmtCategory}").value=''; } oldG = document.getElementById("{!$Component.geography}").value; oldAP = document.getElementById("{!$Component.agmtPurpose}").value; searchServer( document.getElementById("Name").value, document.getElementById("{!$Component.agmtPurpose}").value, document.getElementById("{!$Component.agmtCategory}").value, document.getElementById("{!$Component.geography}").value, document.getElementById("{!$Component.subgeography}").value ); } function doClear() { document.getElementById("Name").value=''; document.getElementById("{!$Component.agmtPurpose}").value=''; document.getElementById("{!$Component.geography}").value=''; document.getElementById("{!$Component.agmtCategory}").value=''; document.getElementById("{!$Component.subgeography}").value=''; searchServer( document.getElementById("Name").value, document.getElementById("{!$Component.agmtPurpose}").value, document.getElementById("{!$Component.agmtCategory}").value, document.getElementById("{!$Component.geography}").value, document.getElementById("{!$Component.subgeography}").value ); } </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> // // $('#element').donetyping(callback[, timeout=1000]) // Fires callback when a user has finished typing. This is determined by the time elapsed // since the last keystroke and timeout parameter or the blur event--whichever comes first. // @callback: function to be called when even triggers // @timeout: (default=1000) timeout, in ms, to to wait before triggering event if not // caused by blur. // Requires jQuery 1.7+ // ;(function($){ $.fn.extend({ donetyping: function(callback,timeout){ timeout = timeout || 1e3; // 1 second default timeout var timeoutReference, doneTyping = function(el){ if (!timeoutReference) return; timeoutReference = null; callback.call(el); }; return this.each(function(i,el){ var $el = $(el); // Chrome Fix (Use keyup over keypress to detect backspace) // thank you @palerdot $el.is(':input') && $el.on('keyup keypress',function(e){ // This catches the backspace button in chrome, but also prevents // the event from triggering too premptively. Without this line, // using tab/shift+tab will make the focused element fire the callback. if (e.type=='keyup' && e.keyCode!=8) return; // Check if timeout has been set. If it has, "reset" the clock and // start over again. if (timeoutReference) clearTimeout(timeoutReference); timeoutReference = setTimeout(function(){ // if we made it here, our timeout has elapsed. Fire the // callback doneTyping(el); }, timeout); }).on('blur',function(){ // If we can, fire the event since we're leaving the field doneTyping(el); }); }); } }); })(jQuery); $('#Name').donetyping(function(){ $doSearch(); }); </script> <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors"> <apex:param name="Name" value="" /> <apex:param name="agmtPurpose" value="" /> <apex:param name="agmtCategory" value="" /> <apex:param name="geography" value="" /> <apex:param name="subgeography" value="" /> </apex:actionFunction> <table cellpadding="2" cellspacing="2"> <tr> <td style="font-weight:bold;" onkeyup="doSearch();">Agreement Name<br/> <input type="text" id="Name"/> </td> </tr> <tr> <td style="font-weight:bold;">Agreement Purpose<br/> <apex:inputfield id="agmtPurpose" value="{!agmt1.Nike_SF_Contract_Category__c}" onchange="doSearch();"/> </td> </tr> <tr> <td style="font-weight:bold;">Agreement Category<br/> <apex:inputfield id="agmtCategory" value="{!agmt1.Apttus__Agreement_Category__c}" onchange="doSearch();"/> </td> </tr> <tr> <td style="font-weight:bold;">Geography<br/> <apex:inputfield id="geography" value="{!agmt1.NikeSF_Geography__c}" onchange="doSearch();"/> </td> </tr> <tr> <td style="font-weight:bold;">Sub-Geography<br/> <apex:inputfield id="subgeography" value="{!agmt1.NikeSF_Sub_Geography__c}" onchange="doSearch();"/> </td> </tr> </table> <apex:pageBlockButtons location="bottom"> <apex:commandButton style="text-align:center" onClick="doClear()" title="Clear" value="Clear" rerender="results,debug,errors"/> </apex:pageBlockButtons> </apex:pageBlock> </td> <td valign="top"> <apex:pageBlock mode="edit" id="results"> <apex:pageBlockButtons location="top" > <apex:outputPanel id="myButtons"> <apex:commandButton action="{!Beginning}" title="Beginning" value="<<" disabled="{!disablePrevious}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <apex:commandButton action="{!Previous}" title="Previous" value="<Previous" disabled="{!disablePrevious}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <apex:commandButton action="{!Next}" title="Next" value="Next>" disabled="{!disableNext}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <apex:commandButton action="{!End}" title="End" value=">>" disabled="{!disableNext}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <br/> </apex:outputPanel> </apex:pageBlockButtons> <apex:pageBlockButtons location="bottom" > <apex:outputPanel id="myButtons2"> <apex:outputlabel style="text-align:center" value="Showing Page #{!pageNumber} of {!totalPages}"/> <br/> <br/> <apex:commandButton action="{!Beginning}" title="Beginning" value="<<" disabled="{!disablePrevious}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <apex:commandButton action="{!Previous}" title="Previous" value="<Previous" disabled="{!disablePrevious}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <apex:commandButton action="{!Next}" title="Next" value="Next>" disabled="{!disableNext}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> <apex:commandButton action="{!End}" title="End" value=">>" disabled="{!disableNext}" reRender="myPanel,myButtons" oncomplete="doSearch()"/> </apex:outputPanel> </apex:pageBlockButtons> <apex:pageBlockTable value="{!agmts}" var="agmt"> <apex:column > <apex:facet name="header"> <apex:commandLink value="Agreement Name " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Name', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Name' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Name' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="Name" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Name" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputLink value="/{!agmt.id}">{!agmt.Name}</apex:outputLink> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Agreement Category " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Agreement Category', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Agreement Category' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Agreement Category' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="Apttus__Agreement_Category__c" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Agreement Category" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputField value="{!agmt.Apttus__Agreement_Category__c}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Agreement Type " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Agreement Type', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Agreement Type' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Agreement Type' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="NikeSF_Agreement_Type__c" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Agreement Type" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputField value="{!agmt.NikeSF_Agreement_Type__c}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Status Category " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Status Category', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Status Category' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Status Category' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="Apttus__Status_Category__c" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Status Category" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputField value="{!agmt.Apttus__Status_Category__c}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Status " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Status', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Status' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Status' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="Apttus__Status__c" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Status" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputField value="{!agmt.Apttus__Status__c}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Geography " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Geography', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Geography' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Geography' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="NikeSF_Geography__c" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Geography" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputField value="{!agmt.NikeSF_Geography__c}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Sub-Geography " action="{!toggleSort}" rerender="results,debug" style="{!IF(sortValue=='Sub-Geography', 'font-style: italic', 'font-style: normal')}"> <apex:outputPanel layout="none" rendered="{!sortValue=='Sub-Geography' && sortDir=='desc'}">&#x25B2;</apex:outputPanel> <apex:outputPanel layout="none" rendered="{!sortValue=='Sub-Geography' && sortDir!='desc'}">&#x25BC;</apex:outputPanel> <apex:param name="sortField" value="NikeSF_Sub_Geography__c" assignTo="{!sortField}"/> <apex:param name="sortValue" value="Sub-Geography" assignTo="{!sortValue}"/> </apex:commandLink> </apex:facet> <apex:outputField value="{!agmt.NikeSF_Sub_Geography__c}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </td> </tr> </table> <apex:pageBlock title="Debug - SOQL" id="debug"> <apex:outputText value="{!debugSoql}" /> </apex:pageBlock> </apex:pageBlock> </apex:form> </apex:page> A: $('#name').keyup(function() { delay(function (){ // Whatever you want to trigger paste it here. }, 1000 ); }); and this 1000 decides after how much milliseconds you want to trigger when user stops typing
{ "pile_set_name": "StackExchange" }
Q: CSS Scroll thumb fixed circle size I want to style a scroll bar thumb as a fixed circle, there is something I'm missing because I cant fix height size. Now what is happening is that depending on how long the scroll bar is, how long the thumb is too, and I'd like to get a fixed circle no matters how long the scroll bar is. Here is what I have: .container { display: flex; flex-direction: row; } .list1 { overflow-y: scroll; height: 100px; width: 100px; margin: 50px; } .list1::-webkit-scrollbar-track { border-radius: 10px; border: 1px solid blue; width: 50px; } .list1::-webkit-scrollbar { width: 50px; background-color: blue; border-radius: 10px; } .list1::-webkit-scrollbar-thumb { border-radius: 100px; background-color: red; border: 5px solid blue; } <div class="container"> <ul class="list1"> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> <ul class="list1"> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> </div> As you can see, depending on how many items i have is the hight that the scroll bar thumb will take. Below the way I want it to look like: A: You just need to set a height value in the .list1::-webkit-scrollbar-thumb: .list1::-webkit-scrollbar-thumb { height:50px; } .container { display: flex; flex-direction: row; } .list1 { overflow-y: scroll; height: 100px; width: 100px; margin: 50px; } .list1::-webkit-scrollbar-track { border-radius: 10px; border: 1px solid blue; width: 50px; } .list1::-webkit-scrollbar { width: 50px; background-color: blue; border-radius: 10px; } .list1::-webkit-scrollbar-thumb { border-radius: 100px; background-color: red; border: 5px solid blue;height:50px; } <div class="container"> <ul class="list1"> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> <ul class="list1"> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> </div>
{ "pile_set_name": "StackExchange" }
Q: MVC5 One Click Delete from Details Page I started with the scaffolding that VS MVC 5 can create, and it was working fine, but I wanted to be able to delete records ("Interviews", in this case) from the details page. I started by copying the markup from the delete button on the Delete page over to Details, but it would simply redirect to the Details action. How can I get a button on the Details page to run the DeleteConfirmed method? Here is the relevant code from the controller: public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Interview interview = db.Interviews.Find(id); if (interview == null) { return HttpNotFound(); } return View(interview); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Interview interview = db.Interviews.Find(id); db.Interviews.Remove(interview); db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Interview interview = db.Interviews.Find(id); if (interview == null) { return HttpNotFound(); } return View(interview); } and here is the markup that I copied from the Delete page and put into the Details view: @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-actions no-color"> <input type="submit" value="Delete" class="btn btn-danger" /> </div> } Here is the markup I needed to make it work: @using (Html.BeginForm("Delete", "Interviews", new { id = Model.ID })) { @Html.AntiForgeryToken() <div class="form-actions no-color"> <input type="submit" value="Delete" class="btn btn-danger" /> </div> } A: You need to post to the DeleteConfirm action. Here, you're posting to the Details action because you're using just Html.BeginForm(). You need: @using (Html.BeginForm("Delete", new { id = Model.Id })) {
{ "pile_set_name": "StackExchange" }
Q: SELECT epoch timestamp bigger then my variable Why is this SELECT strftime('%s', timestamp,'localtime') from locationLog WHERE strftime('%s', timestamp,'localtime') > 999999999999999999 ORDER BY _id DESC return any outputs when all of my rows have a lower value in "timestamp" in my case the query above returns 1334735588 1334735349 1334734317 1334734178 1334734172 and so on... it returns my whole table. if I switch > to < it returns nothing. I guess I'm trying to compare different type of variables or something like that. A: You are comparing a text value with a integer value, so sqlite casts the integer value to text, and does a string comparison: sqlite> select strftime('%s', '2002-02-02', 'localtime'); 1012611600 sqlite> select typeof(strftime('%s', '2002-02-02', 'localtime')); text sqlite> select typeof(999999999999999999); integer sqlite> select strftime('%s', '2002-02-02', 'localtime') > 999999999999999999; 1 sqlite> select cast(strftime('%s', '2002-02-02', 'localtime') as integer) > 999999999999999999; 0 As shown above, the solution is to cast the returned value of strftime to some numeric type.
{ "pile_set_name": "StackExchange" }
Q: Thread/threadpool or backgroundworker I would like to know what to use for tasks that need alot of performance. Backgroundworker, Thread or ThreadPool? I've been working with Threads so far, but I need to improve speed of my applications. A: BackgroundWorker is the same thing as a thread pool thread. It adds the ability to run events on the UI thread. Very useful to show progress and to update the UI with the result. So its typical usage is to prevent the UI from freezing when works needs to be done. Performance is not the first goal, running code asynchronously is. This pattern is also ably extended in later .NET versions by the Task<> class and the async/await keywords. Thread pool threads are useful to avoid consuming resources. A thread is an expensive operating system object and you can create a very limited number of them. A thread takes 5 operating system handles and a megabyte of virtual memory address space. No Dispose() method to release these handles early. The thread pool exists primarily to reuse threads and to ensure not too many of them are active. It is important that you use a thread pool thread only when the work it does is limited, ideally not taking more than half a second. And not blocking often. It is therefore best suited for short bursts of work, not anything where performance matters. Handling I/O completion is an ideal task for a TP thread. Yes, it is possible to also use threads to improve the performance of a program. You'd do so by using Thread or a Task<> that uses TaskContinuationOptions.LongRunning. There are some hard requirements to actually get a performance improvement, they are pretty stiff: You need more than one thread. In an ideal case, two threads can half the time needed to get a job done. And less, the more threads you use. Approaching that ideal is however hard, it doesn't infinitely scale. Google "Amdahl's law" for info. You need a machine with a processor that has multiple cores. Easy to get these days. The number of threads you create should not exceed the number of available cores. Using more will usually lower performance. You need the kind of job that's compute-bound, having the execution engine of the processor be the constrained resource. That's fairly common but certainly no slamdunk. Many jobs are actually limited by I/O throughput, like reading from a file or dbase query. Or are limited by the rate at which the processor can read data from RAM. Such jobs don't benefit from threads, you'll have multiple execution engines available but you still have only one disk and one memory bus. You need an algorithm that can distribute the work across multiple threads without hardly any need for synchronization. That's usually the tricky problem to solve, many algorithms are very sequential in nature and are not easily parallelizable. You'll need time and patience to get the code stable and performing well. Writing threaded code is hard and a threading race that crashes your program once a month, or produces an invalid result occasionally can be a major time sink.
{ "pile_set_name": "StackExchange" }
Q: Fetch google drive data of domain user using Java or HTTP I am writing a program (written in java) for businesses that manages google drive data of domain users (download/read/...). I need to authenticate once, using domain admin's credentials, get a token and refresh token, and fetch the data of all domain users. I succeeded with doing it for the admin user itself, using google's Drive REST API How can I manage all the domain users with one access token and refresh token? A: In Google Apps, the admin does not have the ability to access the user's information directly. The way to achieve this is through a service account and domain wide delegation. With this approach, after the admin grants permissions to you app, the app will be able to impersonate users in the domain and perform actions on their behalf. e.g. you can access users Drive information.
{ "pile_set_name": "StackExchange" }
Q: How do I pass objects in EventArgs I have a usercontrol that raises an event after communicating with a web service. The parent handles this event when raised. What I thought would be the proper approach would be to pass the object returned from the webservice to the parent as eventargs??? If this is the proper way I can't seem to find the instructions on how to do so. UserControl public event EventHandler LoginCompleted; then later after the service returns biz object: if (this.LoginCompleted != null) { this.LoginCompleted(this, new EventArgs() //this is where I would attach / pass my biz object no?); } Parent ctrl_Login.LoginCompleted += ctrl_Login_LoginCompleted; ....snip.... void ctrl_Login_LoginCompleted(object sender, EventArgs e) { //get my object returned by login } So my question is what would be the "approved" method for getting the user object back to the parent? Create a property class that everything can access and put it there? A: You would have to declare your event using EventHandler<T> where T is your class that derives from EventArgs: public event EventHandler<LoginCompletedEventArgs> LoginCompleted; LoginCompletedEventArgs could look like this: public class LoginCompletedEventArgs : EventArgs { private readonly YourBusinessObject _businessObject; public LoginCompletedEventArgs(YourBusinessObject businessObject) { _businessObject = businessObject; } public YourBusinessObject BusinessObject { get { return _businessObject; } } } Usage would be like this: private void RaiseLoginCompleted(YourBusinessObject businessObject) { var handler = LoginCompleted; if(handler == null) return; handler(this, new LoginCompletedEventArgs(businessObject)); } Please notice how I implemented RaiseLoginCompleted. This is a thread-safe version of raising the event. I eliminates a possible NullReferenceException that can occur in a race condition scenario where one thread wants to raise the event and another thread un-subscribes the last handler after the if check but before actually invoking the handler. A: Well, you could do all that or you could define a delegate as your EventHandler and define your properties in its signature. Such as: public delegate void MyEventEventHandler(int prop1, string prop2, object prop3...); public event MyEventEventHandler MyEvent; A: I personally like Toni Petrina's approach (see https://coderwall.com/p/wkzizq/generic-eventargs-class). It differs from the accepted answer in that you don't have to create a special EventHandler class (e.g. LoginCompletedEventArgs). (Note: I am using VS 2015 and C# v6. In older versions of Visual Studio and C#, you may have to add using System.Linq;) Create a generic EventArgs<T> class that inherits from EventArgs... class EventArgs<T> : EventArgs { public T Value { get; private set; } public EventArgs(T val) { Value = val; } } Declare your event handler... public event EventHandler<EventArgs<object>> LoginCompleted; Assuming you have declared and assigned an object named loginObject, add code to raise you event... private void RaiseLoginCompleted() { if (LoginCompleted != null) LoginCompleted(this, new EventArgs<object>(loginObject)); } In your client code, add the LoginCompleted event handler (uses Linq and calls a local method)... LoginCompleted += (o, e) => onLoginCompleted(e.Value); // calls a local method void onLoginCompleted(LoginObject obj) { // add your code here }
{ "pile_set_name": "StackExchange" }
Q: Get conflict line/range Is it possible to get which line numbers conflict? i.e, the lines between the <<<<<<<, ======= and >>>>>>> markers. if I have the following file: <<<<<<< HEAD master ======= develop >>>>>>> develop git some command and the output will be some data about files and line numbers in conflict? Edit: File master: 1. shared 2. 3. master 4. 5. shared File develop: 1. shared 2. 3. develop 4. 5. shared File merge: 1. shared 2. 3. <<<<<<< HEAD 4. master 5. ======= 6. develop 7. >>>>>>> develop 8. 9. shared run git diff: diff --cc test.txt index cf590df,7415cb0..0000000 --- a/test.txt +++ b/test.txt @@@ -1,5 -1,5 +1,9 @@@ shared ++<<<<<<< HEAD +master ++======= + develop ++>>>>>>> develop shared Desired output is something like: Master 3 - 3 Develop 3 - 3 Merged 3 - 7 I.e for each conflict what are the line ranges.. The merged one is bonus.. =) A: When you run git diff in a conflicted state, you will get a special diff format called Combined diff format. I added a second line in the develop branch for clarity. It looks like this: $ git diff diff --cc foo index 1f7391f,1e25601..0000000 --- a/foo +++ b/foo @@@ -1,1 -1,2 +1,6 @@@ ++<<<<<<< HEAD +master ++======= + develop + second line ++>>>>>>> develop The line beginning with @@@ shows the ranges for each of the three files, that is in this case the file on master, develop, and the file with the conflict markers. @@@ -1,1 -1,2 +1,6 @@@ | | | | | - file with conflict markers | - develop - master More information in section COMBINED DIFF FORMAT of man git-diff.
{ "pile_set_name": "StackExchange" }
Q: Magento form submit problem I have a form with different different button when ever i click it should submit same page it self <?php if ($status != 'canceled'){?> <?php $orderIdForm = $order->getId(); ?> <form action="<?php echo $this->getUrl('mpshippingmanager/shipping/savetrackingnumber/',array('id' =>$orderIdForm))?>" id="shipping-form" method="post"> <?php $tracking=$this->getTrackingNumber($order->getId()); if($tracking!=""){ $disabled=$tracking->getTrackingNumber()==''? "":"readonly='readonly'"; $shipmentId = $tracking->getShipmentId(); $invoiceId=$tracking->getInvoiceId(); $shippingamount=$tracking->getShippingCharges(); }?> <div class="shipping_top" style="display:none"> <span class="shipping_service"><?php echo $helper->__('Carrier');?></span> <span class="row_total"><?php echo $helper->__('Tracking Number');?></span> </div> <div class="items"> <input class="required-entry" type="hidden" value="<?php echo $order->getId(); ?>" name="order_id"/> <div class="wk_item"> <span class="carrier" style="display:none"><input class="required-entry carrier" value="<?php echo $tracking->getCarrierName(); ?>" <?php echo $disabled;?> type="text" name="carrier"/></span> <span class="row_total wk_track_input" style="display:none"> <!-- <input value="<?php //echo $tracking->getTrackingNumber(); ?>" <?php //echo $disabled;?> type="text" name="tracking_id"/> --> <input value="0" type="text" name="tracking_id"/> </span> <div class="order-status"> <?php if(count($shipping_coll)): ?> <?php if($status=="Ordered"): ?> <a href="<?php echo $this->getUrl('mpshippingmanager/shipping/cancelorder',array('id'=>$mageorderid))?>"> <button class="button wk_mp_btn" style="flaot:none" title="<?php echo $helper->__('Cancel Order') ?>" type="button" id="save_butn" > <span><span><?php echo $helper->__('Cancel Order') ?></span></span> </button> </a> <?php endif; ?> <?php endif; ?> <?php if($status == "processing" ){?> <button class="button wk_mp_btn" style="flaot:none" title="<?php echo $helper->__('Generate Invoice') ?>" type="submit" id="save_butn" > <span><span><?php echo $helper->__('Invoice') ?></span></span> </button> <?php } ?> <!-- Custom Order Status --> <?php if ($status == "Invoice"){?> <!-- <a href="<?php //echo $this->getUrl('mpshippingmanager/shipping/shipementorder',array('id'=>$orderIdForm))?>"> --> <button class="button wk_mp_btn" style="flaot:none" title="<?php echo $helper->__('Shipment') ?>" type="submit" id="save_butn" > <span><span><?php echo $helper->__('Shipment') ?></span></span> </button> <!-- </a> --> <?php }?> <?php if ($status == 'Shipement'){?> <a href="<?php echo $this->getUrl('mpshippingmanager/shipping/rtoorder',array('id'=>$mageorderid))?>"> <button class="button wk_mp_btn" style="flaot:none" title="<?php echo $helper->__('RTO') ?>" type="button" id="save_butn" > <span><span><?php echo $helper->__('RTO') ?></span></span> </button> </a> <?php }?> <!-- Custom Order Status --> </div> </div> </div> </form> Here invoice button is working but Shipment not working. I am using wrong way can you please tell what is the problem in this? A: <?php if ($status == 'Shipement'){?> <a href="<?php echo $this->getUrl('mpshippingmanager/shipping/rtoorder',array('id'=>$mageorderid))?>‌​"> <button class="button wk_mp_btn" style="flaot:none" title="<?php echo $helper->__('RTO') ?>" type="button" id="save_butn" > <span><span><?php echo $helper->__('RTO') ?></span></span> </button> </a> <?php }?> replace with <?php if ($status == 'Shipement'){?> <a href="<?php echo $this->getUrl('mpshippingmanager/shipping/rtoorder',array('id'=>$orderIdForm))?>‌​"> <button class="button wk_mp_btn" style="flaot:none" title="<?php echo $helper->__('RTO') ?>" type="button" id="save_butn" > <span><span><?php echo $helper->__('RTO') ?></span></span> </button> </a> <?php }?>
{ "pile_set_name": "StackExchange" }
Q: Why do multiple instances of Mate-terminal have the same PID? I've noticed, that all mate-terminal instances I start, be it inside a mate-terminal or via a link button, have the same PID. For example, I got something like $ wmctrl -lp <omitted lines that don't matter> 0x03c0001f 1 7411 <hostname> Terminal 0x03c06b9f 1 7411 <hostname> Terminal 0x03c07349 1 7411 <hostname> Terminal 0x03c073f4 1 7411 <hostname> Terminal 0x03c0749f 1 7411 <hostname> Terminal 0x03c0754c 1 7411 <hostname> Terminal 0x03c075f9 1 7411 <hostname> Terminal 0x03c076a6 1 7411 <hostname> Terminal 0x0340000b 1 <pid1> <hostname> xeyes 0x0460000b 1 <pid2> <hostname> xeyes which clearly shows that there are multiple Terminal windows, all with the same PID. As stated above, it didn't matter, whether or not the process was started inside a terminal or by clicking a menu bar link. Neither did it matter, whether or not I started the process in the background inside the terminal. What is the applied rule here, or "why is this so"? My understanding used to be that every command I start in a shell would obtain a unique PID. Isn't it kind of impractical to have multiple terminals with the same PID? I can't kill them individually by PID anymore. Edit: Kernel version: 3.16.0-4-amd64 A: All the instances of Mate Terminal have the same PID because they are in fact a single process which happens to display multiple windows. Mate Terminal runs in a single process because that's the way the application is designed. When you run the command mate-terminal, it contacts the existing process and sends it an instruction to open a new window. As of Mate Terminal 1.8.1, you can run mate-terminal --disable-factory to open a new window in a new process. Beware that this option has been removed from the Gnome version in 3.10; I don't know whether the Mate developers have decided to merge that change. See Run true multiple process instances of gnome-terminal for a similar question regarding Gnome-terminal.
{ "pile_set_name": "StackExchange" }
Q: On what Cloth Simulation Model is Blender Cloth Physics Based? What research papers were leveraged to implement Blender Cloth? I know of several cloth models - Geometric, Physical, Particle. There are several researchers who have published work within each type of model (Provot, Baraff & Witkin) and I am not certain if Blender utilizes one over others or a combination of multiple. In short, I am not entirely certain what each of the Cloth Settings actually represents as far as a calculation is concerned. I am not sure what units are being manipulated for, say, "Structural Stiffness", when you decrease the value from 15 to 10. I'm unsure of what a "Stiffness" of 1 unit actually means (mathematically or physically). I know that it cannot be arbitrary (at least I hope). A further understanding of the actual physics and math behind the "Quality" step sizes, the "Structural" and "Bending" qualities, and the "Spring" variables under the Damping setting are of interest. This powerpoint has helped, as has this .pdf, but neither offer a total picture on what Blender may be using. A: Summary: Initially in 2004, Todd Koeckeritz leveraged Provot's Cloth Model (Deformation Constraints in a Mass-Spring Model to Describe Rigid Cloth Behavior); also, he leveraged simplified portions of Provot's Cloth Collision Model (Collision and self-collision handling in cloth model dedicated to design garments). Then in 2006, Daniel Genrich completed an implementation of Mezger's Cloth Collision Model (Improved Collision Detection and Response Techniques for Cloth Animation). Additionally, Todd Koeckeritz created a parameter named "Steps"/"Quality" to handle time steps. Finally in 2008, Daniel Genrich released Blender Cloth (according to BlenderNation.com). Research Papers: Todd Koeckeritz (Contributor of Blender Cloth) says in April 2006: Provot was chosen when we started the project because I had the code written already from two years ago when I was working on cloth as a python module. So, we've started with that. However, the few semi-unique characteristics of the Provot paper referenced in the wiki page are being replaced now with a similar process from another paper. So, in some ways Provot is gone, or will be in the next release. However, the nice feature described by Provot in section 5 of his paper, deals with eliminating the super-elastic/rubbery effect that some cloth simulators exhibit. That was my reason for choosing the paper two+ years ago. The initial checkin of Blender Cloth files for "trunk/blender/source/blender/makesdna/DNA_cloth_types.h" by Daniel Genrich (Contributor of Blender Cloth) reads in September 2007: +/** +* This struct contains all the global data required to run a simulation. +* At the time of this writing, this structure contains data appropriate +* to run a simulation as described in Deformation Constraints in a +* Mass-Spring Model to Describe Rigid Cloth Behavior by Xavier Provot. +* +* I've tried to keep similar, if not exact names for the variables as +* are presented in the paper. Where I've changed the concept slightly, +* as in stepsPerFrame comapred to the time step in the paper, I've used +* variables with different names to minimize confusion. +**/ Todd Koeckeritz talks about his implementation of Provot's Cloth Collision Model in April 2006: What we have now is a partial implementation of one described by Provot in his paper "Collision and self collision handling in cloth model dedicated to design garments." We may not implement all that is described in that paper, but we do need to get friction working properly and get it working properly with moving and/or deforming collision objects. What we have now works fine for dropping pieces of cloth on cubes and such, but there's no sliding when there should be and it isn't working now with collision meshes being deformed by armatures and such. Todd Koeckeritz talks about Daniel Genrich implementation of Mezger's Cloth Collision Model in March/April 2006: Genscher is focusing on work on the k-dop collision system [...] The collision system we've implemented is described in papers by Metzger in 2002 and 2003 and is known as K-DOP BVH. From an end user standpoint, there isn't too much that needs to be understood about this implementation that is specific to the collision system. In most cases, you either want to spend CPU time computing collisions or you don't. Todd Koeckeritz talks about Time Steps in April 2006: There is one more important concept for an end user to understand and that is the one of how the simulation deals with time. It is impossible to model all the atoms or molecules in a piece of cloth and those objects with which it might collide as it would simply take too much time to compute the results, so we compromise by using the point masses and springs described above. There is a similar problem when it comes to dealing with time. While some parts of the cloth modifier attempt to deal with time in a continuous sense, other parts only compute the results at specific points in time. For example, think of dropping a ball on frame one and having it hit the ground on frame 21. If you only had results on frame 1 and frame 21, you'd have no idea on how the ball behaved between those frames. It might have been moving at a constant velocity or it might have been accelerated from rest by gravity or another force. On the other hand, if you had all the frames from 1 to 21, you could examine the position of the ball in each frame and then know much better how the ball moved during that time. With that new information, you can then better predict how the ball should move between frames 22 and 51. The cloth modifier has some similar problems, although we deal with them at the sub-frame level. To do this a parameter called Steps is provided. The higher the number of steps, the more time is spent computing a result, however that result should be more precise. The lowest setting for Steps is 1, meaning we'll run the simulation once per frame. This is the fastest way to get a result from the cloth modifier, however, the results might be less physically accurate than if you choose a larger number. In April 2006, Todd Koeckeritz called it "Steps". Between September 2007 and January 2008, Daniel Genrich renamed "Steps Per Frame" to "Quality". The following code diff of "/source/blender/src/buttons_object.c" represents these changes: - uiDefButS(block, NUM, B_DIFF, "Steps:", 10,80,100,20, &sb->minloops, 1.00, 30000.0, 10, 0, "Solver steps/frame "); - uiDefButI(block, NUM, B_DIFF, "Steps per Frame:", 10,150,150,20, &clmd->sim_parms.stepsPerFrame, 1.0, 100.0, 5, 0, "Quality of the simulation (higher=better=slower)"); + uiDefButI(block, NUM, B_CLOTH_RENEW, "Quality:", 10,150,150,20, &clmd->sim_parms->stepsPerFrame, 4.0, 100.0, 5, 0, "Quality of the simulation (higher=better=slower)"); Parameters: The Blender Cloth Modifier is based on a Spring Network, according to Todd Koeckeritz in April 2006: The spring network is built of three types of springs and the user is allowed to control the stiffness of the springs separately: (1) Structural Springs are built on the edges of the mesh. They provide the main structural integrity of the cloth. (2) Shear Springs are built on the diagonals of quad faces and provide some resistance to shearing forces in the cloth. (3) Flexion Springs are built similarly to the Structural Springs, but are built on top of two close to parallel Structural Springs. Flexion Springs provide resistance to folding, the stiffer they are, the more the cloth will attempt to retain its original shape. Think of them as starch for your collar. The Blender Cloth Controls were more detailed in April 2006: Collision : This toggles whether the object is a collision object. Collision objects are not cloth objects, they only allow the cloth objects to react to them when they collide. To collide with a cloth object, this button should be toggled on and the object should share a layer with the cloth objects with which it should collide. Bake Settings : This button switches the mode of the cloth modifier panel to baking mode, allowing the user to bake the results. Simulation Type : Presently there is only one solver implemented, the Provot solver as described in his paper above. There are however 3 forms of integration, Explicit Euler, Middle Point and Runge-Kutta. Collision Type : This allows the user to specify what type of collisions to process for the cloth object. Presently only the None and KDOP options are available. Pinned Vertex Group : If a vertex group is chosen in this menu, those vertices are not affected by the cloth modifier. They are pinned in place. Mass Scale Vertex Group : This vertex group allows the user to multiply the point mass by the influence/weight a vertice has in the vertex group. Thus parts of the cloth can have different weights making part of it appear wet or heavier for other reasons. Mass Vertex Group : This vertex group allows the user to directly specify the weight of the vertices. The Scale parameter is used to adjust the results of this. Scale : This allows the user to scale the results of applying a Mass Vertex Group. Gravity X, Y and Z : These provide an external force to the cloth. Spring Stiffness : These three parameters control the Structural, Shear and Flexion spring stiffness. Damping Springs : This is the damping factor applied to motion produced by the springs. Damping Viscous : This damping factor is applied to all motion of the cloth, higher values produce results like moving through water or mud. Damping Self Fr : This will be used as the damping factor for friction caused by self collisions of the cloth. Damping Friction : This damping factor is applied to the cloth vertices that collide with collisoin objects. Simulation Steps : This controls how many steps per frame are used in the simulation. Higher values produce better results in general, but take longer to compute. Simulate Adjustments : Adjustments controls whether or not attempts are made to keep the springs in the cloth from exceeding their original length multipled by Tc. When set to -1, the Structural springs get increasingly stiffer, up to 100 times stiffer, as the springs's length divided by its original length aproaches Tc. At 0 (zero), not adjustments are made. At 1 (one) or greater, Provot's algorithm of adjusting the springs is done as many times as specified by this parameter. Simulation Mass : This specifies the base mass of a vertice in a cloth object. The final value of the mass for any given vertice can be influenced by the Mass Scale Vertex Group and/or the Maxx Vertex Group. Simulation MinZ : Provides an artificial floor below which the cloth vertices will not go. Simulation Epsilon : This provides a buffer distance for collision detection and response. In the current implementation, small values in the range of 0.001 to 0.005 generally work best, although in some cases larger values may be desired. Simulatin Tc : This specifies the critical deformation length as a ratio to the original spring length. This value has no effect if Adjustments are 0 (zero). Simulation Spr Len : This allows the user to specify an artificially large or small base spring length. When this value is 1.0, the simulation behaves normally. With values less than 1 (one), the springs are treated as if they were shorter than they actually are which can be useful to shrink clothing to fit tighter on a model ... think spandex. If this value is greater than 1 (one), it provides an artificial force to expand the cloth object which can be useful to give bounce to a skirt or dress. Simulation Pre-roll : This provides some artificial frames prior to the start of the animation to allow the cloth to find its resting position. Simulation Col Loop : This is the maximum number of times per step collisions will be tested. This parameter is likely to go away. Daniel Genrich simplified the controls by May 2008: StructStiff: Structural Stiffness also includes shear stiffness. Both define the stiffness of the structure of the cloth. Lower values will make the cloth look like elastic rubber. BendStiff: Bending Stiffness describes how the cloth forms its wrinkles. Higher values result in bigger but not necessarily more wrinkles. Spring Damp: Specifies how much the amount of movement will be lowered. This can prevent unwanted jiggling, and can result also in smoother animation. Air Damp: How thick is the air? How much movement will it stop due to its thickness? Practically speaking, you receive slower movement of cloth with higher air damping. With air damping set to zero, you have moon surface conditions. Quality: More quality gives more stable cloth (less jiggling with high BendStiff) and additionally you receive better collision responses. Mass: More mass gives heavier cloth, with slightly more weight on the border like normal cloth. Gravity: X, Y and Z direction of the gravity you want to have working on the cloth. Min Distance: Defines the cloth thickness where the collision response kicks in. It helps to keep a minimum distance between the Cloth and the colliding mesh. Just increase it if you encounter collision penetrations (This is only one of two available options to resolve that issue - you could also increase the Quality on the first Cloth panel). Friction: Friction defines how good a cloth can slide over a collision object. See this for how friction effects the cloth collisions. Min Distance: Defines the cloth thickness where the selfcollision response kicks in. It helps to keep a minimum distance between the Cloth. Selfcoll Quality: This values helps you to resolve several layers of selfcollisions. Be carefull: the Collision Quality has to be at least as high as Selfcoll Quality to have it working! StructStiff VGroup: Vertex Group to be used for Structural Stiffness scaling. BendStiff VGroup: Vertex Group to be used for Bending Stiffness scaling. StructStiff Max: Defines the Structural Stiffness maximum. The structural stiffness gets scaled between this maximum (the red painted values on the vertex group) and the minimum StructStiff on the first Cloth panel (blue painted vertices on the vertex group). A linear interpolation function is used inbetween. BendStiff Max: Defines the Bending Stiffness maximum. The bending stiffness gets scaled between this maximum (the red painted values on the vertex group) and the minimum BendStiff on the first Cloth panel (blue painted vertices on the vertex group). A linear interpolation function is used inbetween. As of today (April 2015), the controls for Blender have three damping forces (Spring, Velocity, Air). Provot's model explains these three damping forces as follows (respectively: Internal, Gravity, Viscous-Damping/Air): The internal force is the resultant of the tensions of the springs linking P_ij to its neighbors. The external force is of various nature according to the kind of load to which we wish the model to be exposed. Omnipresent loads will be gravity, a viscous damping, and a viscous interaction with an air stream or wind. Let g be the acceleration of gravity, the weight of P_ij is given by F_g=mg. The viscous damping will be given by F_d=-C_dv where C_d is a damping coefficient and v is the velocity of point P_ij. The role of this damping is in fact to model in first approximation the dissipation of the mechanical energy of our model. It is introduced as an external force but could actually be considered as an internal force as well. Finally, a viscous fluid moving at a uniform velocity u exerts on the surface of a body moving at a velocity v a force F_v = C_v((n dot (u-v))n where n is the unit normal on the surface. The controls today (April 2015) are very similar to the controls in May 2008. The full set of updated parameters can be found in the the current Blender Manual: http://www.blender.org/manual/physics/cloth.html
{ "pile_set_name": "StackExchange" }
Q: Reduce Permutation I need an algorithm that can map the runs in a permutation to a single number, but also reduce the subsequent numbers. So a run is a sequential set of numbers in a permutation that is sorted and in-order. In the list, 1;2;3;5;6;4 there are two runs, 1;2;3 and 5;6. I want to replace these with a single number, a minimum, so if, after removing runs, we have a permutation of 4 elements, the permutation uses the numbers 1 ... 4. In the above, we have to reduce the two runs. the first run would be 1, 4 transforms to 2, and [5;6] transforms to 3, to hold the second criteria. If I sort the reduced permutation then expand the elements inside from the mapping, and sort the original permutation I will get the same result. The resultant permutation shouldn't have any runs in it. For example (i've highlighted the runs): (1;2;3;4;5;6) => 1 //Mappings: 1->1;2;3;4;5;6 (2;3;4);1;(5;6) => 2 1 3 // Mappings: 2->2;3;4, and 3->5;6 (3;4);(1;2);(5;6) => 2 1 3 // Mappings: 2->3;4, and 1->1;2 and 3->5;6 for now, I am passing over the list and making a list of lists, grouping the runs. Really the second part is the hard part to make a clean solution. I have thought of the naive approach, curious if anyone has some clever trick that can do it better then mine, I'm at like O( 2n + n log n), replacing the runs with the head element of the run and inserting that data into a hashtable (for recoverability) sorting to create a map to the missing digits with it's sorted index. [1;6;5;4] would output [(1,1);(4,2);(5,3);(6,4)] replacing the list in step1 with the map created in step2 and updating the hashtable for translation. running through an example, again: step 1: replace runs with the head element of the run and inserting data into a hash table [1;3;4;2;5;6;] -> [1;3;2;5] step 2: sort array to create map [1235], so we know that, in the previous array, 1 maps to 1, 2 to 2, 3 to 3, 4 to 5. step 3: do above translation on array from step one. [1;3;2;4] If I sort this permutation and reconstruct: [1;2;3;4], 3->3;4 and 4->5;6 I get, 1;2;3;4;5;6. Also sorted. I'm using lists, so a functional approach would be preferred. No code necessary. All ideas, of course, welcome. EDIT: mweerden: It's not clear to me what the precise conditions on the mapping are. Why exactly isn't it allowed to just produce the permutation [1,2,...,N] for a permutation with N runs? You seem to prefer to map a run to a number from that run, but (as this isn't always possible) you seem to allow some freedom. – I don't prefer to map a run to a number within that run (look above!), but I need to preserve an ordering. The permutation [1;2;3...N] is a run, and thus can be reduced further. That is why it is invalid. The order will matter in further operations in another algorithm, but the individual elements can be expanded at the end to rescue the original permutation. A: Notation: counting starts at 1 l.i is element i of list l l+m is the concatenation of lists l and m a run is a maximal sublist that is an list [n,n+1,n+2,...,m] for some n and m with n <= m So we are given a permutation p of the list [1,2,...,N]. We divide p up into runs r_1,r_2,...,r_M such that p = r_1+r_2+...+r_M. We are then looking for a permutation q of [1,2,...,M] such that r_(q.1)+r_(q.2)+...+r_(q.M) = [1,2,...,N]. For example, if p = [1,3,4,2,5,6], we have N=6, M=4, r_1 = [1], r_2 = [3,4], r_3 = [2] and r_4 = [5,6]. In this case we need q to be [1,3,2,4] as r_1+r_3+r_2+r_4 = [1]+[2]+[3,4]+[5,6] = [1,2,3,4,5,6]. Note that q cannot contain runs of length greater than one per definition; if it would, then there is an i < M with q.i + 1 = q.(i+1) and thus a sublist r_(q.i)+r_(q.(i+1)) = r_(q.i)+r_(q.i + 1) of [1,2,...,N], but r_(q.i)+r_(q.i + 1) is also a sublist of p which contradicts that r_(q.i) and r_(q.i + 1) are runs. Now, to find a q given a p, we assume the availability of a mapping data structure with O(1) inserts and lookups of numbers and lists with O(1) appends and forward traversal. Then we do the following. First we construct the list runheads = [r_1.1,r_2.1,...,r_M.1]. This can be done trivially by traversing p whilst maintaining the current run. During this step we also remember the maximal number encountered to obtain N at the end and construct a mapping heads with the elements of runheads as keys. This step is clearly O(n). Note that it is not relevant what the values of heads are, so we can just use run r_i as value for key r_i.1. Next we iterate from 1 to (and including) N maintaining a value k with initial value 1. For each value i we check to see if i is in heads. If this is the case we add i -> k to a mapping f and increase k. This step is also clearly O(n). To be able to get back from q to p we can also store an additional mapping rev with k -> i or even k -> runheads(i) at no extra big-O cost. Finally we apply mapping f to the elements of runheads to get q. Again O(n). To illustrate with an example we look at the case that p = [1,3,4,2,5,6]. In the first step we get runheads = [1,3,2,5], N=6 and heads = { 1 -> [1], 3 -> [3,4], 2 -> [2], 5 -> [5,6] }. For the second steps we four cases for which we have to do something: 1, 2, 3 and 5. For these cases we have values for k that are 1, 2, 3 and 4, respectively. This means that f will be { 1 -> 1, 2 -> 2, 3 -> 3, 5 -> 4 }. (And rev would be { 1 -> 1, 2 -> 2, 3 -> 3, 4 -> 5 } or { 1 -> [1], 2 -> [2], 3 -> [3,4], 4 -> [5,6] }, depending on what you chose to store.) To get q we calculate map(f,runheads) which is [f(1),f(3),f(2),f(5)] or, equivalently, [1,3,2,4]. So, if I didn't make a mistake and if the data structures satisfy the above requirements, this solution should be O(n). Note that in practice it might actually be more useful to use your own (O(n*log(n))) solution. If you have a big p but with just a couple of runs, sorting runheads and using that to build the mappings might be more efficient. I do think that p would have to be quite big for this to be the case.
{ "pile_set_name": "StackExchange" }
Q: Java FTPClient: Getting "Connection reset by peer" when calling getReply() I was recently trying to connect to a FTP server via a mobile application. I'm able to connect to my server and check if it's connected (which it is). Next thing is to login with a username and password following with a passive mode setup. Last thing I did was get the reply code from the server, but when my application is running, my screens goes black. When I reopen my application it says "recv failed: ECONNREST (Connection reset by peer)" as the error message I output. Here is my code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); ftpClient = new FTPClient(); textView = (TextView)findViewById(R.id.textView_id); textView2 = (TextView)findViewById(R.id.textView2_id); textView3 = (TextView)findViewById(R.id.textView3_id); textView4 = (TextView)findViewById(R.id.textView4_id); textView5 = (TextView)findViewById(R.id.textView5_id); try{ ftpClient.connect(ip, port); boolean connectSucces = ftpClient.isConnected(); ftpClient.login(userName,passWord); ftpClient.enterLocalPassiveMode(); ftpClient.getReply(); int connectionMode = ftpClient.getDataConnectionMode(); if(connectionMode == ftpClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE) { textView.setText("Connected: " + connectSucces + " ConnectionMode: " + connectionMode); } }catch(Exception e){ textView.setText(e.getMessage()); } } Am I missing something? A: I believe it's the call to getReply() that deadlocks your code. You didn't send any command to which the server should reply, so the client waits for the response until it or the server times out. The latter happened probably, that's why the connection was closed/reset by the server. You generally do not call getReply() yourself. In most cases it's called internally by the FTPClient for you: Only use this method if you are implementing your own FTP client or if you need to fetch a secondary response from the FTP server. While I have no experience with Android development, from the symptoms and your code, I assume you connect to the FTP server from a GUI thread, what is rather a bad practice. That would explain why the screen goes blank while you wait.
{ "pile_set_name": "StackExchange" }
Q: How can I improve the speed of my spoken Chinese? I'm currently trying to learn '听妈妈的话' on SingChineseSongs, and I'm having trouble keeping up with the fast parts. I also have trouble trying to speak terribly fast in Mandarin anyway. Does anyone have any tips or suggestions on how I can improve the speed of my spoken Chinese without losing clarity or making lots of mistakes (which is my current problem when speaking too fast)? A: The shape of your mouth and the muscles you need to speak effect the way that you speak another language. So you will naturally find yourself tripping over certain sounds or combinations of words. The only way you can improve this is by practicing. I have been casually teaching overseas students for over 10 years and the best way to do this is by doing two things: Read at a suitable level so you can read fast enough and read aloud so you are training your mouth and getting feedback via your ears. I started by practicing with childrens' books, you will find your mouth starts to hurt after a short while of reading if you are doing it constantly. Practice daily then you will notice your speaking will also improve. Songs are a good way to train with, however this is usually via memorisation so it may improve the speed of your spoken Chinese, but not your conversational Chinese, that is, it's not going to teach you to speak better. Because speaking in a conversation requires you to consider a response and to have the skill to present that response with the right vocabulary and grammar.
{ "pile_set_name": "StackExchange" }
Q: Finding the key of the max value in a javascript array I have an empty array into which I am pushing values using javascript. I am able to find the max value of the array and set that to a variable using the following: Array.max = function( array ){ return Math.max.apply( Math, array ); }; var maxX = Array.max(xArray); How can I find the key associated with that value? A: Assuming that the values are unique, you could use Array.indexOf: var maxX = Array.max(xArray); var index = xArray.indexOf(maxX); If the keys are not unique, index will contain the key of the first element found. If the value does not exist at all, the "key" will be -1.
{ "pile_set_name": "StackExchange" }
Q: Challenge on Property of Complement in Language We have: and M be a finite automata. Suppose d(M) be a deterministic automata that equivalence to M. if $M_1$ and $M_2$ be two finite automata, $M_1 + M_2$ is the finite automata such that the language of this automata is the union of language $M_1$ and $M_2$. if $G_1$ and $G_2$ be two regular grammar such that language of these be $M_1$ and $M_2$, how the author conclude: $L(G_1)-L(G_2)=L(\overline{d(\overline{d(M_1)}+M_2))} $ is true. my question is why for example the following false: $L(G_1)-L(G_2)=L(\overline{\overline{d(M_1)}+\overline{d(M_2)}})$ I ran into another question why before complement we should deterministic the automat? A: This is a good example of how bad notation can make simple questions much more difficult. (1) There is no reason to introduce grammars. You may as well denote by $L_1$ the language accepted by $M_1$ and by $L_2$ the language accepted by $M_2$. (2) Let us denote by $L^c$ the complement of a language $L$. Then your first (correct) equality amounts to prove that $L_1 - L_2 = (L_1^c \cup L_2)^c$. Your second expression however would be $(L_1^c \cup L_2^c)^c = L_1 \cap L_2$. As for your last question, you cannot directly compute an automaton accepting the complement of an automaton if you start with a nondeterministic automaton. Actually, there are known examples of a language with an $n$-state minimal DFA for which the minimal DFA of its complement has $2^n$ states.
{ "pile_set_name": "StackExchange" }
Q: I can't center more than one widget in stack I want to use stack for some reason and all my widgets should be centered. It's ok when I use one positioned and one align. However using second align widget does not place under the first text. Widget _body() { return Stack( children: <Widget>[ Positioned( left: 0, child: Text("Text here"), ), Align( child: Text( "First Centered Text", style: TextStyle(color: Colors.black87, fontSize: 30), ), ), Align( child: Text( "Second Centered Text", style: TextStyle(color: Colors.black87, fontSize: 30), ), ), ], ); } I want to reach this enter image description here A: Widget _buildBody() { return Stack( alignment: Alignment.center, children: <Widget>[ Align( alignment: Alignment(0, -0.95), child: Image.asset('assets/images/profile.jpg', width: 200, height: 200, fit: BoxFit.cover,), ), Align( alignment: Alignment(0, -0.35), child: Text("Centered Text"), ), Align( alignment: Alignment(0, -0.1), child: Text("Second centered text"), ), Align( alignment: Alignment(0, 0.1), child: CircularProgressIndicator(), ) ], ); }
{ "pile_set_name": "StackExchange" }
Q: selected value in Django forms.ChoiceField Here i have the form vote = forms.ChoiceField(widget=forms.Select(), choices=(('1', '1',), ('2', '2',), ('3', '3',)), initial='2') Django1.3 create from it the code <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> This selected-tag does not work. Should be <option value="2" selected>2</option> What am I doing wrong? A: Occasionally, I've seen browsers not select the appropriate option, even with selected="selected" when doing an F5 or Command + R (on Mac). However, doing a full refresh of the page (Ctrl + F5) in FF on Windows, or reloading the url from the address bar, will correctly select the selected option. FireFox does sometimes behave this way: http://www.beyondcoding.com/2008/12/16/option-selectedselected-not-working/
{ "pile_set_name": "StackExchange" }
Q: Group Policy to force all web traffic to a specific page OR GPO to display unclosable popup to get users attention We have a number of tasks users need to complete over the month (time sheets, reports, etc) and I am trying to think of the best way to force users to complete these tasks. Currently, we send reminder emails. These are easily ignored. Accounts waste tons of time chasing people up. I was hoping to find a way via group policy to redirect all their web traffic to a specific page informing them they need to get on top of their tasks. (A bit BOFH, I know...) Or some other method that the user cannot ignore to force them to complete these tasks (they take 5 mins in total). What do you guys think? A: This is a classic case of trying to use technology to enforce a process or business practice and doing such things often leads to unintended results. I'd find some other "incentive" to "encourage" them to do these things before forcing it down their throats with technology. A: You could use GPO to force the browsers to use a specific web proxy and then install a forward web proxy such as apache on a new server and put the functionality you need into the proxy itself. Clever users may be able to work out ways to bypass the proxy e.g. by using browsers that dont look at GPO settings but you could always block outbound HTTP and HTTPS traffic at your firewall for all servers except your forward web proxy Unfortunately the "put the functionality you need" step is probably the big unknown and I'm not an expert in configuring Apache as a forward web proxy to know if what you want to do is possible It will depend on what you mean by "redirect all their web traffic" and how to determine WHO to do this for as I presume you dont want to do it for everyone all the time!
{ "pile_set_name": "StackExchange" }
Q: Different Glyphicons on Chrome desktop and real mobile device I have very different presentations of Glyphicons on a Desktop display and on an real mobile device. It looks as follows: On the left you see Chromes mobile view and the right side is a real mobile device screenshot. Why is the right side messed up? I am using font awesome icons with a bootstrap framework (Froundry) like this: <i class="icon fa fa-wifi icon"></i> A: Found the error: You have to have the folder fonts which contain fontawesome-webfont.woff and other files, because font-awesome.css links to this files.
{ "pile_set_name": "StackExchange" }
Q: firebreath plugin create a full screen window, but the window always under the browser window when it appers, how can I bring it to top CaptureScreenApp app; int MyPluginAPI::captureScreen(const FB::JSObjectPtr& callback) { boost::thread cs(boost::bind(&CaptureScreenApp ::captureScreen, app, callback)); return 1; } class CaptureScreenApp { public: CaptureScreenApp() { HRESULT hRes; hRes = OleInitialize(NULL); ATLASSERT(SUCCEEDED(hRes)); AtlInitCommonControls(ICC_WIN95_CLASSES); g_Module.Init(NULL, NULL); }; ~CaptureScreenApp() { g_Module.Term(); OleUninitialize(); }; bool captureScreen() { CMessageLoop theLoop; CMainDialog g_MainDlg; g_Module.AddMessageLoop(&theLoop); if (NULL == g_MainDlg.Create(NULL)){ DWORD ret = GetLastError(); return FALSE; } g_MainDlg.ShowWindow(SW_SHOW); g_MainDlg.UpdateWindow(); int nRet = theLoop.Run(); g_Module.RemoveMessageLoop(); return TRUE; }; }; class CMainDialog : public CDialogImpl<CMainDialog> { public: enum {IDD = IDD_MAIN}; .... } the window(the new window is a full screen window with a desktop pic as the background) I create in CaptureScreenApp::captureScreen always under the browser window when it appears(browser window always actived in other word), what ever how I set the HWND_TOPMOST for the new window. like this: enter link description here how can i bring the full screen window to top when it appers? A: SetWindowPos API lets you change Z order (make sure to read Remarks there). You create your window with NULL parent, so your window is completely independent from browser window, so there is nothing to push it to the front: it would be either you or interactive user.
{ "pile_set_name": "StackExchange" }
Q: how to use angular chrome debug tool to debug across iframe I have an iframe nested in my app that has an angular project in it. How can I get access to the scope inside that? A: Select iframe from debug options and do something like below: jQuery('#my_element_id').scope(); To do this with javascript, I have setup a plunker link: http://plnkr.co/edit/whVo7wanhmcUfC7Nem9J?p=preview Below js method access the scope of a element and passes to the parent method: var passScopeToParent = function() { var scope = angular.element(jQuery("#myListItem")).scope(); parent.change(scope); } parent widnow method accesses scope and changes its expressions: var change = function(scope) { scope.$apply(function() { scope.department = 'Superhero'; }); } You can tweak this link to access the scope an element within iframe from parent window and print it in the console window.
{ "pile_set_name": "StackExchange" }
Q: Place embed place how to bring back in editable mode File > place embedded → This is how we import the files. see attachment → But as soon as we right click and then click place: Then how can we bring back in editable mode? where we can change size etc? A: Please consider reviewing some basic tutorials: Get to know Photoshop from Adobe This is really core knowledge regarding the application functionality. Reviewing basic tutorials will assist you in working more quickly rather than having to post questions about basic functionality. To resize content on a layer... Highlight the layer in the Layers Panel then choose Edit > Free Transform or Edit > Transform > [whatever option you want]
{ "pile_set_name": "StackExchange" }
Q: Powershell: copying profiles from one location to another trying to iterate over a profiles folder to copy their desktop a new location, but cant piece together the iteration properly. get-childitem -path c:\users\*\desktop\ ` | ForEach-Object { Copy-Item $_ -Force -Destination D:\Users\*\ } A: So something like this then? Get-ChildItem -Path c:\users | ForEach-Object{ Copy-Item "$($_.FullName)\Desktop" -Force -Destination "D:\Users\$($_.Name)\Desktop" } Let it figure out what the user names are in the folder (Might have to omit some users like Administrator). Then using the folder names collected (Represented by $_.Name inside the loop) we can use that to address the source desktop and destination desktop. Warning that this does not do any error checking for path validation. Something like that would be very prone to error since you cannot guarantee that a folder will exist in the target. Could address that with something like this: Get-ChildItem -Path c:\users -Exclude "public","administrator" | ForEach-Object{ $sourceDesktop = "$($_.FullName)\Desktop" $targetDesktop = "D:\Users\$($_.Name)\Desktop" If(((Test-Path $sourceDesktop,$targetDesktop) -eq $false).Count -gt 0){ Copy-Item $sourceDesktop -Destination $targetDesktop -Force } } (((Test-Path $sourceDesktop,$targetDesktop) -eq $false).Count -gt 0) breaks down like this Test-Path will be returning an array of True`False` for all folders provided. If any of the tests return false at least one of the folders does not exist so we should not attempt the transfer. Also has an exclusion section that you could remove if you chose to.
{ "pile_set_name": "StackExchange" }
Q: Using optionsCaption in a select tag that uses optgroups I am trying to get the optionsCaption of my <select> tag to work. <select class="form-control" data-bind="foreach: Roles, value: SelectedRole, optionsCaption: 'Select...'"> <optgroup data-bind="attr: {label: Group}, foreach: GroupRoles"> <option data-bind="value: $data, text:Name"></option> </optgroup> </select> When I do this, the Select... given in the optionsCaption parameter does not show in the drop down list. I need to use optionsCaption because I want to set SelectedRole back to Select... when I put self.SelectedRole(null) in the .js viewmodel file. Edit Just to clarify further, the Select... must sit outside of the optgroups at the top of the list. I have tried manually setting an <option> tag above the <optgroup> tag but I can not it to be selected when using self.SelectedRole(null) A: So there does not seem to be a way to use optionsCaption from my understangind (feel free to answer if you know a way that I have not seen and I will mark it as the answer!) Instead, I used a workaround for this. <select class="form-control" data-bind="value: SelectedCrmRole"> <option data-bind="value:''">Select...</option> <!-- ko foreach: CrmRoles --> <optgroup data-bind="attr:{label: Group}"> <!-- ko foreach: GroupRoles --> <option data-bind="value: $data, text:Name"></option> <!-- /ko --> </optgroup> <!-- /ko --> </select> I created a seperate <option> above the <optgroup> tag with the text set to Select.... From what I understand, the important part is the data-bind="value: ''. Now, in the viewmodel when I use self.SelectedCrmRole(null);, it will know that this is the null/default value because of that empty value for the option I wanted to be the default. It may not be the best work around but it is working as necessary! Hope this helps anyone who runs into this problem as well.
{ "pile_set_name": "StackExchange" }
Q: Find minimum of function $\frac{\left| x-12\right| }{5}+\frac{\sqrt{x^2+25}}{3}$ Find minimum of function $f(x) = \frac{\left| x-12\right| }{5}+\frac{\sqrt{x^2+25}}{3}$ I tried compute min using by definition of abs function. I consider two cases: when $x > 12$ we have: $f_{1}(x) = \frac{x-12}{5}+\frac{\sqrt{x^2+25}}{3}$ using standard method $f_{1}'(x)=0$ for $x_{0}=-15/4$ but $x_{0}$ is not in $ [12, \infty]$ when $x \leq 12$ we have $f_{2}(x) = \frac{-x+12}{5}+\frac{\sqrt{x^2+25}}{3}$ similarly $f_{2}'(x) = 0$, and $x = 15/4$ So using observation from this method I computed minimum of $f(15/4) = 56/15$. Does it be a correct way? A: We can use C-S and the triangle inequality: $$\frac{|x-12|}{5}+\frac{\sqrt{x^2+25}}{3}=\frac{|x-12|}{5}+\frac{\sqrt{(3^2+4^2)(x^2+5^2)}}{15}\geq$$ $$\geq \frac{|x-12|}{5}+\frac{|3x+20|}{15}=\left|\frac{12}{5}-\frac{x}{5}\right|+\left|\frac{4}{3}+\frac{x}{5}\right|\geq $$ $$\geq \left|\frac{12}{5}-\frac{x}{5}+\frac{4}{3}+\frac{x}{5}\right|=\frac{56}{15}.$$ The equality occurs for $(3,4)||(x,5)$ and $\left(\frac{12}{5}-\frac{x}{5}\right)\left(\frac{4}{3}+\frac{x}{5}\right)\geq0,$ which gives $x=\frac{15}{4},$ which says that we got a minimal value.
{ "pile_set_name": "StackExchange" }
Q: How to redirect to captcha for x failed attempted without circular redirects in CakePHP? I am using the core Auth component. I have created a user login that manages all of the permissions. The way I am implementing the login monitoring is by checking for $this->Auth->user() in the app_controller. Each time the app_controller cycles the beforeFilter() function and !$this->Auth->user(), it will increment the Captcha.LoginAttempts session variable. When Captcha.LoginAttempts is > 3, I want it to redirect to the Captchas controller, displaying a captcha screen requiring the user to confirm they are a human. (Similar to how stackoverflow does it). The issue I am having is if I am using an element somewhere or referencing something within the cake framework on the page, it will hit the redirect and cause an endless circular redirect for every accessing element/component being called external to the actual controller/action. Is there a better way to implement this? Here is the actual code I have been messing with. But it basically sucks (IMO): // this is in the app_controller beforeFilter() method. if($this->Auth->user()) { $this->Session->delete('Captcha'); } else { $this->Session->write('Captcha.LoginAttempts', $this->Session->read('Captcha.LoginAttempts') + 1); if ($this->Session->read('Captcha.LoginAttempts') > 3) { if (!$this->Session->read('Captcha.controller')) { $this->Session->write('Captcha.controller', $this->params['controller']); $this->Session->write('Captcha.action', $this->params['action']); } if ($this->Session->read('Captcha.fail') !== 'true') { // avoid circular reference redirects $this->Session->write('Captcha.fail', 'true'); $this->redirect(array('controller' => 'captchas', 'action' => 'index')); } } } You can see how I try to avoid the circular reference. But then the user could just go to the login page and since the Captcha.fail session variable is already set, it will ignore the redirect. There must be a more elegant way to implement this. Anyone? A: Normally, I would just try to answer the way you are trying to do it, but since you asked for any better ideas, what I would do is have the Captcha actually on the login page and use the AuthComponents builtin methods and properties like loginRedirect, autoRedirect, and allow(). Then, just turn the captcha on/off based on the Captchas.loginAttempts variable. For your current method, I don't think you're going to get an elegant way of doing this. However, you might be able to change the properties of the AuthComponent to get what you want. You could change loginRedirect and loginAction so that /captchas/index is the new login form, then on successful captcha, set loginAction back to /users/login or whatever. This way, if someone were to attempt to hit /users/login directly without doing the captcha, then the AuthComponent logic would kick in and redirect to /captchas/index. Here are some relevant manual pages: http://book.cakephp.org/view/392/loginRedirect http://book.cakephp.org/view/382/allow http://book.cakephp.org/view/395/autoRedirect http://book.cakephp.org/view/391/loginAction Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: What do you call this type of spin? Is there a special name for a type of spin in the air where the person's body is almost horizontal? I have seen it in several action scenes, such as this fight scene from a movie (at 1:41). Ninja Assassin Fight Scene A: This looks like the wushu butterfly twist. It's more gymnastic than useful for fighting. A: As per mattm, it's the "butterfly twist" in Wushu. In Capoeira, it's the mariposa (which also means "butterfly" in Spanish, but in Portuguese more often translates to "moth" or "prostitute") and my copy of Unknown Capoeira: Secret Techniques of the Original Brazilian Martial Art notes that it is indeed ornamental, although, as with many spins, lashing your foot out in the midst of it can transform that spinning momentum into a strike, and of course it does work as a dodge, albeit one that's more flashy than utilitarian. Lastly, as with most acrobatic moves, it sometimes can just be intimidating, since it shows your body control and that you're confident enough to waste energy on something flashy.
{ "pile_set_name": "StackExchange" }
Q: Enum и константы в чем отличие? Старый способ имитации "перечисления": public static final int TOM = 1; public static final int JERRY = 1; public static final int REX = 1; Новое, перечисление: public enum Names { BOBBY, BILLY, SOFFIE } Так в чем отличие? Зачем сделали перечисления "Enum"? A: Описание enum -- это, по сути дела, описание класса и одновременно фиксированного набора именованных объектов этого класса. Объекты этого класса могут обладать всеми атрибутами обычных объектов -- конструкторами, полями, методами. Конструкторы могут инициализировать внутренние состояния этих объектов, поля -- хранить их состояния, в том числе ссылки на какие-то более/менее сложные объекты, методы могут реализовать какую-то функциональность. Так что перечисление -- это не просто набор значений, которые можно использовать в операторе switch, их возможности намного больше. С помощью перечислений можно, например, описать набор команд GUI -- каждая команда может иметь состояние (разрешено/запрещено), текст, отображаемый в меню и зависящий от состояния, текст всплывающей подсказки, ссылку на объект, который выполняет команду и т. п. Другой пример -- описание колонок таблицы, с информацией о ширине колонки, о том, как форматировать данные в этой колонке и проч., или параметры, определяющие режим работы приложения. Да вообще много разных применений может быть, во многих случаях, когда количество разных объектов какого-то типа известно заранее. Грамотное использование перечислений может сильно улучшить дизайн приложения. Так что использование их просто в качестве именованных констант -- далеко не главное их применение. Вот навскидку пример того, что можно делать с перечислениями: public class Test_enums_2 { static class EnumData { int intValue; String stringValue; EnumData(int intValue, String stringValue) { this.intValue = intValue; this.stringValue = stringValue; } void setNewString(String s) { this.stringValue = s; } public String toString() { return intValue + ": " + stringValue; } int calcSomething() { return intValue * stringValue.length(); } // Anything else... } enum EnumExample { ENUM1_ITEM1(1, "Раз"), ENUM1_ITEM2(2, "Два"), ENUM1_ITEM3(3, "Три"), ENUM1_ITEM4(4, "Четыре"); private EnumData data; private boolean enabled = true; EnumExample(int intValue, String stringValue) { data = new EnumData(intValue, stringValue); } public void setEnabled(boolean newValue) { enabled = newValue; } public void setString(String newValue) { data.stringValue = newValue; } public String getFullName() { if (!enabled) return "Ничего не скажу. Запрещено"; else return data.toString(); } public String getShortName() { return String.valueOf(data.intValue); } public int calculate() { return data.calcSomething(); } } public static void main(String[] args) { EnumExample.ENUM1_ITEM3.setEnabled(false); for (EnumExample item: EnumExample.values()) { System.out.format("%s: Short name: %s, full name: %s, calc: %s\n", item, item.getShortName(), item.getFullName(), item.calculate()); } System.out.println(); EnumExample.ENUM1_ITEM1.setString("Ку-ку"); EnumExample.ENUM1_ITEM2.setEnabled(false); EnumExample.ENUM1_ITEM3.setEnabled(true); for (EnumExample item: EnumExample.values()) { System.out.format("%s: Short name: %s, full name: %s, calc: %s\n", item, item.getShortName(), item.getFullName(), item.calculate()); } } }
{ "pile_set_name": "StackExchange" }
Q: How to display the innerHtml contents of newly created element function Eval(a){ var element= document.createElement('p'); // Creating a paragraph $(element).addClass("output-class"); element.innerHTML+= a; } The contents added are not displayed even after styling "output-class" dynamically or even within tag. But if I write console.log(element) then I get the required result but not on the webpage. A: You almost there, three main considerations: You don't need jQuery to add a classname, use classList instead. You don't need to use this statement element.innerHTML += a; because this is a newly created element, so the innerHTML attribute is empty. Use this element.innerHTML = a; instead To make that element visible/rendered, you need to add it to a parent element. To accomplish that, use the function appendChild. In this example, the parent is the body element. function Eval(a, parent) { var element = document.createElement('p'); // Creating a paragraph element.classList.add("output-class"); element.innerHTML = a; parent.appendChild(element); } Eval('Ele from SO', document.body) .output-class { font-size: 24px }
{ "pile_set_name": "StackExchange" }
Q: How do I hedge against currency risk without tying up a lot of capital? Is there some kind of synthetic ETF that magnifies changes to exchange rates so that if, for example, the Canadian dollar increases by 5% with respect to the American dollar, the ETF will go up by 10% and vice versa? Is there another way to hedge against currency risk without tying up a lot of capital? A: I'm somewhat shocked that I can't find a leveraged Canadian Dollar to American Dollar ETF. It's possible one exists but if it is not on Bloomberg (or even Wikipedia) it likely doesn't exist. Interestingly, I found a CAD/EUR 3x leveraged ETF, but not a USD one. You could look at using the CAD/EUR and EUR/USD 3x levered ETFs, but given the awful issues with leveraged ETFs I'm not even sure I can recommend this even in the short term as a solution. The traditional way of hedging currency without tying up lots of capital is to use currency futures or forwards. The margins on these contracts are quite reasonable if you are an institution, but may be prohibitive as an individual investor. Check where you trade. Also, there can be complications about rolling these contracts that may make them a pain for an individual. Still, if you really need to do the hedging and are willing to put in the work this is the place to start. Of course, if you are looking for a hedged common index like the S&P 500, that type of ETF certainly exists and it is cheap and you avoid the margins.
{ "pile_set_name": "StackExchange" }
Q: setTimeout inside Promise Race immediately catch I have 2 promise, a fetch and a setTimeout, fetch wait for 5 seconds and setTimeout wait 4 seconds. I don't known why but setTimeout fire immediately! myService( args ) .then( result => { console.log(result); }) .catch( timeoutError => { // <----------------- FIRE IMMEDIATELY console.error(timeoutError); }) ; function myService( args ){ return Promise.race([ fetch("http://localhost/wait-ten-seconds"), new Promise( (_, timeexpired) => { return setTimeout( function() { console.log("timeout"); timeexpired({msg: "call timeout", code: 100, data: null}); } , 4000) }) ]); } A: I solve it in this way: I create a function that simulate timeout let activeTimer = null; let checkTimer = (startTimer, timeExpired) => { activeTimer = setTimeout(() => { if( (new Date()).getTime() - startTimer < TIMEOUT_DURATION_MS ) checkTimer(startTimer, timeExpired); else timeExpired( errorMessage.TIMEOUT_EXPIRED ); }, 1000); }; Promise.race([ new Promise( (httpResponse, httpError) => { return fetch(url) .then(response => { clearTimeout( activeTimer ); activeTimer = null; httpResponse( response ); }) .catch( error => { httpError( error ); }) }) , new Promise( (_, timeExpired) => { checkTimer((new Date()).getTime(), timeExpired); }) ]);
{ "pile_set_name": "StackExchange" }
Q: I don't know why it says 'preventing a complete tally of the injured' The wounded were taken to different hospitals around the city, which police said was preventing a complete tally of the injured. Tally means count, right? In this sentence, the wounded were taken to different hospitals around the city, but why to prevent 'complete tally of the injured'? This sentence comes from Fox News. A: The number of different possibilities exceeds the amount of time available to make a verified account of the involved individuals and their specific circumstances. Dynamic conditions can make an accurate accounting time-dependant. By the time the information is reported by one person, it may have changed, making the existing report incorrect. Where data is in conflict, other time-sensitive information must be located and compared from an acceptable verifiable source. Multiply this situation by all the possible "hospitals" around the city and you get an idea of the complexity. Also, who does the calling? Where does the call go? Who answers these calls? Who verifies the information? How often is the information updated? The sheer complexity of assembling the unassailable true and stable answer makes a complete tally of the injured not possible for the convenience of the Fox News broadcast time by the police spokes-person designate is one very probable answer to why.
{ "pile_set_name": "StackExchange" }
Q: SQL: Joining table A and table B when rows may be missing in TABLE B I'm trying to join data from two table A, and B on a timestamp. I ideally want every row of tableA that meet the unitCode and time constraints, and if there is an associated row in tableB then join it, otherwise assume the coloumns from table B are attached but are null or empty. Assume TableA looks something like this: id | timestamp | itemA1 | itemA2 | itemA3 and TableB looks somthing like this: id | timestamp | itemB1 | itemB2 so data might look like this: timestamp | itemA1 | itemA2 | itemA3 | itemB1 | itemB2 [datetime]| 10 | 11 | 40 | 26 | 12 [datetime]| 10 | 11 | 40 | 26 | 12 [datetime]| 10 | 11 | 40 | null | null [datetime]| 10 | 11 | 40 | 26 | 12 [datetime]| 10 | 11 | 40 | null | null Currently I'm using this: SELECT * FROM tableA AS a JOIN (SELECT * FROM tableB) AS b ON (a.timestamp = b.timestamp) WHERE b.unitCode = 'CODE' AND b.timestamp BETWEEN 'STARTDATETIME' AND 'ENDDATETIME' ORDER BY b.timestamp DESC` but it only makes rows out of the instances where there is a corresponding tableB for a given tableA. A: Use a LEFT JOIN. A LEFT JOIN takes all records on the left side of the condition statement, and all those for which it applies on the right. However, you need to be careful in your WHERE clause, because if it has a value restriction on your right table (in your case table 'b') then it will still exclude those rows. SELECT * FROM tableA AS a LEFT JOIN (SELECT * FROM tableB) AS b ON (a.timestamp = b.timestamp) WHERE b.unitCode = 'CODE' AND b.timestamp BETWEEN 'STARTDATETIME' AND 'ENDDATETIME' ORDER BY b.timestamp DESC` LEFT JOIN reference: https://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html JOIN graphic As @Ike pointed out, your query could be corrected to be: SELECT * FROM tableA AS a LEFT JOIN tableB AS b ON a.timestamp = b.timestamp AND b.unitCode = 'CODE' AND b.timestamp BETWEEN 'STARTDATETIME' AND 'ENDDATETIME' ORDER BY b.timestamp DESC` Since as I mentioned earlier, if the conditions were in the WHERE clause, it would exclude the concept of the LEFT JOIN and therefore all rows with NULL values (because it didn't meet the criteria for table b) would be excluded. To address your comment, if you added WHERE clauses, I would suggest (based on what I understand of your goal) only having the conditions affect tableA and have all the conditions for tableB be in the LEFT JOIN. SELECT * FROM tableA AS a LEFT JOIN tableB AS b ON a.timestamp = b.timestamp AND b.unitCode = 'CODE' AND b.timestamp BETWEEN 'STARTDATETIME' AND 'ENDDATETIME' WHERE a.timestamp BETWEEN 'STARTDATETIME' AND 'ENDDATETIME' ORDER BY b.timestamp DESC` Now, if the a.timestamp condition is what you're looking for, then the condition for tableB in the LEFT JOIN is redundant because we already know that the timestamps in tableB must match a corresponding one in tableA.
{ "pile_set_name": "StackExchange" }
Q: Shorthand Regex expression to match an alphanumeric pattern instead of [A-Za-z0-9] I am trying to validate a string of the pattern IN-XXXXXXXX-X, where X is an alphumeric value. For It I need to write the regex expression The regex I write is /^IN-\w{8}-\w/g But it validates alphanumeric as well as underscores in place of X.The other way would be /^IN-[A-Za-z0-9]{8}-[A-Za-z0-9]/g However this seems way to long. Is there a shorthand to write [A-Za-z0-9] in order to validate alphanumeric values. A: How about using [^\W_] to match alphanumeric characters? \W - non-word characters. Basically, we match anything except non-word characters and underscores, which is the set of alphanumeric characters. The regex would shorten to ^IN-[^\W_]{8}-[^\W_] Try it here: https://regex101.com/r/l3rqsq/1
{ "pile_set_name": "StackExchange" }
Q: Adding controls to a from C# 2015, this.Controls.Add(bla) method not found? public partial class MainWindow : Window { private void Window_Loaded(object sender, RoutedEventArgs e) { WebBrowser wb = new WebBrowser(); this.Controls.Add(wb); } } This results in an error: 'MainWindow' does not contain a definition for 'Controls' and no extension method accepting a first argument of type 'MainWindow' could be found Whats wrong here? This is a WPF Application. I'm new to C#. I find it on internet that to add controls to the form the function is this.Controls.Add(fdfdf) But here this doesn't contain Controls. A: In WPF it should be Children. In WPF you need to add items as Childrens of layout panels like your main Grid. For example if you have a Grid set it's name to grid1 and then in the code you can: grid1.Children.Add(fdfdf) A: You can add a component like your WebBrowser directly to the content of the Window. In WPF you are doing it like this: public partial class MainWindow : Window { private void Window_Loaded(object sender, RoutedEventArgs e) { WebBrowser wb = new WebBrowser(); this.Content = wb; } } But I suggest to do this via the XAML.
{ "pile_set_name": "StackExchange" }
Q: sending specific array value to email php I am using this code to output multiple specific values from array and sending these values to email. If i write this: print_r( $products[1]['Notes'], true ) Then it is displaying 1 value off course I have put "[1]" to just targeting 1 row. and If i write this: print_r( $products, true ) Then it is outputting all the values and all the rows. Is there anyway i can output just multiple values of "Notes"? A: If your php is 5.5 and more - use array_column function: print_r(array_column($products, 'Notes'), true); Otherwise, you need to select required columns with a foreach and print'em: $columns = []; foreach ($products as $prod) { $columns[] = $prod['Notes']; } print_r($columns, true);
{ "pile_set_name": "StackExchange" }
Q: Set element focus in angular way After looking for examples of how set focus elements with angular, I saw that most of them use some variable to watch for then set focus, and most of them use one different variable for each field they want to set focus. In a form, with a lot of fields, that implies in a lot of different variables. With jquery way in mind, but wanting to do that in angular way, I made a solution that we set focus in any function using the element's id, so, as I am very new in angular, I'd like to get some opinions if that way is right, have problems, whatever, anything that could help me do this the better way in angular. Basically, I create a directive that watch a scope value defined by the user with directive, or the default's focusElement, and when that value is the same as the element's id, that element set focus itself. angular.module('appnamehere') .directive('myFocus', function () { return { restrict: 'A', link: function postLink(scope, element, attrs) { if (attrs.myFocus == "") { attrs.myFocus = "focusElement"; } scope.$watch(attrs.myFocus, function(value) { if(value == attrs.id) { element[0].focus(); } }); element.on("blur", function() { scope[attrs.myFocus] = ""; scope.$apply(); }) } }; }); An input that needs to get focus by some reason, will do this way <input my-focus id="input1" type="text" /> Here any element to set focus: <a href="" ng-click="clickButton()" >Set focus</a> And the example function that set focus: $scope.clickButton = function() { $scope.focusElement = "input1"; } Is that a good solution in angular? Does it have problems that with my poor experience I don't see yet? A: The problem with your solution is that it does not work well when tied down to other directives that creates a new scope, e.g. ng-repeat. A better solution would be to simply create a service function that enables you to focus elements imperatively within your controllers or to focus elements declaratively in the html. DEMO JAVASCRIPT Service .factory('focus', function($timeout, $window) { return function(id) { // timeout makes sure that it is invoked after any other event has been triggered. // e.g. click events that need to run before the focus or // inputs elements that are in a disabled state but are enabled when those events // are triggered. $timeout(function() { var element = $window.document.getElementById(id); if(element) element.focus(); }); }; }); Directive .directive('eventFocus', function(focus) { return function(scope, elem, attr) { elem.on(attr.eventFocus, function() { focus(attr.eventFocusId); }); // Removes bound events in the element itself // when the scope is destroyed scope.$on('$destroy', function() { elem.off(attr.eventFocus); }); }; }); Controller .controller('Ctrl', function($scope, focus) { $scope.doSomething = function() { // do something awesome focus('email'); }; }); HTML <input type="email" id="email" class="form-control"> <button event-focus="click" event-focus-id="email">Declarative Focus</button> <button ng-click="doSomething()">Imperative Focus</button> A: About this solution, we could just create a directive and attach it to the DOM element that has to get the focus when a given condition is satisfied. By following this approach we avoid coupling controller to DOM element ID's. Sample code directive: gbndirectives.directive('focusOnCondition', ['$timeout', function ($timeout) { var checkDirectivePrerequisites = function (attrs) { if (!attrs.focusOnCondition && attrs.focusOnCondition != "") { throw "FocusOnCondition missing attribute to evaluate"; } } return { restrict: "A", link: function (scope, element, attrs, ctrls) { checkDirectivePrerequisites(attrs); scope.$watch(attrs.focusOnCondition, function (currentValue, lastValue) { if(currentValue == true) { $timeout(function () { element.focus(); }); } }); } }; } ]); A possible usage .controller('Ctrl', function($scope) { $scope.myCondition = false; // you can just add this to a radiobutton click value // or just watch for a value to change... $scope.doSomething = function(newMyConditionValue) { // do something awesome $scope.myCondition = newMyConditionValue; }; }); HTML <input focus-on-condition="myCondition"> A: I like to avoid DOM lookups, watches, and global emitters whenever possible, so I use a more direct approach. Use a directive to assign a simple function that focuses on the directive element. Then call that function wherever needed within the scope of the controller. Here's a simplified approach for attaching it to scope. See the full snippet for handling controller-as syntax. Directive: app.directive('inputFocusFunction', function () { 'use strict'; return { restrict: 'A', link: function (scope, element, attr) { scope[attr.inputFocusFunction] = function () { element[0].focus(); }; } }; }); and in html: <input input-focus-function="focusOnSaveInput" ng-model="saveName"> <button ng-click="focusOnSaveInput()">Focus</button> or in the controller: $scope.focusOnSaveInput(); angular.module('app', []) .directive('inputFocusFunction', function() { 'use strict'; return { restrict: 'A', link: function(scope, element, attr) { // Parse the attribute to accomodate assignment to an object var parseObj = attr.inputFocusFunction.split('.'); var attachTo = scope; for (var i = 0; i < parseObj.length - 1; i++) { attachTo = attachTo[parseObj[i]]; } // assign it to a function that focuses on the decorated element attachTo[parseObj[parseObj.length - 1]] = function() { element[0].focus(); }; } }; }) .controller('main', function() {}); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script> <body ng-app="app" ng-controller="main as vm"> <input input-focus-function="vm.focusOnSaveInput" ng-model="saveName"> <button ng-click="vm.focusOnSaveInput()">Focus</button> </body> Edited to provide more explanation about the reason for this approach and to extend the code snippet for controller-as use.
{ "pile_set_name": "StackExchange" }
Q: C++ Interop: How do I call a C# class from native C++, with the twist the class is non-static? I have a large application written in native C++. I also have a class in C# that I need to call. If the C# class was static, then it would be trivial (there's lots of examples on the web) - just write the mixed C++/CLI wrapper, export the interfaces, and you're done. However, the C# class is non-static, and can't be changed to static as it has an interface (the compiler will generate an error if you attempt to make the C# class static). Has anyone run into this problem before - how do I export a non-static C# class to native C++? Update 2010-11-09 Final solution: tried COM, this worked nicely but didn't support structures. So, went with a C++/CLI wrapper, because I absolutely needed to be able to pass structures between C++ and C#. I wrote a mixed mode .dll wrapper based on the code here: How to: Marshal Arrays Using C++ Interop How to: Marshal Structures Using C++ Interop As the target class was non-static, I had to use the singleton pattern to make sure I was only instantiating one copy of the target class. This ensured everything was fast enough to meet the specs. Contact me if you want me to post a demo project (although, to be fair, I'm calling C# from C++, and these days most people want to call C++ from C#). A: C++/CLI or COM interop work just as well with non-static classes as with static. Using C++/CLI you just reference your assembly that holds the non-static class and then you can use gcnew to obtain a reference to a new instance. What makes you think that this is not possible with your non-static class? EDIT: there is example code here. using namespace System; public ref class CSquare { private: double sd; public: CSquare() : sd(0.00) {} CSquare(double side) : sd(side) { } ~CSquare() { } property double Side { double get() { return sd; } void set(double s) { if( s <= 0 ) sd = 0.00; else sd = s; } } property double Perimeter { double get() { return sd * 4; } } property double Area { double get() { return sd * sd; } } }; array<CSquare ^> ^ CreateSquares() { array<CSquare ^> ^ sqrs = gcnew array<CSquare ^>(5); sqrs[0] = gcnew CSquare; sqrs[0]->Side = 5.62; sqrs[1] = gcnew CSquare; sqrs[1]->Side = 770.448; sqrs[2] = gcnew CSquare; sqrs[2]->Side = 2442.08; sqrs[3] = gcnew CSquare; sqrs[3]->Side = 82.304; sqrs[4] = gcnew CSquare; sqrs[4]->Side = 640.1115; return sqrs; } A: Two options come to mind. Expose the class as a COM object and use it as a COM object from C++. Create a static C# class that exposes an interface to interact with the non-static C# class.
{ "pile_set_name": "StackExchange" }
Q: Angular6 ngrx: Cannot read property 'ids' of undefined I'm trying to do a simple selector test. However, the test does not pass and gives me the following error: "Cannot read property 'ids' of undefined". In app works correctly, but when selectCustomers is called, it returns undefined. Test fdescribe('Customer Selector', () => { const customerState: fromQuoteCustomers.CustomerState = { customersLoaded: true, entities: { 'cus01': { id: 'cus01', web: 'web01', cif: 'cif01', currencyId: 'id-01', telephone: 666616666, name: 'name1', email: '[email protected]' }, 'cus02': { id: 'cus02', web: 'web02', cif: 'cif02', currencyId: 'id-02', telephone: 111000000, name: 'name2', email: '[email protected]' } }, ids: ['cus01', 'cus02'] }; it('select customers', () => { expect(selectCustomers(customerState).length).toBe(2); }); }); The selector code is the following: export const selectCustomer = createFeatureSelector<CustomerState>('customer'); export const selectCustomers = createSelector( selectCustomer, fromCustomer.selectAll ); The reducer: export const adapter: EntityAdapter<Customer> = createEntityAdapter<Customer>(); export const initialState: CustomerState = adapter.getInitialState({ customersLoaded: false, }); export function reducer(state = initialState, action: CustomerActions): CustomerState { if (action) { switch (action.type) { case CustomerActionTypes.LoadCustomers: return adapter.addMany(action.payload.customerList, state); default: return state; } } return state; } export const { selectAll, selectEntities, selectIds, selectTotal } = adapter.getSelectors(); A: You have to wrap your state inside a root state because you're also using the selectCustomer selector under the hood. const customerState = { customer: { customersLoaded: true, entities: { 'cus01': { id: 'cus01', web: 'web01', cif: 'cif01', currencyId: 'id-01', telephone: 666616666, name: 'name1', email: '[email protected]' }, 'cus02': { id: 'cus02', web: 'web02', cif: 'cif02', currencyId: 'id-02', telephone: 111000000, name: 'name2', email: '[email protected]' } }, ids: ['cus01', 'cus02'] } }; Another option is to use the projector function as explained in the docs. More examples could be found in How I test my NgRx selectors
{ "pile_set_name": "StackExchange" }
Q: Moving object at the same time div { position: relative; width: 100px; height: 100px; margin-bottom: 20px; } <div class="first" style="background:#DC143C;"> </div> <br> <div class="second" style="background:#CD5C5C;"> </div> <br> <div class="third" style="background:#FF69B4;"> </div> <br> <div class="fourth" style="background:#FF7F50;"> </div> <script> $(document).ready(function(){ $("class").click(function(){ $(".first").animate({ left: '250px' }); }); $(".third").mouseover(function(){ $(this).animate().css({ backgroundColor: '#FFF552' }); }) $(".first").click(function(){ $(this).animate({ width: 300 }) }); }); </script> I finished this application and make it works without the button. But now I need to make this four object moving at the same time. I have no idea how to make it. A: There are many ways to animate the div, I will leave that exercise to you. In this case all you have to do is wire up the event properly and there are many ways to do so. Please look at following fiddle. This may not fit to your need entirely but it may give you some idea. Also look at following methods and see how it works in detail. setInterval setTimeout
{ "pile_set_name": "StackExchange" }
Q: Android Java - Tracking Multiple Touch Objects/Events? I am an experienced programmer with C++/C# trying to get into the android game design world. Using Java in Eclipse. There are a bazillion tutorials on how to move a single object by tracking a touch on an entire screen, but how do i track touch events on many individual objects randomly on screen? For starters i wanted to write a class that would be instantiated multiple times and held in an arraylist. Each is drawn to a random position on a fullscreen, SurfaceView. Easy stuff so far... But for the life of me i cannot find out how to drag any of these objects around!! I have an activity that uses a custom view (extends SurfaceView). Instantiates a GameBoard class that handles game board screen drawing. the GameBoard class also holds/draws an ArrayList of gameCharacters that draw fine on the screen, but need touch control. Im at my wits end, any help out there? A: I wrote a top-down shooter (Akari) which doesn't drag the objects around, but uses their location for collision detection. In my SurfaceView I call theThread.touchEventType(x, y). The thread goes through the objects (in your case, the array), and checks if they match. In the case of a match, it would return a value associated with the object, and all MotionEvent.ACTION_MOVEMENT actions before MotionEvent.ACTION_UP are done on that object. Hope this helps. If you need any sample code let me know.
{ "pile_set_name": "StackExchange" }
Q: 'bool' object not iterable I am working on python3, opencv 3.4 and using Microsoft Azure's FaceAPI function 'CF.face.detect()' As far as I know, 'for loop' needs iterable object to run on like list but simple boolean is not iterable. Though 'res1' is a list I get this error. TypeError: 'bool' object not iterable Please help, Thanks in advance Here is the code: import unittest import cognitive_face as CF from PIL import Image, ImageFont, ImageDraw import time import cv2 from time import strftime CF.Key.set('') #print(CF.Key.get()) CF.BaseUrl.set('https://southeastasia.api.cognitive.microsoft.com/face/v1.0/') #print(CF.BaseUrl.get()) """Setup Person and Person Group related data.""" person_group_id = '' #id from training terminal """Unittest for `face.detect`.""" cap = cv2.VideoCapture('1.mp4') while(cap.isOpened()): ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) print("\n\n ##########.... LOOKING FOR FACES ....########## \n\n") res1 = [] print(type(res1)) res1 = CF.face.detect(cap) print('\n This is the res1: ', res1) c = len(res1) print('\nTOTAL FACES FOUND:', c) detect_id = [] ##error was here so put exception for i in range(c): print("\n\n ##########.... DETECTING FACES ....########## \n\n") print('\n This is i in range c', i, c) detect_id.append(res1[i]['faceId']) #print('\n\n detected faces id ', detect_id[i]) width = res1[i]['faceRectangle']['width'] height = res1[i]['faceRectangle']['height'] x = res1[i]['faceRectangle']['left'] y = res1[i]['faceRectangle']['top'] ################## IF ENDS ######################################################################### cv2.imshow('image',img) k = cv2.waitKey(100) & 0xff if k == 27: break ################ WHILE ENDS #################################### cap.release() cv2.destroyAllWindows() A: @Jonasz is right, you should be detecting faces on images, meaning, in frames from your mp4 file. The method CF.face.detect expects an URI, so in the following code we'll write it to disk before pass it onto CF.face.detect: cap = cv2.VideoCapture('1.mp4') count = 0 # <-- while(cap.isOpened()): ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) filename = "frame%d.jpg" % count # <-- cv2.imwrite(filename, img) # <-- count+=1 # <-- print("\n\n ##########.... LOOKING FOR FACES ....########## \n\n") res1 = [] print(type(res1)) res1 = CF.face.detect(filename) # <--
{ "pile_set_name": "StackExchange" }
Q: using a string as the for loop expressions and condition The following loop works: <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> But the following doesn't: <html> <body> <script type="text/javascript"> var i=0; var x="i=0;i<=5;i++" for (x) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> I'd just like to create a simple variable. Please bear with me as I'm a newbie in JavaScript and let me know what I'm missing. Let me provide my sample Google gadget: <?xml version="1.0" encoding="UTF-8" ?> <Module> <ModulePrefs title="Sample Gadget" /> <UserPref name="order" display_name="Results Order" default_value="i = 0; i <= 5; i++" datatype="enum"> <EnumValue value="i = 0; i <= 5; i++" display_value="Ascending"/> <EnumValue value="i = 5; i >= 0; i--" display_value="Descending"/> </UserPref> <Content type="html"><![CDATA[ <script type="text/javascript"> var i=0; for (__UP_order__) { document.write("The number is " + i); document.write("<br />"); } </script> ]]></Content> </Module> It doesn't work because of the tags <> (they're not supported), and that's why I tried to define a variable for the EnumValue value. A: When you say var x="i=0;i<=5;i++" you are creating a text string. This is not interpreted by JavaScript as you are expecting. There is a definite difference between statements and text strings. Even though it looks to the eye like the same thing, it looks to the interpreter like a text string, like "hello" or "sdflkjsdflkjsdflj". JavaScript is not expecting a text string as loop parameters, it is expecting the three loop control parameters/statements. If you want to have a loop which starts and ends at different points, do something like this... var i=0; var start=0; //you can change the start position by changing this var end=5; //and you can change the end also for (i=start;i<=end;i++) { document.write("The number is " + i); document.write("<br />"); } A: In short: You're confusing code with data. "i=0;i<=5;i++" is data (a piece of text, a string). But when writing a for-loop you have to write initialization, condition and step as code - you cannot pass text that happens to look like the code you'd write there. (In fact, you don't want to - what should happen when the data isn't like valid code? Not to mention it's not needed - see El Ronnoco's)
{ "pile_set_name": "StackExchange" }
Q: How many credit cards is it reasonable to have? Is there a right number of credit cards to hold? (Please don't say zero :) What would be the excessive number of credit cards, or how else would you judge enough is enough? If I have some cards I do not use just stuck in a drawer somewhere, is it a problem? A: Consider getting rid of all your credit cards. This has several benefits: No monthly credit card bill to pay, thus having more money to pay down other debt (if you have any) You won't have the temptation to spend money you don't have You won't have to pay any interest on purchases you make No late charges or interest rate hikes due to your own mistakes (Mistakes do happen) No late charges or interest rate hikes due to the credit card companies mistakes No extra monthly fees for American-Express-like cards Now, in order have some peace of mind without credit cards, you should have an Emergency Fund for 3 - 6 months worth of expenses. That said, there are a couple reasons I see making it reasonable to have one or two cards: You are currently building up an emergency fund, and want to have something to use in a cash-flow related emergency. You plan on getting a mortgage soon (although I would recommend living on the cheap for a while and buying an inexpensive condo or house instead of using debt). If you take this option, make sure you pay off the card on the same day you purchase stuff. Never maintain a balance for more than a day. Other than that, I fail to see any benefits. Sure, you can get free crap like gift certificates and airline miles, but the long term benefits of having no debt are a lot better. A: The number to hold depends on your usage and your goals. However the most important aspect of credit cards is the effect it has on your credit score. Having a good credit score can be useful later when making large purchases like a car or house. Things to consider about credit cards: Paying the minimum monthly balance. Late payments affect your score negatively. Excessive credit. High unused credit limits can flag you as a high risk. Also too many credit cards with low limits can also create lots of unused credit. (Another user mentioned getting free tupperware with every card they got). Merchant support. Not all merchants support all the common cards. e.g. You may want 1 Visa, 1 Mastercard. Reward systems. Some cards have a maximum limit on rewards given based on spending. At that point you may switch to another card. For most people who have never had a credit card 1 credit card is usually enough initially since the expenses should not exceed income (plus this reduces the temptation to get into lots of debt). The best way to find out if you are okay is to check your credit score and do it regularly. In Canada there are several ways to get this information and some of it free like Equifax. A: I have five credit cards. I confess: two are in a drawer and don't ever get used! I do find the other three useful: A Visa card with no annual fee and a 1% cash-back privilege. I use this card a lot. A MasterCard card with no annual fee and travel points. I only use it when Visa isn't taken. An American Express card. I wouldn't be carrying an Amex card at all except it's the only card accepted at Costco and I like the flexibility of using credit there, especially near the holidays. So, I would suggest anything more than five -- I mean, ahem, three might be excessive ;-) The other responses make good points: Consider your overall debt, consider your credit score. And ask yourself, "Do I really need this card?"
{ "pile_set_name": "StackExchange" }
Q: HTML Form GET variables to URL variables Alright so I have a regular search form (method="GET"). The issue is that the controller for it expects a url like this: search/<category>/<int:page> My question is, how can i make it so that the above URL is redirected, rather than: /search?q=jfiejfiaj Do I need to use JS or can I do it in pure HTML? A: Are you using an MVC approach to an web application? You will need to use mod-rewrite on Apache to on the server change the url request. EDIT: Im not sure if there is a better way using the html form itself but send the html form to a page with either of these, or even better: both. Meta (Html): (Using php) <meta http-equiv="refresh" content="0; url=http://stackoverflow.com/?search=<?php echo $_GET['search']; ?>"> Javascript: (Using php) window.location.href = "http://stackoverflow.com/?search=<?php echo $_GET['search']; ?>";
{ "pile_set_name": "StackExchange" }
Q: matching html tag content in regex I know "Dont use regex for html", but seriously, loading an entire html parser isn't always an option. So, here is the scenario <script...> some stuff </script> <script...> var stuff = '<'; anchortext </script> If you do this: <script[^>]*?>.*?anchor.*?</script> You will capture from the first script tag to the /script in the second block. Is there a way to do a .*? but by replacing the . with a match block, something like: <script[^>]*?>(^</script>)*?anchor.*?</script> I looked at negative lookaheads etc, but I can't get something to work properly. Usually I just use [^>]*? to avoid running past the closing block, but in this particular example, the script content has a "<" in it, and it stops matching on that before reaching the anchortext. To simplify, I need something like [^z]*? but instead of a single character or character range, I need a capture group to fit a string. .*?(?!z) doesn't have the same effect as [^z]*? as I assumed it would. Here is where I am stuck at: http://regexr.com?34llp A: Match-anything-but is indeed commonly implemented with a negative lookahead: ((?!exclude).)*? The trick is to not have the . dot repeated. But make it successively match any character while ensuring that character is not the beginning of the excluded word. In your case you would want to have this instead of the initial .*? <script[^>]*?>((?!</script>).)*?anchor.*?</script>
{ "pile_set_name": "StackExchange" }
Q: Can you view your compiled/executed grunt.js file? I realise this might seem like an odd thing to want, but I'd love to see exactly which paths are being output for my sanity. // configurable paths var yeomanConfig = { docroot: 'docroot/', css: this.docroot+'css', fonts: this.docroot+'fonts', sass: this.docroot+'sass', img: this.docroot+'img', js: this.docroot+'js', app: 'app', dist: '<%= yeoman.docroot %>/dist' }; For example the above I'd like to see what the JS thinks this really is. Or another example: jst: { files: [ '<%= yeoman.js %>/templates/*.ejs' ], tasks: ['jst'] } So can you see the final version of the grunt file with variables included and executed? A: Running the task with the verbose option (grunt --verbose) will log expanded output (usually) including the files to be operated on. The grunt api docs specify the behavior of grunt.verbose.write.
{ "pile_set_name": "StackExchange" }
Q: ListView using parse.com Hey i am trying to fetch all the data from parse.com table. My Table called "Code_Description" and i have two column that i have made into my table data they called "surveyCode" , "Description". and i want to fetch them into listView the surveyCode and the Description . please help. i have this code but doesn't working . public class editSurveyManager extends ActionBarActivity { //List<ParseObject> ob; ListView listView; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_survey_manager); //Setting Data adapter = new ArrayAdapter<String>(editSurveyManager.this,R.layout.activity_edit_survey_manager); listView = (ListView)findViewById(R.id.listView); ParseQuery<ParseObject> query = ParseQuery.getQuery("Code_Description"); query.setLimit(1000); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> markers, ParseException e) { if (e == null) { // update your list here somehow // listAdapter.clear(); // listAdapter.addAll(markers); for (ParseObject list : markers){ adapter.add((String)list.get("surveyCodes")); } listView.setAdapter(adapter); } else { Log.e("Error",e.getMessage()); } } }); A: Your first line is wrong. You should do something like that: ParseQuery<ParseObject> query = ParseQuery.getQuery("Code_Description"); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> markers, ParseException e) { if (e == null) { // update your list here somehow // listAdapter.clear(); // listAdapter.addAll(markers); } else { Log.e("Error",e.getMessage()); } } }); Parse will give you top 100 rows of your table. But you can change it with that method below: query.setLimit(1000); // max number you can set is 1000
{ "pile_set_name": "StackExchange" }
Q: DRF - django_filters -Using custom methods I have a model like this: class Agreement(models.Model): file_no = models.IntegerField(primary_key=True) contract_date = models.DateField() contract_time = models.IntegerField() @property def calculate_expiry_date(self): return self.contract_date + relativedelta(years=self.contract_time) @property def is_expired(self): return (self.contract_date + relativedelta(years=self.contract_time)) < timezone.now().date() is_expired function returns true or false for each agreement and I have a simple filter like this: class AgreementFilter(filters.FilterSet): file_no = filters.NumberFilter(lookup_expr='icontains') class Meta: model = Agreement fields = ['file_no',] I think that I cannot filter on the property field because Django filters operate at the database level. So how can I make it work to filter agreement model objects if it is valid or invalid or either true or false A: I managed to write a custom filter for filtering the expired and valid agreements by using the 'method' parameter to specify a custom method - see django-filter docs from datetime import timedelta from django.db.models import F, Case, When, BooleanField from django_filters import rest_framework as filters class AgreementFilter(filters.FilterSet): file_no = filters.NumberFilter(lookup_expr='icontains') is_expired = filters.BooleanFilter(method='filter_is_expired') class Meta: model = Agreement fields = ['file_no',] def filter_is_expired(self, queryset, name, value): if value is not None: queryset = queryset.annotate( expired=Case(When(contract_date__lt=timezone.now().date() - (timedelta(days=365) * F('contract_time')), then=True), default=False, output_field=BooleanField())).filter(expired=value) return queryset Queryset will return if the object of the agreement is either true or false by calculation: For expired agreements http://127.0.0.1:8000/api/agreement/?is_expired=True and For valid agreements http://127.0.0.1:8000/api/agreement/?is_expired=False
{ "pile_set_name": "StackExchange" }
Q: How to declare global variable in order to kill second EXCEL.EXE from Task Manager Following code opens two EXCEL.EXE in the Task Manager. I want to kill second opening EXCEL.EXE from the Task Manager when Form1 is closing. Imports Microsoft.Office.Interop Public Class Form1 Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load 'Kill all EXCEL.EXE process from Task Manager For Each prog As Process In Process.GetProcessesByName("EXCEL") prog.Kill() Next Dim FirstxlApp As New Excel.Application 'Open first EXCEL.EXE in the Task Manager Dim datestart As Date = Date.Now Dim SecondxlApp As New Excel.Application 'Open second EXCEL.EXE in the Task Manager Dim dateEnd As Date = Date.Now SecondxlApp.Visible = True Dim wb1 As Excel.Workbook wb1 = SecondxlApp.Workbooks.Open("C:\Book1.xlsx") End Sub Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing Dim xlp() As Process = Process.GetProcessesByName("EXCEL") For Each Process As Process In xlp If Process.StartTime >= datestart And Process.StartTime <= dateEnd Then Process.Kill() Exit For End If Next End Sub End Class How to declare global variable in order to solve following errors? A: Your variables dateEnd and dateStart are hidden to FormClosing method as they are only declared within the Form_Load method. Change your code to: Public Class Form1 Dim dateEnd, dateStart As DateTime Private Sub Form_load Then they will be accessable to all methods with the form.
{ "pile_set_name": "StackExchange" }
Q: Android Deep Linking issue ! How to use Custom Url scheme myapp://some_data i have tried link1, link2,link3, link4, link5, link6 Here's everything described about DeepLinking What i want is the custom uri myapp://some_data, opens the native application installed in the device that requires some_data to initialise the application. There are 2 scenarios in which the custom url can be clicked. 1) from within the SMS app, when user taps the link it should automatically open the installed otherwise open the googleplay store where the app is hosted 2) from within the body of a email message. I have tried all the above listed links, but none of them works for me. I m having major problem with the scheme part. Here's my AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="MainActivity" android:label="@string/app_name" android:exported="true" > <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="inderbagga" /> </intent-filter> </activity> </application> and here's the MainActivity.java TextView tvText=(TextView)findViewById(R.id.tvid); if (getIntent().getAction() == Intent.ACTION_VIEW&&getIntent().getScheme().equals("inderbagga")) { Toast.makeText(getApplicationContext(), ""+getIntent().getScheme(), Toast.LENGTH_SHORT).show(); Uri uri = getIntent().getData(); // do stuff with uri tvText.setText(uri.toString()); } else tvText.setText("NULL"); To be more specific, i want to open the native application when u url of type inderbagga://a1b22c333 is clicked, Either from sms application or gmail/yahoomail email message body. in order to achieve the same, i 've used intent filters to set the scheme. and getIntent() to read the data that equals to a1b22c333 in the MainActivity. A: click link means this code will work <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" android:host="domain.com(google.com)"android:pathPrefix="/wp/poc1/(sufexes)" /> </intent-filter> get url data //get uri data Uri data = getIntent().getData(); //get schma String scheme = data.getScheme(); // "http" //get server name String host = data.getHost(); // Ipaddress or domain name //get parameter String urltextboxname=data.getQueryParameter("name"); //set value in textview name.setText(urltextboxname); A: To be more specific, i want to open the native application when u url of type inderbagga://a1b22c333 is clicked, Either from sms application or gmail/yahoomail email message body. There are many SMS and email applications available for Android. Precisely none of them know to convert inderbagga://a1b22c333 into clickable entries. You could build a list of all of those apps, contact each of their development teams, and ask them to add it. Or, you could have your app watch for a particular http:// URL instead. While the user would be presented with a chooser, to view that URL within your app or a Web browser, at least it will be clickable. A: You might also want to try out this library which facilitates declaring deep links and extracting out the parameters you need: https://github.com/airbnb/DeepLinkDispatch It allows you to declare the URI you're interested in and the parameter you'd like to extract through annotations, without having to do the parsing yourself.
{ "pile_set_name": "StackExchange" }
Q: Does light interact with electric fields? We know that light is an electromagnetic wave and it does interact with charges. It contains magnetic field and electric field oscillating perpendicularly but when we apply an electric or magnetic field in any direction to the wave the applied electric field or magnetic field vector doesn't alter the magnetic or electric field in the electro magnetic wave (according to vector addition rule)....why? A: An applied electric or magnetic field doesn't alter the field of an electromagnetic field because, as you said, the superposition principle holds. This principle is a principle of linearity, and comes from the linearity of electromagnetic equations : there is no interaction between photons at low energies. You can see it from a field theory point of view, as there is no bare interaction vertex between photons in QED. On the other hand, in other theories such as QCD, gauge bosons (the gluons) carry a colour charge and can interact.
{ "pile_set_name": "StackExchange" }
Q: How to crop the image on opencv and dlib on ubuntu I want to do these on the opencv and dlib using c++ on ubuntu. Detect the human face using dlib.(I did it already.) crop the image of only around mouth part. here is my code. it is base on dlib sample code. #include <dlib/image_processing/frontal_face_detector.h> #include <dlib/image_processing/render_face_detections.h> #include <dlib/image_processing.h> #include <dlib/gui_widgets.h> #include <dlib/image_io.h> #include <iostream> #include <opencv2/opencv.hpp> #include <highgui.h> using namespace dlib; using namespace std; // ---------------------------------------------------------------------------------------- int main(int argc, char** argv) { try { // This example takes in a shape model file and then a list of images to // process. We will take these filenames in as command line arguments. // Dlib comes with example images in the examples/faces folder so give // those as arguments to this program. if (argc == 1) { cout << "Call this program like this:" << endl; cout << "./face_landmark_detection_ex shape_predictor_68_face_landmarks.dat faces/*.jpg" << endl; cout << "\nYou can get the shape_predictor_68_face_landmarks.dat file from:\n"; cout << "http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2" << endl; return 0; } // We need a face detector. We will use this to get bounding boxes for // each face in an image. frontal_face_detector detector = get_frontal_face_detector(); // And we also need a shape_predictor. This is the tool that will predict face // landmark positions given an image and face bounding box. Here we are just // loading the model from the shape_predictor_68_face_landmarks.dat file you gave // as a command line argument. shape_predictor sp; deserialize(argv[1]) >> sp; cv::Mat cimg = cv::imread(argv[1]); image_window win, win_faces; // Loop over all the images provided on the command line. for (int i = 2; i < argc; ++i) { cout << "processing image " << argv[i] << endl; array2d<rgb_pixel> img; load_image(img, argv[i]); /* // Make the image larger so we can detect small faces. pyramid_up(img); */ // Now tell the face detector to give us a list of bounding boxes // around all the faces in the image. std::vector<rectangle> dets = detector(img); cout << "Number of faces detected: " << dets.size() << endl; // Now we will go ask the shape_predictor to tell us the pose of // each face we detected. std::vector<full_object_detection> shapes; for (unsigned long j = 0; j < dets.size(); ++j) { full_object_detection shape = sp(img, dets[j]); cout << "number of parts: "<< shape.num_parts() << endl; cout << "pixel position of first part: " << shape.part(0) << endl; cout << "pixel position of second part: " << shape.part(1) << endl; // You get the idea, you can get all the face part locations if // you want them. Here we just store them in shapes so we can // put them on the screen. shapes.push_back(shape); } // Crop the original image to the defined ROI */ cv::Rect roi; roi.x = 0; roi.y = 0; roi.width = 200; roi.height = 200; cv::Mat crop = cimg(roi); cv::imshow("crop", crop); // Now let's view our face poses on the screen. /* win.clear_overlay(); win.set_image(img); win.add_overlay(render_face_detections(shapes)); // We can also extract copies of each face that are cropped, rotated upright, // and scaled to a standard size as shown here: //dlib::array<array2d<rgb_pixel> > face_chips; //extract_image_chips(img, get_face_chip_details(shapes), face_chips); //win_faces.set_image(tile_images(face_chips)); */ cout << "Hit enter to process the next image..." << endl; cin.get(); } } catch (exception& e) { cout << "\nexception thrown!" << endl; cout << e.what() << endl; } } but it gives me this error. OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /home/bigadmin/opencv-3.1.0/modules/core/src/matrix.cpp, line 508 exception thrown! /home/bigadmin/opencv-3.1.0/modules/core/src/matrix.cpp:508: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat please teach me the solution to solve this issue. thanks. A: You have many errors in your code: cv::Mat cimg = cv::imread(argv[1]); - argv[1] is detector file, not image - you will get empty image, thats why your program crashes you are not iterating through images. try something like this: for (int i = 2; i < argc; ++i) { cout << "processing image " << argv[i] << endl; cv::Mat cvimg = cv::imgread(argv[i]); dlib::cv_image<rgb_pixel> img(cvimg); ... Here you will read file only once and will be able to detect faces you should specify cropping region based on face detector function (and even better - based on shape predictor) ... std::vector<rectangle> dets = detector(img); here each item in dets is a rectangle, describing face, you can crop like this: dlib::rectangle r = dets[j]; cv::Rect roi(r.left(), r.top(), r.width(), r.height()); cv::Mat face = cvimg(roi); But it will be the full face image. If you want to crop only mouth, you should use shape predictor's output (didn't tested - please check if compile well): full_object_detection shape = sp(img, dets[j]); auto mouth_left = shape.part(45); auto mouth_right = shape.part(54); unsigned long mouth_width = (mouth_right - mouth_left).length(); double padding = 0.2; cv::Rect roi(mouth_left.x() - mouth_width * padding, mouth_left.y() - mouth_width*0.5, mouth_width * (1 + padding * 2), mouth_width); cv::Mat mouth = cvimg(roi); This will produce unaligned image of mouth
{ "pile_set_name": "StackExchange" }
Q: Object in javascript In want to get value of a clicked on href attr(is an object) DEMO HTML <a href='#test'>Click on me</a> jQuery $(function () { var g = {}; g.test = { title: 'my title', content: 'Hi,you can do it !', }; $('a').click(function () { var request = $(this).attr('href').slice(1); var request = eval(request); alert(g.request) console.log(g.request); }) }) A: If you want to access an object inside g with its variable name and using the id attribute, try this : $(function () { var g = {}; g.test = { title: 'my title', content: 'Hi,you can do it !', }; $('a').click(function () { var request = $(this).attr('href').slice(1); console.log(g[request]); }) }) http://jsfiddle.net/ekw0fnL9/1/
{ "pile_set_name": "StackExchange" }
Q: MySQL - максимальный размер поля id в Django Использую БД MySQL для Django. Возник вопрос - а какое максимальное значение может хранить в себе поле id, которое создается по стандарту при миграции модели? A: Если мне не изменяет память, то по умолчанию в создаваемой Django таблице MySQL идентификаторы имеют тип int unsigned, а значит могут хранить значения до 4 294 967 295.
{ "pile_set_name": "StackExchange" }
Q: How to find the number of vertices in a graph? Suppose that a connected planar graph has 30 edges. If a planar representation of this graph divides the plane into 20 faces, how many vertices does this graph have? I am not sure how to get started with this ? Please give me some idea. A: You'll want to know about Euler's Characteristic, which applies also to connected, planar graphs. Denote the number of vertices of a connected planar graph $G$ by $V$. Likewise, denote the number of edges of the graph by $E$, and the number of faces of the graph by $F$. Then the following holds for every connected planar graph: $$V - E + F = 2$$ You're given the number of edges $E$, and the number of faces $F$, so you simply need the formula above to calculate the number of vertices of your graph.
{ "pile_set_name": "StackExchange" }
Q: a SOAP reader and writer in JAVA? I want to make a web service client and need a free reader/writer which can read/write soap messages and I easily just set/get message parameters. I have my own network infrastructures and I want to work with them, and I just need something that can read/write from/to a byte array, or ByteBuffer, or somthing... Is there any good hint? A: SAAJ should do the job, and it comes standard with Java as of Java 6. Reading from input stream: ByteArrayInputStream in = ...; MessageFactory mf = MessageFactory.newInstance(); SOAPMessage message = mf.createMessage(new MimeHeaders(), in); System.out.println(message.getSOAPBody().getElementsByTagNameNS("http://tempuri.org", "MyOperation")); Writing: SOAPMessage message = ...; ByteArrayOutputStream out = new ByteArrayOutputStream(); message.writeTo(out); System.out.println(out);
{ "pile_set_name": "StackExchange" }
Q: Running Scrapy on Raspberry Pi 3, python 3.4 I receive an error when running scrapy on Raspberry Pi 3. I have successfully installed it, but when I try to startproject or crawl with a previously created spider, I get the following error: Traceback (most recent call last): File "/usr/local/bin/scrapy", line 7, in <module> from scrapy.cmdline import execute File "/usr/local/lib/python3.4/dist-packages/scrapy/cmdline.py", line 9, in <module> from scrapy.crawler import CrawlerProcess File "/usr/local/lib/python3.4/dist-packages/scrapy/crawler.py", line 7, in <module> from twisted.internet import reactor, defer File "/usr/local/lib/python3.4/dist-packages/twisted/internet/reactor.py", line 38, in <module> from twisted.internet import default File "/usr/local/lib/python3.4/dist-packages/twisted/internet/default.py", line 56, in <module> install = _getInstallFunction(platform) File "/usr/local/lib/python3.4/dist-packages/twisted/internet/default.py", line 44, in _getInstallFunction from twisted.internet.epollreactor import install File "/usr/local/lib/python3.4/dist-packages/twisted/internet/epollreactor.py", line 24, in <module> from twisted.internet import posixbase File "/usr/local/lib/python3.4/dist-packages/twisted/internet/posixbase.py", line 18, in <module> from twisted.internet import error, udp, tcp File "/usr/local/lib/python3.4/dist-packages/twisted/internet/tcp.py", line 28, in <module> from twisted.internet._newtls import ( File "/usr/local/lib/python3.4/dist-packages/twisted/internet/_newtls.py", line 21, in <module> from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol File "/usr/local/lib/python3.4/dist-packages/twisted/protocols/tls.py", line 65, in <module> from twisted.internet._sslverify import _setAcceptableProtocols File "/usr/local/lib/python3.4/dist-packages/twisted/internet/_sslverify.py", line 1865, in <module> "ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:" File "/usr/local/lib/python3.4/dist-packages/twisted/internet/_sslverify.py", line 1845, in fromOpenSSLCipherString SSL.SSLv23_METHOD, SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) File "/usr/local/lib/python3.4/dist-packages/twisted/internet/_sslverify.py", line 1797, in _expandCipherString ctx.set_cipher_list(cipherString.encode('ascii')) TypeError: must be str, not bytes I have no idea why I am getting this or how to fix it, please help? SOLUTION: Thanks everyone for the help, I got Scrapy to work on Raspberry Pi 3 in the end by following these steps: First install virtualenv: sudo pip install virtualenv Then create a virtualenv and active it for Scrapy: virtualenv scrapyenv source scrapyenv/bin/activate Then I ran and updated everything in there: apt-get update apt-get upgrade Install all dependencies: apt-get install libffi-dev apt-get install libxml2-dev apt-get install libxslt1-dev apt-get install libssl-dev apt-get install python-dev Then install Scrapy sudo pip install scrapy I then updated my pyOpenSSL with this: pip -vvvv install --upgrade pyOpenSSL This created a lot of log files and took a bit of time, after that scrapy worked fine with the normal scrapy commands and I have also run a spider - all works. A: What user are you using? i think you need use sudo. also update your ssl. looks like the ssl connection has problems.. Have you run : pip install --verbose twisted Also update your openssl pip -vvvv install --upgrade pyOpenSSL, please copy the output here to check if is updated Regards
{ "pile_set_name": "StackExchange" }
Q: How do you write to a span using jQuery? I'm trying to populate a <span></span> element on the page load with jQuery. At the moment the value that gets populated into the span is just an integer count. Here I have named my span userCount: <a href="#" class="">Users<span id = "userCount"></span></a> I am trying to write the value of the span with no success. $(document).ready(function () { $.post("Dashboard/UsersGet", {}, function (dataset) { var obj = jQuery.parseJSON(dataSet); var table = obj.Table; var countUsers; for (var i = 0, len = table.length; i < len; i++) { var array = table[i]; if (array.Active == 1) { var name = array.Name; } countUsers = i; } userCount.innerHTML = countUsers.toString(); }); }); A: You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html. $('#userCount').html(countUsers); Note also that you don't need to convert your integer to a string manually. if you don't break from the loop, countUsers will always be table.length-1. you have a typo : dataSet instead of dataset. Javascript is case sensitive. you don't need to parse the result of the request you don't need to pass empty data : jQuery.post checks the type of the provided parameters So, this is probably more what you need, supposing you do other things in the loop : $.post("Dashboard/UsersGet", function (dataset) { var table = dataset.Table; var countUsers = table.length; // -1 ? // for now, the following loop is useless for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length var array = table[i]; if (array.Active == 1) { // I hope array isn't an array... var name = array.Name; // why ? This serves to nothing } } $('#userCount').html(countUsers); }); A: Use .html()! <a href="#" class="">Users<span id = "userCount"></span></a> Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html(). $("#userCount").html(5000); Or in your case: $("#userCount").html(countUsers.toString());
{ "pile_set_name": "StackExchange" }
Q: Is there a way to disable my.cnf vertical setting from a shell script running mysql? Because the vertical output mode of the mysql command is very nice, I've setup my environment to default the output to vertical layout. I've done this by creating c:\windows\my.cnf that contains [mysql] vertical Regrettably, all my mysql shell scripts also pick up on this setting, wreaking havoc with parsing the output of the mysql command. Is there command-line switch or SQL I can use to override the vertical setting in my.cnf when invoking mysql from a shell script? Specifically, I have a shell script that looks something like this set SQLFILE=.\cmdelOldRecords.sql set TMPCKTFILE=.\temp2.sql :: get all "_aud" tables from database mysql -h %1 --port=3306 --database=%MYSQL_DB% --user=%MYSQL_USER% --password=%MYSQL_PASSWORD% -B -N -e "show tables like '%%\_aud'" > %TMPCKTFILE% for /F "tokens=1" %%i in ('type %TMPCKTFILE%') do ( echo drop table %%i; >> %SQLFILE% echo commit; >> %SQLFILE% ) mysql -h %1 --port=3306 --database=%MYSQL_DB% --user=%MYSQL_USER% --password=%MYSQL_PASSWORD% -B -N < %SQLFILE% But my .\cmdelOldRecords.sql ends up with stuff like drop table ***************************; A: there is the -E (or --vertical) switch to get the client act vertical this means you could try: mysql --vertical=false
{ "pile_set_name": "StackExchange" }
Q: How can I create a subsection of an existing array using PHP? I know this is probably a very simple question but I have looked around and most answers relate to array intersections which is not what I am looking for. Example: I have an array ($rows). When running print_r($rows) I get: Array ( [0] => Array ( [id] => 184 [0] => 184 [name] => Advantage Membership [1] => Advantage Membership [flag] => 4 [2] => 4 ) [1] => Array ( [id] => 238 [0] => 238 [programname] => Package 2 [1] => Package 2 [flag] => 5 [2] => 5 ) ) I want to essentially create a 'sub' array which contains all of the 'flag' fields in my $rows array so that I can THEN do a if(in_array()) statement with another value. ideal result array would look like: $array2 = array( '4', '5' ) Then I could run the following and be happy: if (in_array(4, $array2)) ... Any suggestions? A: What's wrong with a custom function? function in_sub_array($needle, $ary){ foreach ($ary as $a){ if (isset($a['flag']) && $a['flag'] == $needle) // could use ===, too. return true; } return false; } if (in_sub_arry(4,$array2)) ... Or, as others have suggested, array_map is a good alternative. function get_flags($ary){ return (isset($ary['flag']) ? $ary['flag'] : null); } if (in_array(4,array_map('get_flags',$array2))) ... demos of both methods
{ "pile_set_name": "StackExchange" }
Q: JPA not updating ManyToMany relationship in returning result Here are my entities: @Entity public class Actor { private List<Film> films; @ManyToMany @JoinTable(name="film_actor", joinColumns =@JoinColumn(name="actor_id"), inverseJoinColumns = @JoinColumn(name="film_id")) public List<Film> getFilms(){ return films; } //... more in here Moving on: @Entity public class Film { private List actors; @ManyToMany @JoinTable(name="film_actor", joinColumns =@JoinColumn(name="film_id"), inverseJoinColumns = @JoinColumn(name="actor_id")) public List<Actor> getActors(){ return actors; } //... more in here And the join table: @javax.persistence.IdClass(com.tugay.sakkillaa.model.FilmActorPK.class) @javax.persistence.Table(name = "film_actor", schema = "", catalog = "sakila") @Entity public class FilmActor { private short actorId; private short filmId; private Timestamp lastUpdate; So my problem is: When I remove a Film from an Actor and merge that Actor, and check the database, I see that everything is fine. Say the actor id is 5 and the film id is 3, I see that these id 's are removed from film_actor table.. The problem is, in my JSF project, altough my beans are request scoped and they are supposed to be fetching the new information, for the Film part, they do not. They still bring me Actor with id = 3 for Film with id = 5. Here is a sample code: @RequestScoped @Named public class FilmTableBackingBean { @Inject FilmDao filmDao; List<Film> allFilms; public List<Film> getAllFilms(){ if(allFilms == null || allFilms.isEmpty()){ allFilms = filmDao.getAll(); } return allFilms; } } So as you can see this is a request scoped bean. And everytime I access this bean, allFilms is initially is null. So new data is fetched from the database. However, this fetched data does not match with the data in the database. It still brings the Actor. So I am guessing this is something like a cache issue. Any help? Edit: Only after I restart the Server, the fetched information by JPA is correct. Edit: This does not help either: @Entity public class Film { private short filmId; @ManyToMany(mappedBy = "films", fetch = FetchType.EAGER) public List<Actor> getActors(){ return actors; } A: JB Nizet is correct, but you also need to maintain both sides of relationships as there is caching in JPA. The EntityManager itself caches managed entities, so make sure your JSF project is closing and re obtaining EntityManagers, clearing them if they are long lived or refreshing entities that might be stale. Providers like EclipseLink also have a second level cache http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching
{ "pile_set_name": "StackExchange" }
Q: Laravel/SQL: Query model where relationship = X Context I have three models below: listing, rooms and room types - LISTING |-----|-------------|--------------------| | ID | title | description | |-----|-------------|--------------------| | 1 | some title | some description | | 2 | some title | some description | | 3 | some title | some description | etc ROOMS |-----|---------------|---------------|--------------------| | ID | room_type_id | listing_id | room_description | |-----|---------------|---------------|--------------------| | 1 | 1 | 1 | some description | | 2 | 2 | 1 | some description | | 3 | 1 | 1 | some description | etc ROOM_TYPES |-----|------------| | ID | name | |-----|------------| | 1 | Bedroom | | 2 | Bathroom | | 3 | Kitchen | etc Question I am trying to query the listings model that has X amount of room types e.g. all listings that have >= 2 Bedrooms. I think this sql is right, just not sure how to do this in Laravel - SELECT listing.id, listing.title, count(rooms.id) FROM listing JOIN rooms on rooms.listing_id = listing.id WHERE rooms.`room_type_id` = 10 GROUP BY listing.id HAVING count(rooms.room_type_id) >= 1 Any ideas? PS. I am using Laravel 4 Thanks in advance:) A: So after struggling with a complicated SQL query, I landed up using a model accessor to achieve my goal: On the listing model public function bedroomCount() { return $this->rooms() ->selectRaw('listing_id, count(*) as count') ->where('room_type_id', '=', '1') ->groupBy('listing_id'); } And the query $listings = Listing:: has('bedroomCount', '>=', $x) ->get();
{ "pile_set_name": "StackExchange" }
Q: See call stack while debugging in Pydev Is there a way to see the call stack while debugging python in Pydev? A: This is the "Debug" view of the "Debug" perspective : You can see that I was inside a failUnlessEqual method, called by test_01a, called by a new_method...
{ "pile_set_name": "StackExchange" }
Q: How to get name of bitmap from MediaStore.Images I am getting bitmaps from MediStore like MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(),id,MediaStore.Images.Thumbnails.MICRO_KIND, null); My question is how to get name of every picture ( bitmap ) ? A: Try below code to get the name of the pics and it's folder from the external storage String[] projection = new String[] { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DISPLAY_NAME }; Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; Cursor cur = managedQuery(images, projection, // Which columns to return "", // Which rows to return (all rows) null, // Selection arguments (none) MediaStore.Images.Media.BUCKET_DISPLAY_NAME // Ordering ); Log.i("ListingImages", " query count=" + cur.getCount() + "Columns =" + cur.getColumnCount() + "" + cur.getColumnName(0) + "" + cur.getColumnName(1) + "" + cur.getColumnName(2)); if (cur.moveToFirst()) { int bucketColumn = cur .getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME); int dpColumn = cur .getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); do { Log.i("Folder Name",cur.getString(bucketColumn)); Log.i("Pic Name ",cur.getString(dpColumn)); } while (cur.moveToNext()); } else { Log.i("Ooops","No Media Found"); }
{ "pile_set_name": "StackExchange" }
Q: Storing pointers to C structures in R as integers I've been working on using a C library from R by writing custom C-functions using the library's functionality, and then accessing these C-functions from R using the .C-Interface. In some of the C-code, I allocate space for some custom structures and want to store pointers to them in R so I can use these structures in successive calls to .C. While toying around with the .C function, I noticed I can simply cast the pointer to the C-structure to int and store it in R as an integer. Passing this integer to later calls via .C works fine, I can keep track of my structures and use them without problems. My somewhat naive question: what is wrong with storing these pointers in integers in R? It works fine so I'm assuming there has to be some downside, but I couldn't find any info on it. A: R's integers are 32 bits even on a 64 bits platform. Therefore, when working on a 64 bits system this won't work (the pointers will be 64 bits). R has functionality for this. See the 'Writing R Extensions' manual, the section on 'External pointers and weak references'. If you are willing to switch to c++ (which doesn't mean you have to rewrite all of your code), you can use the Rcpp package which makes this easier. See for example External pointers with Rcpp
{ "pile_set_name": "StackExchange" }
Q: Python equivalent for R's 'zoo' package Are there Python or perhaps pandas equivalents to R's zoo package? In particular, I'm looking for equivalents to: dataLag2 = lag(zoo(train$data), -2, na.pad=TRUE) train$dataLag2 = coredata(dataLag2) Are there equivalents on Python that would produce the same results (the empty entry for zoo functionality in the Pandas documentation is a bit ominous). A: Pandas has the TimeSeries class which implements all the functionalities available in zoo to manipulate and homogenize irregular time series data: if 'ts' is a TimeSeries object containing irregular hourly timestamped data I'd first create an homogeneous time series doing: ts.resample('H').interpolate() And after, to create a lagged timeseries I'd use the shift() method. For example, to lag the previous timeseries 12 hours backwards: ts.shift(-12) http://pandas.pydata.org/pandas-docs/stable/timeseries.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html
{ "pile_set_name": "StackExchange" }
Q: Conditional statement on declaring global const variable Objective C I'm using a private SDK I can only declare one const global variable called const unsigned char KitApplicationKey[]= {0x1b,0 etc.} I would like to check one condition (a bool variable that i save in user default in the appdelagate) and modify the KitApplicationKey depending on the bool value Something like that dash if mybool true (I don't know how to write that) const unsigned char KitApplicationKey[]= {0x1b,0 etc.} dash else const unsigned char KitApplicationKey[]= {0x2C,0x1b etc.} dash endif Can you please help me Thank you A: You can't modify the value of a const char []. If you really need this, you might want to use a simple function instead to switch between the two values: const unsigned char appKey1[]= {0x1b, 0x0}; const unsigned char appKey2[]= {0x2c, 0x1b}; char* appKey() { return myBool ? appKey1 : appKey2; } Obviously, you'll need to modify that for your own purposes to integrate it in your code, but otherwise, that should work just fine.
{ "pile_set_name": "StackExchange" }
Q: pasting in vba data image worksheetI am setting up sheet with hotels details and column "D" has hospitals that are close by eg PMH,SCGH,FSH. What i am trying to do is search column "D" based on a cell value on same sheet. I have code below but it will only do what i want if the cells in column"D" are single entry eg pmh. I need to be able to search all the cells in Column "D" for any instance of the text. Many Thanks for any assistance `Option Explicit Sub finddata() Dim hospitalname As String Dim finalrow As Integer Dim i As Integer Sheets("Results").Range("A4:D100").ClearContents Sheets("Main").Select hospitalname = Sheets("Main").Range("g3").Value finalrow = Sheets("Main").Range("A1000").End(xlUp).Row For i = 2 To finalrow If Cells(i, 4) = hospitalname Then Range(Cells(i, 1), Cells(i, 4)).Copy Sheets("Results").Range("A4").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats End If Next i Sheets("Main").Range("g3").Select End Sub ` A: The two simplest ways to do this would be Using the Like operator: If Cells(i, 4).Value Like "*" & hospitalname & "*" Then This method has the drawback that a hospital name of, for instance, PMH might be matched against another one such as SPMH. Using the InStr function: If Instr("," & Cells(i, 4).Value & ",", "," & hospitalname & ",") > 0 Then In this line, I "wrap" both the cell being looked at, and the value being searched for, within commas so it ends up searching for the string (for instance) ",PMH," within the string ",PMH,SCGH,FSH,". InStr will return the character position at which a match occurs, or zero if no match is found. So testing for > 0 is testing whether a match occurred.
{ "pile_set_name": "StackExchange" }
Q: Javascript : Construct array from an array with duplicate elements by property I have an array of objects that I would like to convert to a new array with different structure by removing duplicate elements based on an attribute of the array. For example, this array would be filtered by date property: var arrayWithDuplicates = [ { "date":"02/08/2018", "startTime": "09:00", "endTime": "12:00" }, { "date":"02/08/2018", "startTime": "14:00", "endTime": "17:00" } ]; ==> would become : var newArray = [ { "date":"02/08/2018", "times": [ { "startTime": "09:00", "endTime": "12:00" }, { "startTime": "14:00", "endTime": "17:00" } ] ]; So, how can i do this using js(ES5) or angularjs A: You can use array reduce and findIndex.findIndex will be used to check if there exist a date ,if it exist it will return a index. Use this index to find the element in the new array and there just update the times array var arrayWithDuplicates = [{ "date": "02/08/2018", "startTime": "09:00", "endTime": "12:00" }, { "date": "02/08/2018", "startTime": "14:00", "endTime": "17:00" } ]; let newArray = arrayWithDuplicates.reduce(function(acc,curr){ let checkIfExist = acc.findIndex(function(item){ return item.date === curr.date }); if(checkIfExist ===-1){ let obj = {}; obj.date = curr.date; obj.times = [{ startTime:curr.startTime, endTime:curr.endTime }] acc.push(obj); } else{ acc[checkIfExist].times.push({ startTime:curr.startTime, endTime:curr.endTime }) } return acc; },[]); console.log(newArray)
{ "pile_set_name": "StackExchange" }
Q: Recurrent equation system How to solve this recurrent equation system? $$\begin{cases}a_{n+1}=a_n+2b_n\\ b_{n+1}=2a_n+b_n\end{cases}$$ The possible solutions should be \begin{cases}a_n=\frac{1}{2}3^n+\frac{1}{2}(-1)^n\\ b_n=\frac{1}{2}3^n-\frac{1}{2}(-1)^n\end{cases} A: Let $X_n =(a_n,b_n)$ with $X_0=(1,0)=(a_0,b_0)$ \begin{cases}a_{n+1}=a_n+2b_n\\ b_{n+1}=2a_n+b_n\end{cases} Then it is equivalent $$X_{n+1} = AX_n \Longleftrightarrow X_n =A^nX_0$$ where, $$A= \begin{pmatrix}1&2\\ 2&1\end{pmatrix}$$ Then prove by induction that, $$A^n= \begin{pmatrix}\frac{1}{2}3^n+\frac{1}{2}(-1)^n &\frac{1}{2}3^n-\frac{1}{2}(-1)^n\\\frac{1}{2}3^n-\frac{1}{2}(-1)^n&\frac{1}{2}3^n+\frac{1}{2}(-1)^n\end{pmatrix}$$ Therefore you will get the desired result. $$X_n= \begin{pmatrix}a_n\\b_n\end{pmatrix}= \begin{pmatrix}\frac{1}{2}3^n+\frac{1}{2}(-1)^n &\frac{1}{2}3^n-\frac{1}{2}(-1)^n\\\frac{1}{2}3^n-\frac{1}{2}(-1)^n&\frac{1}{2}3^n+\frac{1}{2}(-1)^n\end{pmatrix}\begin{pmatrix}1\\0\end{pmatrix}\\=\begin{pmatrix}\frac{1}{2}3^n+\frac{1}{2}(-1)^n\\ \frac{1}{2}3^n-\frac{1}{2}(-1)^n\end{pmatrix}$$
{ "pile_set_name": "StackExchange" }
Q: Usar input select para autocompletar campos en PHP, Mysql, Ajax, Jquery tengo el siguiente formulario: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Autocompletado de Mutiples campos Usando jQuery , Ajax , PHP y MySQL</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> $(function() { $("#codigo").autocomplete({ source: "productos.php", minLength: 2, select: function(event, ui) { event.preventDefault(); $('#codigo').val(ui.item.codigo); $('#descripcion').val(ui.item.descripcion); $('#precio').val(ui.item.precio); $('#id_producto').val(ui.item.id_producto); } }); }); </script> </head> <body> <div class="ui-widget"> Codigo: <input id="codigo"> Producto: <input id="descripcion" readonly> Precio: <input id="precio" readonly> <input type="hidden" id="id_producto"> <p>Ingresa 00</p> </div> </body> </html> Y me trae por medio de una función el archivo -productos.php- <?php if (isset($_GET['term'])){ # conectare la base de datos $con=@mysqli_connect("localhost", "root", "root", "basededatos"); $return_arr = array(); /* Si la conexión a la base de datos , ejecuta instrucción SQL. */ if ($con) { $fetch = mysqli_query($con,"SELECT * FROM productos where codigo_producto like '%" . mysqli_real_escape_string($con,($_GET['term'])) . "%' LIMIT 0 ,50"); /* Recuperar y almacenar en conjunto los resultados de la consulta.*/ while ($row = mysqli_fetch_array($fetch)) { $id_producto=$row['id_producto']; $precio=number_format($row['precio_venta'],2,".",""); $row_array['value'] = $row['codigo_producto']." | ".$row['nombre_producto']; $row_array['id_producto']=$row['id_producto']; $row_array['codigo']=$row['codigo_producto']; $row_array['descripcion']=$row['nombre_producto']; $row_array['precio']=$precio; array_push($return_arr,$row_array); } } /* Cierra la conexión. */ mysqli_close($con); /* Codifica el resultado del array en JSON. */ echo json_encode($return_arr); } ?> Hasta alli todo funciona muy bien, si yo coloco el codigo del producto el me trae los datos y luego cuando elijo un producto me rellena los otros dos campos automaticamente. El problema es que estoy buscando que ese input código sea un select y me traiga de mi base de datos los productos que ya están registrados por default y no necesariamente tenga yo que escribirlo sino que solo tenga que seleccionar el producto y ya me rellene los otros dos campos con la información que ya tengo. De que forma podría hacerlo? muchas gracias quedo atento. A: pues se me ocurre, que podrías rellenar los options con un ajax que te traiga todos los valores del código, y tus otros 2 campos... Aquí tienes el HTML de ejemplo: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(cargarCodigos); $(document).ready(initialEvents); function cargarCodigos() { $.ajax("Productos.php") .done(function (data) { var response = JSON.parse(data); // Convertimos el json a objeto de JavaScript. var sel = $('#codigo'); sel.empty(); sel.append('<option value="-1">Seleccione un código</option>'); // Insertamos un registro para que seleccionen. for (var i = 0; i < response.length; i++) { sel.append('<option value="' + response[i].codigo + '" precio="' + response[i].precio + '" id_producto="' + response[i].id_producto + '" descProducto="' + response[i].descripcion + '">' + response[i].codigo + '</option>'); // Agregamos los distintos registros. } }); } function initialEvents() { $('#codigo').on('change', function () { // Agregamos el evento change al select. var SelectedOption = $($('#codigo option:selected')[0]); // Obtenemos el elemento seleccionado. var descripcion = SelectedOption.attr('descProducto'); var precio = SelectedOption.attr('precio'); var id_producto = SelectedOption.attr('id_producto'); $('#descripcion').val(descripcion); $('#precio').val(precio); $('#id_producto').val(id_producto); }); } </script> </head> <body> <div class="ui-widget"> Codigo: <select id="codigo"></select> Producto: <input type="text" id="descripcion" readonly> Precio: <input type="text" id="precio" readonly> <input type="hidden" id="id_producto"> <p>Ingresa 00</p> </div> </body> </html> Espero que te ayude, un saludo!!
{ "pile_set_name": "StackExchange" }
Q: Can multiple domains point to the same Azure web app? I'm using Azure for my website and I have 2 domain names that I would like to use for the same site. For example, I want these 2 domains www.abc.com and www.abc.asia to be the same website (not redirected). Such that www.abc.com/contactus and www.abc.asia/contactus will be the same page. A: Yes, this is possible (and easy to do). I did the following: Buy two separate domains. Configure the DNS A and TXT records of both domains to point to my Azure web app. On the Custom domains blade, clicked Add hostname to add each domain name. Both domain names now point to the same Azure web app.
{ "pile_set_name": "StackExchange" }
Q: Electric field below conducting plane In Griffiths introduction to Electrodynamics, the classic image problem is presented: There is a charge $q$, above a grounded conducting plane. Griffith says that the electric field below the plane is zero. My question is why is the electric field below the plane zero? Does not the induced charge on the plane create an electric field? A: Does not the induced charge on the plane create an electric field? Yes, of course it does. But don't forget that there is also the electric field of the point charge $q$ above the plane to consider. Remarkably, since this is the electrostatic case, it must be that the electric field of the induced charge precisely cancels the electric field of the point charge $q$ in the region below the plane. This must be the case since (1) there is no charge below the plane and (2) the electric potential must therefore satisfy Laplace's equation in that region. Assuming the potential is set to zero at $\pm \infty$, the fact that the grounded conducting plane is, by definition, at zero potential implies that the potential is zero in the region below the plane. If this were not the case, there would necessarily be a maximum or minimum of the potential in the region below the plane but then the potential would not satisfy Laplace's equation. From Wolfram Mathworld: A function $\psi$ which satisfies Laplace's equation is said to be harmonic. A solution to Laplace's equation has the property that the average value over a spherical surface is equal to the value at the center of the sphere (Gauss's harmonic function theorem). Solutions have no local maxima or minima (emphasis is mine) Since the potential is constant in the region below the plane, the electric field is necessarily zero.
{ "pile_set_name": "StackExchange" }
Q: Filtering a log file and extracts by different properties I have implemented a program to extract a log file which contains a header line, followed by zero or more data lines, in comma-separated value format. The file consists of 3 columns. The first column is the Unix time stamp, the second column is the country code, and the third column is the time in milliseconds. The data lines are not guaranteed to be in any particular order. There are three types of sample log files: Empty file Single lined file (file containing a header line and one data line) Multi lined file (file containing a header line and multi data lines) The code must work for all three input log file types. Sample file: TIMESTAMP,COUNTRY_CODE,RESPONSE_TIME 1511190458,US,500 1756118933,GB,137 DataFiltererTest.java public class DataFiltererTest { @Test public void shouldReturnEmptyCollection_WhenLogFileIsEmpty() throws FileNotFoundException { assertTrue(DataFilterer.filterByCountry(openFile("src/test/resources/empty"), "GB").isEmpty()); } @Test public void shouldReturnfilteredrows_ByCountry_WhenLogFileIsMultiLines() throws FileNotFoundException { String[] myArray = { "1433190845", "US", "539", "1433666287", "US", "789", "1432484176", "US", "850" }; Collection<?> expected = new ArrayList<String>(Arrays.asList(myArray)); assertEquals(expected, DataFilterer.filterByCountry(openFile("src/test/resources/multi-lines"), "US")); } @Test public void shouldReturnfilteredrows_ByCountry_WhenLogFileIsSingleLine() throws FileNotFoundException { String[] myArray = { "1431592497", "GB", "200" }; Collection<?> expected = new ArrayList<String>(Arrays.asList(myArray)); assertEquals(expected, DataFilterer.filterByCountry(openFile("src/test/resources/single-line"), "GB")); } @Test public void shouldReturnEmptyCollection_ByCountry_WhenLogFileIsSingleLine() throws FileNotFoundException { assertTrue(DataFilterer.filterByCountry(openFile("src/test/resources/single-line"), "US").isEmpty()); } @Test public void shouldReturnEmptyCollection_ByCountryWithResponseTimeAboveLimit_WhenLogFileIsEmpty() throws FileNotFoundException { assertTrue(DataFilterer .filterByCountryWithResponseTimeAboveLimit(openFile("src/test/resources/empty"), "GB", 10).isEmpty()); } @Test public void shouldReturnFilteredRows_ByCountryWithResponseTimeAboveLimit_WhenLogFileIsMultiLines() throws FileNotFoundException { String[] myArray = { "1433666287", "US", "789", "1432484176", "US", "850" }; Collection<?> expected = new ArrayList<String>(Arrays.asList(myArray)); assertEquals(expected, DataFilterer .filterByCountryWithResponseTimeAboveLimit(openFile("src/test/resources/multi-lines"), "US", 550)); } @Test public void shouldReturnFilteredRows_ByCountryWithResponseTimeAboveLimit_WhenLogFileIsSingleLine() throws FileNotFoundException { String[] myArray = { "1431592497", "GB", "200" }; Collection<?> expected = new ArrayList<String>(Arrays.asList(myArray)); assertEquals(expected, DataFilterer .filterByCountryWithResponseTimeAboveLimit(openFile("src/test/resources/single-line"), "GB", 150)); } @Test public void shouldReturnEmptyCollection_ByCountryWithResponseTimeAboveLimit_WhenLogFileIsSingleLine() throws FileNotFoundException { assertTrue(DataFilterer .filterByCountryWithResponseTimeAboveLimit(openFile("src/test/resources/single-line"), "GB", 200) .isEmpty()); } @Test public void shouldReturnEmptyCollection_ByCountryWithResponseTimeAboveAverage_WhenLogFileIsEmpty() throws FileNotFoundException { assertTrue(DataFilterer.filterByResponseTimeAboveAverage(openFile("src/test/resources/empty")).isEmpty()); } @Test public void shouldReturnFilteredRows_ByCountryWithResponseTimeAboveAverage_WhenLogFileIsMultiLines() throws FileNotFoundException { String[] myArray = { "1433190845", "US", "539", "1433666287", "US", "789", "1432484176", "US", "850" }; Collection<?> expected = new ArrayList<String>(Arrays.asList(myArray)); double average = getAverageForFilter("src/test/resources/multi-lines"); DataFilterer.setAverage(average); assertEquals(expected, DataFilterer.filterByResponseTimeAboveAverage(openFile("src/test/resources/multi-lines"))); } @Test public void shouldReturnEmptyCollection_ByCountryWithResponseTimeAboveAverage_WhenLogFileIsSingleLine() throws FileNotFoundException { double average = getAverageForFilter("src/test/resources/single-line"); DataFilterer.setAverage(average); assertTrue(DataFilterer.filterByResponseTimeAboveAverage(openFile("src/test/resources/single-line")).isEmpty()); } private double getAverageForFilter(String filename) throws FileNotFoundException { return new Average().findAverage(openFile(filename)); } private FileReader openFile(String filename) throws FileNotFoundException { return new FileReader(new File(filename)); } } DataFilterer.java public class DataFilterer { private static double average; // Method to set the average value of RESPONSETIME public static void setAverage(double avg) { average = avg; } // Method to get the average value of RESPONSETIME public static double getAverage() { return average; } public static Collection<?> filterByCountry(Reader source, String country) { BufferedReader br = new BufferedReader(source); String line = null; Collection<String> additionalList = new ArrayList<String>(); int iteration = 0; try { while ((line = br.readLine()) != null) { // Logic to remove header from the input data. if (iteration == 0) { iteration++; continue; } String[] myArray = line.split(","); List<String> myList = new ArrayList<String>(Arrays.asList(myArray)); if (myList.contains(country)) { additionalList.addAll(myList); } else { return Collections.emptyList(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return additionalList; } public static Collection<?> filterByCountryWithResponseTimeAboveLimit(Reader source, String country, long limit) { BufferedReader br = new BufferedReader(source); String line = null; Collection<String> additionalList = new ArrayList<String>(); int iteration = 0; long count = 0; long responseTime = 0; try { while ((line = br.readLine()) != null) { // Logic to remove header from the input data if (iteration == 0) { iteration++; continue; } String[] myArray = line.split(","); List<String> myList = new ArrayList<String>(Arrays.asList(myArray)); for (String eachval : myArray) { // Finding the RESPONSE TIME from the input line boolean isNumeric = eachval.chars().allMatch(x -> Character.isDigit(x)); if (isNumeric) { count = eachval.chars().count(); // Identifying between RESPONSETIME and // REQUEST_TIMESTAMP.Unix Timestamp will be always 10 // digits or 13 digits if (count < 10) { responseTime = Integer.parseInt(eachval); if (myList.contains(country)) { if (responseTime > limit) { additionalList.addAll(myList); } } else { return Collections.emptyList(); } } } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return additionalList; } public static Collection<?> filterByResponseTimeAboveAverage(Reader source) { BufferedReader br = new BufferedReader(source); String line = null; double average = 0.0; Collection<String> additionalList = new ArrayList<String>(); average = getAverage(); long responseTime = 0; int iteration = 0; long count = 0; String[] myArray = null; try { while ((line = br.readLine()) != null) { // Logic to remove header from the input data. if (iteration == 0) { iteration++; continue; } myArray = line.split(","); List<String> myList = new ArrayList<String>(Arrays.asList(myArray)); for (String eachval : myArray) { // Finding the RESPONSE TIME from the input line boolean isNumeric = eachval.chars().allMatch(x -> Character.isDigit(x)); if (isNumeric) { count = eachval.chars().count(); // Identifying between RESPONSETIME and // REQUEST_TIMESTAMP.Unix Timestamp will be always 10 // digits or 13 digits if (count < 10) { responseTime = Integer.parseInt(eachval); if (responseTime > average) { additionalList.addAll(myList); } else { return Collections.emptyList(); } } } } } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return additionalList; } } Average.java //This class is to find average of RESPONSETIME Field of input file public class Average { // Method to calculate the average of RESPONSETIME public double findAverage(Reader source) { BufferedReader br = new BufferedReader(source); String line = null; int iteration = 0; String[] myArray; Collection<Long> responseTimeList = new ArrayList<Long>(); long responseTime = 0; long count = 0; double average = 0.0; try { while ((line = br.readLine()) != null) { // Logic to remove header from the input file if (iteration == 0) { iteration++; continue; } myArray = line.split(","); for (String eachval : myArray) { // Finding the RESPONSE TIME field from the input line boolean isNumeric = eachval.chars().allMatch(x -> Character.isDigit(x)); if (isNumeric) { count = eachval.chars().count(); // Identifying between RESPONSETIME and // REQUEST_TIMESTAMP. Unix Timestamp will be always 10 // digits or 13 digits if (count < 10) { responseTime = Integer.parseInt(eachval); responseTimeList.add(responseTime); } } } } // Calculating the average average = responseTimeList.stream().mapToInt(Long::intValue).average().getAsDouble(); } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return average; } } The code works as expected for all the input file types. Please suggest improvements for this code. Also, please check and suggest whether I need to write this many number of test cases in TDD methodology. A: Quick skim results: The indentation is off. This might be an artefact of how you pasted the code into the question, though. Inconsistent use of newlines at the start and end of blocks. Sometimes you start a block and put an empty line at its start, sometimes you just don't put a newline there. The same goes for the end of blocks. You should be able to configure your formatting preferences to take care of that for you :) There's some leftover auto-generated TODO comments. If they are fixed, drop them :) Bugs! When any item in your logfile does not match its filter criteria, all the filter methods return an empty list. I don't think that's desired: Consider the following logfile: TIMESTAMP,COUNTRY_CODE,RESPONSE_TIME 1425859632,US,500 1452145245,GB,137 If you now call filterByCountry(logfile, "US"), the result is an empty list. That's most definitively not desired! There is a slim possibility that the caller of the method expects the Reader it passes to remain open. As of now you're closing the BufferedReader. Per the spec, closing a BufferedReader must also close its underlying Reader. This should not be much of an issue here, because you probably expected the method to consume the whole file anyways, but it's something to be aware of. It becomes significantly more relevant when you're handling Writers that follow the same mechanic, but are usually intended to be kept open. General approach: Your overall approach is most likely very slow. You're parsing possibly extreme quantities of files each time you want to filter by anything. If you run these "queries" a lot, you should strongly consider aggregating the log entries in a database. Databases are explicitly designed for querying and aggregation of high volumes of data. This could give you an extreme boost to performance. All RDBMS I know of support importing from CSV. You're also not making use of Object orientation at all. Currently log entries are stored contiguously in a List. This means that any code that consumes the log entries must know how many fields an entry has when iterating over that list. It also means that any change to the structure of your logging entries requires changes in the code using the results from the presented classes, that may not be obvious or even easy to find. To avoid this, you should model a LogEntry in a class, somewhat like this: @Value public class LogEntry { private long timestamp; private String countryCode; // possibly Locale? private int responseTime; } Sidenote: I'm using Lombok's @Value annotation here to automatically generate getters and a constructor for me. This allows you to make your filter methods return a significantly cleaner (and nicer) datatype than Collection<?> with contiguously stored data. Instead we get Collection<LogEntry>. This also exposes an issue with how you parse the log entries for filtering on RESPONSE_TIME. Currently you just assume that the response time is always less than 1000000000. That is probably a reasonable assumption. You also assume that it's the only value in the log entry that only contains digits and is shorter than 10 characters. That may be a less reasonable assumption (especially if the log-entry format changes). To find it in your entry you iterate all values in each entry and manually check each character for being numeric and then check the length of the entry as well. If the columns in your logfiles are always the same, that makes no sense. You know the columns, you know the index they have, make use of that knowledge. If you can only guarantee that the log entry columns are consistent in a single file and the header indicates how they are arranged, you should be using the header to determine the indices of your columns. Consider something like the following: public static Collection<LogEntry> filterByCountry(Reader source, String country) throws IOException { BufferedReader br = new BufferedReader(source); int timestampCol = -1; int countryCol = -1; int responseTimeCol = -1; String line = br.readLine(); // File completely empty, not even a header if (line == null) { return Collections.emptyList(); } String[] headers = line.split(","); for (int i = 0; i < headers.length; i++) { String h = headers[i]; if (h.equals("TIMESTAMP")) { timestampCol = i; continue; } if (h.equals("COUNTRY_CODE")) { countryCol = i; continue; } if (h.equals("RESPONSE_TIME")) { responseTimeCol = i; continue; } } Collection<LogEntry> result = new List<>(); while ((line = br.readLine()) != null) { String[] logEntry = line.split(","); LogEntry entry = new LogEntry(Long.parseLong(logEntry[timestampCol]) , logEntry[countryCol] , Integer.parseInt(logEntry[responsetimeCol])); if (entry.getCountry().equals(country)) { result.add(entry); } } return result; }
{ "pile_set_name": "StackExchange" }
Q: What is this layer of material in the kitchen floor? I have decided to replace the linoleum flooring in my kitchen with a layer of LVT Underlayment, and then Vinyl plank flooring. There were sections of the original floor that were not covered by the linoleum (underneath some, but not all counters) and so I began removing the existing linoleum. The layers of linoleum peel up easily enough, as it is still flexible enough to score with a blade, and roll it as I peel, however this leaves a white fiber-ish layer. That layer is glued down to what I originally assumed was the subfloor which I thought was plywood but one area of it began to scrape away quite easily as I was attempting to remove the glue. From other questions asked, I think it may be rosin paper, but it seems to be fairly thick and links to rosin paper do not seem to match that quality. After I removed the dishwasher, I discovered a small area of what looks to be OSB, and so I am now unsure, what exactly this layer that the linoleum is glued to would be. If the 4th layer (linoleum, white fiber / glue, brown unknown layer - maybe rosin paper?, OSB?) is in fact the true subfloor, would the best idea be to remove everything down to that, and glue the Vinyl Underlayment directly to that surface, before installing the free-floating vinyl planks? A: Looks like hardboard, often used as underlayment. Likely 1/8" thick. If so, you can remove or go over if in decent shape. Follow directions for additional underlayment for product you're installing either way.
{ "pile_set_name": "StackExchange" }
Q: ReferenceError: Can't find variable: should be calling method instead I try to request an URL every 5 seconds. The following code is returning ReferenceError: Can't find variable: validateUserTime $(document).ready(function() { ({ validateUserTime: function() { return $.get('/myurl', function(data) {}); } }); return window.setInterval((function() { validateUserTime(); }), 5000); }); I'm wondering what I'm doing wrong that is preventing a call to the method instead of doing it as a variable. Any idea? A: This simply defines an anonymous object and throws it away: ({ validateUserTime: function() { return $.get('/myurl', function(data) {}); } }); That doesn't define a validateUserTime function or method. You want something like this: var validateUserTime = function() { return $.get('/myurl', function(data) {}); }; or perhaps: function validateUserTime() { return $.get('/myurl', function(data) {}); } A: In the first statement, you are using an object literal without assigning it to anything. Assign it to something to fix it. $(document).ready(function() { var functions = { validateUserTime: function() { return $.get('/myurl', function(data) {}); } }; return window.setInterval((function() { functions.validateUserTime(); }), 5000); });
{ "pile_set_name": "StackExchange" }
Q: How to force a number to be in a range in C#? In C#, I often have to limit an integer value to a range of values. For example, if an application expects a percentage, an integer from a user input must not be less than zero or more than one hundred. Another example: if there are five web pages which are accessed through Request.Params["p"], I expect a value from 1 to 5, not 0 or 256 or 99999. I often end by writing a quite ugly code like: page = Math.Max(0, Math.Min(2, page)); or even uglier: percentage = (inputPercentage < 0 || inputPercentage > 100) ? 0 : inputPercentage; Isn't there a smarter way to do such things within .NET Framework? I know I can write a general method int LimitToRange(int value, int inclusiveMinimum, int inlusiveMaximum) and use it in every project, but maybe there is already a magic method in the framework? If I need to do it manually, what would be the "best" (ie. less uglier and more fast) way to do what I'm doing in the first example? Something like this? public int LimitToRange(int value, int inclusiveMinimum, int inlusiveMaximum) { if (value >= inclusiveMinimum) { if (value <= inlusiveMaximum) { return value; } return inlusiveMaximum; } return inclusiveMinimum; } A: This operation is called 'Clamp' and it's usually written like this: public static int Clamp( int value, int min, int max ) { return (value < min) ? min : (value > max) ? max : value; } A: I see Mark's answer and raise it by a this: public static class InputExtensions { public static int LimitToRange( this int value, int inclusiveMinimum, int inclusiveMaximum) { if (value < inclusiveMinimum) { return inclusiveMinimum; } if (value > inclusiveMaximum) { return inclusiveMaximum; } return value; } } Usage: int userInput = ...; int result = userInput.LimitToRange(1, 5) See: Extension Methods A: A much cleaner method that will work with more than just integers (taken from my own library of shared code): public static T Clamp<T>(T value, T min, T max) where T : IComparable<T> { if (value.CompareTo(min) < 0) return min; if (value.CompareTo(max) > 0) return max; return value; }
{ "pile_set_name": "StackExchange" }
Q: Using the symbol or '|' in r I tried to use the 'or' operator in R. However, it does not behave as expected. (4|6)==1 #TRUE #expected: FALSE (4|6)==6 #FALSE #expected: TRUE 6 %in% c(4,6) #TRUE The latter works as expected. I will use the list version, but why does the or operator behave like it behaves? If i ask whether a number is 4 or 6, I expect that 4 or 6 give me TRUE. However, only 1 is TRUE. A: Read what the page help('|') says (my emphasis): Numeric and complex vectors will be coerced to logical values, with zero being false and all non-zero values being true. So what happens is that both 4 and 6 are coerced to TRUE, then their disjunction is computed. Follow these examples. (4|6) #[1] TRUE (0|1) #[1] TRUE (0|0) #[1] FALSE The last is equivalent to FALSE|FALSE, the only way for a disjunction to give FALSE. What the question is asking for is the result of (4|6) == 1 #[1] TRUE After coercing non-zero 4 and non-zero 6 to the respective logical value, this becomes the same as (TRUE|TRUE) == 1 #[1] TRUE
{ "pile_set_name": "StackExchange" }
Q: One more batch of four sequence puzzles This is my fifth batch of sequence puzzles that are nasty and hard to solve; yet, each of them has a clear and justifiable solution. Sequence 1: T?M, AOT?, ROT?, AN?, T?SB, ROT?, TFA Sequence 2: 5, 12, ?, 14, 11, 8, 16, ?, 19, 3, 17, ?, 15, 10, ?, 13, 4, 18, ?, ... Sequence 3: T, u, b, d, l, ?, ?, ?, i, b, o, h, f Sequence 4: A, P, ?, L, S, A, P, A, ?, B, L, H, M, R, T, ?, M, M, M, ?, ?, ... A: Looking up gave me the answer for sequence 2: Number on a standard, London, or clock dartboard read in a counter- clockwise direction. Sequence: 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10, 6, 13, 4, 18, 1, ... A: Sequence 1: Star wars: * TPM = The Phantom Menace * AOTC = Attack of the Clones * ROTS = Revenge of the Sith * ANH = A New Hope * TESB = The Empire Strikes Back * ROTJ = Return of the Jedi * TFA = The Force Awakens Sequence 3: The letters of Stack Exchange, shifted by one position in the alphabet: S, t, a, c, k, E, x, c, h, a, n, g, e T, u, b, d, l, F, y, d, i, b, o, h, f A: Sequence 4: First letters of host cities for the Summer Olympics with the missing letters being A (Athens), P (Paris), S (St. Louis), L (London), S (Stockholm), A (Antwerp), P (Paris), A (Amsterdam), L (Los Angeles), B (Berlin), L (London), H (Helsinki), M (Melbourne), R (Rome), T (Tokyo), M (Mexico City), M (Munich), M (Montreal), M (Moscow), L (Los Angeles), S (Seoul), B (Barcelona), A (Atlanta), S (Sydney), A (Athens), B (Beijing), L (London), R (Rio de Janeiro), T (Tokyo)
{ "pile_set_name": "StackExchange" }
Q: Knockout JS: Visible applies to all elements inside foreach: loop, instead of the current one Basically I want visible: to fire up only on the div i hover over, but it applies to all of them, no matter which one I hover over. I guess that makes sense, since I am binding to visible: inside foreach: loop, so it is applied to all of them. Is there a KnockoutJS work-around, or should I just use $jQuery.hover() to make it work instead? Html: <div> <div data-bind="foreach: hostGroups"> <div data-bind="css: { style: true }, event: { mouseover: $root.showDeleteLink, mouseout: $root.hideDeleteLink }"> <span data-bind="text: hostName"></span> <span class="delete-link" data-bind="visible: $root.deleteLinkVisible">this is a delete link</span> </div> </div> </div>​ JavaScript: var data = [ { "hostName": "server1" }, { "hostName": "server2" }, { "hostName": "server3" } ]; var viewModel = { hostGroups: ko.observableArray(data), deleteLinkVisible: ko.observable(false), showDeleteLink: function() { viewModel.deleteLinkVisible(true); }, hideDeleteLink: function() { viewModel.deleteLinkVisible(false); } }; ko.applyBindings(viewModel); http://jsfiddle.net/pruchai/KXtTU/3/ A: You should implement hiding and showing the link on each individual item instead of on the root view model. For example: JavaScript: var data = [ { "hostName": "server1"}, { "hostName": "server2"}, { "hostName": "server3"} ]; function Item(hostName) { var self = this; this.hostName = ko.observable(hostName); this.deleteLinkVisible = ko.observable(false); this.showDeleteLink = function() { self.deleteLinkVisible(true); }; this.hideDeleteLink = function() { self.deleteLinkVisible(false); }; } function ViewModel() { var self = this; this.hostGroups = ko.observableArray(ko.utils.arrayMap(data, function(item) { var newItem = new Item(item.hostName); return newItem; })); } var viewModel = new ViewModel(); ko.applyBindings(viewModel);​ Html: <div> <div data-bind="foreach: hostGroups"> <div data-bind="css: { style: true }, event: { mouseover: showDeleteLink, mouseout: hideDeleteLink }"> <span data-bind="text: hostName"></span> <span class="delete-link" data-bind="visible: deleteLinkVisible">this is a delete link</span> </div> </div> </div>​ Example: http://jsfiddle.net/KXtTU/4/
{ "pile_set_name": "StackExchange" }
Q: Echarts pie chart cannot render on laravel blade? Laravel version:5.3 I am use this echarts demo: Here is my source php array from var_export: $pieData = array ( 0 => array ( 0 => 'date', 1 => '2019-12-12', 2 => '2019-12-13', 3 => '2019-12-14', 4 => '2019-12-15', 5 => '2019-12-16', 6 => '2019-12-17', 7 => '2019-12-18', 8 => '2019-12-19', 9 => '2019-12-20', 10 => '2019-12-21', 11 => '2019-12-23', 12 => '2019-12-24', 13 => '2019-12-25', ), 1 => array ( 0 => 'Central Region', 1 => 285, 2 => 365, 3 => 216, 4 => 129, 5 => 358, 6 => 339, 7 => 389, 8 => 1, 9 => 28, 10 => 0, 11 => 11, 12 => 1, 13 => 15, ), 2 => array ( 0 => 'Eastern Region', 1 => 160, 2 => 119, 3 => 106, 4 => 159, 5 => 141, 6 => 132, 7 => 107, 8 => 0, 9 => 0, 10 => 5, 11 => 17, 12 => 22, 13 => 0, ), 3 => array ( 0 => 'Western Region', 1 => 147, 2 => 196, 3 => 181, 4 => 48, 5 => 183, 6 => 175, 7 => 247, 8 => 5, 9 => 4, 10 => 15, 11 => 21, 12 => 2, 13 => 0, ), 4 => array ( 0 => 'Northern Region', 1 => 65, 2 => 24, 3 => 33, 4 => 10, 5 => 21, 6 => 40, 7 => 33, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, ), ); I passed the above array json_encode to the blade template,But the pie chart cannot be rendered,this is my code: setTimeout(function () { var dom = document.getElementById("submitOrderPie"); var myChart = echarts.init(dom); var app = {}; option = null; option = { legend: {}, tooltip: { trigger: 'axis', showContent: true }, dataset: { source: {!! $pieData !!}, }, xAxis: {type: 'category'}, yAxis: {gridIndex: 0}, grid: {top: '55%'}, series: [ @for($i=1;$i<count(json_decode($pieData));$i++) { type: 'line', smooth: true, seriesLayoutBy: 'row' }, @endfor { type: 'pie', id: 'pie', radius: '30%', center: ['50%', '25%'], label: { formatter: '{b}: {@2012} ({d}%)' }, encode: { itemName: 'date', value: '2012', tooltip: '2012' } } ] }; myChart.on('updateAxisPointer', function (event) { var xAxisInfo = event.axesInfo[0]; if (xAxisInfo) { var dimension = xAxisInfo.value + 1; myChart.setOption({ series: { id: 'pie', label: { formatter: '{b}: {@[' + dimension + ']} ({d}%)' }, encode: { value: dimension, tooltip: dimension } } }); } }); myChart.setOption(option); Effect after page loading: The effect of the mouse over the line chart: But if I move the mouse over the line chart, the pie chart above will be displayed.I want the pie chart to display after the page loads. I suspect it is a problem with the data format,But I use JSON.parse({!! $pieData !!}),still so. Thanks folks! A: The data format is OK.'s because the date I started rendering was set incorrectly,Like this series: [ { type: 'pie', id: 'pie', radius: '30%', center: ['50%', '25%'], label: { formatter: '{b}: {@2019-12-12} ({d}%)' }, encode: { itemName: 'date', value: '2019-12-12', tooltip: '2019-12-12' } } ]
{ "pile_set_name": "StackExchange" }
Q: A language design with variable qualifier I am planning to design a programming language. One challenge I face with is whether it is a good idea to have const as a variable qualifier instead of a type qualifier. For example in C++: const int x = 5; means that x is of type const int. While in my language, H++, the variable x is a const and its type is int. This will impact the AST design: | const as a variable qualifier | const as a type qualifier | | | | | x: | x: | | const: true | type: T | | type: T | | | | T: | | T: | typename: int | | typename: int | const: true | Besides the AST design, it will impact the templates too. For example: template<typename T> void myfunc(T arg) { ... } Now, depending on whether const a variable property or type property, the value of T will be different. If const is a variable property, T = int while if it is a type property, then T = const int. I am not sure whether this is a good idea or not. Questions: Is variable qualifier technically possible at all? What are the advantages and disadvantages of variable qualifier? Is there any commonly known programming language which has const or the other qualifier as a variable qualifier instead of type? A: This is hard to answer in isolation. A lot depends on the overall design of your language and the goals you want to reach. To quote Bjarne Stroustrup quoting Dennis Ritchie: “There are two kinds of programming languages: The ones that want to solve a problem and the ones that want to prove a point.” Which of the two is yours? What problem do your future users have now that you want to solve with the new language’s constness system? Or what’s the point you want to prove with the constness system? Answering that will probably make the best course of action a lot clearer. And now for a few hopefully helpful musings. Is variable qualifier technically possible at all? I don’t see any reason why it shouldn’t be. Roughly it boils down to the question of where to keep track of the information. What are the advantages and disadvantages of variable qualifier? There is at least one significant disadvantage. If you attach constness to the variable you pull it out of the type system proper. That makes the type system less expressive and leads me to a follow-up question to your template example: How would you model something like variant<T, const U, const V>? Making everything const by default – although an attractive idea in general – doesn’t help here either. The question then just reverses to: How do you model a variant<mutable T, U, V>? In the end, type based meta programming would be less powerful overall. I have a hard time to come up with any significant advantage of making const a variable qualifier. I was thinking along the lines of simpler type-based matching algorithms at first. But that doesn’t work. If you don’t want to punch huge holes in your const correctness, there’s no way around including it when searching for matching types. I have a feeling that most (all?) other potential advantages will fail for the same reason. Are these really advantages and disadvantages as stated? That depends entirely on the goals of your language. Even throwing out constness altogether can be the right choice. Just look at Python. Maybe both options are useful. Two kinds of constness are in play, so maybe you want to use both attachement points. One kind of constness is a property of the object type itself. Nobody is allowed to mutate, period. In C++: void mutable_foo(Type& t); int main() { const Type t; // constant object mutable_foo(t); // non-constant usage: does not compile } The other kind of constness is a property of the usage of an object. It’s a way to selectively restrict mutable access. In C++: void const_foo(const Type& t); int main() { Type t; // non-constant object const_foo(t); // constant usage: compiles ok } You could make object constness a part of the object’s type and usage constness a property of the variable. That way you still have access to the full type of the original object inside the function. In contrast in C++ there is no way to determine whether the underlying object of a const& argument is const itself or not. Another idea to use both attachment points would be to control rebindability of variables. In C++ that would be the difference between a const pointer and a pointer to const. Could something similar be useful for values, too? Both ideas aim at finer grained control over different aspects of and different targets for constness. From the theoretical and language design side there’s definitely a lot to explore here. From the practical programmer’s side, I don’t have an immediate application in mind for such a level of control. But I’m anything but objective in that regard.
{ "pile_set_name": "StackExchange" }