text
stringlengths
64
81.1k
meta
dict
Q: unexpected token:where when using spring data jpa with hibernate I am trying to use spring data jpa and hibernate in my project. I added the annotation @Query in repository, trying to write a hql with a Pageable argument passed in like this: @Query("select name,code,id from Region where fatherId is NULL or fatherId=''") Page<Region> findAllRoots(Pageable pageable); but when I tried to compile and run it, I got unexpected token: where printed on console. Full info is: Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: where near line 1, column 14 [select count(where) from com.nitccs.demo.entity.Region where fatherId is NULL or fatherId=''] How could it ran like this? I am totally confused. Why it is not select count(id) or something? I am sure I got no variable named where in my pojo. A: You need an alias in your query in order for the count query necessary for Pageable results getting created correctly. So this should work. select r from Region r where r.fatherId is NULL or r.fatherId='' A: In you above query, you are doing wrong, you are expecting name,code,id and how this will convert into Region object if you want data with pagination try to use SpringData specifications click here to have a look on this
{ "pile_set_name": "StackExchange" }
Q: Find and replace with MySQL version 5.5.3 I am trying to find a weird character thats in front of my £ sign and replace it with nothing. Coding I tried was update [orders_total] set [text]=replace([text],'[Â]','[]'); but mysql returns this 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[orders_total] set [text]=replace([text],'[Â]','[]')' at line 1 I know nothing of Mysql but its going to take me ages to manually remove these chars so any help would be much appreciated. Thanks in advance A: Thats not mysql syntax and in mysql it should be as update orders_total set text=replace(text,'Â','');
{ "pile_set_name": "StackExchange" }
Q: Only One Product and Product-view on frontsite I would like to use Magento to sell only one Product with multiple product Attributes in my Store. So i want my ONLY product on the start site of the Magento Store with some Product Attribute Dropboxes. I ve seen that this is possible on sites like: www.sita-shop.de you can see this is a magento theme customized and there is just 1 product and its on the start site of magento store. would be very nice if anyone knows how to handle this and would help me. thanks ! A: Magento admin panel > System > Configuration > Under General > Web > Default Pages. You'll find a Default Web URL which points to cms by default. You can then use catalog/product/view/id/123 (replace 123 with your product id) and the homepage will by default go to your single product page.
{ "pile_set_name": "StackExchange" }
Q: Is consumable in-app purchase is available with different tires? I am bit new for in-App purchase. I want user to buy different digital content with different price. Like i have list of video but user can only buy a single video which he/she select. (after purchasing any video i will manage from my server side to make that video available to user). But there can be possibility many video in single tier and i want user buy again same tire for another video. so i think i have to go with consumable type. But i am not sure consumable IAP is available with tires or not? A: For a given product identifier, it will have a single tier assignment. Answering your question "literally", the answer is "no". As you have a server you can work around this. The better solution if you want to control tier pricing is to have your server vend to the client (the app) the appropriate product identifier to use. The net effect of this would achieve what you want. This does mean slightly more complicated server to managed the proper vending of product identifiers to video. And depending on your approach, you may need some handshaking with the server or maintain some state on the client (all server solution is best here if it can be done). Actually, this method in general is better, as it also provides the means to be extended into a flexible A/B testing scheme to test pricing.
{ "pile_set_name": "StackExchange" }
Q: Do I simply delete the bashrc 'return' command? I've been advised to remove the return command from my bashrc file in order to allow Ruby Version Manager to function properly. Do I simply delete the return command, or do I replace it with some other command? I am hesitant to mess with my System-wide shell without some proper direction. But I would really like to get RVM working as it is a time saver. My bashrc is located in the etc directory and looks like this: # System-wide .bashrc file for interactive bash(1) shells. if [ -z "$PS1" ]; then return fi PS1='\h:\W \u\$ ' # Make bash check its window size after a process completes shopt -s checkwinsize if [[ -s /Users/justinz/.rvm/scripts/rvm ]] ; then source /Users/justinz/.rvm/scripts/rvm ; fi The last line, is an insert, described in the RVM installation. A: I wouldn't. That return is probably there for a good reason. It obviously doesn't want to execute anything after that if the PS1 variable is empty. I would just move the inserted line up above the if statement. In addition, if that's actually in the system-wide bashrc file, you should be using something like: ${HOME}/.rvm/scripts/rvm rather than: /Users/justinz/.rvm/scripts/rvm I'm sure Bob and Alice don't want to run your startup script. If it's actually your bashrc file (in /Users/justinz), you can ignore that last snippet above.
{ "pile_set_name": "StackExchange" }
Q: running a command after the ssh has opened the tunnel I want to run some process that requires an opened ssh tunnel. How do you run some command AFTER the ssh tunnel is successfully opened? Timers are not good enough as network speed and remote machine load might heavily affect the time needed to open up the connection... --UPDATE-- I want to open the tunnel and run the command on the local machine A: You can use LocalCommand ssh option, but there are some limitations. From man ssh_config: LocalCommand Specifies a command to execute on the local machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. The following escape character substitutions will be performed: ‘%d’ (local user's home directory), ‘%h’ (remote host name), ‘%l’ (local host name), ‘%n’ (host name as provided on the command line), ‘%p’ (remote port), ‘%r’ (remote user name) or ‘%u’ (local user name). The command is run synchronously and does not have access to the session of the ssh(1) that spawned it. It should not be used for interactive commands. This directive is ignored unless PermitLocalCommand has been enabled. Here is quick example: ssh -v -o PermitLocalCommand=yes -o 'LocalCommand=/bin/date >/tmp/test' localhost Later, you probably need to put those options into proper Host section in $HOME/.ssh/config file.
{ "pile_set_name": "StackExchange" }
Q: Store Image in DataTable I want to store image into my datatable and while adding colum I want to set its default value, sending you code doing with checkboxes.. public void addCheckBoxesRuntime(){ for (int i = 0; i < InformationOne.Length; i++) { dt = new DataColumn(InformationOne[i][1] + " (" + InformationOne[i][0] + " )"); dt.DataType = typeof(Boolean); viewDataTable.Columns.Add(dt); dt.DefaultValue = false; } } A: Make a DataColumn with type string and then store the string binary of the image into the field. Alternatively, use the binary itself with a byte[]. Should work 100%. Something along the lines of this: public string ImageConversion(System.Drawing.Image image) { if (image == null) return string.Empty; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif); string value = string.Empty; for (int intCnt = 0; intCnt <= memoryStream.ToArray.Length - 1; intCnt++) { value = value + memoryStream.ToArray(intCnt) + ","; } return value; } }
{ "pile_set_name": "StackExchange" }
Q: Find sublists with common starting elements - python I have a nested list: lists =[['a','b','c'], ['a','b','d'], ['a','b','e'], ['с','с','с','с']] I need to find sublists with 2 or more common (2 or more occurrences) first elements, make a single string from this elements, and make a single string from sublists, which does not contain common first elements. Sublists can go in different order, so just checking next or previous element is the wrong way, I suppose. Desired output: [['a b','c'], ['a b','d'], ['a b','e'], ['с с с с']] I tried some for loops, but with no success. I currently don't know, where to start, so any help would be appreciated. Thank you for your time! A: Probably not the most efficient way, but you could try something like this: def foo(l,n): #Get all of the starting sequences first_n = [list(x) for x in set([tuple(x[:n]) for x in l])] #Figure out which of those starting sequences are duplicated duplicates = [] for starting_sequence in first_n: if len([x for x in l if x[:n] == starting_sequence])>2: duplicates.append(starting_sequence) #make changes result = [] for x in l: if x[:n] in duplicates: result.append([" ".join(x[:n])]+x[n:]) else: result.append([" ".join(x)]) return result Set's have no repeats, but elements of sets must be hashable. Since lists are unhashable, that is why I have converted them into tuples and then back into lists.
{ "pile_set_name": "StackExchange" }
Q: set environment variable with whitespaces in the value using withEnv in Jenkinsfile I need to have the effect of MAVEN_OPTS="-server -Xms4G -Xmx4G" mvn clean verify -f pom.xml with Jenkinsfile. The below does not work. What is the correct syntax for it? withEnv(['MAVEN_OPTS="-server -Xms4G -Xmx4G"']) { sh 'mvn clean verify -f pom.xml' } A: Just remove double quotes after the equals sign withEnv(['MAVEN_OPTS=-server -Xms4G -Xmx4G']) { sh 'mvn clean verify -f pom.xml' }
{ "pile_set_name": "StackExchange" }
Q: Multiple Instances of the same Fragment in a FragmentStatePagerAdapter I have a FragmentStatePagerAdapter which displays different instances of the same fragment but having different data, as shown: class MyAdapter extends FragmentStatePagerAdpater{ public MyAdapter (FragmentManager fm){ super(fm); } public Fragment getItem(int i){ Frag f = new Frag(); f.setState(i); //sets the value of the "State" instance variable //of the fragment return f; } public int getCount(){ return 100; } } Now, my question is that as the FragmentStatePagerAdapter saves the state of a fragment instance before it destroys them, and as the different instances may have different data saved in the onSaveInstanceState, then how does the FragmentStatePagerAdapter decide which savedInstanceState to be restored on re-creation of the Fragment instances when they need to be re-displayed? A: If you look at the source code to FragmentStatePagerAdapter, it looks like the state is saved and restored based on position.
{ "pile_set_name": "StackExchange" }
Q: PRISM2 commands and silverlight I have noticed a strange behaviour when using the command functionality in Silverlight: When the adding the commands:Click.Command and CommandParameter property, the IsEnabled property stops functioning: <Button Content="Delete" x:Name="Btn_Delete" Margin="0,0,8,0" MinWidth="75" commands:Click.Command="{Binding DeleteCommand}" commands:Click.CommandParameter="{Binding SelectedDepartment}" IsEnabled="false" /> If I remove the commands: attributes the IsEnabled functions correctly. This behaviour is the same if IsEnabled is bound to a value on my view model too. Is this a bug? Anyone know of any work arounds? Thanks, Mark A: Here is the proper answer too: http://compositewpf.codeplex.com/Thread/View.aspx?ThreadId=50456&ANCHOR&ProjectName=CompositeWPF
{ "pile_set_name": "StackExchange" }
Q: How to deal with people copy'ing your edit I've had a weird situation where I improved a post a lot, there were over 20 grammatical mistakes that were all fixed. However, the person who asked the question did not accept my edit: Instead he copied it over and made his own edit, resulting in a negative edit suggestion in my account. The question here is mainly, is there a way to remove this history from my account? I know it is not really a big problem, especially since the asker did not really did something wrong: He probably has no understanding of SO yet. But I'm trying to get as many edits approved, and this kinda makes me not want to edit these questions anymore. In case you're wondering: I'm talking about the following edit: https://stackoverflow.com/posts/28626514/revisions [Asker edit] https://stackoverflow.com/review/suggested-edits/7107069 [My edit] A: Their edit and yours conflicted. It was automatically rejected, and doesn't count against you. See Edit ban because of Community rejections It looks to me like an honest mistake here; the OP tried to take your edit to heart and included the changes. They just didn't know how to approve your edit properly. There isn't anything that needs to be done here; the edit got applied, the rejection doesn't affect your record.
{ "pile_set_name": "StackExchange" }
Q: Create UIView programmatically in Swift I am generating View and setting constraints programmatically in UIViewController import UIKit import SnapKit class LoginViewController: UIViewController { lazy var topImageView = UIImageView() lazy var centerStackView = UIStackView() lazy var phoneTextField = UITextField() lazy var sendOTPButton = UIButton() lazy var bottomStackView = UIStackView() lazy var separatorLine = UILabel() lazy var signUpButton = UIButton() override func viewDidLoad() { super.viewDidLoad() makeUI() } private func makeUI() { self.view.backgroundColor = .white self.view.addSubview(topImageView) topImageView.backgroundColor = UIColor.magenta.withAlphaComponent(0.4) topImageView.snp.makeConstraints {(make) -> Void in make.width.equalToSuperview() make.height.equalTo(225) make.topMargin.equalToSuperview() make.centerX.equalToSuperview() } centerStackView.translatesAutoresizingMaskIntoConstraints = false centerStackView.axis = .vertical centerStackView.distribution = .fillEqually self.view.addSubview(phoneTextField) self.view.addSubview(sendOTPButton) self.view.addSubview(centerStackView) centerStackView.addArrangedSubview(phoneTextField) centerStackView.addArrangedSubview(sendOTPButton) phoneTextField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2) phoneTextField.delegate = self sendOTPButton.setTitle("Send OTP", for: .normal) sendOTPButton.addTarget(self, action: #selector(generateAccessToken), for: .touchUpInside) sendOTPButton.backgroundColor = .blue centerStackView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.equalToSuperview() make.height.equalTo(100) } bottomStackView.translatesAutoresizingMaskIntoConstraints = false bottomStackView.axis = .vertical bottomStackView.distribution = .fillProportionally self.view.addSubview(separatorLine) self.view.addSubview(signUpButton) self.view.addSubview(bottomStackView) bottomStackView.addArrangedSubview(separatorLine) bottomStackView.addArrangedSubview(signUpButton) separatorLine.backgroundColor = .white signUpButton.backgroundColor = .orange bottomStackView.snp.makeConstraints { (make) in make.bottomMargin.equalTo(additionalSafeAreaInsets) make.width.equalToSuperview() make.height.equalTo(80) } } The makeUI functions essentially creates the views, adds them to UIController's view (as a subview) and set constraints on them (AutoLayout). But the ViewController become bulky if more UIViews are added. My question is: Should I move the UI code to another file (say LoginView.swift)? Or is it recommended to keep the UI code in UIViewController as they are tightly coupled? A: You can move setting properties to lazy var declarations eg. lazy var centerStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.distribution = .fillEqually return stackView }() This will divide your code nicely. In my opinion, extracting views to separate files has a sense only if they have a more complex structure and you want to reuse them in other places. What is important is keeping functions short and on point. Also, try to use more empty lines to visually divide logic blocks, eg. adding subview and setting constraints to it from another subview. A: The other obvious alternative, which you haven’t contemplated here, is to design it right in the storyboard or NIB in Interface Builder, which would eliminate all of this code. The only view creation related code that I would put in the view controller is those just-in-time adjustments/subviews that cannot be determined at design-time, but rather are dictated by the presence or absence of relevant model data. Anyway, if you do that, then the view controller can focus on its core responsibilities: A view controller’s main responsibilities include the following: Updating the contents of the views, usually in response to changes to the underlying data. Responding to user interactions with views. Resizing views and managing the layout of the overall interface. Coordinating with other objects—including other view controllers—in your app.
{ "pile_set_name": "StackExchange" }
Q: Continuously poll as a background service So I was reading this topic: Continuously poll a REST service in Grails What I'm looking for is slightly different. I want to continually update a list of users so I want to create an endless loop that will run as a background service that continually grabs the next user, makes a REST call, update the user, and then grabs the next one. I thought about implementing quartz, but because a REST call is being made I don't want to have multiple threads running or set it on some cadence. I'd rather if a single thread continually ran and when the user is updated it continues onto the next user. If anything, I'd want a quartz job to check to make sure the loop is still properly looping and re-start it if the thread dies for some reason. A: In the end, I implemented this with quartz. There is a setting allows me to avoid multiple threads from running simultaneously and I've never run into issues where the thread dies unless an exception isn't handled. def concurrent = false From the Quartz Plugin Documentation: "By default Jobs are executed in concurrent fashion, so new Job execution can start even if previous execution of the same Job is still running. If you want to override this behavior you can use 'concurrent' property, in this case Quartz's StatefulJob will be used"
{ "pile_set_name": "StackExchange" }
Q: Given a symmetric matrix $A$, find $P$ such that $P^T A P$ is a diagonal matrix Given $$A =\begin{pmatrix} 0 & 3 & 0 \\ 3 & 0 & 4 \\ 0 & 4 & 0\end{pmatrix}$$ find a matrix $P$ such that $P^T A P$ orthogonally diagonalizes $A$. Verify that $P^TAP$ is diagonal. I'm not sure how to approach this problem. Any help is appreciated. Thanks! A: You want to find the eigenvalues and eigenvectors of $A$. Since $A$ is a real symmetric matrix, the eigenvectors should be orthogonal if the eigenvalues are distinct (which it is in this case): if they were not distinct you might have to use the Gram-Schmidt procedure to make the eigenvectors orthogonal. Divide each by its length, so they are orthonormal. Then form the matrix $P$ whose columns are those orthonormal eigenvectors.
{ "pile_set_name": "StackExchange" }
Q: Enabling/Disabling Microsoft Virtual WiFi Miniport I disabled my Microsoft Virtual WiFi Miniport network adapter from Control Panel\Network and Internet\Network Connections. Just right clicked on the miniport nic and clicked disable, and its gone. Now how could I enable it? After disabling the nic, netsh wlan start hostednetwork is not working any more. The response is, The hosted network couldn't be started. The group or resource is not in the correct state to perform the requested operation. It was working flawlessly, before I disabled the adapter, Anyway, for reference here is the output of netsh wlan show drivers, Interface name: Wi-Fi Driver : Qualcomm Atheros AR9285 Wireless Network Adapter Vendor : Qualcomm Atheros Communications Inc. Provider : Microsoft Date : 7/3/2012 Version : 3.0.0.130 INF file : C:\Windows\INF\netathrx.inf Files : 2 total C:\Windows\system32\DRIVERS\athrx.sys C:\Windows\system32\drivers\vwifibus.sys Type : Native Wi-Fi Driver Radio types supported : 802.11b 802.11g 802.11n FIPS 140-2 mode supported : Yes 802.11w Management Frame Protection supported : Yes Hosted network supported : Yes Authentication and cipher supported in infrastructure mode: Open None Open WEP-40bit Open WEP-104bit Open WEP WPA-Enterprise TKIP WPA-Personal TKIP WPA2-Enterprise TKIP WPA2-Personal TKIP Vendor defined TKIP WPA2-Enterprise Vendor defined Vendor defined Vendor defined WPA-Enterprise CCMP WPA-Personal CCMP WPA2-Enterprise CCMP Vendor defined CCMP WPA2-Enterprise Vendor defined Vendor defined Vendor defined WPA2-Personal CCMP Vendor defined Vendor defined Authentication and cipher supported in ad-hoc mode: Open None Open WEP-40bit Open WEP-104bit Open WEP WPA2-Personal CCMP Vendor defined Vendor defined netsh wlan show hostednetwork, Hosted network settings Mode : Allowed SSID name : "aczire" Max number of clients : 100 Authentication : WPA2-Personal Cipher : CCMP Hosted network status Status : Not available After executing, netsh wlan set hostednetwork mode=allow The hosted network mode has been set to allow. But again in, netsh wlan show hostednetwork Hosted network settings Mode : Allowed SSID name : "aczire" Max number of clients : 100 Authentication : WPA2-Personal Cipher : CCMP Hosted network status Status : Not available netsh wlan show settings Wireless LAN settings Show blocked networks in visible network list: No Only use GP profiles on GP-configured networks: No Hosted network mode allowed in WLAN service: Yes Allow shared user credentials for network authentication: Yes Block period: Not Configured. Auto configuration logic is enabled on interface "Wi-Fi" Any idea how to re-enable the Microsoft Virtual WiFi Miniport adapter (in Windows 8 Pro RTM)? I'm at my wits end, Please help :( A: You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it. After that, you start your cmd with admin privileges, then try: netsh wlan start hostednetwork A: From accepted answer: You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it Maybe your device is hidden - first you should unhide it from the device manger, then re-enable the adapter from the device manger tools. A: I had the exact problem and I couldn't find the hosted network adapter in network connections or device manager. So what I did was to disable and enable the wifi adapter after this the hosted network adapter should be listed in the device manager, then you just enable the adapter from there.
{ "pile_set_name": "StackExchange" }
Q: Getting values from mouse hover on a class object C# I've a txt file with a 360 numbers, I must read all of these and draw a kind of Disc made of FillPie eachone colored in scale of grey due to the value of the list. Until here everything is quite simple.I made a class with the data(value in the txt and degree) of one single fillpie with a Paint method that draw it of the correct color. this is the code of the class: class DatoDisco { int valoreSpicchio; int gradi; public DatoDisco(int valoreTastatore, int gradiLettura) { valoreSpicchio = valoreTastatore; gradi = gradiLettura; } public void Clear() { valoreSpicchio = 0; gradi = 0; } private int ScalaGrigi() { int grigio = 0; if (valoreSpicchio <= 0) { grigio = 125 + (valoreSpicchio / 10); if (grigio < 0) grigio = 0; } if (valoreSpicchio > 0) { grigio = 125 + (valoreSpicchio / 10); if (grigio > 230) grigio = 230; } return grigio; } public void Paint (Graphics grafica) { try { Brush penna = new SolidBrush(Color.FromArgb(255, ScalaGrigi(), ScalaGrigi(), ScalaGrigi())); grafica.FillPie(penna, 0, 0, 400, 400, gradi, 1.0f); } catch { } } public int ValoreSpicchio { get { return valoreSpicchio; } } public int Gradi { get { return gradi; } } } here is where I draw everything: public partial class Samac : Form { libnodave.daveOSserialType fds; libnodave.daveInterface di; libnodave.daveConnection dc; int rack = 0; int slot = 2; int scalaGrigi = 0; int angolatura = 0; List<int> valoriY = new List<int>(); //Disco disco = new Disco(); List<DatoDisco> disco = new List<DatoDisco>(); float[] valoriTastatore = new float[360]; public Samac() { InitializeComponent(); StreamReader dataStream = new StreamReader("save.txt"); textBox1.Text = dataStream.ReadLine(); dataStream.Dispose(); for (int i = 0; i <= 360; i++ ) chart1.Series["Series2"].Points.Add(0); //AggiornaGrafico(textBox1.Text, chart1); SetStyle(ControlStyles.SupportsTransparentBackColor, true); } string indirizzoIpPlc { get { FileIniDataParser parser = new FileIniDataParser(); IniData settings = parser.LoadFile("config.ini"); return settings["PLC_CONNECTION"]["PLC_IP"]; } } private void AggiornaGrafico(string nomeFile, Chart grafico, bool online) { int max = 0; int min = 0; grafico.Series["Series1"].Points.Clear(); grafico.Series["Series2"].Points.Clear(); grafico.Series["Series3"].Points.Clear(); grafico.Series["Series4"].Points.Clear(); grafico.ChartAreas[0].AxisX.Maximum = 360; grafico.ChartAreas[0].AxisX.Minimum = 0; grafico.ChartAreas[0].AxisY.Maximum = 500; grafico.ChartAreas[0].AxisY.Minimum = -500; String file = nomeFile; valoriY.Clear(); disco.Clear(); if (online == false) { System.IO.File.WriteAllText("save.txt", nomeFile); } StreamReader dataStreamGrafico = new StreamReader(file); StreamReader dataStreamScheda = new StreamReader("Scheda.sch"); string datasample; string[] scheda = new string[56]; for (int i = 0; i < 56; i++) { scheda[i] = dataStreamScheda.ReadLine(); } dataStreamScheda.Close(); int gradi = 1; while ((datasample = dataStreamGrafico.ReadLine()) != null) { grafico.Series["Series2"].Points.Add(0); grafico.Series["Series2"].Color = Color.Red; grafico.Series["Series2"].BorderWidth = 3; grafico.Series["Series3"].Points.Add(Convert.ToInt32(float.Parse(scheda[5]))); grafico.Series["Series3"].Color = Color.Green; grafico.Series["Series3"].BorderWidth = 3; grafico.Series["Series4"].Points.Add(Convert.ToInt32(-float.Parse(scheda[5]))); grafico.Series["Series4"].Color = Color.Green; grafico.Series["Series4"].BorderWidth = 3; grafico.Series["Series1"].Points.Add(int.Parse(datasample)); grafico.Series["Series1"].BorderWidth = 5; valoriY.Add(int.Parse(datasample)); //disco.Add(int.Parse(datasample)); disco.Add(new DatoDisco(int.Parse(datasample), gradi)); gradi++; } dataStreamGrafico.Close(); max = Convert.ToInt32(chart1.Series["Series1"].Points.FindMaxByValue().YValues[0]); min = Convert.ToInt32(chart1.Series["Series1"].Points.FindMinByValue().YValues[0]); lblCampanatura.Text = (((float)max + min) / 2000.0).ToString(); lblSbandieramento.Text = (((float)max - min) / 1000.0).ToString(); if ((Math.Abs(max) > 800) || (Math.Abs(min) > 800)) { if (Math.Abs(max) >= Math.Abs(min)) { chart1.ChartAreas[0].AxisY.Maximum = max + 200; chart1.ChartAreas[0].AxisY.Minimum = -(max + 200); } else { chart1.ChartAreas[0].AxisY.Maximum = min + 200; chart1.ChartAreas[0].AxisY.Minimum = -(min + 200); } } else { chart1.ChartAreas[0].AxisY.Maximum = 800; chart1.ChartAreas[0].AxisY.Minimum = -800; } boxGraficaDisco.Refresh(); } private void button1_Click(object sender, EventArgs e) { DialogResult result = openFileDialog1.ShowDialog(); textBox1.Text = openFileDialog1.FileName; if (result == DialogResult.OK) { AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled); } } ToolTip tooltip = new ToolTip(); private int lastX; private int lastY; private void chart1_MouseMove(object sender, MouseEventArgs e) { if (e.X != this.lastX || e.Y != this.lastY) { try { int cursorX = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X)); tooltip.Show("X:" + cursorX.ToString("0.00") + "Y:" + Convert.ToInt32(chart1.Series[0].Points[cursorX].YValues[0]).ToString(), this.chart1, e.Location.X + 20, e.Location.Y + 20); } catch { } } this.lastX = e.X; this.lastY = e.Y; } private void button1_Click_1(object sender, EventArgs e) { int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5]))+1; if (File.Exists(textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt")) { textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"; try { AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled); } catch { MessageBox.Show("Il File non esiste"); } } else { MessageBox.Show("Il File non esiste"); } } private void btnGrafMeno_Click(object sender, EventArgs e) { int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5])) - 1; if (indice >= 0) { textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"; try { AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled); } catch { MessageBox.Show("Il File non esiste"); } } else { MessageBox.Show("Prima lettura disco"); } } private void btnConnetti_Click(object sender, EventArgs e) { fds.rfd = libnodave.openSocket(102, indirizzoIpPlc); fds.wfd = fds.rfd; if (fds.rfd > 0) { di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k); di.setTimeout(1000000); dc = new libnodave.daveConnection(di, 0, rack, slot); int res = dc.connectPLC(); timer1.Start(); // AggiornaGrafico("Disco.csv", chart1, timer1.Enabled); } else { MessageBox.Show("Impossibile connettersi"); } } private void timer1_Tick(object sender, EventArgs e) { if (timer1.Enabled == true) { int res; res = dc.readBytes(libnodave.daveDB, 21, 40, 1, null); if (res == 0) { var letturaDati = (dc.getS8At(0) & (1 << 0)) != 0; if (letturaDati == true) { int puntatore = 30; StreamWriter datiDisco = new StreamWriter("DatiDaPlc.csv"); datiDisco.WriteLine("X;" + "C;" + "Z;"); while (puntatore <= 10838) { res = dc.readBytes(libnodave.daveDB, 3, puntatore, 192, null); if (res == 0) { for (int i = 0; dc.getU32At(i) != 0; i = i + 12) { datiDisco.Write(dc.getU32At(i).ToString() + ";"); datiDisco.Write(dc.getU32At(i + 4).ToString() + ";"); datiDisco.WriteLine(dc.getFloatAt(i + 8).ToString() + ";"); } } puntatore = puntatore + 192; } datiDisco.Close(); StreamReader lettura = new StreamReader("DatiDaPlc.csv"); StreamWriter scritt = new StreamWriter("Disco.csv"); var titolo = lettura.ReadLine(); var posizioneLettura = lettura.ReadLine(); var posX = posizioneLettura.Split(';'); int minX = Convert.ToInt32(posX[0]) - 5; int maxX = Convert.ToInt32(posX[0]) + 5; int contatore = 0; while (!lettura.EndOfStream) { var line = lettura.ReadLine(); var values = line.Split(';'); if ((Convert.ToInt32(values[1]) >= contatore && Convert.ToInt32(values[1]) < contatore + 1000) && (Convert.ToInt32(values[0]) > minX && Convert.ToInt32(values[0]) <= maxX)) { scritt.WriteLine(Convert.ToInt32(float.Parse(values[2]) * 1000).ToString()); contatore += 1000; } } lettura.Close(); scritt.Close(); AggiornaGrafico("Disco.csv", chart1, timer1.Enabled); } } else { timer1.Stop(); MessageBox.Show("Disconnesso"); dc.disconnectPLC(); di.disconnectAdapter(); fds.rfd = libnodave.closeSocket(102); fds.wfd = fds.rfd; } } } private void btnDisconnetti_Click(object sender, EventArgs e) { if (timer1.Enabled == true) { dc.disconnectPLC(); di.disconnectAdapter(); fds.rfd = libnodave.closeSocket(102); fds.wfd = fds.rfd; timer1.Stop(); AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled); } } private void Samac_FormClosing(object sender, FormClosingEventArgs e) { if (timer1.Enabled == true) { dc.disconnectPLC(); di.disconnectAdapter(); libnodave.closeSocket(102); timer1.Stop(); } } private void button1_Click_2(object sender, EventArgs e) { if (timer1.Enabled == true) { AggiornaGrafico("Disco.csv", chart1, timer1.Enabled); } else { AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled); } } private void chart2_MouseMove(object sender, MouseEventArgs e) { if (e.X != this.lastX || e.Y != this.lastY) { try { int cursorX = Convert.ToInt32(chart2.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X)); int cursorY = Convert.ToInt32(chart2.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y)); //tooltip.Show("X:" + chart2.Series[0].Points[cursorX].XValue.ToString() + "Y:" + chart2.Series[0].Points[cursorX].YValues[0].ToString(), this.chart2, e.Location.X + 20, e.Location.Y + 20); tooltip.Show("X:" + cursorX.ToString() + "Y:#VALY" , this.chart2, e.Location.X + 20, e.Location.Y + 20); //chart2.Series[0].ToolTip="#VALY"; } catch { } } this.lastX = e.X; this.lastY = e.Y; } private void boxGraficaDisco_Paint(object sender, PaintEventArgs e) { Graphics grafica = e.Graphics; //disco.Paint(grafica); foreach (DatoDisco d in disco) { d.Paint(grafica); } } private void boxGraficaDisco_MouseMove(object sender, MouseEventArgs e) { if (e.X != this.lastX || e.Y != this.lastY) { try { foreach (DatoDisco d in disco) { } } catch { } } this.lastX = e.X; this.lastY = e.Y; } } Now I need that when i go with the mouse over the drawn disc, a tooltip show me the data of the fillPie(degree and value of txt) but i can't figure out how. Anyone can help me? this is an image of the disc A: Eventually it looks as if all you want is a function to get the angle between the mouse position and the center of the disc.. Here is a function to calculate an angle given two points: double AngleFromPoints(Point pt1, Point pt2) { Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y); double alpha = 0d; if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d; else { double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y)); alpha = Math.Acos(f) * 180d / Math.PI; if (P.Y > 0) alpha = 360d - alpha; } return alpha; }
{ "pile_set_name": "StackExchange" }
Q: Carry across multiple capture groups in array but match only one group I am trying to make a simple modification to some existing code without much luck, i want to carry across one more capture group from FILE1: $2, before comparing $1 as usual with data in FILE2 and printing both if a successful match occurs. Please keep the answer similar to my attempt if possible, so i am able to understand the changes. FILE1 data: abc 99269 +t abc 550 -a abc 100 +a gdh 126477 +t hduf 1700 +c FILE2 data: 517 1878 forward 2156 3289 forward 99000 100000 forward 22000 23000 backward 999555 999999 backward Desired output: 99269 +t 99000 100000 forward 550 -a 517 1878 forward 1700 +c 517 1878 forward Code: #!/usr/bin/perl use strict; use warnings; use autodie; my $outputfile = "/Users/edwardtickle/Documents/CC22CDSpositive.txt"; open FILE1, "/Users/edwardtickle/Documents/CC22indelscc.txt"; open FILE2, "/Users/edwardtickle/Documents/CDS_rmmge.CC22.CORE.aln"; open (OUTPUTFILE, ">$outputfile"); my @file1list=(); my @indels=(); while (<FILE1>) { if (/^\S+\s+(\d+)\s+(\S+)/) { push @file1list, $1; push @indels, $2; } } close FILE1; while ( my $line = <FILE2> ) { if ($line =~ /^>\S+\s+\S+\s+(\d+)\s+(\d+)\s+(\S+)/) { my $cds1 = $1; my $cds2 = $2; my $cds3 = $3; for my $cc22 (@file1list) { for my $indel (@indels) { if ( $cc22 > $cds1 && $cc22 < $cds2 ) { print OUTPUTFILE "$cc22 $indel $cds1 $cds2 $cds3\n"; } } } } } close FILE2; close OUTPUTFILE; Thanks in advance! A: It's frustrating that you don't seem to be learning from the many solutions and pieces of advice you've been given. Here's a program that will do as you ask. use strict; use warnings; use 5.010; use autodie; chdir '/Users/edwardtickle/Documents'; open my $fh, '<', 'CDS_rmmge.CC22.CORE.aln'; my @file2; while (<$fh>) { next unless /\S/; push @file2, [ split ]; } open my $out, '>', 'CC22CDSpositive.txt'; open $fh, '<', 'CC22indelscc.txt'; while (<$fh>) { my @line1 = split; for my $line2 (@file2) { if ( $line1[1] >= $line2->[0] and $line1[1] <= $line2->[1] ) { my @out = ( @line1[1,2], @$line2 ); print $out "@out\n"; last; } } }
{ "pile_set_name": "StackExchange" }
Q: AVL Rotation - Which node to rotate I have read many sources about AVL trees, but did not find anyone addressing this issue: When AVL tree gets unbalanced, which node should be rotated first? Assuming I have the tree: 10 / \ 5 25 / 20 and I'm trying to add 15, both the root and its child 25 will be unbalanced. 10 / \ 5 25 / 20 / 15 I could do a RR rotation (or single rotation) of 25, resulting in the following tree: 10 / \ 5 20 /\ 15 25 or a RL rotation (double rotation) about the root, creating the following tree: 20 / \ 10 25 / \ 5 15 I am confused about which rotation is the most suitable here and in similar cases. A: The RR rotation is correct here. The rotation should be done as soon (as low) as the rule is broken. Which is for 25 here. The higher rotations first don't necessarily break the rule and secondly would become too complex although it doesn't seem so here at the first sight.
{ "pile_set_name": "StackExchange" }
Q: On the coincidence (or non-coincidence) of two norms defined on the quotient of a given Hilbert $ C^{\ast} $-module by a certain linear subspace Let $ A $ be a $ C^{\ast} $-algebra, $ I $ a closed two-sided ideal of $ A $, and $ \mathcal{E} $ a Hilbert $ A $-module. Let $$ \mathcal{E}_{I} \stackrel{\text{df}}{=} \{ x \in \mathcal{E} \mid \langle x,x \rangle_{\mathcal{E}} \in I \}. $$ Using the Cauchy-Schwarz Inequality for Hilbert $ C^{\ast} $-modules, it is not difficult to show that $$ \mathcal{E}_{I} = \{ x \in \mathcal{E} \mid (\forall y \in \mathcal{E})(\langle x,y \rangle_{\mathcal{E}} \in I) \}. $$ This implies that $ \mathcal{E}_{I} $ is a linear subspace of $ \mathcal{E} $. Furthermore, as the $ A $-valued inner product on $ \mathcal{E} $ is continuous, $ \mathcal{E}_{I} $ is a $ \| \cdot \|_{\mathcal{E}} $-closed subset of $ \mathcal{E} $. All of this implies that $ \mathcal{E}_{I} $ is a Hilbert $ I $-module. Now, the quotient space $ \mathcal{E} / \mathcal{E}_{I} $ is a Banach space w.r.t. the quotient norm $ \| \cdot \|_{\text{q}} $ defined by $$ \forall x \in \mathcal{E}: \qquad \| x + \mathcal{E}_{I} \|_{\text{q}} \stackrel{\text{df}}{=} \inf_{y \in \mathcal{E}_{I}} \| x + y \|_{\mathcal{E}}. $$ It is also a right $ (A / I) $-module equipped with an $ (A / I) $-valued pre-inner product $ [\cdot,\cdot] $ defined by $$ \forall x_{1},x_{2} \in \mathcal{E}: \qquad [x_{1} + \mathcal{E}_{I},x_{2} + \mathcal{E}_{I}] \stackrel{\text{df}}{=} \langle x_{1},x_{2} \rangle_{\mathcal{E}} + I. $$ Question. Is the norm on $ \mathcal{E} / \mathcal{E}_{I} $ that is induced by $ [\cdot,\cdot] $ the same as $ \| \cdot \|_{\text{q}} $, i.e., $$ \forall x \in \mathcal{E}: \qquad \| x + \mathcal{E}_{I} \|_{\text{q}} = \sqrt{\| \langle x,x \rangle_{\mathcal{E}} + I \|_{A / I}}? $$ Thank you for your help! A: Here are a couple of supplements to Omar's answer. The first thing to note is that the module $\mathcal{E}_I$ is equal to the module $\mathcal{E}I=\{ei\ |\ e\in \mathcal{E},\ i\in I\}$. The inclusion $\mathcal{E}I\subset \mathcal{E}_I$ follows easily from the linearity of the inner product and from the fact that $I$ is an ideal. For the reverse inclusion, let $i_\lambda$ be an approximate unit for $I$, and then show (by expressing the norm in terms of the inner product) that for each $e\in \mathcal{E}_I$ one has $\| e-ei_\lambda\|\to 0$ as $\lambda\to\infty$. This gives $\mathcal{E}_I\subset \overline{\mathcal{E}I}$, and the latter is equal to $\mathcal{E}I$ by the Cohen factorisation theorem. For full details see Lemma 3.23 in: Raeburn, Iain; Williams, Dana P., Morita equivalence and continuous-trace $C^*$-algebras, Mathematical Surveys and Monographs. 60. Providence, RI: American Mathematical Society (AMS). xiv, 327 p. (1998). ZBL0922.46050. Now, turning to the inner product on $\mathcal{E}/\mathcal{E}_I$: here are three arguments showing that the norm defined by the inner product is equal to the quotient norm. (1) A short direct computation is given in Lemma 3.1 in: Zettl, Heinrich H., Ideals in Hilbert modules and invariants under strong Morita equivalence of C*-algebras, Arch. Math. 39, 69-77 (1982). ZBL0498.46034. (2) An argument based on the uniqueness of the $C^*$-norm on the linking algebra is given in Proposition 3.25 in the book of Raeburn-Williams cited above. (The authors attribute the argument to Siegfried Echterhoff.) (3) Here is a third proof, using ideas around operator modules and the Haagerup tensor product. All of the necessary background can be found in Blecher, David P.; Le Merdy, Christian, Operator algebras and their modules -- an operator space approach, London Mathematical Society Monographs. New Series 30; Oxford Science Publications. Oxford: Oxford University Press (ISBN 0-19-852659-8/hbk). x, 387~p. (2004). ZBL1061.47002. Consider $I\to A\to A/I$ as an exact sequence of operator $A$-bimodules. Taking the Haagerup tensor product with $\mathcal E$ (viewed as a right operator module over $A$) gives $$ \mathcal E\otimes_A I \to \mathcal E\otimes_A A \to \mathcal E\otimes_A (A/I). $$ By the exactness property of the Haagerup tensor product over a $C^*$-algebra (a theorem of Anantharaman-Delaroche and Pop), the first map in the display is a (completely) isometric embedding, and the second map induces a (completely) isometric isomorphism $$ (\mathcal E\otimes_A A)/ (\mathcal E\otimes_A I) \cong \mathcal E\otimes_A (A/I)\qquad (*) $$ where the left-hand side carries its canonical quotient operator space structure (and in particular, the usual Banach-space quotient norm). The module action gives a (completely) isometric isomorphism $\mathcal E\otimes_A A \to \mathcal E$, which restricts to an isomorphism $\mathcal E\otimes_A I \to \mathcal E I=\mathcal E_I$. Making these identifications, the isomorphism $(*)$ is given by the formula $$ \mathcal E/\mathcal E_I\to \mathcal E\otimes_A (A/I),\qquad (ea+\mathcal E_I)\mapsto e\otimes(a+I).\qquad (**) $$ Now, $A/I$ is a (right) Hilbert $C^*$-module over itself, and the quotient map $A\to A/I$ gives a (left) action of $A$ on this $C^*$-module by adjointable operators. We can thus form the Hilbert $C^*$-module tensor product $\mathcal E\otimes^{C^*}_A (A/I)$, which will be a Hilbert $C^*$-module over $A/I$. A theorem of Blecher asserts that the identity map on the algebraic tensor products extends to a (completely) isometric isomorphism between $\mathcal E\otimes^{C^*}_A (A/I)$ and the Haagerup tensor product $\mathcal E\otimes_A (A/I)$. A straightforward computation shows that the map $(**)$ is isometric with respect to the inner product $[\cdot,\cdot]$ on $\mathcal E/\mathcal E_I$, and the canonical inner product on $\mathcal E\otimes^{C^*}_A (A/I)$. Since $(**)$ is also isometric for the quotient norm, the latter must coincide with the norm induced by $[\cdot,\cdot]$. A: Yes, I think this is true. Here is an argument to show why. First for $E=A$, then this is just the standard theorem saying that the quotient norm on $A/I$ is the $C^*$-algebra norm. (any ref on $C^*$-algebras has a proof) Then you argue directly that the case $E=A$ implies that it is also true for $E=l^2(\mathbb{N})\otimes A$. Then you could use Kasparov stabilization theorem to prove it for coutably generated $C^*$-modules. To prove it for all modules, you might argue that both norms calcuated at a fixed element, only needed a countably generated submodule to be computed on. (Both are infimum of something so you take the submodules generated by a sequence reaching the infimum) Edit: Here some more details, I will use $E'$ to denote the module $E\oplus l^2(\mathbb{N})\otimes A$. We directly see that $E'_I=E_I\oplus l^2(\mathbb{N})\otimes I$, hence $E'/E'_I=E/E_I\oplus l^2(\mathbb{N})\otimes A/I.$ Hence the inclusion map $i:E/E_I\to E'/E'_I$ preserves the two norms defined in the question. Theorem(Kasparov's Specialization theorem)(reference in a comment) Let $E$ be a countably generated $A$-module, then $E\oplus l^2(\mathbb{N})\otimes A\simeq l^2(\mathbb{N})\otimes A$. Here the isomorphism is a unitary isomorphism. Since the module $E'$ is untarly equivalent to $l^2(\mathbb{N})\otimes A$ it follows that the two norms are equal on $E'/E'_I$ and hence on $E/E_I$.
{ "pile_set_name": "StackExchange" }
Q: Deriving the Pauli-Schrödinger equation from the Dirac equation Since the Schrödinger Pauli equation describes a non-relativistic spin ½ particle. This equation must be an approximation of the Dirac equation in an electromagnetic field. I was trying to derive this but I got stuck at a point. The free particle Dirac can be reduced to the equations \begin{align} σ^{i}(p_{i}+eA_{i}) u_B & = (E-m+eA_0)u_A. \\ \sigma^{i}(p_{i}+eA_{i})u_A & = (E+m+A_{0})u_B \end{align} I multiplied both sides of the first equation by $(E+m+eA_0)$ to get the Schrödinger Pauli equation. I was not able to eliminate $u_B$ completely from the equation. Can someone help me with the derivation? A: Dirca's equation has is the following form: $$i\hbar\gamma^{\mu}\partial_{\mu}\psi - mc\psi = 0$$ where $\mu = 0,1,2,3$ and $\gamma^{\mu}$ are the $4\times4$ matrices(in Dirac's representation): \begin{align} \gamma^0 = \begin{bmatrix} \mathbb{1} & 0 \\ 0 & -\mathbb{1} \end{bmatrix} \gamma^k = \begin{bmatrix} 0 & \sigma_k \\ -\sigma_k & 0 \end{bmatrix} \end{align} Where $\sigma_k$ are the Pauli Matrices ($k = 1,2,3$): \begin{align} \sigma_1 = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix} \sigma_2 = \begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix} \sigma_3 = \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix} \end{align}. Using the momentum e energy in quantum mechanics differential operators; $\vec{p} = -i\hbar\vec{\nabla}$, $E = ih\partial_t = i\hbar c\partial_0$ the Dirac's equation become: $$(E\gamma^0 -c\gamma^{k} p_k - mc^2)\psi = 0$$ Breaking the four dimensional spinnor $\psi$ in two components the equation in a matrix for become: \begin{align} \begin{bmatrix} (E - mc^2)\mathbb{1}& -\sigma_k p_k c\\ \sigma_k p_k c & -(E + mc^2)\mathbb{1} \end{bmatrix} \begin{bmatrix} u\\ v \end{bmatrix} =0 \end{align} To coupling the EM field the energy and the momentum change \begin{align} E \rightarrow E - e \Phi \\ \vec{p} \rightarrow \vec{p} - e \vec{A} \end{align} So the EM weak coupling Dirac's equation in matricial form become: \begin{align} \begin{bmatrix} (E - e \Phi - mc^2)\mathbb{1}& -\sigma_k (p_k - e A_k) c\\ \sigma_k (p_k - e A_k) c & -(E - e \Phi + mc^2)\mathbb{1} \end{bmatrix} \begin{bmatrix} u\\ v \end{bmatrix} =0 \end{align} Now writing it in function of $u$ and $v$: \begin{align} (E - e \Phi - mc^2) u -(\sigma_k (p_k - e A_k) c)v =0 \\ \sigma_k (p_k - e A_k)c u -(E - e \Phi + mc^2)v =0 \end{align} In the second equation the $u$ and $v$ relation become: \begin{align} \frac{\sigma_k (p_k - e A_k)c}{E - e \Phi + mc^2}u=v \end{align} For the non relativistic approach $e \Phi << mc^2$ and $E = mc^2$ So the $u$ and $v$ relation became: \begin{align} \frac{\sigma_k (p_k - e A_k)c}{2mc^2}u=v \end{align} Plugging this non relativistic relation in the first equation: \begin{align} (E - e \Phi - mc^2) u -\frac{(\sigma_k (p_k - e A_k)c)^2}{2mc^2}u =0 \end{align} Renaming $E - mc^2= E_{NR}$ and reorganizing: \begin{align} \left( e \Phi +\frac{(\sigma_k (p_k - e A_k)c)^2}{2mc^2}\right)u =E_{NR}u \end{align} Focus in the $(\sigma_k (p_k - e A_k))^2$ term we have: \begin{align} (\sigma_k (p_k - e A_k))^2 &= (\sigma_i (p_i - e A_i)(\sigma_j (p_j - e A_j)\\ &= \sigma_i \sigma_j \Pi_i \Pi_j \end{align} Where $\Pi_i = p_i - e A_i$ From Pauli anti-commutation and commutation relations: $$\sigma_i \sigma_j = \delta_{ij} + i \varepsilon_{ijk}\sigma_k $$ With that the quadratic term become: \begin{align} (\sigma_k (p_k - e A_k))^2 &= \Pi_i \Pi_i + i \varepsilon_{ijk}\sigma_k \Pi_i \Pi_j \end{align} The last term in $(\sigma_k (p_k - e A_k))^2 u$ is: \begin{align} i \varepsilon_{ijk}\sigma_k \Pi_i \Pi_j u &= i \varepsilon_{ijk}\sigma_k\left[(-i\hbar\partial_i - e A_i)(-i\hbar \partial_j - e A_j)\right] \\ &= i \varepsilon_{ijk}\sigma_k\left[-\hbar^2 \partial_i \partial_j + e^2 A_i A_j + i\hbar e(\partial_i A_j + A_i \partial_j)\right]u \end{align} The first two terms are symmetrical so they become: \begin{align} \varepsilon_{ijk} \partial_i \partial_j &= \frac{1}{2}\varepsilon_{ijk}(\partial_i \partial_j + \partial_j \partial_i) \\ &= \frac{1}{2}(\varepsilon_{ijk}\partial_i \partial_j +\varepsilon_{ijk}\partial_j \partial_i) \\ &= \frac{1}{2}(\varepsilon_{ijk}\partial_i \partial_j -\varepsilon_{jik}\partial_j \partial_i)\\ & = 0 \end{align} The same thing are value for the $A_i A_j$ so the term become: \begin{align} i \varepsilon_{ijk}\sigma_k \Pi_i \Pi_j u &= -\hbar e \varepsilon_{ijk}\sigma_k\left[ \partial_i( A_j u) + A_i \partial_j (u)\right] \\ &= -\hbar e \varepsilon_{ijk}\sigma_k\left[ \partial_i( A_j)u+ A_j \partial_i (u) + A_i \partial_j (u)\right] \end{align} Where were applied the product rule in the first derivative. Now looking in the last two terms we can show that they vanish each other: \begin{align} \varepsilon_{ijk}\left[ A_j \partial_i + A_i \partial_j \right] &= \varepsilon_{ijk}A_j \partial_i + \varepsilon_{ijk}A_i \partial_j \\ &= \varepsilon_{ijk}A_j \partial_i - \varepsilon_{jik}A_i \partial_j \\ &= 0 \end{align} The only term that does not vanish is the $k$-th component os the curl of $\vec{A}$ \begin{align} i \varepsilon_{ijk}\sigma_k \Pi_i \Pi_j &= -\hbar e \varepsilon_{ijk}\sigma_k \partial_i( A_j) \\ &= -\hbar e \sigma_k \varepsilon_{kij}\partial_i A_j \\ &= -\hbar e \vec{\sigma}\cdot \vec{B} \end{align} With that we can write: \begin{align} (\sigma_k (p_k - e A_k))^2 &= \frac{(p_k - e A_k)^2}{2m} - \frac{\hbar e}{2m}\vec{\sigma}\cdot \vec{B} \end{align} Now finally putting all together the non relativistic Dirac's equation is: \begin{align} \left( e \Phi + \frac{(p_k - e A_k)^2}{2m} - \frac{\hbar e}{2m}\vec{\sigma}\cdot \vec{B}\right)u =E_{NR}u \end{align}
{ "pile_set_name": "StackExchange" }
Q: Is there SQL-syntax aware Swing component? I am looking for some Java Swing component (textarea like) which is aware of SQL syntax - meaning it recognizes and highlights it. If there isn't I will need to do it myself, any useful advices there how not waste too much of time (eg. which component to use) ? A: JSyntaxPane appears to support SQL highlighting (I have not tried it myself).
{ "pile_set_name": "StackExchange" }
Q: In which order object class members with no parameters in their constructor functions are initialized? I have three class. First one is the 'Game', which is dependent to the other two. My second class is 'Window', which is a dependence for the third class 'VKBase'. Those last two classes have no parameters in their constructor functions. Game contains the others as object members, and Window have to get initialised before VKBase. class Game { Boolean bit = true; Window window; VKBase VkBase; public: Game(); ~Game(); void _Set(); void Loop(); void Exit(); }; Because that these two class not have parameters in their constructor functions, i can't initialise them in the constructor function of the Game. So they will get initialised whenever i create an object from the class Game. But the question is, since initialisation order is important, which one will get initialised first? The window or the VkBase? A: In which order object class members [...] are initialized? In the order in which they were declared. In your example, bit is initialized first, window second, VkBase third. Whether these data members have a default constructor or one depending on parameters doesn't matter here. Because that these two class not have parameters in their constructor functions, i can't initialise them in the constructor function of the Game You kind got that wrong, you do in fact initialize the instances by calling the default constructor. Note that for any class that has a default constructor, ClassWithDefaultCtor instance; does call this default constructor when this variable is instantiated (might be when an enclosing class is constructed, if the above declaration is a class data member). This syntax is called default initialization, and this is exactly what happens in your class. Note that you can change the above to ClassWithDefaultCtor instance{}; which might make it clearer that the object is properly initialized.
{ "pile_set_name": "StackExchange" }
Q: Pulling a string with both ends fixed Consider a string with both ends fixed. If somewhere in middle of it be pulled and released, how would it oscillate and what is it's equation? My solution assuming the result is a standing wave: The point which is pulled will be an anti-node, so the length of string before this point is $(2n-1)\times\frac{\gamma}{4}$ and the length of string after this point will be $(2n^\prime-1)\times\frac{\gamma}{4}$. Considering the first length $l$ and the second length $l^\prime$, we will have: $$\frac{2n-1}{2n^\prime-1}=\frac{l}{l^\prime}$$ So the oscillator will be in it's $n+n^\prime -1$ harmonic. But what if that equation doesn't have natural answer, and what if it has answer so double of that is still an answer? A: Mathematically the shape of the string is the superposition of multiple standing waves. In general it has the form: $$ y(x,t) = \sum_{i=1}^{\infty} \sin \left(i\frac{ \pi x}{\ell} \right) \left( A_i \sin \left( i\frac{ \pi c t}{\ell} \right)+ B_i \cos \left( i\frac{ \pi c t}{\ell} \right) \right) $$ where $\ell$ is the length from end to end, and $c$ is the speed of wave propagation along the string. Now given an initial pluck of the string, of triangular shape you find the coefficients $A_i$ and $B_i$ using Fourier transform. The result is: $$ \begin{align} A_i &= 0 \\ B_i &= Y \frac{2 \ell^2 \sin \left( \frac{i \pi x_p}{\ell} \right)}{\pi^2 i^2 x_p (\ell-x_p)} \end{align} $$ where $x_p$ is the position of the pluck point, $Y$ is the pluck amplitude, and $i=1 \ldots \infty$ To arrive at this use the pluck shape $y_0(x) = Y\,{\rm if}(x \leq x_p, \tfrac{x}{x_p}, 1-\tfrac{x-x_p}{\ell-x_p})$ and the known initial conditions $$ \begin{aligned} \lim \limits_{t\rightarrow 0} y(x,t) & = y_0(x) = {\rm triangle} \\ \lim \limits_{t\rightarrow 0} \frac{\partial}{\partial t} y(x,t) & = v_0(x) =0 \end{aligned}$$ Now pre-multiply with $\sin\left(i \frac{\pi x}{\ell} \right)$ and integrate over the length of the string $$ \begin{aligned} \int \sin\left(i \frac{\pi x}{\ell} \right) y_0(x) {\rm d}x &= \int \sin\left(i \frac{\pi x}{\ell} \right) \lim_{t\rightarrow 0} y(x,t) {\rm d}x = B_i \frac{\ell}{2} \\ \int \sin\left(i \frac{\pi x}{\ell} \right) v_0(x) {\rm d}x &= \int \sin\left(i \frac{\pi x}{\ell} \right) \lim_{t\rightarrow 0} \frac{\partial}{\partial t} y(x,t) {\rm d}x = A_i \frac{i\,\pi\, c}{2} \end{aligned} $$ or $$\begin{aligned} A_i &= \frac{2}{i\,\pi\,c} \int \sin\left(i \frac{\pi x}{\ell} \right) v_0(x) {\rm d}x = 0 \\ B_i & = \frac{2}{\ell} \int \sin\left(i \frac{\pi x}{\ell} \right) y_0(x) {\rm d}x = \frac{2 Y \ell^2}{\pi^2 i^2 x_P (\ell-x_p)} \sin\left(i \frac{\pi x_p}{\ell} \right)\end{aligned} $$
{ "pile_set_name": "StackExchange" }
Q: increase max_connections in mysql on ubuntu wily I have ubuntu wily installed on my server. I'm trying to increase max_connections of mysql server to 1237 but when running mysql client and executing show variables like 'max_connections'; i get 214. i did the following: i edit /etc/sysctl.conf and added fs.file-max = 2459688 then executed sysctl -p. I edited /etc/security/limit.conf and added the following lines: * soft nofile 4096 * hard nofile 4096 then rebooted. ulimit -a shows 4096, but mysql proc still shows soft 1024 connections. which means.. I do the following commands: # cat /var/run/mysqld/mysqld.pid 1099 # cat /proc/1099/limits Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 8388608 unlimited bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 62891 62891 processes Max open files 1024 4096 files Max locked memory 65536 65536 bytes Max address space unlimited unlimited bytes Max file locks unlimited unlimited locks Max pending signals 62891 62891 signals Max msgqueue size 819200 819200 bytes Max nice priority 0 0 Max realtime priority 0 0 Max realtime timeout unlimited unlimited us any ideas? A: https://dba.stackexchange.com/questions/12061/mysql-auto-adjusting-max-connections-values in the question i posted above, someone tried to increase the max opened files for mysql. when I did what he did, i could increase the max_connections to whatever i want.
{ "pile_set_name": "StackExchange" }
Q: Select from table with additional predefined records not existing in database Is it possible to Select rows from table in database with addition of predefined rows not existing in database? SELECT Name FROM [dbo].[TableFoo] -> returns Names (Name1, Name2, Name3) I want it to additionally return predefined value 'NameNotInDatabase': SELECT Name FROM [dbo].[TableFoo] + some tsql -> returns Names (Name1, Name2, Name3, NameNotInDatabase) A: Are you looking for UNION ALL? SELECT Name FROM [dbo].[TableFoo] UNION ALL SELECT 'NameNotInDatabase';
{ "pile_set_name": "StackExchange" }
Q: Penetration Testing Silverlight Applications What would be the process in pentesting a Silverlight application? What would be the best method to proceed in a manual test? Any specific tools use? For example an application with lot of file upload, user input fields and database connectivity (with and without ORM). A: If you are code reviewing then I would recommend that you use Microsoft Visual Studio Unit Tests (See http://silverlight.codeplex.com/ and http://weblogs.asp.net/scottgu/archive/2008/04/02/unit-testing-with-silverlight.aspx) or Nant to test the code. It is would be the most effective way to do these type of tests. If you don’t have access to the source code and need to do external/blind tests then you should cover the following above normal web application testing. Coverage In Silverlight there are typically 3 areas that need to be tested over and above a normal web application: Deep linking Isolated Storage Back-end services Deep Linking Test for flaws in flow particularly authorization and data input. Allows direct access to a page within Silverlight and could allow bypassing security such as authorization if authorization checks are only done at specific points. For example: An application only checks authorisation on or just after the login screen, but application is deep linked to allow direct access to data read/write. Isolated Storage Same as any data storage tests however the special note is that it is client-side storage. Questions such as: What can be stored in isolated storage? What can be overridden in isolated storage? For example, had the application stored files that can be overridden by the user? How is that presented back to the user? Backend Services In web application usage cases Silverlight will commonly form the top tier / front-end and a backend web service will be responsible for some sort of data handling / storage. Because Silverlight is a client-side technology web services if they exist are exposed to the client to, which is different to the usual server-side web application which may not need to expose these at all. Web services should be aggressively tested using automated and manual tools. The normal tests of content type, size constraints, and performance are important. Also some fuzzing would also be good. This all falls back to the generic web services testing is not Silverlight specific. Tools First Floor's Silverlight Spy can aid in investigating the isolated storage issues: http://firstfloorsoftware.com/silverlightspy/download-silverlight-spy/ It is also sometimes helpful to review the xbap code of the app using ILSpy or .Net Reflector: http://wiki.sharpdevelop.net/ILSpy.ashx Try these for web services: Are there any tools for automated penetration testing of Silverlight applications? https://www.owasp.org/index.php/Fuzzing Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Jenkins pipeline exception - Getting docker not found I am running Jenkins service on azure kubernetes services, and I have simple pipeline script to build my demo angular project.. pipeline { agent any stages { stage(‘Build’) { steps { checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'mygithub', url: 'https://github.com/prabaharanit/docker-angular-example']]]) } } stage('Fetch dependencies') { agent { docker 'circleci/node:9.3-stretch-browsers' } steps { sh 'yarn' stash includes: 'node_modules/', name: 'node_modules' } } } } when I build my pipeline i am getting below error, /var/jenkins_home/workspace/worklist-pipeline@2@tmp/durable-ec84fb4d/script.sh: docker: not found. how to make Jenkins to use my host docker container for builds.. this is for testing purpose and I want to use my host docker to run the build and create images.. I have tried adding docker form global tool configurations.. but it doesn't work. A: In order to use your Jenkins host docker engine. Remove the below agent statement from the pipeline - agent { docker 'circleci/node:9.3-stretch-browsers' } PS - You can use agent { label 'master' } in the stage whenever you want to use the Jenkins host machine.
{ "pile_set_name": "StackExchange" }
Q: Inexact coefficient message showing up without any inexact coefficients I have seen this message (Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result.) appear when trying to find when a function equals zero. However, I have no "inexact coefficients" - all my coefficients are exact. I looked into this problem, and the error for everyone else is that they used floating point numbers, but I didn't. Maybe the function is so complicated that this shows up. How can I fix this problem? If it is not possible to fix, is it possible to get the "corresponding exact system" that Mathematica uses? If so, how can it be done? The function for anyone interested is g[s_] = -262144 + 229376 s + 4390912 s^2 - 4956160 s^3 - 24862720 s^4 + 29081600 s^5 + 67333120 s^6 - 80308224 s^7 - 98554368 s^8 + 120892160 s^9 + 80048000 s^10 - 102716096 s^11 - 33825728 s^12 + 47124296 s^13 + 5700652 s^14 - 9795666 s^15 + 486201 s^17 + 1245184 s Sqrt[-1 + s^2] - 1392640 s^2 Sqrt[-1 + s^2] - 11075584 s^3 Sqrt[-1 + s^2] + 12812288 s^4 Sqrt[-1 + s^2] + 39093248 s^5 Sqrt[-1 + s^2] - 46153728 s^6 Sqrt[-1 + s^2] - 69393408 s^7 Sqrt[-1 + s^2] + 84210176 s^8 Sqrt[-1 + s^2] + 65260928 s^9 Sqrt[-1 + s^2] - 82670016 s^10 Sqrt[-1 + s^2] - 30979392 s^11 Sqrt[-1 + s^2] + 42412512 s^12 Sqrt[-1 + s^2] + 5701556 s^13 Sqrt[-1 + s^2] - 9553152 s^14 Sqrt[-1 + s^2] + 486204 s^16 Sqrt[-1 + s^2] + 131072 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 114688 s Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 1916928 s^2 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 2158592 s^3 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 9879552 s^4 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 11588608 s^5 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 24290560 s^6 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 29032704 s^7 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 31443520 s^8 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 38716736 s^9 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 21446992 s^10 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 28044736 s^11 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 6775772 s^12 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 10132796 s^13 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 554458 s^14 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] + 1297852 s^15 Sqrt[4 - s^2 - 4 s Sqrt[-1 + s^2]] - 557056 s Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 638976 s^2 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 4579328 s^3 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] - 5326848 s^4 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] - 14688768 s^5 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 17385984 s^6 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 23093120 s^7 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] - 28069760 s^8 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] - 18266080 s^9 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 23458560 s^10 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 6499368 s^11 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] - 9483360 s^12 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] - 554648 s^13 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] + 1297874 s^14 Sqrt[-4 + 5 s^2 - s^4 + 4 s Sqrt[-1 + s^2] - 4 s^3 Sqrt[-1 + s^2]] A: First make sure that there are not any old definitions for g Clear[g] The definition for g can be shortened by defining common subexpressions. g[s_] := Module[ {sr1 = Sqrt[s^2 - 1], sr2, sr3}, sr2 = Sqrt[4 - s^2 - 4 s sr1]; sr3 = Sqrt[-4 + 5 s^2 - s^4 + 4 s sr1 - 4 s^3 sr1]; -262144 + 229376 s + 4390912 s^2 - 4956160 s^3 - 24862720 s^4 + 29081600 s^5 + 67333120 s^6 - 80308224 s^7 - 98554368 s^8 + 120892160 s^9 + 80048000 s^10 - 102716096 s^11 - 33825728 s^12 + 47124296 s^13 + 5700652 s^14 - 9795666 s^15 + 486201 s^17 + 1245184 s sr1 - 1392640 s^2 sr1 - 11075584 s^3 sr1 + 12812288 s^4 sr1 + 39093248 s^5 sr1 - 46153728 s^6 sr1 - 69393408 s^7 sr1 + 84210176 s^8 sr1 + 65260928 s^9 sr1 - 82670016 s^10 sr1 - 30979392 s^11 sr1 + 42412512 s^12 sr1 + 5701556 s^13 sr1 - 9553152 s^14 sr1 + 486204 s^16 sr1 + 131072 sr2 - 114688 s sr2 - 1916928 s^2 sr2 + 2158592 s^3 sr2 + 9879552 s^4 sr2 - 11588608 s^5 sr2 - 24290560 s^6 sr2 + 29032704 s^7 sr2 + 31443520 s^8 sr2 - 38716736 s^9 sr2 - 21446992 s^10 sr2 + 28044736 s^11 sr2 + 6775772 s^12 sr2 - 10132796 s^13 sr2 - 554458 s^14 sr2 + 1297852 s^15 sr2 - 557056 s sr3 + 638976 s^2 sr3 + 4579328 s^3 sr3 - 5326848 s^4 sr3 - 14688768 s^5 sr3 + 17385984 s^6 sr3 + 23093120 s^7 sr3 - 28069760 s^8 sr3 - 18266080 s^9 sr3 + 23458560 s^10 sr3 + 6499368 s^11 sr3 - 9483360 s^12 sr3 - 554648 s^13 sr3 + 1297874 s^14 sr3]; The real roots are confined to FunctionDomain[g[s], s] (* s <= -1 || 1 <= s <= 2/Sqrt[3] *) There are six real roots soln = Solve[g[s] == 0, s, Reals] // SortBy[#, N[#] &] & Only four of these roots are distinct soln2 = DeleteDuplicates[soln] soln2 // N (*b{{s -> -3.09518}, {s -> -1.60486}, {s -> 1.1473}, {s -> 1.15185}} *)
{ "pile_set_name": "StackExchange" }
Q: tabcolsep for a single cell I would like to use nested tables instead of multirow, I have this example \documentclass{article} \usepackage[utf8]{inputenc} \begin{document} %\tabcolsep0pt %this makes the second table \begin{tabular}{|l|l|} \hline Test & Test2 \\ \hline Test 3 & {\begin{tabular}{|l|} \hline can i remove \\ \hline the spaceing here \\ \hline \end{tabular}} \\ \hline \end{tabular} \end{document} That's how the output looks like. I know that \tabcolsep0pt can remove that space between the cell content and the table lines. But it removes it for all cells and it looks bad for the other cells: Now my question can I set the \tabcolsep0pt just for that single cell containing the nested table? A: \documentclass{article} \begin{document} \begin{tabular}{|l|l@{}|}\hline Test & Test2 \\\hline Test 3 & \hfil\hspace{\dimexpr-1\tabcolsep} \begin{tabular}{l} can i remove \\\hline the spaceing here \\ \end{tabular} \\\hline \end{tabular} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Ceramic Capacitors What is the difference between General purpose and Automotive grade ceramic capacitors, if they have the same capacitance, temperature coefficient and operating temperature. is there a manufacturing or design difference or are they the same except the Automotive ones go through additional screening? A: What it really means is; you are maybe unlikely to find any Chinese Supplier qualified to AEC-Q200 due to quality control, traceability. They will be Japanese companies who take quality most seriously like ... Panasonic, Toyo Yuden, Rubicon for caps. AEC-Q100: Integrated circuits (ICs) AEC-Q101: Discrete semiconductor components (transistors, diodes, etc.) AEC-Q200: Passive components (capacitors, inductors, etc.) They include temperature grades from 105~150C for under the hood or interior etc. MTBF drops 50% /+10’C rise , so life tests at elevated temps are mandatory and bunch of other stress tests,
{ "pile_set_name": "StackExchange" }
Q: Persistent push with comet long-polling on Jetty? I am trying to create a Jetty servlet that allows clients (web browsers, Java clients, ...) to get broadcast notifications from the web server. The notifications should be sent in a JSON format. My first idea was to make the client send a long-polling request, and the server respond when a notification is available using Jetty's Continuation API, then repeat. The problem with this approach is that I am missing all the notifications that happen between 2 requests. The only solution I found for this, is to buffer the Events on the server and use a timestamp mechanism to retransmit missed notifications, which works, but seems pretty heavy for what it does... Any idea on how I could solve this problem more elegantly? Thanks! A: HTTP Streaming is most definitely a better solution than HTTP long-polling. WebSockets are an even better solution. WebSockets offer the first standardised bi-directional full-duplex solution for realtime communication on the Web between any client (it doesn't have to be a web browser) and server. IMHO WebSockets are the way to go since they are a technology that will continue to be developed, supported and in demand and will only grow in usage and popularity. They're also super-cool :) There appear to be a few WebSocket clients for Java and Jetty also supports WebSockets. A: Sorry for bumping this up, yet I believe numerous people will come across this thread and the accepted answer, IMHO, is at least outdated, not to say misleading. In order of priority I'd put it as following: 1) WebSockets is the solution nowadays. I've personally had the experience of introducing WebSockets in enterprise oriented applications. All of the major browsers (Chrome, Firefox, IE - in alphbetical order :)) support WebSockets natively. All major servers/servlets (IIS, Tomcat, Jetty) are the same and there are quite a number of frameworks in Java implementing JSR 356 APIs. There is a problem with proxies, especially in cloud deployment. Yet there is a high awareness of the WebSockets requirements, so NginX supported them already 1.5 year ago. Anyway, secured 'wss' protocol solves proxy problem in 99.9% (not 100% just to be on the safe side, never experienced that myself). 2) Long Polling is probably the second best solution, and the 'probably' part is due to 'short polling' alternative. When speaking of long polling I mean the repeated request from client to server, which responses as soon as any data available. Thus, one poll can finish in a few millis, another one - till the max wait time. Be sure to limit the poll time to something lesser than 2mins since usually otherwise you'll need to manage timeout error in you client side. I'd propose to limit the poll time to something like tens of seconds. To be sure, once poll finished (timely or before that) it is immediately repeated (yet better to establish some simple protocol and give to your server a chance to say to the client - 'suspend'). Cons of the long polling, which IMHO justifies the continuation of the list, is that it holds one of just a few (4, 8? still not that many) allowed connections, that browser allows each page to establish to a server. So that is can eat up ~12% to ~25% of your website's client traffic resource. 3) Short polling not that much loved by many, but sometimes i prefer it. The main Cons of this one, is, of course, the high load on the browser and the server while establishing new connections. Yet, i believe that if connections pools are used properly, that overhead much lesser than it look like on the first glance. 4) HTTP streaming, either it be page streaming via IFrame or XHR streaming, is, IMHO, highly BAD solution since it's like an accumulation of Cons of all the rest and more: you'll hold the connections opened (resources of browser and server); you'll still be eating up from total available client traffic limit; most evil: you'll need to design/implement (or reuse design/implementation) the actual content delivery in order to be able to differentiate the new content from the old one (be it in pushing scripts, oh my! or tracking the length of the accumulated content). Please, don't do this. Update (20/02/2019) If WebSockets are not an option - Server Sent Events is the second best option IMHO - effectively browsers implemented HTTP streaming for you here at the lower level.
{ "pile_set_name": "StackExchange" }
Q: Expressing solubility in binary solvents with non-additive volumes I have experimentally obtained data that shows the molarity of a saturated solution in mixed solvents, with different proportions of solvents. The issue here is that the two solvents (water/ethanol) have non-additive volumes, and expressing the solubility as $\mathrm{mol}$ $\mathrm{L^{-1}}$ thus seems a bit odd, especially when comparing solubilities between different solvent ratios. Would mole fraction be a better alternative? If so, why? And is it possible to convert from the "old" amount-per-volume answer to the new, better one? Also, I include a graphical representation of my results, with solvent composition on the x-axis and solubility on the y-axis. Would it be appropriate to use mole fraction (or whatever other unit is better suited) on both axes: the mole fraction of solvents on the x-axis and that of the solute in the mixed solvent on the y-axis? A: For solvent mixtures, especially in mixture or solubility design of experiments, I work in mass for the solvents. It's unaffected by temperature, more accurate (very advantageous if small values are being used) and should get around your problem. You can quote your initial results as %w/w
{ "pile_set_name": "StackExchange" }
Q: Calculate total duration for properties in object I've got the following object in an array[0]: var arr[0]= [ { "startTime": "1300", "endTime": "1700", "eventName": "Sleep", "end_datetime": "20180510M0100", "start_datetime": "20180509M2300", }, { "startTime": "0800", "endTime": "1200", "eventName": "Breakfast", "end_datetime": "20180507M1200", "start_datetime": "20180507M0800", }, { "startTime": "1300", "endTime": "1400", "eventName": "Lesson", "end_datetime": "20180507M1400", "start_datetime": "20180507M1300", }, { "startTime": "1300", "endTime": "1700", "eventName": "Ski", "end_datetime": "20180511M170000", "start_datetime": "20180511M130000", } ] end_datatime is in format yyyymmddMhhmmss(first 4 digits are year, follow by months, days, separator 'M', hours, minutes, and seconds. I would like to calculate total duration of all the events? (Total of 11 hours which is 2 hours in sleep + 4 hours in breakfast + 1 hour in lesson + 4 hours in ski) A: Here's one possible implementation, taking into consideration times spanning multiple days: const input = [{ "startTime": "1300", "endTime": "1700", "eventName": "Sleep", "end_datetime": "20180510M0100", "start_datetime": "20180509M2300", }, { "startTime": "0800", "endTime": "1200", "eventName": "Breakfast", "end_datetime": "20180507M1200", "start_datetime": "20180507M0800", }, { "startTime": "1300", "endTime": "1400", "eventName": "Lesson", "end_datetime": "20180507M1400", "start_datetime": "20180507M1300", }, { "startTime": "1300", "endTime": "1700", "eventName": "Ski", "end_datetime": "20180511M170000", "start_datetime": "20180511M130000", } ]; function getDiff(datestr1, datestr2) { const m1 = moment(datestr1, 'YYYYMMDD*hhmm'); const m2 = moment(datestr2, 'YYYYMMDD*hhmm'); const minuteDifference = m2.diff(m1, 'minutes'); return minuteDifference; } const totalMinutes = input.reduce( (accum, { end_datetime, start_datetime }) => accum + getDiff(start_datetime, end_datetime), 0 ); const totalHours = totalMinutes / 60; console.log(totalMinutes + ' minutes = ' + totalHours + ' hours'); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: ConcurrentModificationException when invoking putAll I have difficulties in understanding the following error. Suppose you have a class A in which I implement the following method: Map<Double,Integer> get_friends(double user){ Map<Double,Integer> friends = user_to_user.row(user); //friends.putAll(user_to_user.column(user)); return friends;} Then in the main I do the following: A obj = new A(); Map<Double,Integer> temp = obj.get_friends(6); Well this works fine. However when I uncomment the follwing line in class A: friends.putAll(user_to_user.column(user)); and I run again the program, it crashes and throws me the concurrentModificationException. It is to be noted, that I am creating the Table user_to_user as follows: private HashBasedTable<Double,Double,Integer> user_to_user;// user_to_user = HashBasedTable.create(); What is further surprising is that when I interchange the way I am filling friends, I mean in that way: Map<Double,Integer> friends = user_to_user.column(user); friends.putAll(user_to_user.row(user)); Then everyting will work fine. Any idea ? A: The issue is that HashBasedTable is internally implemented as a Map<Double, Map<Double, Integer>>, and that the implementation of user_to_user.column(user) is iterating over the rows at the same time you're modifying the row associated with user. One workable alternative would be to copy user_to_user.column(user) into a separate Map before putting it into the row.
{ "pile_set_name": "StackExchange" }
Q: Не корректно идет проверка по POST Написал проверку на корректность и занятость E-mail адреса у пользователей, но почему-то POST запрос идет не правильно. Запрос идет больше секунды и почему-то нельзя использовать ответ от запроса в условии <script> if(email == '') { event.preventDefault(); $("#email").addClass('input_error'); $('#error_reg').show(); $('#error_reg_info').text('Необходимо заполнить все поля'); } else { var resEmail = email.search(/[-0-9a-z_]+@[-0-9a-z_]+\.[a-z]{2,6}/i); if(resEmail == -1){ event.preventDefault(); $("#email").addClass('input_error'); $('#error_reg').show(); $('#error_reg_info').text('Неверный формат Email'); } else { var url = host+"/resources/classes/testEmail.class.php"; $.post(url, { email: email}, function(data){ //Если здесь вывести ответ, то он работает ( alert(data); ) if(data == 'no') { event.preventDefault(); $("#email").addClass('input_error'); $('#error_reg').show(); $('#error_reg_info').text('E-mail занят'); } else { $("#email").removeClass('input_error'); } }); } } </script> <?php include '../basic/config.php'; include '../basic/function.php'; $email = tm($_POST['email']); $query = "SELECT `id` FROM `users` WHERE `email`='{$email}' LIMIT 1"; $sqle = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($sqle)==1) { echo "no"; } else { echo "yes"; } ?> A: Вот в чем смысл проверять на JS'e? Его можно убрать и сделать запрос? Я вообще не вижу смысл проверок на клиентской части. Сразу, без проверок подавайте где вам нужно будет написать только одну строчку используя функцию filter (FILTER_VALIDATE_EMAIL), в пхп все есть).
{ "pile_set_name": "StackExchange" }
Q: How do I manage large art assets appropriately in DVCS? Is there any good way to handle large assets (i.e. 1000's of images, flash movies etc.) with a DVCS tool such as hg and git. As I see it, to clone repositories that are filled with 4 GB assets seems like an unnecessary overhead as you will be checking out the files. It seems rather cumbersome if you have source code mixed together with asset files. Does anyone have any thoughts or experience in doing this in a web development context? A: These are some thoughts I've had on this matter of subject. In the end you may need to keep assets and code as separate as possible. I can think of several possible strategies: Distributed, Two Repositories Assets in one repo and code in the other. Advantages In web development context you won't need to clone the giant assets repository if you're not working directly with the graphic files. This is possible if you have a web server that handles assets separate from dynamic content (PHP, ASP.NET, RoR, etc.) and is syncing with the asset repo. Disadvantages DVCS tools don't keep track of other repositories than their own so there isn't any direct BOM (Bill of Materials) support, i.e. there is no clear cut way to tell when both repositories are in sync. (I guess this is what git-submodule or repo is for). Example: artist adds a new picture in one repository and programmer adds function to use the picture, however when someone has to backtrack versions they are forced to somehow keep track of these changes on their own. Asset repository overhead even though it only affects those who do use it. Distributed, One Repository Assets and code reside in the same repository but they are in two separate directories. Advantages Versioning of code and assets are interwoven so BOM is practical. Backtracking is possible without much trouble. Disadvantages Since distributed version control tools keep track of the whole project structure there is usually no way to just check out one directory. You still have the problem with repository overhead. Even more so, you need to check out the assets as well as the code. Both strategies listed above still have the disadvantage of having a large overhead since you need to clone the large asset repository. One solution to this problem is a variant of the first strategy above, two repositories; keep the code in the distributed VCS repo and the assets in a centralized VCS repo (such as SVN, Alienbrain, etc). Considering how most graphic designers work with binary files there is usually no need to branch unless it is really necessary (new features requiring lots of assets that isn't needed until much later). The disadvantage is that you will need to find a way to back up the central repository. Hence a third strategy: Off-Repository Assets (or Assets in CMS instead) Code in repository as usual and assets are not in repository. Assets should be put in some kind of content/media/asset management system instead or at least is on a folder that is regularly backed up. This assumes that there is very little need to back-track versions with graphics. If there is a need for back-tracking then graphic changes are negligible. Advantages Does not bloat the code repository (helpful for e.g. git as it frequently does file checking) Enables flexible handling of assets such as deployment of assets to servers dedicated for just assets If on CMS with a API, assets should be relatively easy to handle in code Disadvantages No BOM support No easy extensive version back-tracking support, this depends on the backup strategy for your assets A: Thoughts, no experience: I would indeed seperate code from data. Assuming that there is a set of images that belongs to the application, I would just keep that on a centralized server. In the code, I would then arrange (through explicit coding) that the application can integrate both local or remote assets. People contributing can then put new images in their local store at first, integrating it with some kind of (explicit) upload procedure into the central store when required and approved.
{ "pile_set_name": "StackExchange" }
Q: SQL is only reading 1 UserID When I'm Requesting A Picture + Name from the ID. Wondering Why I have an asp repeater reading a datasource and it's linked eventually to this code through the code behind [dbo].[GetFeatStatic] AS BEGIN DECLARE @FeaturedStatic TABLE ( UserID INT, UserTitle varchar(50), Title varchar(50), Summary text, DatePosted date, FirstName varchar(50), LastName varchar(50), Picture varchar(100) ) INSERT INTO @FeaturedStatic SELECT TOP 6 StaticContent.UserID, StaticContent.UserTitle, StaticContent.Title, SUBSTRING(StaticContent.Article, 0, 200) AS Summary, StaticContent.DatePosted, 'FirstName', 'LastName', 'Picture' FROM StaticContent INNER JOIN FeaturedStatic ON FeaturedStatic.ContentID = StaticContent.ContentID ORDER BY FeaturedStatic.DateFeatured DESC UPDATE @FeaturedStatic SET FirstName = Users.FirstName, LastName = Users.LastName, Picture = Users.Picture FROM Users INNER JOIN FeaturedStatic ON UserID = Users.UserID SELECT * FROM @FeaturedStatic END Wondering why it won't read Users.Picture + Users.First/LastName. I think it has something to do with INNER JOIN FeaturedStatic ON UserID = Users.UserID, but not sure. Thanks in advance. A: You should be able to do this all on your insert without needing the update. INSERT INTO @FeaturedStatic SELECT TOP 6 StaticContent.UserID, StaticContent.UserTitle, StaticContent.Title, SUBSTRING(StaticContent.Article, 0, 200) AS Summary, StaticContent.DatePosted, Users.FirstName, Users.LastName, Users.Picture FROM StaticContent INNER JOIN FeaturedStatic ON FeaturedStatic.ContentID = StaticContent.ContentID INNER JOIN Users ON StaticContent.UserID = Users.UserID ORDER BY FeaturedStatic.DateFeatured DESC
{ "pile_set_name": "StackExchange" }
Q: colon breaks the bash script I'm trying to run this script: #!/bin/bash DAR=$(ffprobe -v error -of default=noprint_wrappers=1:nokey=1 -show_entries stream=display_aspect_ratio $1) echo $DAR if [ $DAR -eq 16:9 ] then echo sixteen-by-nine else echo not-sixteen-by-nine the result of the script is: 16:9 line 3: [: 16:9: integer expression expected not-sixteen-by-nine How can I safely use the string 16:9? A: Use = for string comparison (-eq is only for comparing integers, hence the error integer expression expected) and quote both values like "$DAR" and "16:9": if [ "$DAR" = "16:9" ] Quoting is probably not strictly necessarily here, but considered to be "good practice" since sooner or later you'll have a string like 16 9 (with space) which will break stuff. Typically, you always want to quote strings to be on the safe side (I also find it easier to read since strings can now be syntax highlighted).
{ "pile_set_name": "StackExchange" }
Q: animation issues when editing a uitableview This is really simple, though still driving my nuts. I have a uitableview where I am trying to animate transition in and out of editing mode. This is what I took from an example that I have seen. It does do the job, but without the animation. Any thoughts? - (IBAction) EditTable:(id)sender { if(self.editing) { [super setEditing:NO animated:YES]; [tblSimpleTable setEditing:NO animated:YES]; [tblSimpleTable reloadData]; [self.navigationItem.leftBarButtonItem setTitle:@"Edit"]; [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain]; } else { [super setEditing:YES animated:YES]; [tblSimpleTable setEditing:YES animated:YES]; [tblSimpleTable reloadData]; [self.navigationItem.leftBarButtonItem setTitle:@"Done"]; [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone]; } } PS: I am also not sure why I need this line: [super setEditing:NO animated:YES]; but things just dont seem to work at all without it. I just saw a few examples online that dont do that. Thanks! A: Maybe you should not reloadData when set editing property. BTW, What's your "super" class? Normally you don't have to invoke [super setEditing:YES animated:YES];
{ "pile_set_name": "StackExchange" }
Q: no module name datetime after ubuntu 13.04 upgrade Just did an upgrade from ubuntu 12.10 to 13.04 and getting this when running django site in virtualenv (virtualenv)sysadmin@ubuntu:~/webapps/devsite/djangosite$ ./manage.py runserver Traceback (most recent call last): File "./manage.py", line 2, in <module> from django.core.management import execute_manager File "/home/sysadmin/webapps/devsite/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 7, in <module> from django.core.management.base import BaseCommand, CommandError, handle_default_options File "/home/sysadmin/webapps/devsite/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 14, in <module> from django.utils.encoding import smart_str File "/home/sysadmin/webapps/devsite/virtualenv/local/lib/python2.7/site-packages/django/utils/encoding.py", line 4, in <module> import datetime ImportError: No module named datetime A: Just do virtualenv /home/sysadmin/webapps/devsite/virtualenv/ this will reinstall Python in the VirtualEnv and it will work after that (and you won't need to reinstall the libraries). Update: when I was dealing with the same problem after upgrading from 14.04 to 14.10, virtualenv didn't want to overwrite the existing symlink to Python, so I had to remove it first (in this example that would be rm /home/sysadmin/webapps/devsite/virtualenv/python)
{ "pile_set_name": "StackExchange" }
Q: Leave some columns while copying to new DataFrame in R I want to remove some columns of a DataFrame in R and copy the rest into a new DataFrame. Since the number of columns i have to copy is more, and the number of columns that I need not to copy is just three, I don't want to write individual colnames for copying. Here is what I wrote - col = c("ta_rating_score","id","city_id","image_quality_score") imp_col = data[,~col] I got this error- Error in .subset(x, j) : invalid subscript type 'language' Not able to get where I am going wrong. A: You can use setdiff and names to select columns by exclusion. Without recreating your data... df <- data.frame(x = 1:8, y = 11:18, z = 21:28) print(df[,setdiff(names(df),'y')]) A: You can try with data[, -which(colnames(data) %in% col)] For example you can see with mtcars dataset mtcars # mpg cyl disp hp drat wt qsec vs am gear carb #Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 #Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 #Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 #Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 #Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 #Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 #Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 #Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 #Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 #Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 #Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 #Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 #Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 #Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 #Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 #Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 #Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 #Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 #Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 #Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 #Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 #Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 #AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 #Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 #Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 #Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 #Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 #Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 #Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 #Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 #Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 #Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 cols <- c("mpg", "cyl") mtcars[, -which(colnames(mtcars) %in% cols)] # disp hp drat wt qsec vs am gear carb #Mazda RX4 160.0 110 3.90 2.620 16.46 0 1 4 4 #Mazda RX4 Wag 160.0 110 3.90 2.875 17.02 0 1 4 4 #Datsun 710 108.0 93 3.85 2.320 18.61 1 1 4 1 #Hornet 4 Drive 258.0 110 3.08 3.215 19.44 1 0 3 1 #Hornet Sportabout 360.0 175 3.15 3.440 17.02 0 0 3 2 #Valiant 225.0 105 2.76 3.460 20.22 1 0 3 1 #Duster 360 360.0 245 3.21 3.570 15.84 0 0 3 4 #Merc 240D 146.7 62 3.69 3.190 20.00 1 0 4 2 #Merc 230 140.8 95 3.92 3.150 22.90 1 0 4 2 #Merc 280 167.6 123 3.92 3.440 18.30 1 0 4 4 #Merc 280C 167.6 123 3.92 3.440 18.90 1 0 4 4 #Merc 450SE 275.8 180 3.07 4.070 17.40 0 0 3 3 #Merc 450SL 275.8 180 3.07 3.730 17.60 0 0 3 3 #Merc 450SLC 275.8 180 3.07 3.780 18.00 0 0 3 3 #Cadillac Fleetwood 472.0 205 2.93 5.250 17.98 0 0 3 4 #Lincoln Continental 460.0 215 3.00 5.424 17.82 0 0 3 4 #Chrysler Imperial 440.0 230 3.23 5.345 17.42 0 0 3 4 #Fiat 128 78.7 66 4.08 2.200 19.47 1 1 4 1 #Honda Civic 75.7 52 4.93 1.615 18.52 1 1 4 2 #Toyota Corolla 71.1 65 4.22 1.835 19.90 1 1 4 1 #Toyota Corona 120.1 97 3.70 2.465 20.01 1 0 3 1 #Dodge Challenger 318.0 150 2.76 3.520 16.87 0 0 3 2 #AMC Javelin 304.0 150 3.15 3.435 17.30 0 0 3 2 #Camaro Z28 350.0 245 3.73 3.840 15.41 0 0 3 4 #Pontiac Firebird 400.0 175 3.08 3.845 17.05 0 0 3 2 #Fiat X1-9 79.0 66 4.08 1.935 18.90 1 1 4 1 #Porsche 914-2 120.3 91 4.43 2.140 16.70 0 1 5 2 #Lotus Europa 95.1 113 3.77 1.513 16.90 1 1 5 2 #Ford Pantera L 351.0 264 4.22 3.170 14.50 0 1 5 4 #Ferrari Dino 145.0 175 3.62 2.770 15.50 0 1 5 6 #Maserati Bora 301.0 335 3.54 3.570 14.60 0 1 5 8 #Volvo 142E 121.0 109 4.11 2.780 18.60 1 1 4 2 PS: I have used variable name as cols here as col is a base R function, so it is advised not use a variable with a function name. See ?col
{ "pile_set_name": "StackExchange" }
Q: gdb fails to run ELF 64-bit program with "File format not recognized" I'm trying to use GDB to debug (to find an annoying segfault). When I run: gdb ./filename from the command line, I get the following error: This GDB was configured as "i686-pc-linux- gnu"..."/path/exec": not in executable format: File format not recognized When I execute: file /path/executable/ I get the following info: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.4.0, dynamically linked (uses shared libs), not stripped I am using GDB 6.1, and the executable is compiled with gcc version 3.4.6. I'm a little out of my water in terms of using gdb, but as far as I can tell it should be working in this instance. Any ideas what's going wrong? A: The executable is 64-bit (x86-64) and the debugger is a 32 bit (i686-pc-linux) build. You may need to install a 64-bit (x86-64) version of the debugger. A: I'm not sure if this is your problem, but I faced this situation very often. The executable in the build tree, build by make/automake is not a binary, but a script, so you cannot use gdb with it. Try to install the application and change the directory, because else gdb tries to debug the script. A: The question refers to "./filename" and to "/path/executable". Are these the same file? If you are doing a post-mortem analysis, you would run: gdb executable-file core-file If you are going to ignore the core file, you would run: gdb executable-file In both cases, 'executable-file' means a pathname to the binary you want to debug. Most usually, that is actually a simple filename in the current directory, since you have the source code from your debug build there. On Solaris, a 64-bit build of GDB is supposed to be able to debug both 32-bit and 64-bit executables (though I've had some issues with recent versions of GDB). I'm not sure of the converse - that a 32-bit GDB can necessarily debug 64-bit executables.
{ "pile_set_name": "StackExchange" }
Q: How can I set what will be done when my python program terminates with error? Is there any method to set certain action when my python program ends abruptly? Especially I want to delete a folder and leave a log what was the error using logging module. A: Depending on what you mean by "ends abruptly", the atexit module https://docs.python.org/2/library/atexit.html may be what you are looking for.
{ "pile_set_name": "StackExchange" }
Q: No resource ID found, when resource exists I am creating an app, that fetchs data from JSON, and i got stuck on one part: When i try to read my image from string to ImageView, i get error: E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2 Process: , PID: 9535 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.RuntimeException: No resource ID found for: i_coal / class android.graphics.drawable.Drawable at com.infonuascape.osrshelper.fragments.BankViewFragment.getResId(BankViewFragment.java:69) at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems.doInBackground(BankViewFragment.java:100) at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems.doInBackground(BankViewFragment.java:74) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NoSuchFieldException: i_coal at java.lang.Class.getDeclaredField(Class.java:890) at .fragments.BankViewFragment.getResId(BankViewFragment.java:66) at .fragments.BankViewFragment$GetItems.doInBackground(BankViewFragment.java:100) at .fragments.BankViewFragment$GetItems.doInBackground(BankViewFragment.java:74) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) How can i fix it? The resource exists if i try to use R.Drawable.i_coal; Also how can i check if the resource does not exist to skip it instead of throwing an error? BankViewFragment: import android.content.Context; public class BankViewFragment { private static final String TAG = "BankViewFragment"; private static Account account; private ListView lv; private ImageView iv; ArrayList<HashMap<String, String>> ItemList; public static BankViewFragment newInstance(final Account account) { BankViewFragment fragment = new BankViewFragment(); Bundle b = new Bundle(); fragment.setArguments(b); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.bank_view, null); ItemList = new ArrayList<>(); new GetItems().execute(); lv = (ListView) view.findViewById(R.id.list); iv = (ImageView) view.findViewById(R.id.logo); SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); String nikas = sharedPref.getString("bankname", "null"); return view; } public static int getResId(String resourceName, Class<?> c) { try { Field idField = c.getDeclaredField(resourceName); return idField.getInt(idField); } catch (Exception e) { throw new RuntimeException("No resource ID found for: " + resourceName + " / " + c, e); } } private class GetItems extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE); String nikas = sharedpreferences.getString("bankname", "null"); String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas; String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "NIKAS: " + nikas); Log.e(TAG, "ACCOUNT: " + account); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); JSONObject items = jsonObj.getJSONObject("bank"); Iterator keys = items.keys(); while(keys.hasNext()) { String dynamicKey = (String)keys.next(); JSONObject line = items.getJSONObject(dynamicKey); String item = line.getString("item"); Integer image = getResId(item, Drawable.class); String amount = line.getString("amount"); Log.e(TAG, "DAIGTAS: " + item); Log.e(TAG, "KIEKIS: " + amount); HashMap<String, String> contact = new HashMap<>(); String itembank = item.replaceAll("i_", ""); String itembanks = itembank.replaceAll("_", " "); contact.put("name", itembanks); contact.put("email", amount); ImageView ims = (ImageView) lv.findViewById(R.id.logo); lv.setBackgroundResource(getResId(item, Drawable.class)); ItemList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); new Runnable() { @Override public void run() { Toast.makeText(getContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }; } } else { Log.e(TAG, "Couldn't get json from server."); new Runnable() { @Override public void run() { Toast.makeText(getContext(), "Couldn't get json from server!", Toast.LENGTH_LONG).show(); } }; } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter(getContext(), ItemList, R.layout.list_item, new String[]{ "email","name"}, new int[]{R.id.email, R.id.name}); lv.setAdapter(adapter); } } } list_item.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="@dimen/activity_horizontal_margin"> <ImageView android:id="@+id/logo" android:layout_height="match_parent" android:layout_weight="1" app:srcCompat="@android:drawable/btn_star" android:layout_width="0dp" /> <TextView android:id="@+id/name" android:layout_width="219dp" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" android:textColor="@color/black" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/email" android:layout_width="83dp" android:layout_height="match_parent" android:paddingBottom="2dip" android:textColor="@color/black" /> </LinearLayout> A: try this context.getResources().getIdentifier(String name, String defType, String defPackage)
{ "pile_set_name": "StackExchange" }
Q: gson: Add function result to an object created by toJson() gson is such a great serialize/deserialization tool. It's really simple to get a JSON representation of an arbitrary object by using the toJson-function. Now I want to send the data of my object to the browser to be used within javascript/jQuery. Thus, I need one additional JSON element defining the dom class of the object which is coded within my object as a dynamic/memberless function public String buildDomClass() How to add this string to my String created by the toJson function? Any ideas? Thanks a lot A: An easy way is to combine a TypeAdapterFactory and an interface. First an interface for your method : public interface MyInterface { public String buildDomClass(); } then the factory : final class MyAdapter implements TypeAdapterFactory { @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) { final TypeAdapter<T> adapter = gson.getDelegateAdapter(this, tokenType); return new TypeAdapter<T>() { @Override public T read(JsonReader reader) throws IOException { return adapter.read(reader); } @Override public void write(JsonWriter writer, T value) throws IOException { JsonElement tree = adapter.toJsonTree(value); if (value instanceof MyInterface) { String dom = ((MyInterface) value).buildDomClass(); JsonObject jo = (JsonObject) tree; jo.addProperty("dom", dom ); } gson.getAdapter(JsonElement.class).write(writer, tree); } }; } } Easy to understand, if the object you want to serialize implement the interface, you delegate the serializing, and then you add an extra property holding you DOM. In case you don't know, you register a factory like this Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MyAdapter()).create();
{ "pile_set_name": "StackExchange" }
Q: What does it mean to "construct a sequence"? I am doing some Real Analysis homework, and one of the questions asks me to construct a sequence that obeys certain conditions-it is increasing etc. What does this mean exactly? What should my answer look like? A: There's no special mathematical meaning of the word "construct" in this context. It just means your answer will be a sequence. "Give" or "find" a sequence are other ways of phrasing it. Very simple example: Construct a sequence whose terms are strictly increasing. Answer: Let $a_n = n$ for all $n \ge 0$. Then $\{a_n\}_{n=1}^{+\infty}$ is a sequence whose terms are strictly increasing, because $a_{n+1} = n+1 > n = a_n$ for all $n \ge 0$. Note that the notation you're using in your course may vary slightly.
{ "pile_set_name": "StackExchange" }
Q: Popup menu writing value from array I have successfully created a custom dialog box which uses an array to read in a list of developer names from a table, and populates the selected record based on the row number pulled in from the developer table. Table is Developer ID Developer Name 1 A developer 2 B developer 3 C developer 4 D Developer 5 AAA Developer 6 C2 developer I have also had success in then populating the selected value from the popup menu back to the table. At present the developer list contains about 400 names. As new names are found, they need to be added to the table. In above example- ID 1 to 4 were added initially then 5 and 6 later and they aren't sorted alphabetically. My question is does anyone know if there any way that I can I get the table from the array in alphabetical order without upsetting the row numbers from the developer table? If I add say another 50 developers to the bottom of the table then it becomes hard to find them as they are not sorted alphabetically - whilst the first 400 I put in are. Given that the popup menu reads in the row number and assigns this to the value in the popup menu then writes it based on the value selected in the popup, I am unsure whether this can be done. iRows1 = TableInfo(developer, TAB_INFO_NROWS) 'redim developername array based on number of rows in table ReDim sDeveloperName1(iRows1) For iLoop1 = 1 to iRows1 Fetch rec iLoop1 from developer sDeveloperName1(iLoop1) = developer.developername Next 'Developer details groupbox control groupbox title "Developer Details" Position 5,206 width 130 height 97 control statictext position 10,216 title "Primary developer" control popupmenu position 10,228 width 120 ID 20 Title from Variable sDeveloperName1 into iDeveloperID1out Sub ReadIn_PopUpMenu_Items 'converts table value into the popupmenu item for primary developer listed dim developerID1temp as integer developerID1temp=selection.developerID1 if developerID1temp=0 then alter control 20 value 1 Else alter control 20 value developerID1temp End if End 'if 1st value in popup menu is selected then developer is unknown so write the 'value back to the selected record as 0 If iDeveloperID1out=1 then Update Selection set col20=0 else Update Selection set col20=iDeveloperID1out End If A: A very simple solution to your request would be to use a sorted table for reading and writing back the data/developer names. Currently you seem to be using the base table called Developer. You would basically just add a SQL Select that sorts the table and then use the sorted query in stead of the base table. Select * From DEVELOPER Order By DEVELOPERNAME Into __DEVELOPER__SORTED NoSelect Now you reading of the developer names would look like this: iRows1 = TableInfo(__DEVELOPER__SORTED, TAB_INFO_NROWS) 'redim developername array based on number of rows in table ReDim sDeveloperName1(iRows1) For iLoop1 = 1 to iRows1 Fetch rec iLoop1 from __DEVELOPER__SORTED sDeveloperName1(iLoop1) = __DEVELOPER__SORTED.DEVELOPERNAME Next It's important that you also use the sorted table when writing data back as the ROWID refers to the sorted query not the base table. And I would always recommend using a Do Until EOT() loop when looping thru a table - never a For loop: iRows1 = TableInfo(__DEVELOPER__SORTED, TAB_INFO_NROWS) 'redim developername array based on number of rows in table ReDim sDeveloperName1(iRows1) Fetch First From __DEVELOPER__SORTED Do Until EOT(__DEVELOPER__SORTED) iLoop1 = __DEVELOPER__SORTED.ROWID sDeveloperName1(iLoop1) = __DEVELOPER__SORTED.DEVELOPERNAME Fetch Next From __DEVELOPER__SORTED Loop Also looking a bit more at your code it seems that you update another table with the ROWID from the DEVELOPER that. If that's true you are definitely going down the wrong lane. The ROWID of a table is very dynamic; if you pack the table the ROWID might change. I would recommend that you add a more static ID column to your DEVELOPER table and use that in stead. You could change the reading to this: iRows1 = TableInfo(__DEVELOPER__SORTED, TAB_INFO_NROWS) 'redim developername array based on number of rows in table ReDim sDeveloperName1(iRows1) ReDim nDeveloperID1(iRows1) Fetch First From __DEVELOPER__SORTED Do Until EOT(__DEVELOPER__SORTED) iLoop1 = __DEVELOPER__SORTED.ROWID sDeveloperName1(iLoop1) = __DEVELOPER__SORTED.DEVELOPERNAME nDeveloperID1(iLoop1) = __DEVELOPER__SORTED.DEVELOPERID Fetch Next From __DEVELOPER__SORTED Loop And you can change the setting of the developer and the update to this: Sub ReadIn_PopUpMenu_Items 'converts table value into the popupmenu item for primary developer listed dim developerID1temp, i as integer developerID1temp=selection.developerID1 if developerID1temp=0 then alter control 20 value 1 Else For i = 1 To Ubound(nDeveloperID1) If developerID1temp = nDeveloperID1(i) Then alter control 20 value i End if Next End if End 'if 1st value in popup menu is selected then developer is unknown so write the 'value back to the selected record as 0 If iDeveloperID1out=1 then Update Selection set col20=0 else Update Selection set col20=nDeveloperID1(iDeveloperID1out) End If
{ "pile_set_name": "StackExchange" }
Q: Execute cmdlet through variable? I want to use an if \ else statement to determine which cmdlet to run while keeping the same params for both commands: For example I have this call: New-AzureRmResourceGroupDeployment ` -ResourceGroupName $ResourceGroup ` -TemplateFile $TemplateUri ` -TemplateParameterFile $TemplateParamFile But I want to use a variable to determine the verb: $myVerb = if ($booleanTest) {"Test"} else {"New"} [$myVerb]-AzureRmResourceGroupDeployment ` -ResourceGroupName $ResourceGroup ` -TemplateFile $TemplateUri ` -TemplateParameterFile $TemplateParamFile OR something like this: $command = if ($booleanTest) {"Test-AzureRmResourceGroupDeployment"} else {"New-AzureRmResourceGroupDeployment"} $command ` -ResourceGroupName $ResourceGroup ` -TemplateFile $TemplateUri ` -TemplateParameterFile $TemplateParamFile I tried the $command version but it failed with this: At C:\Users\Administrator\Dropbox\projects\deloitte\Suncore\Dev\scripts\az-d eploy.ps1:36 char:13 + -ResourceGroupName $ResourceGroup + ~~~~~~~~~~~~~~~~~~ Unexpected token '-ResourceGroupName' in expression or statement. At C:\Users\Administrator\Dropbox\projects\deloitte\Suncore\Dev\scripts\az-d eploy.ps1:36 char:32 + -ResourceGroupName $ResourceGroup + ~~~~~~~~~~~~~~ A: To do exactly what you are describing you'd need to wrap the whole command as a string and then call it with Invoke-Expression. For Example: $MyCommand = "$myVerb-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroup -TemplateFile $TemplateUri" Invoke-Expression $MyCommand But I think this isn't a very clear way to write a script. A better option would be to use Splatting, which is where you create a hashtable of the parameters that you can then send the cmdlet via a special @ character with the variable name. For example: $AzureParams = @{ ResourceGroupName = $ResourceGroup TemplateFile = $TemplateUri TemplateParameterFile = $TemplateParamFile } If ($booleanTest) { Test-AzureRmResourceGroupDeployment @AzureParams } Else { New-AzureRmResourceGroupDeployment @AzurParams } This also has the benefit of avoiding using the backtick character, which is generally encouraged as it's hard to spot and easy to break. A: I don't recommend using this over the other answer but to directly answer your question, add the invocation operator & $command = if ($booleanTest) { "Test-AzureRmResourceGroupDeployment" } else { "New-AzureRmResourceGroupDeployment" } & $command ` -ResourceGroupName $ResourceGroup ` -TemplateFile $TemplateUri ` -TemplateParameterFile $TemplateParamFile
{ "pile_set_name": "StackExchange" }
Q: How to send data to bluetooth printer via android app? I am developing an app which will send data to a printer via bluetooth to print (A thermal printer for receipts). I have followed the code which in this link. http://pastie.org/6203514 and this link also http://pastie.org/6203516 I am able to see the device and its MAC Address and its name, when I send the data to the printer (the light LED on the printer stops blink and becomes standard i.e the printer is connected with my android phone) but when I send the data it is not printing and nor it is giving any error also. I have googled a lot and I found many codes and tried all set of codes but could not able to print . Please any one could help me out of here. I heard with Intents it can be done easily but could not get the exact solution with Intents. Any help would be appreciated Thanks in Advance Ganesh A: Finally I solved this problem by my self and the problem is that the header byte which I am sending to the printer is the real culprit. Actually I am sending 170,1 (where 170 is the first byte that the printer must receive and the second byte is the printer id I mean some com port which these two values are given by Printer control card designer). Actual I have to send 170,2 where 2 is the Printer Id so that it gives the correct print and for every printer it is common of sending the data based on their control card's. Thanks a lot friends and here is my code that u can use these code for all types of printers(for POS-Thermal Printers) public void IntentPrint(String txtvalue) { byte[] buffer = txtvalue.getBytes(); byte[] PrintHeader = { (byte) 0xAA, 0x55,2,0 }; PrintHeader[3]=(byte) buffer.length; InitPrinter(); if(PrintHeader.length>128) { value+="\nValue is more than 128 size\n"; txtLogin.setText(value); } else { try { for(int i=0;i<=PrintHeader.length-1;i++) { mmOutputStream.write(PrintHeader[i]); } for(int i=0;i<=buffer.length-1;i++) { mmOutputStream.write(buffer[i]); } mmOutputStream.close(); mmSocket.close(); } catch(Exception ex) { value+=ex.toString()+ "\n" +"Excep IntentPrint \n"; txtLogin.setText(value); } } } And this code for the rest: public void InitPrinter() { try { if(!bluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) { for(BluetoothDevice device : pairedDevices) { if(device.getName().equals("Your Device Name")) //Note, you will need to change this to match the name of your device { mmDevice = device; break; } } UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID //Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); //mmSocket = (BluetoothSocket) m.invoke(mmDevice, uuid); mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); bluetoothAdapter.cancelDiscovery(); if(mmDevice.getBondState()==2) { mmSocket.connect(); mmOutputStream = mmSocket.getOutputStream(); } else { value+="Device not connected"; txtLogin.setText(value); } } else { value+="No Devices found"; txtLogin.setText(value); return; } } catch(Exception ex) { value+=ex.toString()+ "\n" +" InitPrinter \n"; txtLogin.setText(value); } }
{ "pile_set_name": "StackExchange" }
Q: C++ multiple files with common name beginning Is there any way to open files which have common name beginning without specifying their full names and amount? They should be open one by one, not all at once. For example, I have files: certainstr_123.txt, certainstr_5329764.txt, certainstr_1323852.txt. Or, maybe, it can be more easily done in some another language? Thank you. A: C++ doesn't define a standard way for listing files in that way. The best cross platform approach is to use a library such as the boost filesystem module. I don't think boost::filesystem has wildcard search, you have to filter files yourself but it isn't difficult. You could use regular expressions, like in the other answer (it's the perfect-fit solution). Probably it could be enough to check file extension (i->path().extension()) and filename starting with "certainstr_" (boost::starts_with or std::string::substr). If you choose C++11 standard regex library make sure to have a recent libstdc++. There are a lot of system specific functions. E.g. see: How can I get the list of files in a directory using C or C++? How do I get a list of files in a directory in C++? for some Unix/Windows examples. You could also try something like (Windows): std::system("dir /b certainstr_*.txt > list.txt"); or (Unix): std::system("ls -m1 certainstr_*.txt > list.txt"); parsing the list.txt output file (of course this is a hack). Anyway, depending on your needs, Python-based (or script-based) solutions could be simpler (see also How to list all files of a directory?): [glob.glob('certainstr_*.txt')][3] or also: files = [f for f in os.listdir('.') if re.match(r'certainstr_\d+.txt', f)] This is the Python equivalent of https://stackoverflow.com/a/26585425/3235496
{ "pile_set_name": "StackExchange" }
Q: AJAX data post is not received correctly I have two files in my site home.php (view) and home.php (controller). In home.php (view) I have a jquery function that sends an AJAX request (it's mostly taken from the W3 jquery/AJAX example). In home.php (controller) I have a PHP variable that should accept the posted value form (view), but it doesn't. I've put an echo to check the value, but nothing appears. Is there any problem with my code? home.php (view) $(document).ready(function(){ $("button").click(function(){ $.post("home.php", { name:"George" }); }); }); home.php (controller) $name = $_POST['name']; echo ($name); Checking Firebug's console the POST has a response that is comprised of the whole HTML code of home.php (view) and post parameters: name George A: You aren't doing anything with data in your success function. It isn't going to be visible on the page unless you add the data to the page.
{ "pile_set_name": "StackExchange" }
Q: Get from observable no more than every 100ms, but always get the final value I have a worker which exposes a Subject<string>, which publishes log messages very quickly. Writing to the console is slow, so I want to only write to the console every 100ms, at the most. When the task is finished I want to write out the most recent published string, to avoid having things like Doing work 2312/2400 ...done. (or even ...done if the task takes <100ms.) I'm new to reactive extensions, and though I've heard talks about how awesome they are, this is the first time I've noticed a situation where they could help me. So, in summary, 1) Don't give me an event more than once every 100ms 2) I need to know about the final event, regardless of when it arrives. I'll put my code in an answer below, but please suggest something better. Maybe I've missed a standard call which achieves this? A: It's actually simpler than you make out if the observable that is the source of your events called OnCompleted() when it's done. This will do the trick by itself: observable.Sample(TimeSpan.FromMilliseconds(100)).Subscribe(log); This is because Sample will fire one last time when the source of it's events completes. Here's a full test: var sub = new Subject<string>(); var gen = Observable.Interval(TimeSpan.FromMilliseconds(50)).Select((_,i) => i).Subscribe(i => sub.OnNext(i.ToString())); sub.Sample(TimeSpan.FromSeconds(1)) .Subscribe(Console.WriteLine); Thread.Sleep(3500); sub.OnCompleted(); Even though I sleep for 3.5 seconds, 4 events fire, the last one firing when I call OnCompleted(). Another point to note is that it's bad form if Worker.GetObservable() actually returns a Subject<string> - even if it is that in the Worker class, what it really should do is return just the IObservable<string> interface. This is more than mere style, it is a separation of concerns and returning the minimum functional interface needed.
{ "pile_set_name": "StackExchange" }
Q: Links in Excel workbook not loading due to local google drive location I originally posted this in SuperUser, but I think that may have been the wrong place, so I am cross posting it here. -Edit: The tag is Google-drive-sdk, but it's a problem with google drive in windows, not the api. I guess there's no option for google drive itself I have a master workbook which has links to about nine different files. I also have two other workbooks used by other people that link to the master workbook for information. All of these files are saved on google drive and everyone associated has access to all of the files individually. Up until yesterday there wasn't a problem with anyone loading the files, but now all of a sudden when opening the files on other computers, they can't find the links and can't load with the new information. I'm assuming that part of the problem is due to me having google drive saved to my D:\ drive instead of C:\ like most of the other computers, and in my files the links all point to D:\google drive\, but as I said, it was all working up until yesterday. Is there any way to work around this issue, without actually changing my drive location? I know I'm not the only person that has put google drive on a different partition than windows, so there is the potential for even that, causing conflicts. Thank you for your help, and let me know if you need any more information. A: This doesn't look like a Drive API - specific inquiry, but I'll try to pitch in. I'm presuming you're using Google Drive for Windows (since you indicated the Google Drive is installed in D:), the location of the files referenced inside the workbook file would be absolute. You (and others) who installed the Drive app on D:\ wouldn't see the problem, but the others who installed it on the default location may have (which is what happened when you opened the files on other computers). Check if you can set relative paths instead of absolute paths (same principle can be said on drive files), for example D:\Google Drive\SharedFolder\Workbook01.xls D:\Google Drive\SharedFolder\Workbook02.xls D:\Google Drive\SharedFolder\Workbook02.xls links referencing would be Workbook01.xls Workbook02.xls Workbook03.xls Hopefully this would help with the location issue.
{ "pile_set_name": "StackExchange" }
Q: Changing Style Sheet javascript I got this HTML code: <head> <script type="application/javascript" src="javascript.js"> <link id="pagestyle" href="default.css" rel="stylesheet" type="text/css" /> </head> <body> <button id="stylesheet1" > Default Style Sheet </button> <button id="stylesheet2" > Dark Style Sheet </button> </body> And in javascript.js I got this: function swapStyleSheet(sheet) { document.getElementById("pagestyle").setAttribute("href", sheet); } function initate() { var style1 = document.getElementById("stylesheet1"); var style2 = document.getElementById("stylesheet2"); style1.onclick = swapStyleSheet("default".css); style2.onclick = swapStyleSheet("dark".css); } window.onload = initate; I want to the style sheets to change while pressing this buttons. I can't figure out why it is not working. A: One guess would be the missing .css property, another would be the fact that onclick is not a function, but a result from invoking one: Make all of .css a string and assign functions to onclick: style1.onclick = function () { swapStyleSheet("default.css") }; style2.onclick = function () { swapStyleSheet("dark.css"); };
{ "pile_set_name": "StackExchange" }
Q: What resolution images could I use for posters on the wall? If I wanted to print an image found online and get a typical 27" x 40" sized poster what resolution image do I need? 4000 x 6000 or double that? I am confused over DPI and PPI. A: It depends on how close you expect the viewer to stand, as vision is based on angular frequency. If your image has a certain size and you need to print it at some size then there is not much you can do about the resolution. 150 PPI is usually quite acceptable for items you view at a distance. Most human sized outdoor commercials are at that kind of resolution. Especially if your text items are vectors. You could use online calculators to verify your values, if you have no idea what your doing.
{ "pile_set_name": "StackExchange" }
Q: How to change Anchor Tag text on Click in angular 2 I have to toggle the text On view and Hide How do i do that? I tried many but didnt work. I dont want to use Jquery for this. I want to use only angular. Can anyone help me with this?? <a class="history-link view-history-class" id="show-view-address" (click)="view()" >View</a> Component: view : boolean ; view(){ this.view = !this.view } For this when i click view It will toggle a table. Then the text should change to Hide. Same when i click hide. A: import {Component, NgModule, VERSION} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'my-app', template: ` <div> <a href = "#" (click) = "on()">{{value}}</a> </div> `, }) export class App { value = "View"; toogle = true; on(val:boolean){ //either this this.value = (!this.toogle)?"View":"Hide"; this.toogle = !this.toogle; //or this this.value = (this.value == "View")?"Hide":"View"; // and remove toogle } } @NgModule({ imports: [ BrowserModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {} PLUNKER LINK - https://plnkr.co/edit/Wt8s8HSraBsnx9PzgDrA?p=preview
{ "pile_set_name": "StackExchange" }
Q: It also execute my else statement My if statement is true but it also executes my else statement if ((request.readyState === 4) && (request.status === 200)) { var i = JSON.parse([request.responseText]); console.log(i); } else { alert("no file"); } A: Maybe you expected this snippet to be executed only once, but the readyStateChange event is fired multiple times. Try this: if (request.readyState===4) { if (request.status===200) { var i = JSON.parse([request.responseText]); console.log(i); } else { alert("no file"); } }
{ "pile_set_name": "StackExchange" }
Q: What is an English adjective that means "able to learn new things quickly"? What is an English adjective to describe the following skill: "able to learn new things quickly"? For example: Billy is very _________, as he learns new skills more quickly than an average person. A: Fast learner or quick learner A: I would say clever, quick-witted or, informally, smart: clever (adjective) quick to understand, learn, and devise or apply ideas; intelligent. quick-witted (adjective) showing or characterized by an ability to think or respond quickly or effectively. A: here are some words that came to mind - sagacious, Exhibiting or marked by keen intellectual discernment, especially of human motives and actions; having or proceeding from penetration into practical affairs in general; having keen practical sense; acute in discernment or penetration; discerning and judicious; shrewd: as, a sagacious mind. there's astute, Quick at seeing how to gain advantage, especially for oneself; shrewd; critically discerning. and of course, polymathic Pertaining to polymathy; acquainted with many branches of learning. and autodidactic :) Relating to or having the characteristics of an autodidact; self-taught.
{ "pile_set_name": "StackExchange" }
Q: Passing custom vertex structure to GLSL shaders I'm trying to pass a structure to a simple GLSL vetrex shader. Here's how the structure look like on the C++ side: struct Vertex { float position[3]; char boneIndex[4]; float weights[4]; float normals[3]; float textureCords[2]; }; Is it possible to pass array of this vertex to the vertex shader without creating a separate array for each component? Can I do something like this: #version 330 core uniform mat4 MVP; layout(location = 0) in struct Vertex { vec3 position; uint boneIndex; vec4 weights; vec3 normals; vec2 textureCords; } vertex; out vec2 UV; void main() { gl_Position = MVP * vec4(vertex.position, 1.0f); UV = vertex.textureCords; } (Dont mind that not all of the components are in use, it's just for the example.) And if I can, how can I pass the data to it from the C++ side using the glVertexAttribPointer() function? (According to my understanding you can pass only 1,2,3,4 to the size parameter). Is it the even the right way to do things? I'm a beginner in OpenGL programming so if you have an answer please don't hesitate to include obvious details. Edit: I ended up doing something like this: glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); //float position[3] glVertexAttribPointer(1, 1, GL_INT, GL_FALSE, 12, (void*)0); //char boneIndex[4] glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 16, (void*)0); //float weights[4] glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 32, (void*)0); //float normals[3] glVertexAttribPointer(4, 2, GL_FLOAT, GL_FALSE, 44, (void*)0); //float textureCords[2] glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indiceBuffer); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, (void*)0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); On the C++ size, and on the GLSL vertex shader: #version 330 core uniform mat4 MVP; layout(location = 0) in vec3 position; layout(location = 1) in int boneIndex; layout(location = 2) in vec4 weight; layout(location = 3) in vec3 normal; layout(location = 4) in vec2 UVCords; out vec2 UV; void main() { gl_Position = MVP * vec4(position, 1.0f); UV = UVCords; } But it still won't work, the model wont render correctly A: The method you've used to transfer the interleaved data is correct (that is, using glVertexAttribPointer, however, your last two parameters are incorrect). The penultimate is the stride (which is the same for every item in the struct, and should be the size of the struct), and the last is the offset, which should be different for each element (as they are at different offsets in the struct itself). Also it is best not to use constants here, but instead, use the sizeof() operator, to make your code as platform independent as possible. Here's what it should look like: glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr ); //float position[3] glVertexAttribIPointer( 1, 1, GL_INT, GL_FALSE, sizeof(Vertex), std::reinterpret_cast<void *>(offsetof(Vertex, boneIndex)) ); //char boneIndex[4] glVertexAttribPointer( 2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), std::reinterpret_cast<void *>(offsetof(Vertex, weights)) ); //float weights[4] glVertexAttribPointer( 3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), std::reinterpret_cast<void *>(offsetof(Vertex, normals)) ); //float normals[3] glVertexAttribPointer( 4, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), std::reinterpret_cast<void *>(offsetof(Vertex, textureCoords)) ); //float textureCoords[2] Also, you should probably ensure that your Vertex struct is not packed to fit into a nice word boundary. This is done by using #pragma pack(0), if your compiler supports it. (Remember to reset this after after your struct, because otherwise the compiler will use this directive throughout the rest of the compilation process, and all your aggregate data structures will be structured in a way that doesn't yield to the best possible fit with regards to world alignment.), here's what that looks like: #pragma pack(push, 0) struct Vertex { float position[3]; char boneIndex[4]; float weights[4], normals[4], textureCoords[2]; }; #pragma pack(pop)
{ "pile_set_name": "StackExchange" }
Q: How to start with a Minimalistic build in Dwarf Fortress What are the first things you should do when starting with a minimalistic build (1 anvil, 1 copper nugget) in Dwarf Fortress. A: A true minimalistic build is 1 anvil and 2 copper nuggets; so I'm going to assume that's what you meant. De-construct your wagon (you have no other way to get wood). Make your wood furnace (copper nugget #1) Cook 1 ash and 2 coal from your three wood De-construct your furnace Use the ash to make a smelter (ash is a fire safe material in DF) Smelt 1 copper bar (you're going to need the other one) Build a forge (nugget #2 + anvil) Forge a battle axe (use this to cut down 3 trees) De-construct your forge Build a second wood furnace (with the nugget from the forge) Bake 1 ash and 2 coal again De-construct the furnace Build a forge out of the ash and the anvil (again the ash is a fire safe material) Smelt the copper bar from the wood furnace Forge a pick This gets you a forge, a smelter, an axe and a pick, thus completing the minimalist challenge. Or you could just start out with 2 ash, 2 coal, an axe, a pick and an anvil and skip this otherwise tedious beginning. Its worth noting that with 1 copper nugget you have the choice of either a pick or an axe. As a result you either don't have enough copper or not enough wood to complete the challenge. Edit: actually if you had above ground lava, you could avoid needing the second copper nugget and make two ash giving you have enough for the forge (as lava forges don't need coals). DF2010 In DF2010 (the latest build) you can use the training axe in place of a normal axe to cut down more trees. People who traditionally used the minimalistic build consider this "cheating" as you essentially get your axe for free. This can let you use 1 copper nugget. De-construct your wagon (you have no other way to get wood). Build a carpenter's shop (wood #1) Construct a training axe (wood #2) Make your wood furnace out of the copper nugget Cut down 3 trees Cook 2 ash and 2 coal Use the ash to make a smelter Deconstruct the furnace to get your nugget back Smelt your copper bar (using ash #1 and the nugget) Build a forge from the ash and anvil (using ash #2) Forge the bar into a pick This gets you your forge, smelter, axe and pick. Everything you need to build a full society. A: A true minimalistic build is nothing but a wagon; but I'm going to assume that's not what you meant. The idea is to survive the summer until the caravan arrives in the fall. Before the introduction of training axes, this meant you had only three logs with which you would need to use sparingly until fall when you built a trade depot from them. You also need to build up enough wealth to purchase some tools in the fall, which you can do by gathering, then farming those seeds, fishing, and cooking the food you have into prepared meals. Now that training axes can cut down trees, you can use one of your three logs from your wagon to make an axe, then build a wooden fortress, barrels and a still, etc. If you try this out, good luck! I myself usually spend all my starting points, but bring along an anvil and ore in lieu of the more expensive zero-quality tools.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to do this query without the sub-select? I'm not positive but I believe sub-selects are less than optimal (speedwise?). Is there a way to remove this sub-select from my query (I think the query is self-explanatory). select * from tickers where id = (select max(id) from tickers where annual_score is not null); A: Would something like: SELECT * FROM ticker WHERE annual_score IS NOT NULL ORDER BY id desc LIMIT 1 work? A: That particular sub-select shouldn't be inefficient at all. It should be run once before the main query begins. There are a certain class of subqueries that are inefficient (those that join columns between the main query and the subquery) because they end up running the subquery for every single row of the main query. But this shouldn't be one of them, unless MySQL is severely brain-damaged, which I doubt. However, if you remain keen to get rid of the subquery, you can order the rows by id (descending) and only fetch the first, something like: select * from tickers where annual_score is not null order by id desc limit 0, 1
{ "pile_set_name": "StackExchange" }
Q: Are client side cookies accessible by all and are there cookies on the server side If I have a SITEA writing a cookie to my browser, can SITEB write code to access the cookie or are cookies hidden from websites that didn't create them ? My answer to that was that YES, SITEB can read the document.cookie and if he knows what's the cookie name, it can access it. Was I right ? Regarding the second questions, I don't think there are Server Side cookies other than SESSIONS. Am I right? A: Cookies are usable by both the server and the client. Cookies can only be read by the website the domain that creates them; you can use sub-domains domains, url paths. Cookies are generally considered insecure if used from the client side, and should not be used to hold sensitive data if accessed from the client side. The server can encrypt information and store it in the cookie as long as the encryption is done on safe manner on the server. Using cookies are a good way of avoiding the use of a session server, and if you do not save sensitive data they are a good way to store state in a web application. Although they can be more challenging than other session mechanisms, the do work on both the client and the server. Advertising products like double click use cookies to track a monitor user activity, which is how ads follow you from site to site. Third-party and first-party cookies Cookies are categorized as third-party or first-party depending on whether they are associated with the domain of the site a user visits. Note that this doesn’t change the name or content of the actual cookie. The difference between a third-party cookie and a first-party cookie is only a matter of which domain a browser is pointed toward. The exact same kind of cookie might be sent in either scenario. https://support.google.com/adsense/answer/2839090
{ "pile_set_name": "StackExchange" }
Q: How to get from input datalist selected id Hello i have one datalist and some input with list. i can`t get input selected id I try do it but it`s not work $(".updateResolutions").click(function () { let regDate = $(this).closest('div').find('#regDate').val(); var opt = $('.Organizations option[value="' + $(this).val() + '"]'); console.log(opt.attr('id')); console.log(opt); ); }); this is html <datalist id="OrganizationsList"> <option id="1" value="Name1" /> <option id="2" value="Name2" /> </datalist> <div class="col-md-11 borderDiv"> <input type="date" name="regdate" id="regDate" /> <label for="regdate"> Организация : </label> <input type="text" list="OrganizationsList" name="resOrg" class="resOrgId Organizations" value="@item.OrgName" style="width:30em" /> <button type="button" id="updateResolutions" class="btn btn-default updateResolutions">изменить</button> </div> <div class="col-md-11 borderDiv"> <input type="date" name="regdate" id="regDate" /> <label for="regdate"> Организация : </label> <input type="text" list="OrganizationsList" name="resOrg" class="resOrgId Organizations" value="@item.OrgName" style="width:30em" /> <button type="button" id="updateResolutions" class="btn btn-default updateResolutions">изменить</button> </div> div can be more than 2 (3-10) A: You can get selected option by its value: $('#OrganizationsList option[value="' + $(this).siblings('input[name=resOrg]').val() + '"]'). $(function(){ $(".updateResolutions").click(function (e) { var opt = $('#OrganizationsList option[value="' + $(this).siblings('input[name=resOrg]').val() + '"]').attr('id'); console.log(opt); }); }); <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <datalist id="OrganizationsList"> <option id="1" value="Name1" /> <option id="2" value="Name2" /> </datalist> <div class="col-md-11 borderDiv"> <label for="regdate1"> Организация : </label> <input type="text" list="OrganizationsList" name="resOrg" id="" value="Name1" style="width:30em" /> <button type="button" id="regdate1" class="btn btn-default updateResolutions">изменить</button> </div> <div class="col-md-11 borderDiv"> <label for="regdate2"> Организация : </label> <input type="text" list="OrganizationsList" name="resOrg" id="" value="Name2" style="width:30em" /> <button type="button" id="regdate2" class="btn btn-default updateResolutions">изменить</button> </div> Additionally, the id value should be unique in your buttons and other inputs.
{ "pile_set_name": "StackExchange" }
Q: How to create an object diagram in Magic Draw? I want to create an object diagram of an existing class diagram in Magic Draw version 16.0. How can I do that? The official support of Magic Draw wrote in the forum "what do you mean by an object diagram" so I do not expect any help from that site :-) A: Yes there is. It is available from the context menu after right-click on a package that is shown in the "containment tree".
{ "pile_set_name": "StackExchange" }
Q: LaravelQuestion - Class admin does not exist i found a issue it say 'Class admin does not exist'. Anything I missing for the issue? Thanks. Here is my Route.php Route::group(['prefix' => 'admin', 'middleware'=> ['auth' => 'admin']], function () { Route::get('/','AdminController@index'); Route::get('profile','AdminController@profile'); Route::get('/addProduct','AdminController@addProduct'); }); Here is my AdminController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class AdminController extends Controller { public function index(){ return view('admin.index'); } public function profile(){ return view('admin.profile'); } public function addProduct(){ return view('admin.addProduct'); } } A: Issue with in the route file to assign middlewares to route group If you have two middlewares then assign like this ["auth", "admin"] instead of ["auth" => "admin"]. Route::group(['prefix' => 'admin', 'middleware'=> ['auth', 'admin']], function () { Route::get('/','AdminController@index'); Route::get('profile','AdminController@profile'); Route::get('/addProduct','AdminController@addProduct'); });
{ "pile_set_name": "StackExchange" }
Q: What happens when a company I have shares in invests in another company If I own shares in a company. Let’s say Alphabet (Google) and they invest in another company say Tesla. How does that affect my holdings in Alphabet. For example if the Tesla share price goes up does that increase the value of the Alphabet shares or does this only happen if they sell them? Basically I just want to know if they invest in a winner or loser how it affects me as a share holder? A: Ideally, yes, the price of the owner's stock would increase to reflect the increased value of the assets it holds. If Alphabet in this example owns $1 billion in Tesla stock, then the number of Alphabet shares * Alphabet's share price should be $1 billion plus whatever value the market places on the rest of Alphabet's business. In practice, this doesn't always happen. For example, at one point in 2015, Yahoo was worth ~$1 billion less than the stakes it held in other companies. When that happens, someone will usually do something to unlock the value. Either the company itself will spin off the valuable assets into a new company or someone else will initiate a hostile takeover in order to sell off the assets or the market will realize the parent company's stock is undervalued and bid up the price to cover the underlying assets.
{ "pile_set_name": "StackExchange" }
Q: Accessing an API endpoint on the same website using D3.JS I am putting together a D3.JS visualization, as a part of which I have created a MongoDB database and exposed it via an API endpoint on my webservice. I am using Python Flask to do this. I've validated that the data emitted is in valid JSON format and I've made sure to set the MIME type to application/json. However, while in visiting the URL in question everything is fine, when I try to call into that URL using d3.json: d3.json("http://127.0.0.1:5000/citibike-api/bike-inbounds/id/72", function (data, error) { if(error) throw error; console.log(data); }); Console yells at me: uncaught exception: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] Are there other things that I need to do to make this request work? Do I need something with JSONP to do this? A: Swap data with error. Instead of: d3.json("http://127.0.0.1:5000/citibike-api/bike-inbounds/id/72", function (data, error) { if(error) throw error; console.log(data); }); It should be: d3.json("http://127.0.0.1:5000/citibike-api/bike-inbounds/id/72", function (error, data) { if(error) throw error; console.log(data); }); Explanation According to the API, in d3.json... ...the callback is invoked with two arguments: the error, if any, and the parsed JSON The argument error is optional. You can just write: function (data){ But, if you use the argument error, the sequence has to be: function (error, data){
{ "pile_set_name": "StackExchange" }
Q: How can I install haskell-platform? Haskell-platform currently has unmet dependencies on Ubuntu 11.04. This is a known bug, but I'd like to get it installed sooner rather than later. Can anyone recommend a way to install haskell-platform on 11.04? The bug report that I linked to offers a solution that requires editing a binary package (?) using vim, but I'd rather install something from source than go that route. A: This bug has now been fixed and is in 11.04 -proposed. Therefor you can enable proposed packages and install haskell-platform. If you do not want to keep getting -proposed updates you can disable it once you have haskell-platform installed. Look here for a guide on how to enable -proposed updates. This bug is fixed in 11.10.
{ "pile_set_name": "StackExchange" }
Q: What is the best way to stop phishing for online banking? Phishing is a very serious problem that we face. However, banks are the biggest targets. What methods can a bank use to protect its self from phishing attacks? What methods should someone use to protect themselves. Why does it stop attacks? A: Phishing usually works by directing the consumer to a scraped version of the website. One method that's starting to be more common is a dynamic website, where after entry of username and before entry of password, the bank site reveals some image or phrase chosen by the consumer, which I will call the counter-password. In essence, not only must the consumer present a valid password, so does the bank. Mutual authentication. The phishing site cannot display the correct counter-passwordwithout querying the bank, and this gives the bank an opportunity to detect, confound, and prosecute the proxy. This can be enhanced with use of an out-of-band communication channel. If the IP address making the request (which would be the proxy, possibly via onion routing) isn't one the consumer has logged in from before, send the consumer an SMS with a one-time code they must additionally use before the counter-password is revealed and login enabled. Other methods are for the browser to cache the correct server certificate and tell the consumer when they visit a site without a cached certificate, thus warning the consumer that this isn't the familiar site they've used before. A: IMO, the best thing that a bank can do is to educate it's users on when and how they will communicate with them. Many users have no idea about what phishing is and so showing them examples and raising their awareness about fraud will do more than any technical solution (though the technical side should be pursued just as aggressively). A user aware that phishing can occur will be far less likely to fall prey to it. A: The best way to prevent phishing attacks should rely on technical means that don't require the user to understand the problem. The target audience will always be large enough to find someone who gets fooled. A good way to prevent from attacks is to use an authentication mechanism that doesn't rely on a simple pass phrase or transaction authentication number (TAN) that an attacker can steal. Existing methods e.g. use dynamic TANs (Indexed TAN or iTAN), or a TAN submitted on a separate channel via SMS (mobile TAN or mTAN), or - most secure and also preventing from real-time man-in-the-middle attacks - require the user to sign each transaction, e.g. using DigiPass or a smartcard. The reason that this is not widely implemented is probably that it is still more cost-effective for banks to pay for the damage from phishing attacks than investing in security.
{ "pile_set_name": "StackExchange" }
Q: How to remove custom suffix after file extension in Windows via script? I have a folder full of CSV files which get stored with a time stamp and an identifier after the file type, meaning Windows does not recognize the files as CSVs (and any VBA code to access them won't recognize them either). The file format is always: ABCDEFG.csv.20161205-071658 ABCDEFG.csv never changes. How do I remove all characters after the second .? A: The following batch file could be used to get the file ABCDEFG.csv.20161205-071658 renamed to ABCDEFG_20161205-071658.csv in folder C:\Temp as well as all other non hidden files matching the pattern *.csv.*. @echo off setlocal EnableExtensions EnableDelayedExpansion for %%I in ("C:\Temp\*.csv.*") do ( for %%J in ("%%~nI") do ( set "DateTime=%%~xI" set "DateTime=!DateTime:~1!" ren "%%I" "%%~nJ_!DateTime!%%~xJ" ) ) endlocal For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. echo /? endlocal /? for /? set /? setlocal /?
{ "pile_set_name": "StackExchange" }
Q: How do I use a Google Account for Pokemon Go I have tried to make a new Trainers Club Account, but the site is down. Does anybody know how I can use my Google Account to make an account? Thanks. A: On the opening screen (after the Niantic logo screen) there are two buttons. The top one allows you to sign in with a Google account. Tapping it will present you with a pop-up menu of all the different Google accounts associated with your phone. It's not the same color as the Trainer Club button, so it's easy to miss. If you do not see the button, try uninstalling and reinstalling the Pokemon Go app, and when asked your age, saying you are over 13.
{ "pile_set_name": "StackExchange" }
Q: Prevent Orbeon to encode dropdown values by position I want to prevent Orbeon from encoding dropdown values (i.e. values of select options) by position, since I need to use exact values on the client-side via JavaScript. E.g: My options have values (150, 250, 350), but they are rendered/encoded by position as (1,2,3) on the front-end. I have tried with setting the property in properties-local.xml: <property as="xs:boolean" name="oxf.xforms.encrypt-item-values" value="false"/> However, for some reason this doesn't work. Not sure if I am missing something. Does anybody have an idea what could be the reason for this and is it possible that I need to set this property somewhere else? If matters, I'm using Orbeon forms with hybris Commerce suite. A: Form Runner overrides the oxf.xforms.encrypt-item-values property, which explains why it has not effect in your case. If you have only a few controls which require this, you should be able to set the attribute xxf:encrypt-item-values="false" directly on the xf:select1 control in the form source. This said, I notice that if using a dropdown with fr:dropdown-select1, the attribute is not forwarded properly. So I entered an issue for this.
{ "pile_set_name": "StackExchange" }
Q: Have bio-organic weapons ever gotten past the testing phase? I'm not really up to speed on most of RE lore; I've only completed 4 and 5. Reading through plot summaries for most of the other entries, it doesn't seem like the zombie/monster plagues ever get sold and used as actual bio-organic weapons though. Is there a instance in the series where they're actually bought and used, instead of just testing them on the locals, or having an accidental outbreak? This can be about any RE media, but preferably the games. A: No, there's nothing that explicitly stated that BOWs were ever bought and then used as weapons. Below is a list of all the BOW outbreaks I could find to back that up. Only the incidents in Revelations and Damnation come close, but the method of aquisition of the BOWs is vague in those. Arklay Mountains, USA - 1998 RE0, RE1/REmake Sabotage. Virus gets loose, people die, mansion is blown up. Raccoon City, USA - 1998 RE3, RE2, Operation Raccoon City, Outbreak 1&2, 4D-Executer (CG film) Accident. An indirect consequence of the Arklay Mountains incident, laboratory waste spills over into Raccoon City. People die, city is blown up. Sheena Island - 1998 Survivor Sabotage. Done to silence anyone who might tell of Umbrella's nefarious deeds. People die, island is blown up. Rockfort Island/Antarctic base - 1998 Code Veronica Sabotage. Wesker tries capturing someone from the island, but bombs it first. This releases a virus held there. Wesker also releases other BOWs. Atlantic Facility - 2002 Dead Aim Accident. People die, facility is blown up. South America - 2002 Darkside Chronicles Byproduct of experimentation. Javier Hidalgo did probably did buy the virus, but used it to try to save his daughter. BOWs break loose due to carelessness (I think - feel free to correct me on this). People die, nothing is blown up. Does not qualify. The virus is purchased, but there's no deliberate use of the BOWs as weapons (I should play the game to confirm this). Cuacasus mountains, Russia - 2003 Umbrella Chronicles Sabotage. This is Wesker doing away with the last remnant of Umbrella. People die, but the facility surprisingly does not explode. Spain - 2004 RE4 Attempt to gain control over the president of the United States with homegrown parasites. Does not qualify, as there's been no purchase, just an excavation of the parasites and purposeful conversion of the locals. Terragrigia and the Queen Zenobia, Mediterranean Sea - 2004/2005 Revelations Deliberate. Unknown how the virus was aquired. People die, a city and 3 cruise ships are blown up. Harvardville Airport, USA - 2005 Degeneration (CG film) Sabotage. Passenger on a plane is infected, plane crashlands, zombies spill out, people die, the vaccine is blown up. The saboteur tries to sell the virus to terrorists afterwards (the attack itself was a sales pitch of sorts), but is caught before he can. Kijuju - 2008/2009 RE5 Byproduct of experimentation. As far as I can tell, Wesker and Irving were using Kijuju as a testbed for Las Plagas derivatives. Irving intends to eventually sell them, while Wesker wants to use Uroboros to wipe the world of most of its population. Both die before they can. Eastern Slavic Republic - 2010 Damnation (CG film) BOWs used as weapons in a civil war. It's never specified how the BOWs are aquired. It's implied they could have gotten them from the black market. Large part of the population seems to be wiped out. Multiple outbreaks - 2012/2013 RE6 Deliberate. The work of Neo Umbrella, which did not need to buy the viruses. One city is blown up.
{ "pile_set_name": "StackExchange" }
Q: Applying KVL to DC bias calculation I'm trying to use Kirchhoff's voltage law to find the bias point of a bjt amplifier circuit, as shown below: I begin with switching off the signal and opening all capacitors simulate this circuit – Schematic created using CircuitLab The transistors are identical, both with beta of 150. I then assume Q1 and Q2 are in forward active mode, and arrive at the following: Vc - VBE2 + r4* ix = 0 ---> (1) Vc - VBE2 -iy* R6 - VBE2 - R3* ix = 0 --- >(2) ix = 151*iy ---> (3) Solving the above in Wolfram, I find that both ix and iy are negative. What do I do then? Does it mean Q1 is not forward active, and all the assumptions are wrong? I hate to ask a "please check my calculations" sort of question, but I've verified the steps again and again for hours and am getting nowhere. Please enlighten me! A: simulate this circuit – Schematic created using CircuitLab Try again with KVL with same schematic re-arranged, so that you do not confuse Ie1 with Ie2 both being the same Ix.
{ "pile_set_name": "StackExchange" }
Q: BASH label for IP addresses My fault: I have been so busy learning other linux stuff that I completely neglected the power of bash. I have a number of systems to access remotely for very simple operations. The problem is that I need to remember each single IP address. And they are a lot. Using aliases in ~./bashrc is an option: alias ssh_customer1='ssh [email protected]' alias ssh_customer2='ssh [email protected]' alias copy_customer1='scp * [email protected]:/etc/example/' alias copy_customer2='scp * [email protected]:/etc/example/' alias get_customer1='scp [email protected]:/etc/example/* .' alias get_customer2='scp [email protected]:/etc/example/* .' but the flexibility is minimal. Another possibility is to define functions using the name of system as a parameter but I don't like this: sshx('customer1') scpx('customer2') I would prefer to just replace a label with the corresponding IP address without the need to remember it, and use standard commands: ssh root@ip_customer1 scp root@ip_customer2:/etc/example/* . Is this possible? A: Setup a ~/.ssh/config file: $ cat ~/.ssh/config Host cust1 HostName 10.X.X.X User root Host cust2 HostName 10.X.X.Y User root Now you can use: ssh cust1 Another cool thing is that you can now attach identity files to each server: $ cat ~/.ssh/config Host cust1 HostName 10.X.X.X User root IdentityFile ~/.ssh/cust1.id_rsa Host cust2 HostName 10.X.X.Y User root IdentityFile ~/.ssh/cust2.id_rsa This will let you use ssh and scp without password, assuming the key is without password or ssh-agent is used.
{ "pile_set_name": "StackExchange" }
Q: HTML.SelectListFor selectedValue never gets set I have the following partial view which renders a drop down list: @model MartinDog.Core.Models.Section @{ @Html.DropDownListFor(x=>x.Name , new SelectList(Model.Dock.DockTemplate.Columns, "Id", "FriendlyName", Model.DockTemplateColumn.Id.ToString()) , new { @id = "ddlb_dockTemplateColumns" + Model.Id.ToString()}) } I render it on my page like so: @{Html.RenderPartial("_Admin_Page_DockTemplateColumnDropDown", Model);} The partial view is rendered once for every Section object. A Section object one I've created and is editable in a jquery dialog box (change the name, display order, dock template column, etc.) On the test page I am using, this Section dialog box is rendered four times (as there are four of them in my parent object). The problem: *The SelectedValue in the SelectList for the drop down never gets set* - that is to say, the correct item in the drop down list is never selected when the dialog is displayed and I can't quite work out why. I thought it might be because the drop down is rendered four times, so I tried rendering it for just one of the 'Sections' but still the same problem. Anyone know what I can do? ***edit Not sure if I'm doing it in a sucky way. I had thought of building the dialog just once with jquery and json but I'd prefer to do it this way as it just feels cleaner. A: Doh... fixed - totally my own fault. I had set up my html.dropdownlistfor like so @Html.DropDownListFor(x=>x.Name, When it should've been like so: @Html.DropDownListFor(x=>x.DockTemplateColumn.Id, Setting the first argument to x=>x.DockTemplateColumn.Id (which uniquely identifies the items in my list) instead of x.Name fixed the issue straight away. Just thought I'd post it here in case someone else makes the same mistake I did. edit Found the answer here: C# mvc 3 using selectlist with selected value in view
{ "pile_set_name": "StackExchange" }
Q: Facebook text share not working with UIActivityViewController Well, the situation is when I am trying to share text in facebook with UIActivityViewController, the share text shows blank in the facebook popup whereas the URL provided comes but text doesn't show in Facebook share dialog or popup. One more thing sometimes the URL also don't come or show in share dialog. NOTE: Facebook native app is already installed in device and logged in from device settings, I have also updated the app to version 31.0. Device used:- iPhone 6 with iOS 8.3 Code:- NSString *shareString = [NSString stringWithFormat:@"Welcome to family."]; NSURL *website = [NSURL URLWithString:@"http://google.com"]; NSArray *shareArray = @[shareString,website]; UIActivityViewController *activityController = [[UIActivityViewController alloc]initWithActivityItems:shareArray applicationActivities:nil]; [self presentViewController:activityController animated:YES completion:nil]; [activityController setCompletionHandler:^(NSString *activityType, BOOL completed){ }]; A: This won't work if you have the newest Facebook app installed - the text always blank and sometimes URL doesn't show in facebook version 31.0 . This share feature only works older app means version less than 28..
{ "pile_set_name": "StackExchange" }
Q: How to find different colorings of cubes with restrictions When painting a cube, say 1 side is painted color a, 2 are painted color b, and 3 are painted color c. How can I find the number of possible ways it can be painted? Rotations ARE the same configuration. A: I'm going to use red, green, and blue as my colors (since that feels more natural to me). One side needs to be red, two sides are going to be green, and three sides are going to be blue (since I like blue, I want the cube to be mostly blue). I'm going to start by paining one face red. Next, I am going to paint the opposite face. I have two choices: I can paint that face either green, or blue. If I paint the opposite face green, then I have to paint one of the remaining face green, and the other three remaining face blue. There is only one way to do this. If I paint the opposite face blue, then I have to color two of the remaining faces green. There are two ways to do this: either I paint two adjacent faces green, or I paint two opposite faces green. As these two cases exhaust all possibilities, there are a total of three different ways of painting a cube subject to the constraints you gave.
{ "pile_set_name": "StackExchange" }
Q: pass data to object of uiviewcontroller on iPhone I have an iPhone app with a tableviewcontroller. When you click a certain cell it opens a new uiviewcontroller with this code: nextViewController = [[avTouchViewController alloc] initWithNibName:@"avTouchViewController" bundle:nil]; The uiviewcontroller above called avTouchViewController has a property that looks like: IBOutlet SomeObject *controller; SomeObject is an object with all relevant view properties. I would like to pass an nsstring parameter from the tableviewcontroller I initialize the avTouchViewController with to someObject. How can I do this? A: I'm a little confused by your question; you say you're creating your avTouchViewControllers when a cell is tapped inside an existing UITableView, but your last part describes the inverse situation. Basically, if you want to pass information to a view controller, just give it a property that can be set (which may already be the case), e.g.: nextViewController = [[avTouchViewController alloc] initWithNibName:@"avTouchViewController" bundle:nil]; nextViewController.controller = theInstanceOfSomeObjectIWantToPass; You also may want to rename your controller property. To a reader, it doesn't make sense that a view controller has a property called controller which is actually a SomeObject*. As well, your class names should be capitalized, i.e. use AvTouchViewController instead of avTouchViewController.
{ "pile_set_name": "StackExchange" }
Q: Converting strange coordinates from shapefile into regular lat and long using GeoTools? I use this dataset from the European Union: http://www.eea.europa.eu/data-and-maps/data/administrative-land-accounting-units Opening the shapefile with Java' Geotools, I see coordinates like: 4591000 2713000 and I would need to translate these into regular lat and long coordinates. I've seen posts suggesting the .prj file can help solving this problem, so I post its content here: PROJCS ["ETRS_1989_LAEA",GEOGCS["GCS_ETRS_1989",DATUM["D_ETRS_1989",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["False_Easting",4321000.0],PARAMETER["False_Northing",3210000.0],PARAMETER["Central_Meridian",10.0],PARAMETER["Latitude_Of_Origin",52.0],UNIT["Meter",1.0]] I am not a specialist of GIS. A: The dataset use Pan-European mapping standard projection system - EPSG3035 If you are open to non-java tool and simplicity, you will be able to reproject the file to WGS84 using GDAL/OGR : http://www.gdal.org/, that way : ogr2ogr -f "ESRI Shapefile" path/to/NUTSV9_LEAC.shp NUTSV9_LEAC_wgs84.shp -s_srs EPSG:3035 -t_srs EPSG:4326
{ "pile_set_name": "StackExchange" }
Q: How to make Terminal open every new tab in the "Homebew" profile? I really like Terminal's "Homebrew" profile (black background with green front, instead of the default white background with black font), so I set it as my default profile. This makes it so that when I initially open Terminal, the first tab that opens will use the "Homebrew" profile. But I came across an issue where once I close the open Terminal window then try to open a new one by clicking on the terminal icon in my dock, the new Terminal window opens in the system default "Basic" profile. Can I make Terminal open every new window with the "Homebrew" profile? A: Goto Terminal (Next to the Apple icon) -> Preferences -> Profiles Then select HomeBrew and click "default" you can find it down there in the section you select HomeBrew. If you like HomeBrew you might like iTerm2. Just give it a try. https://www.iterm2.com
{ "pile_set_name": "StackExchange" }
Q: Find critical points of $\langle Av,v\rangle$ Let $A$ be an $n \times n$ real symmmetric matrix. Find the critical points of the function $\langle Av,v\rangle$ restricted to the unit sphere in $\mathbb{R}^n$. I would think you just use Lagrange multipliers, and $\nabla\langle Av,v\rangle=2Ax$, since $A$ is symmetric. But this only gives the possible locations for the local max/min. So the gradient is zero at these points, but doesn't necessarily include all points were the gradient is zero. Is there something I'm missing here? A: Since we are dealing here with a symmetric $n\times n$ real matrix $A$, we can use the spectral theorem. So, we know that there are $n$ eigenvectors $v_1,\ldots,v_n$ of $A$ such that $(v_1,\ldots,v_n)$ is an orthogonal basis of $\mathbb{R}^n$. Therefore, after a change of variables, the fuction that we are dealing with here is just$$(x_1,x_2,\ldots,x_n)\mapsto\lambda_1{x_1}^2+\lambda_2{x_2}^2+\cdots+\lambda_n{x_n}^2$$ restricted to the unit sphere, where, for each $j\in\{1,2,\ldots,n\}$, $A.v_j=\lambda_jv_j$. The gradient of this map is$$(x_1,x_2,\ldots,x_n)\mapsto2(\lambda_1x_1,\lambda_2x_2,\ldots,\lambda_nx_n)$$and, within the unit sphere, this is $0$ if and only if $(x_1,x_2,\ldots,x_n)$ is an eigenvector (of $A$) with eigenvalue $0$. So, going back to the original problem, if $E_0=\{v\in\mathbb{R}^n\,|\,A.v=0\}$, then the set of critical points of your function is $E_0\cap S^{n-1}$. Added note: Please take into account the remark provided by skyking below.
{ "pile_set_name": "StackExchange" }
Q: Thrust: How to returns indices of active array elements How can I use thrust to return the indices of active array elements i.e. return a vector of indices in which array elements are equal to 1? Expanding on this, how would this work in the case of multi-dimensional indices given the array dimensions? Edit: currently the function looks like this template<class VoxelType> void VoxelVolumeT<VoxelType>::cudaThrustReduce(VoxelType *cuda_voxels) { device_ptr<VoxelType> cuda_voxels_ptr(cuda_voxels); int active_voxel_count = thrust::count(cuda_voxels_ptr, cuda_voxels_ptr + dim.x*dim.y*dim.z, 1); device_vector<VoxelType> active_voxels; thrust::copy_if(make_counting_iterator(0), make_counting_iterator(dim.x*dim.y*dim.z), cuda_voxels_ptr, active_voxels.begin(), _1 == 1); } Which is giving the error Error 15 error : no instance of overloaded function "thrust::copy_if" matches the argument list A: Combine counting_iterator with copy_if: #include <thrust/copy.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/functional.h> ... using namespace thrust; using namespace thrust::placeholders; copy_if(make_counting_iterator<int>(0), make_counting_iterator<int>(array.size()), // indices from 0 to N array.begin(), // array data active_indices.begin(), // result will be written here _1 == 1); // return when an element or array is equal to 1
{ "pile_set_name": "StackExchange" }
Q: A function that can make caller return I am writing some BASH script and I want it have some error handling mechanism: function f() { command1 || { echo "command1 failed"; return 1; } command2 || { echo "command2 failed"; return 1; } command3 || { echo "command3 failed"; return 1; } command4 || { echo "command4 failed"; return 1; } } I want to make this repetitive structure more readable by defining some function: function print_and_return() { echo "$@" # some way to exit the caller function } so that I can write function f as function f() { command1 || print_and_return "command1 failed" command2 || print_and_return "command2 failed" command3 || print_and_return "command3 failed" command4 || print_and_return "command4 failed" } What's the best way to achieve this? Thanks. A: Maybe you can use set -e, though you have to be careful since it exits the shell: function f() { ( set -e command1 command2 command3 command4 ) } As long as the commands diagnose any problems, this function will stop when the first command fails. Test version: function f() { ( set -e true echo true true echo true false echo false true echo true ) } echo calling function f echo still here Output: calling function true true still here NB: When I used the sequence: echo calling function if f then echo still here - f passed else echo still here - f failed fi Then the function behaved differently under bash 3.2.48 on Mac OS X 10.7.4: calling function true true false true still here - f passed So, inventive, but not wholly reliable.
{ "pile_set_name": "StackExchange" }
Q: Bidirectional data binding on a component input property I am trying to make something work on angular2 and I am unable to find something about this behavior. I have an application that implements a custom component like this one : import {Component,Input} from 'angular2/core' @Component({ selector:'my-comp', template:`<input type="text" style="text-align:center; [(ngModel)]="inputText"> <p>{{inputText}}</p>` }) export class MyComp{ @Input() inputText : string; } And I am trying to do a bidirectional databinding on my inputText variable from my component like this: <my-comp [(inputText)]="testString"></my-comp> Where the testString is a variable defined in the MyApp.ts which contains a string. I want my testString variable to be modified when my inputText is modified by the user. Here is a Plunker with a simple sample code : https://plnkr.co/edit/zQiCQ3hxSSjCmhWJMJph?p=preview Is there a way to make this works simply ? Do I have to implements an Angular2 class on my custom components and overload functions in order to make this works like an ngModel ? Do i necessarily have to create a inputTextChanged variable of EventEmitter type that emit my data when it's changed and do something like this : <my-comp [inputText]="testString" (inputTextChanged)="testString = $event;"></my-comp> Thank you in advance. A: This is explained in the Template Syntax doc, in the Two-Way Binding with NgModel section: <input [(ngModel)]="currentHero.firstName"> Internally, Angular maps the term, ngModel, to an ngModel input property and an ngModelChange output property. That’s a specific example of a more general pattern in which it matches [(x)] to an x input property for Property Binding and an xChange output property for Event Binding. We can write our own two-way binding directive/component that follows this pattern if we're ever in the mood to do so. Note also that [(x)] is just syntactic sugar for a property binding and an event binding: [x]="someParentProperty" (xChange)="someParentProperty=$event" In your case, you want <my-comp [(inputText)]="testString"></my-comp> so your component must have an inputText input property and an inputTextChange output property (which is an EventEmitter). export class MyComp { @Input() inputText: string; @Output() inputTextChange: EventEmitter<string> = new EventEmitter(); } To notify the parent of changes, whenever your component changes the value of inputText, emit an event: inputTextChange.emit(newValue); In your scenario, the MyComp component binds input property inputText using the [(x)] format to ngModel, so you used event binding (ngModelChange) to be notified of changes, and in that event handler you notified the parent component of the change. In other scenarios where ngModel isn't used, the important thing is to emit() an event whenever the value of property inputText changes in the MyComp component. A: I'll combine @pixelbits and @Günter Zöchbauer answers and comments to make a clear answer on my question if someone in the future is searching for this. To make bidirectional data binding works on custom variables you need to creates your component based on the following. MyComp.ts file : import {Component,Input,Output,EventEmitter} from 'angular2/core' @Component({ selector:'my-comp', templateUrl:`<input type="text" style="text-align:center;" [ngModel]="inputText" (ngModelChange)="inputText=$event;inputTextChange.emit($event);">` }) export class MyComp{ @Input() inputText : string; @Output() inputTextChange = new EventEmitter(); } MyApp.ts file: import {Component} from 'angular2/core' import {MyComp} from './MyComp' @Component({ selector:'my-app', templateUrl:`<h1>Bidirectionnal Binding test </h1> <my-comp [(inputText)]="testString"></my-comp><p> <b>My Test String :</b> {{testString}}</p>`, directives:[MyComp] }) export class MyApp{ testString : string; constructor(){ this.testString = "This is a test string"; } } There the bidirectional data binding to the inputText variable works correctly. You can comment the answer for a more beautiful or simpler way to implement this code.
{ "pile_set_name": "StackExchange" }
Q: Значение словосочетания «культурный шлейф» Может ли кто-то точно объяснить, что оно означает? Казалось бы, шлейф — само слово указывает на некую вторичность или на какое-то следование в фарватере определённого культурного явления. Но вот несколько цитат, содержащих это выражение, и вот они-то окончательно сбивают меня с толку. Хотя в первой есть даже частичное разъяснение. «Временнýю глубину концепту придают примыкающие к понятийному уровню шлейфы — генетический, историко-культурный, интертекстуальный. […] Историко-культурный шлейф складывается из фрагментов знаний о прежних реальных воплощениях концепта, его языковым отражением служат историзмы и некоторые прецедентные имена, под которыми хранятся в памяти образцы и выделяющиеся примеры (Дж. Лакофф), как, например, царь, Советы, империя, Сталин в историко-культурном шлейфе концепта «государство». Немалую часть паремий можно отнести к регулятивной зоне историко-культурного шлейфа…» (О. Евтушенко, «Художественная речь как инструмент познания»). Тут достаточно понятно, но для нижеприведённых цитат такая трактовка не вполне годится. «Пожалуй, самая престижная выставочная площадка в России — это зал на «Беговой» МОСХа в Москве. Его культурный шлейф из профессиональных и человеческих страстей не только меняет восприятие, но и погружает в какой-то тихий, чуть приметный транс» («Творческий союз художников России», http://www.tcxp.ru/articles/bronzovyy-gost ). «Слово, транслируемое книгой, постоянно изменяло своё значение и культурный шлейф, оно вступало во взаимодействие внутри возникавших медиа и изменяло медиапространство» (К. Костюк, «Книга в новой медийной среде»). *«…И рок — это стихия нашей свободы, это наша музыкальная культура. И вот так у неё получилось воедино связать понятие вот такой музыкальной свободы, некой нашей идеологии такой внутренней, современной музыки и того культурного шлейфа, и того духа братства, который мы хотели бы видеть в нашей организации» (Из интервью Н. Коледина в телепередаче «Рассвет»). Дело в том, что я затрудняюсь заменить этот «культурный шлейф» синонимичным словом или словосочетанием, не совсем понимая, что имеется в виду. Прошу разъяснить, кто знает. A: Шлейф-многозначное слово: длинный, волочащийся сзади подол женского платья геол. полоса отложений, окаймляющая подножье возвышенности перен. след, полоса от движения чего-либо перен. ряд каких-либо действий, последствий и ещё 2 значения,которые нам ничего не дают в данных примерах. У второго значения (полоса отложений) тоже есть переносное - пласт событий. Вот как шлейф культурного слоя - пласт с археологическими находками одного времени, так и шлейф культурных событий. В 4 значении употреблено сочетание шлейф культурных инноваций:"Проникновение на территорию Кавказа носителей урукских традиций в IV тысячелетии до н.э. повлек за собой целый шлейф культурных инноваций". В Ваших примерах: 1.«Временнýю глубину концепту придают примыкающие к понятийному уровню шлейфы — генетический, историко-культурный, интертекстуальный. […] Историко-культурный шлейф складывается из фрагментов знаний о прежних реальных воплощениях концепта, его языковым отражением служат историзмы и некоторые прецедентные имена, под которыми хранятся в памяти образцы и выделяющиеся примеры (Дж. Лакофф)... Историко-культурный шлейф=историко-культурный пласт. 2."...зал на «Беговой» МОСХа в Москве. Его культурный шлейф из профессиональных и человеческих страстей не только меняет восприятие, но и погружает в какой-то тихий, чуть приметный транс» («Творческий союз художников России», http://www.tcxp.ru/articles/bronzovyy-gost ).Культурный шлейф = содержание, наполнение культурного пласта. Но есть и оттенок значения "след", "ряд чего-то, каких-то последствий как хвост", ведь в тихий транс погружает атмосфера выставочного зала, полоса человеческих страстей, которая тянется как некий туманный хвост. «Слово, транслируемое книгой, постоянно изменяло своё значение и культурный шлейф(т.е. культурное содержание, тот же пласт), оно вступало во взаимодействие внутри возникавших медиа и изменяло медиапространство» (К. Костюк, «Книга в новой медийной среде»). *«…И рок — это стихия нашей свободы, это наша музыкальная культура. И вот так у неё получилось воедино связать понятие вот такой музыкальной свободы, некой нашей идеологии такой внутренней, современной музыки и того культурного шлейфа (культурного содержания,наполнения, пласта)
{ "pile_set_name": "StackExchange" }
Q: Beautiful Soup Not able to get_text after using extract() i am working on web scrapping and i want just text from any website so i am using Beautiful Soup. Initially i found that get_text() method was also returning JavaScript code so to avoid i come across that i should use extract() method but now i have a weird problem that after extraction of script and style tag Beautiful Soup doesn't recognize its body even its present in new `html. let me clear you first i was doing this soup = BeautifulSoup(HTMLRawData, 'html.parser') print(soup.body) here print statement was printing all html data but when i do soup = BeautifulSoup(rawData, 'html.parser') for script in soup(["script", "style"]): script.extract() # rip it out print(soup.body) Now its is printing None as element is not present but for debugging after that i did soup.prettify() then it print whole html including body tag and also there was no script and style tag :( now i am very confused that why its happening and if body is present than why its saying None please help thanks and i am using Python 3 and bs4 and rawData is html extracted from website . A: Problem: Using this html example: <html> <style>just style</style> <span>Main text.</span> </html> After extracting the style tag and calling get_text() it returns only the text it was supposed to remove. This due to a double newline in the html after using extract(). Call soup.contents before and after .extract() and you will see this issue. Before extract(): [<html>\n<style>just style</style>\n<span>Main text.</span>\n</html>] After extract(): [<html>\n\n<span>Main text.</span>\n</html>] You can see the double newline between html and span. This issue brakes get_text() for some unknown reason. To validate this point remove the newlines in the example and it will work properly. Solutions: 1.- Parse the soup again after the extract() call. BeautifulSoup(str(soup), 'html.parser') 2.- Use a different parser. BeautifulSoup(raw, 'html5lib') Note: Solution #2 doesn't work if you extract two or more contiguous tags because you end up with double newline again. Note: You will probably have to install this parser. Just do: pip install html5lib
{ "pile_set_name": "StackExchange" }
Q: Grouping a list of list using linq I have these tables public class TaskDetails { public string EmployeeName {get; set;} public decimal EmployeeHours {get; set;} } public class Tasks { public string TaskName {get; set;} public List<TaskDetails> TaskList {get; set;} } I have a function that returns a List<Tasks>. What I would need is to create a new List that groups the EmployeeNames and SUM the EmployeeHours irrespective of the TaskName. That is, I need to fetch TotalHours of each Employees. How to get that? P.S: And to what have I done so far. I have stared at the code for a long time. Tried Rubber Duck Problem solving to no avail. I can do get the results using a foreach and placing it to a Dictionary<string, decimal>. That logic will be to check if key does not exist, add a new key and assign the value and if the key exists add the decimal value to the original value. But I feel its too much here. I feel there is a ForEach - GroupBy - Sum combination which I am missing. Any pointers on how to do it will be very helpful for me. A: var results = tasks.SelectMany(x => x.Tasks) .GroupBy(x => x.EmployeeName) .ToDictionary(g => g.Key, g => g.Sum(x => x.EmployeeHours)); Gives you Dictionary<string, decimal>. To get a list just replace ToDictionary with Select/ToList chain: var results = tasks.SelectMany(x => x.Tasks) .GroupBy(x => x.EmployeeName) .Select(g => new { EmployeeName = g.Key, Sum = g.Sum(x => x.EmployeeHours) }).ToList(); A: a SelectMany would help, I think. It will "flatten" the Lists of TaskDetail of all your Task elements into a single IEnumerable<TaskDetail> var result = listOfTasks.SelectMany(x => x.Tasks) .GroupBy(m => m.EmployeeName) .Select(m => new { empName = m.Key, hours = m.Sum(x => x.EmployeeHours) });
{ "pile_set_name": "StackExchange" }
Q: Find Certificate by hash in Store C# How to get Certificate by hash in Windows Store using C#? sha1 example:7a0b021806bffdb826205dac094030f8045d4daa this loop works but: X509Store store = new X509Store(StoreName.My); store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 mCert in store.Certificates) { Console.WriteLine( mCert.Thumbprint); } store.Close(); Is there a direct method? A: var cert = store.Certificates.Find( X509FindType.FindByThumbprint, thumbprint, true ).OfType<X509Certificate>().FirstOrDefault();
{ "pile_set_name": "StackExchange" }
Q: jquery validation of the form except one div I want to validate complete content of my form except all the inputs that are in a specific div, lets say <div class="noValid"> for example. So what I want to do is something like $("myForm").valid() that will execute jQuery validation on all the form inputs except the ones that are in my specific div. Can you tell me how to exclude this specific div from the global form selector? Thanks A: You could pass a selector in the ignore option to validate(): $("#myForm").validate({ // your options, ignore: ":hidden, #yourDiv :input" }); From there on, $("#myForm").valid() will ignore the form controls inside #yourDiv.
{ "pile_set_name": "StackExchange" }
Q: Proving a 4-variable equation unsolvable META: I wrote the explanation for this problem assuming a monospace font... it might be easier to read if you copy and paste it into a text file and view it separately. Or, if you know how, feel free to edit it to have a monospace font with automatic line breaks because I don't know how. Let 4 variables $a,b,c,d$ be rationals in $[0,1]$ which, when multiplied by $255$, become integers. (That is, $a,b,c,d\in \{\frac{x}{255}\mid 0\leq x\leq 255,\ x\in\mathbb{Z}\}$. Examples of valid values are $1/255$, $2/255$, $3/255$, etc. The variables are related in one equation. I want to prove that there are no solutions to this equation, by which I mean there are no valid values for the 4 variables that will satisfy the equation. $$\frac{ac + (1-a)bd}{a+(1-a)b} = \frac{1}{2}$$ Now I'm going to redefine $a,b,c,d$ to be non-negative integers in the domain $[0,255]$. The equation will still hold if I add the denominator $255$ to the variables. $$\begin{align*} \frac{\frac{a}{255}\;\frac{c}{255} + \left(1-\frac{a}{255}\right)\frac{b}{255}\;\frac{d}{255}}{\frac{a}{255} + \left(1 - \frac{a}{255}\right)\frac{b}{255}} &= \frac{1}{2}\\ \frac{\frac{ac}{255^2} + \frac{(255-a)bd}{255^3}}{\frac{a}{255}+\frac{(255-a)b}{255^2}} &= \frac{1}{2}\\ \frac{\quad\frac{255ac + (255-a)bd}{255^3}\quad}{\frac{255a + (255-a)b}{255^2}}&=\frac{1}{2}\\ \frac{255 ac + (255-a)bd}{255^3}\;\frac{255^2}{255a+(255-a)b} &= \frac{1}{2}\\ \frac{255ac + (255-a)bd}{255(255a + (255-a)b)}&=\frac{1}{2}\\ \frac{255 ac + (255-a)bd}{255^2a + 255(255-a)b}&=\frac{1}{2}. \end{align*}$$ $a,b,c,d$ are non-negative integers in the domain $[0,255]$. Is it possible to prove that there are no solutions to this equation? One way to determine this is to test all ($255^4=4228250625$) possible combinations, however I'm looking for a more compelling proof. Both the numerator and denominator will each evaluate to a non-negative integer value. That being said, a part of the set of possible evaluated fractions will look like this: $$\frac{1}{2}, \frac{2}{4}, \frac{3}{6},\frac{4}{8},\frac{5}{10},\frac{6}{12},\frac{7}{14},\frac{8}{16},\frac{9}{18},\frac{10}{20},\ldots$$ The denominator must evaluate to an even number. Here are some of the rules of parity (even or odd) arithmetic: Addition/subtraction: Even Odd __________ Even |Even Odd Odd |Odd Even Multiplication: Even Odd __________ Even |Even Even Odd |Even Odd The denominator has only two variables $a$ and $b$ that I need to worry about. Let's consider the possible cases of parity and see which combinations result in an even number. $$255^2a + 255(255-a)b$$ $$(\mathrm{Odd})a + (\mathrm{Odd})((\mathrm{Odd})-a)b$$ $a$: Even; $b$: Even (Odd)(Even) + (Odd)((Odd)-(Even))(Even) (Even) + (Odd)(Odd)(Even) (Even) + (Odd)(Even) (Even) + (Even) (Even) a: Odd; b: Even (Odd)(Odd) + (Odd)((Odd)-(Odd))(Even) (Odd) + (Odd)(Even)(Even) (Odd) + (Even)(Even) (Odd) + (Even) (Odd) a: Even; b: Odd (Odd)(Even) + (Odd)((Odd)-(Even))(Odd) (Even) + (Odd)(Odd)(Odd) (Even) + (Odd)(Odd) (Even) + (Odd) (Odd) a: Odd; b: Odd (Odd)(Odd) + (Odd)((Odd)-(Odd))(Odd) (Odd) + (Odd)(Even)(Odd) (Odd) + (Even)(Odd) (Odd) + (Even) (Odd) Therefore, the denominator is only even when both $a$ and $b$ are even. Let's see the parity of the numerator with $a$ and $b$ both being even. $$255ac + (255-a)bd$$ (Odd)(Even)c + ((Odd)-(Even))(Even)d (Even)c + (Odd)(Even)d (Even)c + (Even)d (Even) + (Even) (Even) Therefore, the numerator must be an even number as well, reducing the set of possible evaluated fractions to those with even numerators: $$\frac{2}{4},\frac{4}{8},\frac{6}{12},\frac{8}{16},\frac{10}{20},\ldots$$ .. this is the furthest I could go with my insular analysis. Are there any other rules I could use to reduce the set of possible evaluated fractions down to 0? A: You are really trying to solve the diophantine equation $$510 ac + (510-2a)bd = 255^2a + 255(255-a)b$$ with $0\leq a,b,c,d\leq 255$, $a^2+b^2\gt 0$ (so the denominator is not zero). The left hand side is even; for the right hand side to be even, we either need $a$ to be even (so $255^2a$ to be even) and $b$ even (so $255(255-a)b$ will also be even); or $255^2a$ odd and $255(255-a)b$ odd; but $a$ odd implies $255-a$ even, so this is impossible. Modulo $3$, we have $-2abd \equiv 0\pmod{3}$, so one of $a,b,d$ must be a multiple of $3$ Modulo $5$, we have $-2abd \equiv 0\pmod{5}$, so one of $a$, $b$, $d$ must be a multiple of $5$. Modulo $17$ (why $17$? Because $255=3\times 5\times 17$) we also have $-2abd\equiv 0\pmod{17}$, so one of $a,b,d$ must be a multiple of $17$. This led me to consider whether the conditions could be satisfied by the same one of $a,b,d$. If it is $a$ or $b$, then they are forced to be $0$ by the conditions above. If $a=0$, we get $510bd = 255^2b$; or $2d = 255$, which is impossible. If $b=0$, then we get $510ac = 255^2a$, or $2c=255$, again impossible. Now, $d$ can satisfy the condition either as $d=0$ or $d=255$. If $d=0$, then we get $$510ac = 255^2a + 255(255-a)b$$ which reduces to $$2ac = 255a + (255-a)b$$ or $$b = \frac{2ac-255a}{255-a} = \frac{(2c-255)a}{255-a}.$$ For $b$ to be nonnegative, we need $c\gt 127$. But I found a way to make all values work: take $c=150$, $a=210$; then $$b=\frac{(300-255)210}{255-210} = \frac{(45)(210)}{45} = 210.$$ So, we can try $a=b=210$, $c=150$, $d=0$; indeed, $$\begin{align*} \frac{255 ac + (255-a)bd}{255^2a + 255(255-a)b}&= \frac{255(210)(150) + (255-210)(210)(0)}{255^2(210) + 255(255-210)(210)}\\ &= \frac{(255)(210)(150)}{(255)(210)(255+45)}\\ &= \frac{150}{300} = \frac{1}{2}. \end{align*}$$ Or in your original equation, $d=\frac{0}{255}$, $a=b=\frac{210}{255}$, $c=\frac{150}{255}$. There are probably other solutions. If $d=255$ (for completeness), we get $$510 ac + (510-2a)bd = 255^2a + 255(255-a)b$$ which simplifies: $$\begin{align*} 510ac + 255(510-2a)b &= 255^2a + 255(255-a)b\\ 255(2ac + (510-2a)b) &= 255(255a + (255-a)b)\\ 2ac + (510-2a)b &= 255a + (255-a)b\\ 2ac - 255a &= (255-a)b - 2(255-a)b\\ 2ac - 255a &= -(255-a)b\\ \frac{a(255-2c)}{255-a} &= b \end{align*}$$ which is just the dual of the last solution. For example, taking $a=210$ again, we can take $c=105$ to get $b=210$ as another solution. Note that this $c$ is just the complement of the previous $c$ relative to $255$. And we get an easy family of solutions, all with $a=b$: take $a=b=2k$, $0\leq k\leq 127$, $c=k$, $d=255$; or $a=b=2k$, $c=255-k$, $d=0$. The above analysis does not necessarily exhaust all possible solutions, but since you said you only wanted to prove that there were no solutions (which is unfortunately not the case), I stopped there. I don't know if there are any solutions with $a\neq b$.
{ "pile_set_name": "StackExchange" }
Q: Get thread name in gdb In gdb when I gave command info th I got the output like: (gdb) info th 5 Thread 0x7ffff3b54700 (LWP 1542) 0x00007ffff6705343 in poll () from /lib64/libc.so.6 4 Thread 0x7ffff2752700 (LWP 1544) 0x00007ffff670f163 in epoll_wait () from /lib64/libc.so.6 3 Thread 0x7ffff3153700 (LWP 1543) 0x00007ffff670f163 in epoll_wait () from /lib64/libc.so.6 2 Thread 0x7ffff4763700 (LWP 1541) 0x00007ffff69c7930 in sem_wait () from /lib64/libpthread.so.0 * 1 Thread 0x7ffff7fe17e0 (LWP 1520) 0x00007ffff66d2cdd in nanosleep () from /lib64/libc.so.6 I can conclude that there are 5 threads are running. But I can't get name of the function of the threads. How can I get function name of the thread using gdb? The thread 5 is paused its execution on poll(). But poll() is called by a function which is started by the thread. In my case I stated thread for set_up_socket_to_listen(). From where 'poll' is called. I want to print 'set_up_socket_to_listen'. pthread_t l_thread; pthread_create(&l_thread, 0, (void *)&set_up_socket_to_listen, NULL); I want to print set_up_socket_to_listen name A: If you want to see thread 5: (gdb) thread 5 (gdb) bt will show you the call stack for that thread.
{ "pile_set_name": "StackExchange" }
Q: Memcache tags simulation Memcached is a great scalable cache layer but it have one big problem (for me) that it cannot manage tags. And tags are really useful for group invalidation. I have done some research and I'm aware about some solutions: Memcache tag fork http://code.google.com/p/memcached-tag/ Code implementation to emulate tags (ref. Best way to invalidate a number of memcache keys using standard php libraries?) One of my favorite solution is namespace, and this solution is explained on memcached wiki. However I don't understand why we are integrate namespace on key cache? From what I understood about namespace trick is: to generate key we have to get value of the namespace (on cache). And if the namespace->value cache entry is evicted, we can no longer compute the good key to fetch cache... So the cache for this namespace are virtually invalidate (I said virtually because the cache still exist but we can no more compute the key to access). So why can we not simply implement something like: tag1->[key1, key2, key5] tag2->[key1, key3, key6] key1->["value" => value1, "tags" => [tag1, tag2]] key2->["value" => value2, "tags" => [tag1]] key3->["value" => value3, "tags" => [tag3]] etc... With this implementation I come back with the problem that if tag1->[key1, key2, key5] is evicted we can no more invalidate tag1 key. But with function load($cacheId) { $cache = $memcache->get($cacheId); if (is_array($cache)) { $evicted = false; // Check is no tags have been evicted foreach ($cache["tags"] as $tagId) { if (!$memcache->get($tagId) { $evicted = true; break; } } // If no tags have been evicted we can return cache if (!$evicted) { return $cache } else { // Not mandatory $memcache->delete($cacheId); } // Else return false return false; } } It's pseudo code We are sure to return cache if all of this tags are available. And first thing we can say it's "each time you need to get cache we have to check(/get) X tags and then check on array". But with namespace we also have to check(/get) namespace to retrieve namespace value, the main diff is to iterate under an array... But I do not think keys will have many tags (I cannot imagine more than 10 tags/key for my application), so iterate under size 10 array it's quite speed.. So my question is: Does someone already think about this implementation? And What are the limits? Did I forget something? etc Or maybe I have missunderstand the concept of namespace... PS: I'm not looking for another cache layer like memcached-tag or redis A: I think you are forgetting something with this implementation, but it's trivial to fix. Consider the problem of multiple keys sharing some tags: key1 -> tag1 tag2 key2 -> tag1 tag2 tag1 -> key1 key2 tag2 -> key1 key2 Say you load key1. You double check both tag1 and tag2 exist. This is fine and the key loads. Then tag1 is somehow evicted from the cache. Your code then invalidates tag1. This should delete key1 and key2 but because tag1 has been evicted, this does not happen. Then you add a new item key3. It also refers to tag1: key3 -> tag1 When saving this key, tag1 is (re)created: tag1 -> key3 Later, when loading key1 from cache again your check in the pseudo code to ensure tag1 exists succeeds. and the (stale) data from key1 is allowed to be loaded. Obviously a way around this is to check the values of the tag1 data to ensure the key you are loading is listed in that array and only consider your key valid if this is true. Of course this could have performance issues depending on your use case. If a given key has 10 tags, but each of those tags is used by 10k keys, then you are having to do search through an array of 10k items to find your key and repeat that 10 times each time you load something. At some point, this may become inefficient. An alternative implementation (and one which I use), is more appropriate when you have a very high read to write ratio. If reads are very much the common case, then you could implement your tag capability in a more permanent database backend (I'll assume you have a db of sorts anyway so it only needs a couple extra tables here). When you write an item in the cache, you store the key and the tag in a simple table (key and tag columns, one row for each tag on a key). Writing a key is simple: "delete from cache_tags where id=:key; foreach (tags as tag) insert into cache_tags values(:key, :tag); (NB use extended insert syntax in real impl). When invalidating a tag, simply iterate over all keys that have that tag: (select key from cache_tags where tag=:tag;) and invalidate each of them (and optionally delete the key from the cache_tags table too to tidy up). If a key is evicted from memcache then the cache_tags metadata will be out of date, but this is typically harmless. It will at most result in an inefficiency when invalidating a tag where you attempt to invalidate a key which had that tag but has already been evicted. This approach gives "free" loading (no need to check tags) but expensive saving (which is already expensive anyway otherwise it wouldn't need to be cached in the first place!). So depending on your use case and the expected load patterns and usage, I'd hope that either your original strategy (with more stringent checks on load) or a "database backed tag" strategy would fit your needs. HTHs
{ "pile_set_name": "StackExchange" }
Q: Change document root with htaccess I made a router using a /public folder. This folder contains my index.php that routes every route i need plus some css, js and stuff. Using Wamp and a command line i can change the root folder to be /public php -S localhost:8000 -t public My job's done and i want to upload my newly created website to a server. And... Yeah, i need to configure a .htaccess. So, after some researches i found a "universal" solution: RewriteEngine on RewriteCond %{HTTP_HOST} ^domain-name.com$ [NC,OR] RewriteCond %{HTTP_HOST} ^www.domain-name.com$ RewriteCond %{REQUEST_URI} !folder/ RewriteRule (.*) /folder/$1 [L] I needed to change the last line: RewriteRule ^(.*)$ /public/index.php [L] Everything routes perfectly, the only problem is that css/js doesn't load. Looking at the superglobal $_SERVER it appears that ["DOCUMENT_ROOT"]=> string(15) "/home/routerphp" does not contain my public folder. I also tried: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ public/index.php With the same result. I'm kinda desperate. Any help is appreciated. A: Sometimes you just need to take a break and clear cache. Everything is alright...
{ "pile_set_name": "StackExchange" }
Q: Using Application.Run in Class Library I have read in these forums where invoking Application.Run more than once is bad because it creates more than one message pump which throws an exception. My question is... Is it okay or bad practice if a windows application, uses a class library, which contains windows form(s) and Application.Run is invoked from within the class library in order to show a form. A class method would wrap over the call or invocation of Application.Run(new frmMyForm) in order to show it. Something to keep in mind about the application I have encountered in this scenario: The dlls extend the application functionality and the form(s) as classes within the DLL do not return data or state back to the main application but rather do independent tasks. A: I don't see anything wrong with that. It's really up to you how you want to package the code that makes that call. Wrapping it in a class library is not conceptually different from just wrapping it in a simple method called from your main method.
{ "pile_set_name": "StackExchange" }
Q: Java & Spring - polling the http endpoint until the server finishes processing I'm struggling with picking up the right way to poll server with constant interval (eg ~1 second). The flow goes as follows client application receives message, that indicates the polling could start with provided parameters (it doesn't poll when there is no need to) client application starts polling the http endpoint every ~1second with parameters arrived with message (like query parameter) server application responds with status pending so that indicates the client should continue polling server application responds with status finished and returns the result - there is no need to keep polling. We can have multiple threads, as the client application might receive multiple message in the short time - polling should start immediately I don't want to reinvent the wheel, maybe there is a proper tool that works with java/spring that I can use? Key features poll only when there is a need to poll with custom parameters (custom params in a query string) scale polling as the application could poll multiple endpoints simultaneously with the same interval I was going through various libs like Apache Camel or Spring Integration PollableChannel, but I feel like none of these is going to give me the right solution out of the box. If there is no lib like this - I'm going to write it on my own using redis and simple loop, but maybe someone has faced similar problem. A: If I understand your architecture correctly, the point is to call the same HTTP endpoint from the client application until expected result. In this case I would suggest something like RequestHandlerRetryAdvice with an AlwaysRetryPolicy and a FixedBackOffPolicy (1 second by default). To simulate an exception I would suggest an ExpressionEvaluatingRequestHandlerAdvice with the propagateOnSuccessEvaluationFailures = true option to re-throw an exception from the onSuccessExpression when reply from the server is pending. Both of these advises (in the exact RequestHandlerRetryAdvice, ExpressionEvaluatingRequestHandlerAdvice) you need to apply to @ServiceActivator for the HttpRequestExecutingMessageHandler. See more info in the Reference Manual: https://docs.spring.io/spring-integration/reference/html/messaging-endpoints-chapter.html#message-handler-advice-chain
{ "pile_set_name": "StackExchange" }
Q: Duplicating text within prompt - Node.js I am working on a Node.js program that takes input and adds it to a list. I am going to use this program through terminal. I have written the following function. Problem Areas: add: function () { console.log("What do you want to add to the ToDo List?"); // Starts the prompt prompt.start(); // Gets input called content prompt.get(['content'], function(err, result) { content = result.content // Pushed content to the list toDo.list.push(content); }); It is called when this switch command exicutes. switch (command){ case "list": toDo.print(); break; case "add": toDo.add(); break; } The issue is that all the input next duplicates while I input it. Output: All my Code (if you need it): var prompt = require('prompt'); // Empty variables that we will use for prompt input var content = ""; var command = ""; // Exits the program when this variable changes state var done = false; // Object that holds all functions and data for the ToDo portion of this program var toDo = { // List that everything all ToDos will be stored within list: ["Example", "Example 2"], // Print function prints the list print: function () { console.log(toDo.list); }, // The add function should add a value to the list add: function () { console.log("What do you want to add to the ToDo List?"); // Starts the prompt prompt.start(); // Gets input called content prompt.get(['content'], function(err, result) { content = result.content // Pushed content to the list toDo.list.push(content); }); } } // Main loop function getCommand() { // Starts the prompt prompt.start(); // Ask for name until user inputs "done" prompt.get(['timeManage'], function(err, result) { command = result.timeManage; // Checks if it is equal to exit; if so it exits the program if (command === 'exit') { console.log('Thanks for using timeManage.'); } else { // Checks the remaining commands; if it finds one it executes switch (command){ case "list": toDo.print(); break; case "add": toDo.add(); break; } // Loops the prompt unless the word exit is run getCommand(); } }); } getCommand(); Ps: I am a Node.js noob so if you spot any mistakes please tell me. Thanks, Base A: var toDo = { // List that everything all ToDos will be stored within list: ["Example", "Example 2"], // Print function prints the list print: function () { console.log(toDo.list); }, // The add function should add a value to the list add: function () { console.log("What do you want to add to the ToDo List?"); // Starts the prompt prompt.start(); // Gets input called content prompt.get(['content'], function(err, result) { content = result.content // Pushed content to the list toDo.list.push(content); getCommand(); }); } } function getCommand() { // Starts the prompt prompt.start(); // Ask for name until user inputs "done" prompt.get(['timeManage'], function(err, result) { command = result.timeManage; // Checks if it is equal to exit; if so it exits the program if (command === 'exit') { console.log('Thanks for using timeManage.'); } else { // Checks the remaining commands; if it finds one it executes switch (command){ case "list": toDo.print(); getCommand(); break; case "add": toDo.add(); break; } } }); } I basically removed the getCommand() you were calling after the end of the switch case and called it in, one inside the switch case where case "list" and the other inside the function toDo.add() I guess when you called getCommand() like before, both prompts for content and timeManage where executed on the console and that maybe the reason why you get double letter when you type a single letter. Here is an image to demonstrate what happened with your code. I have consoled the text "Add" after prompt.start() in toDo.add() and "getCommand" after prompt.start() in getCommand()
{ "pile_set_name": "StackExchange" }
Q: Setting DataSource in VB.NET Dim inc As Integer Dim MaxRows As Integer Dim con As New OleDb.OleDbConnection Dim dbProvider As String Dim dbSource As String Dim dA As OleDb.OleDbDataAdapter Dim dS As New DataSet Dim SQL As String Private Sub AbrirToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AbrirToolStripMenuItem.Click Dim strFileName As String Dim ClikedOk As Integer OpenFD.InitialDirectory = "C:\" OpenFD.Title = "Ubica la base de datos" OpenFD.Filter = "Agenda|Agenda.mdb" OpenFD.ShowDialog() If ClikedOk = DialogResult.OK Then strFileName = OpenFD.FileName dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" dbSource = "Data Source = Agenda.mdb" con.ConnectionString = dbProvider & dbSource con.Open() SQL = "SELECT * FROM Contactos" dA = New OleDb.OleDbDataAdapter(SQL, con) dA.Fill(dS, "Agenda") con.Close() MaxRows = dS.Tables("Agenda").Rows.Count inc = -1 End If End Sub What I want to do is this: The user should press Menu Item and select the Data Base file, then the Data Source would be directed to where the user pointed the Data Base file. What should I put in the line "dbSource = Data Source = ..."? Access Data Base is .mdb because I got troubles using .accdb A: Change this line: dbSource = "Data Source = Agenda.mdb" to this: dbSource = "Data Source=""" & OpenFD.FileName & """" and that will point the Data Source to the file the user selected.
{ "pile_set_name": "StackExchange" }
Q: Determine whether the following subsets of $\mathbb{R}^2$ are open with respect to the metric $d$. Consider the plane $\mathbb{R}^2$ equipped with its standard metric $d$ given by $$d((x_1,y_1),(x_2,y_2)) = \sqrt{(x_1-x_2)^2 + (y_1 - y_2)^2}$$ Determine whether the following subsets of $\mathbb{R}^2$ are open with respect to the metric $d$. Justify your answers. a) $ A = \{(x,y) \in \mathbb{R}^2 | x \geq 0\}$. I have been given the solution to this question but don't quite understand it. This is the solution I have been given: Let $r > 0$.Denote the point $(0,0) \in \mathbb{R}^2$ by $0$ and consider the open ball $B_r(0) \subset \mathbb{R}^2$. For the point $p_r = (-\frac{r}{2}, 0)$ we have $$d(p_r,0) = \sqrt{\frac{r^2}{4}} = \frac{r}{2}<r$$ and therefore $p_r \in B_r(0)\subset \mathbb{R}^2$. Note that $0 \in A$. If $A$ were open, then we would be able to find a radius $r>0$ with the property that $B_r(0)$ is never entirely contained in $A$. Thus, $A$ is not an open set of $\mathbb{R}^2$ with respect to the metric $d$. Looking at this solution I have a couple of questions. Why is the point $p_r = (-\frac{r}{2}, 0)$ used? I understand where the $d(p_r,0)$ comes from. If someone could help me break it down a bit. Thanks in advance. A: The point of the proof is that it's not an open set because $(0,0)$ is not an interior point. For that matter $(0,k)$ for any $k$ is not an interior point, but the proof choose $(0,0)$ because it makes the math easier. To show $(0,0)$ fails the interior test set we have to show there does NOT exist an $r > 0$ so that $B_r(0,0)$ is contained in $A$. To do that we just have to find a point $(j,k)$ so that $d((0,0),(j,k)) < r$ and $(j,k) \in A$. If $(j,k)\not \in A$ then $j < 0$. And it doesn't matter what $k$ is. So to make the math easy we will let $k = 0$. So we need a $(j,0)$ so that 1: $\sqrt{(j-0)^2 + (0-0)^2} = |j| < r$. and 2: $(j,0) \not \in A$ i.e. $j < 0$. So we need $-r < j < 0$. .... and they chose $\frac {-r}2$. It actually doesnt matter what you choose. They chose $(\frac {-r}2,0)$ because it makes the math easier. The could have chosen $(-\frac{r}{e},10^{-57}r)$ but that would make our math hard as hell. [ $\sqrt{(-\frac{r}{e}-0)^2 + (10^{-57}r - 0)^2} < r$] But with testing is $(\frac {-r}2,0)\in B_r(0,0)$ the math is easy. Is $d((\frac {-r}2,0),(0,0)) < r$? Of course. And is $(\frac {-r}2, 0) \in A$? Of course not. So $A$ is not open.
{ "pile_set_name": "StackExchange" }