source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0008148532.txt" ]
Q: php Error: XML or text declaration not at start of entity Source whenever I use the following code in PHP files , it gives me the error (Error: XML or text declaration not at start of entity Source) <?xml version='1.0' encoding='utf-8'?> I don't know what could be the solution please help Thanks in advance <?xml version='1.0' encoding='utf-8'?><rows><page>1</page><records>15</records><total>1</total><row id='18'><cell>18</cell><cell>2011-9-13</cell><cell>AL</cell><cell>2011-10-19</cell><cell>2011-10-21</cell><cell>3</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='17'><cell>17</cell><cell>2011-5-25</cell><cell>SL</cell><cell>2011-5-19</cell><cell>2011-5-19</cell><cell>1</cell><cell></cell><cell></cell><cell>Approved</cell><cell>Davinder</cell><cell>Kavita y</cell></row><row id='16'><cell>16</cell><cell>2011-5-25</cell><cell>SL</cell><cell>2011-5-24</cell><cell>2011-5-24</cell><cell>1</cell><cell></cell><cell></cell><cell>Approved</cell><cell></cell><cell>Kavita y</cell></row><row id='15'><cell>15</cell><cell>2011-5-26</cell><cell>AL</cell><cell>2011-7-08</cell><cell>2011-7-12</cell><cell>0</cell><cell></cell><cell></cell><cell>Disapproved</cell><cell></cell><cell>Kavita y</cell></row><row id='14'><cell>14</cell><cell>2011-5-25</cell><cell>AL</cell><cell>2011-6-30</cell><cell>2011-7-02</cell><cell>3</cell><cell></cell><cell></cell><cell>Approved</cell><cell></cell><cell>Kavita y</cell></row><row id='13'><cell>13</cell><cell>2011-9-14</cell><cell>CL</cell><cell>2011-6-15</cell><cell>2011-6-15</cell><cell>1</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell></cell><cell>Kavita y</cell></row><row id='12'><cell>12</cell><cell>2011-5-25</cell><cell>CL</cell><cell>2011-6-10</cell><cell>2011-6-12</cell><cell>3</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell></cell><cell>Kavita y</cell></row><row id='11'><cell>11</cell><cell>2011-5-25</cell><cell>SL</cell><cell>2011-5-20</cell><cell>2011-5-17</cell><cell>4</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell></cell><cell>Kavita y</cell></row><row id='10'><cell>10</cell><cell>2011-5-25</cell><cell>CL</cell><cell>2011-6-03</cell><cell>2011-6-05</cell><cell>3</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='9'><cell>9</cell><cell>2011-5-26</cell><cell>SL</cell><cell>2011-5-18</cell><cell>2011-5-22</cell><cell>5</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='8'><cell>8</cell><cell>2011-5-24</cell><cell>AL</cell><cell>2011-5-20</cell><cell>2011-5-20</cell><cell>0</cell><cell></cell><cell></cell><cell>Disapproved</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='7'><cell>7</cell><cell>2011-5-24</cell><cell>CL</cell><cell>2011-5-20</cell><cell>2011-5-20</cell><cell>1</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='4'><cell>4</cell><cell>2011-9-14</cell><cell>SL</cell><cell>2011-5-20</cell><cell>2011-5-20</cell><cell>1</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='3'><cell>3</cell><cell>2011-5-24</cell><cell>SL</cell><cell>2011-5-20</cell><cell>2011-5-20</cell><cell>1</cell><cell></cell><cell></cell><cell>Waiting for approval</cell><cell>mohan</cell><cell>Davinder Singh</cell></row><row id='1'><cell>1</cell><cell>2011-5-24</cell><cell>SL</cell><cell>2011-5-20</cell><cell>2011-5-22</cell><cell>0</cell><cell>dd</cell><cell>remarks</cell><cell>Disapproved</cell><cell>mohan</cell><cell>Davinder Singh</cell></row></rows> and the php code header("Content-type: text/xml;charset=utf-8"); $s = "<?xml version='1.0' encoding='utf-8'?>"; $s .= "<rows>"; $s .= "<page>".$page."</page>"; $s .= "<records>".$count."</records>"; $s .= "<total>".$total_pages."</total>"; // be sure to put text data in CDATA while($row = mysql_fetch_array($result,MYSQL_ASSOC)) { $s .= "<row id='". $row['fld_id']."'>"; $s .= "<cell>". $row['fld_id']."</cell>"; $s .= "<cell><![CDATA[". getDepartmentName($row['deptSr'])."]]></cell>"; $s .= "<cell>". $row['email']."</cell>"; $s .= "<cell>". $row['fname']."</cell>"; $s .= "<cell>". $row['lname']."</cell>"; $s .= "<cell>". $row['password']."</cell>"; $s .= "<cell>". listlevel($row['level'])."</cell>"; $s .= "<cell>". date('Y-m-d G:i:s', $row['date_create'])."</cell>"; $s .= "<cell>". date('Y-m-d G:i:s', $row['last_login'])."</cell>"; $s .= "<cell>". $row['ip_addr']."</cell>"; $s .= "<cell>". $row['dob']."</cell>"; $s .= "<cell>". $row['street']."</cell>"; $s .= "<cell>". $row['phone_mob']."</cell>"; $s .= "<cell>". $row['phone_home']."</cell>"; $s .= "<cell>". liststatus($row['fld_enabled'])."</cell>"; $s .= "</row>"; } $s .= "</rows>"; echo $s; A: XML or text declaration not at start of entity indicates that the prolog isn’t the first line in the output. Most likely, a blank line is somehow finding its way into your output. This error isn’t unique to WordPress; however, as I mentioned in my comment, I did a search for the error message on Google and WordPress comes up in a lot of the results. If you’re not using WordPress, kindly disregard the remainder of this answer. Disclaimer: I know nothing about WordPress so I’m reluctant to answer in that capacity; however, since there are no other answers as of this writing, I’ll simply show you what I’ve found on the subject. Wordpress leading whitespace fix seems to help some people with the error you specified. Additional suggestions are available here. How to fix: XML Parsing Error: XML or text declaration not at start of entity deals with white space before the prolog. The comment suggests using ob_start() and ob_end_clean(). If you are using WordPress, you may attract better answers by adding the WordPress tag to your question. There’s no guarantee, but it could draw the attention of those more knowledgeable than myself.
[ "stackoverflow", "0037100754.txt" ]
Q: JS Array called "name" behaves strangely I played around a bit and created a javascript array containing some strings. When I tried to access the array it behaves quite strangely. The array is created correctly and works as expected if it is called something else. var name = ["foo", "bar"]; alert(name); // shows "foo,bar" Why is the array converted into a string, if the variable name is name? According to the standard (which the linked website is based on) it should be a valid variable name: https://mothereff.in/js-variables#name A: If you execute javascript in a browser environment, the code is executed in the window context. This context already has some global variables set. One of those is the window.name which is a string. When the variable is set, the browser will automatically cast the new value to string which causes the strange behavior. So even though name is a valid variable name, it should not be used in the global context if you are executing your javascript in the browser (It should work fine in e.g. node.js).
[ "stackoverflow", "0058041226.txt" ]
Q: Setting up GitHub webhooks for an OpenShift build I tried to set up a github webhook to trigger builds on OpenShift following these docs. I am confused about two things: (1) When I create the secret, as prescribed by the above docs, do I need to create one YAML entry or two? Ie. are the following snippets (taken from the above link) supposed to be the same YAML entry? type: "GitHub" github: secretReference: name: "mysecret" with the second one being: - kind: Secret apiVersion: v1 metadata: name: mysecret creationTimestamp: data: WebHookSecretKey: c2VjcmV0dmFsdWUx (2) If I query oc describe bc [name-of-my-build-config], I get (all masks of [this] form were added by me) Webhook GitHub: URL: https://[blabla].openshift-online.com:6443/apis/build.openshift.io/v1/namespaces/[my-namespace]/buildconfigs/[my-build-config]/webhooks/<secret>/github So now when I enter this url as a GitHub webhook, what should I replace <secret> with in the above URL? Also, what should I enter in the textbox for Secret on Github (see screenshot below) I understand that the WebHookSecretKey: c2VjcmV0dmFsdWUx is just an encoded version of the plaintext secret key... So where should I use the plaintext key? Should I also use mysecret anywhere, eg substitute in for <secret> in the above url? A: The easiest way to get the full GitHub Webhook URL in OpenShift 4.x is to first get the URL from $ oc describe bc my-build ... Webhook GitHub: URL: https://api.example.com:6443/apis/build.openshift.io/v1/namespaces/my-project/buildconfigs/my-build/webhooks/<secret>/github ... Then, to fill in the <secret> portion of the URL, you get this from $ oc get bc -o yaml ... triggers: - github: secret: 467ed550-c447-411d-87ad-2d3a3fa81538 type: GitHub ... So, for this example, the GitHub Webhook URL would be https://api.example.com:6443/apis/build.openshift.io/v1/namespaces/my-project/buildconfigs/my-build/webhooks/467ed550-c447-411d-87ad-2d3a3fa81538/github
[ "latin.stackexchange", "0000013078.txt" ]
Q: Maxima - a speech competition? At some point in childhood I learnt there were speech competitions in ancient Rome when people would express complex ideas in very few words. And I believed since those short sentences called "maxima" This happened couple decades before public Internet and wikipedia. I always believed it to be common knowledge. However tried recently to find confirmation and couldn't get past "plural for maximus" copy/paste on 50 websites. Are there real scholars of Latin and/or ancient Rome history who can confirm or correct my understanding that maxima is a short phrase which explains a complex construct I don't know if this example would qualify as maxima in ancient times but looks good to me: If you tell the truth you don’t have to remember anything. – Mark Twain A: The word maxima [sententia] indicates a sentence that is a general truth or is generally assumed to be true. Not necessarily it explains a complex context, you can instead think of a maxima as an axiom, that for its evidence becomes a foundation or a rule of behaviour. It is a "maxima" sentence because of its universal validity. Maxima is still present in English as "maxim", in Italian as "massima", which have the same meaning.
[ "stackoverflow", "0000873628.txt" ]
Q: What is the proper etiquette for handling potentially reusable legacy code in large projects? I have been wondering what is the best way to tackle this situation. Is the best way to leave the old code in a comment block in case someone decides to add that functionality into the project again, or should this code be deleted for the purposes of keeping the source code clean and readable? A: This is a duplicate, but I don't have time to find the duplicates. This also is not specific to legacy code. All code is legacy code, until it is no longer used. The answer is: use source control. That's what it's for. The text in your source files should be what's currently being executed. Nothing else. A: As long as you are using source control, I think it's better to delete unused code. Leaving commented-out code mixed in with active code "just in case" can leave the file difficult to maintian. If the rest of the code is under active development, chances are that the commented code will quickly get left behind. If the zombie code ever is uncommented it might not work at all, or the resurrected code might cause a difficult-to-detect problem. I've worked on "do not delete" projects. It was like working in a junkyard. Searching the code made me want to cry. Some methods contained more commented code than compiling code. Madness!
[ "stackoverflow", "0038075199.txt" ]
Q: MYSQL Duplicate rows I am trying to insert values into a table in MYSQL, the table has a column which should be unique,so that column always will have different values. I tried putting UNIQUE for the coloumn but it did not work, Also tried putting that column as PRIMARY KEY and insert IGNORE INTO command it did not work (http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm) My intention is to put phonenumber column unique so every value in this column is different. if the newly inserting value is not unique it should skip wihout giving error. My code to Create table: public function create_member_table($table) { $this->sql ="CREATE TABLE IF NOT EXISTS $table ( id BIGINT NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, phonenumber VARCHAR(20) NOT NULL, country VARCHAR(2) NOT NULL, profession VARCHAR(5000) NOT NULL, profilepic VARCHAR(5000) NOT NULL, smskey VARCHAR(100) NOT NULL, status INT NOT NULL, reg_date_time DATETIME NOT NULL, UNIQUE (id,phonenumber)) PARTITION BY HASH(id) PARTITIONS 1023;"; $this->tb = mysqli_query($this->ret,$this->sql); if(!$this->tb){ echo "Table not created<br>"; } else{ echo "Table created<br>"; } Insert table: public function table_member_insert($table,$phonenumber="",$username="",$country="",$profession="",$profilepic="0",$smskey="",$status="") { $this->sql = "INSERT INTO $table (username,phonenumber,country,profession,profilepic,smskey,status,reg_date_time) VALUES ('$username','$phonenumber','$country','$profession','$profilepic','$smskey','$status',now());"; $this->tb = mysqli_query($this->ret,$this->sql); if(!$this->tb){ echo "values not inserted<br>"; } else{ echo "values inserted<br>"; } } A: The problem is that you defined the combination of id and phonenumber fields as unique. Since your id field is defined as auto_increment, it will be unique on its own, therefore any combination with phonenumber field will also be unique. You need to define the phonenumber field alone as unique. After that you can use insert ignore to insert a new record with an existing phone number without raisin an error. However, pls note that in case of a match, the unique index will prevent the entire record from being inserted.
[ "stackoverflow", "0045651125.txt" ]
Q: RxJava Android sequence print data I'm learning RxJava in Android. I have: Observable<Country> getCountries(){} // returns Countries Observable<City> getCapital(int countryId){} // returns capital by country id I want: Print all country names returned by getCountries(). Then print capital name of each country from getCapital() method, except country with id=1. This all should be in one chain. For example: private Observable<Country> getCountries(){ return Observable.just( new Country(0, "Luxemburg"), new Country(1, "Netherlands"), new Country(2, "Norway"), new Country(3, "India"), new Country(4, "Italy") ); } private Observable<City> getCapital(int countryId){ City city; switch (countryId){ case 0: city = new City("Luxembrug"); break; case 1: city = new City("Amsterdam"); break; case 2: city = new City("Oslo"); break; case 3: city = new City("Delhi"); break; case 4: city = new City("Rome"); break; default: city = new City(""); break; } return Observable.just(city); } getCountries() .doOnNext(country -> Log.d("TAG", "Country: id="+country.getId()+" name="+country.getName())) .filter(country -> country.getId()!=1) .flatMap(country -> getCapital(country.getId())) .subscribe(city -> Log.d("TAG", "City: "+city.getName())); What I want to get: D: Country: id=0 name=Luxemburg D: Country: id=1 name=Netherlands D: Country: id=2 name=Norway D: Country: id=3 name=India D: Country: id=4 name=Italy D: City: Amsterdam D: City: Oslo D: City: Delhi D: City: Rome What I get: D: Country: id=0 name=Luxemburg D: Country: id=1 name=Netherlands D: City: Amsterdam D: Country: id=2 name=Norway D: City: Oslo D: Country: id=3 name=India D: City: Delhi D: Country: id=4 name=Italy D: City: Rome How can I achieve this? I should at first get all countries, print it and after then get capitals for this countries. But I don't understand how can I do this in one chain.. Thanks for any tips! A: Assuming you can't change the getCountries() and getCapital(int countryId) methods you can achieve it like this: RxJava 1x: getCountries() .toList() .doOnNext(countries -> { for (Country country : countries) { Log.d("TAG", "Country: id=" + country.getId() + " name=" + country.getName()); } }) .flatMap(Observable::from) .filter(country -> country.getId() != 1) .flatMap(new Func1<Country, Observable<City>>() { @Override public Observable<City> call(Country country) { return getCapital(country.getId()); } }) .subscribe(city -> Log.d("TAG", "City: " + city.getName())); RxJava 2x: getCountries() .toList() .doOnSuccess(countries -> { for (Country country : countries) { Log.d("TAG", "Country: id=" + country.getId() + " name=" + country.getName()); } }) .toObservable() .flatMap(Observable::fromIterable) .filter(country -> country.getId() != 1) .flatMap(new Function<Country, ObservableSource<City>>() { @Override public ObservableSource<City> apply(@NonNull Country country) throws Exception { return getCapital(country.getId()); } }) .subscribe(city -> Log.d("TAG", "City: " + city.getName()));
[ "stackoverflow", "0033348019.txt" ]
Q: Entity Framework appending '1' to property name when it matches entity name I am using Entity Framework version 4.0 to create a model using the database first approach. In the database, there's a number of tables that contain columns named the same as their parent table. So for example we have table State with columns State and StateName table Status with columns Status and Description The issue is that when one of these tables is imported into the EF model, the property names that those columns get mapped to get a '1' appended to the end of them. So I end up with entity State with properties State1 and StateName entity Status with properties Status1 and Description When I attempt to remove the '1' at the end, I get a message saying "The name Status cannot be duplicated in this context. Please choose another name." Is there a way for me to have my properties keep their names or is this a documented limitation in the framework? A: You can't have a member in your class which is named like your class is. Example: class Test { // Invalid int Test; // Invalid public int Test {get; set; } // OK int Test1; }
[ "stackoverflow", "0029264635.txt" ]
Q: Why my linq query projecting one item in the model class? I have more than one item in xml file and want to print all of them. But for some reason, it is only printing first item from the xml file. Here is my xml file. stored in the database table in a column called XmlFile:- <root> <item name="one" action="GetListOne" print="2" /> <item name="two" action="GetListTwo" print="1" /> <item name="three" action="GetListThree" print="2" /> <item name="four" action="GetListFour" print="0" /> </root> Here is my model class:- public class ItemList { public string Name { get; set; } public string Action { get; set; } public string Print { get; set; } } And Linq:- var items = _repo.GetItemsById(Id).Single(); var xml = XDocument.Parse(items.XmlFile); var model = from x in xml.Descendants("root") select new ItemList { Name = x.Element("item").Attribute("name").Value, Action = x.Element("item").Attribute("action").Value, Print = x.Element("item").Attribute("print").Value, }; foreach (var m in model) { Console.WriteLine(String.Format("Name = {0}",m.Name)); } Output:- Name = One A: You are always getting first item of the root, you need: var model = from x in xml.Descendants("item") select new ItemList { Name = x.Attribute("name").Value, Action = x.Attribute("action").Value, Print = x.Attribute("print").Value, };
[ "stackoverflow", "0036255991.txt" ]
Q: Is including ng-binding in your css selectors a bad practice? I just ran across this piece of code in our code base li.ng-binding span { font-size: 13px; font-family: Arial, Helvetica, sans-serif; font-weight: bold; } and this selector doesnt apply to one of the li elements it was meant to apply to because of the .ng-binding present in the selector. Though this code works, isnt including ng-binding in a CSS selector a bad practice? A: I agree with your hesitation. CSS is designed primarily to enable the separation of document content from the document presentation (separation of structure), Since Angular is essentially a middleman for binding to the attributes of HTML DOM elements, standard directives (like ngStyle) or custom directives should be used to help style DOM elements In addition; after some initial investigation there is a class="ng-binding" which is used internally by Angular. Examining the ngBind source there are a few lines that adds the class and associates the binding with .data: In Angular < 1.3 there is a reference to this: element.addClass('ng-binding').data('$binding', attr.ngBindHtml); I would not use this class.
[ "stackoverflow", "0030544331.txt" ]
Q: How to draw four images in circle quarterly equal? I need to draw four group images in a circle quarterly equal. can anyone help me below is the screen A: You can follow these steps to achieve this. In create a view in .xib according to attach image. I have created a view "imageViewHolder". which have four UIImageView. Since I have all four image with white background so I have used 2 label with black color and used them as line separator bitween images. U can use any color according to your requirement. set IBoutlet to ImageViewHolder edit below code according to your requirement - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // first make imageViewHolder round [self getRoundCollage]; } -(UIImage *)getRoundCollage{ // first make imageViewHolder as circular view self.imageViewHolder.layer.cornerRadius = self.imageViewHolder.frame.size.width/2; self.imageViewHolder.clipsToBounds = YES; // now take screen shot of imageView UIGraphicsBeginImageContext(self.imageViewHolder.frame.size); CGContextRef context = UIGraphicsGetCurrentContext(); [self.imageViewHolder.layer renderInContext:context]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } see result If u like my answer. Then do not forget to vote my answer A: You just need to add a view,for example 200*200 Then add 4 imageviw to this view Then set cornerRadius self.testview.layer.cornerRadius = 100; self.testview.layer.masksToBounds = YES; I just set background color,it looks like this
[ "stackoverflow", "0000369594.txt" ]
Q: WebBrowser.Navigated Only Fires when I MessageBox.Show(); I have a WebBrowser control which is being instantiated dynamically from a background STA thread because the parent thread is a BackgroundWorker and has lots of other things to do. The problem is that the Navigated event never fires, unless I pop a MessageBox.Show() in the method that told it to .Navigate(). I shall explain: ThreadStart ts = new ThreadStart(GetLandingPageContent_ChildThread); Thread t = new Thread(ts); t.SetApartmentState(ApartmentState.STA); t.Name = "Mailbox Processor"; t.Start(); protected void GetLandingPageContent_ChildThread() { WebBrowser wb = new WebBrowser(); wb.Navigated += new WebBrowserNavigatedEventHandler(wb_Navigated); wb.Navigate(_url); MessageBox.Show("W00t"); } protected void wb_Navigated(object sender, WebBrowserNavigatedEventArgs e) { WebBrowser wb = (WebBrowser)sender; // Breakpoint HtmlDocument hDoc = wb.Document; } This works fine; but the messagebox will get in the way since this is an automation app. When I remove the MessageBox.Show(), the WebBrowser.Navigated event never fires. I've tried supplanting this line with a Thread.Sleep(), and by suspending the parent thread. Once I get this out of the way, I intend to Suspend the parent thread while the WebBrowser is doing its job and find some way of passing the resulting HTML back to the parent thread so it can continue with further logic. Why does it do this? How can I fix it? If someone can provide me with a way to fetch the content of a web page, fill out some data, and return the content of the page on the other side of the submit button, all against a webserver that doesn't support POST verbs nor passing data via QueryString, I'll also accept that answer as this whole exercise will have been unneccessary. Solution: I ended up just not using the BackgroundWorker and slave thread at all at the suggestion of the team architect... Though at the expense of responsiveness :( A: WebBrowser won't do much unless it is shown and has a UI thread associated; are you showing the form on which it resides? You need to, to use the DOM etc. The form could be off-screen if you don't want to display it to the user, but it won't work well in a service (for example). For scraping purposes, you can normally simulate a regular HTML browwser using WebClient etc. IS this not sufficient? You can use tools like "Fiddler" to investigate the exact request you need to make to the server. For more than that, you might look at the HTML Agility Pack, which offers DOM access to HTML without a browser.
[ "stackoverflow", "0021729687.txt" ]
Q: How to hide tr items when td is 0 in jquery? I want to hide all of the <tr> where td's text is 0. How can I do that? I have to mention that in reality i have more than 600 rows. But the example below is a demo. THX <table id ="list2"> <tbody> <tr> <td>2</td> <td>213</td> <td id ="hideRow">0</td> <tr> <tr> <td>vb</td> <td>asf</td> <td id ="hideRow">0</td> <tr> <tr> <td>cxvb</td> <td>xcvb</td> <td id ="hideRow">2</td> <tr> <tr> <td>cas</td> <td>asdf</td> <td id ="hideRow">45</td> <tr> </tbody> </table> This is my try :| . The event is loaded by onclick event $('#list2').find("tr td #hideRow").each(function(){ var txt2 = $(this).text(); if (txt2 =="0"){ $('#list2').find("tr").each(function(){ $(this).hide(); }); } }) A: First of all do not use id for duplicate names. Try doing it like following. <table id ="list2"> <tbody> <tr> <td>2</td> <td>213</td> <td class="hideRow">0</td> <tr> <tr> <td>vb</td> <td>asf</td> <td class="hideRow">0</td> <tr> <tr> <td>cxvb</td> <td>xcvb</td> <td class="hideRow">2</td> <tr> <tr> <td>cas</td> <td>asdf</td> <td class="hideRow">45</td> <tr> </tbody> </table> $('#list2').find(".hideRow").each(function(){ var txt2 = $(this).text(); if (txt2 =="0"){ $(this).parent().hide(); } }) A: IDs on elements need to be unique, you can't have multiple <td id="hideRow"> elements and expect things to play nicely all of the time. I'd suggest changing it to a class. Then, select all elements: var elems = $('span.hideRow'); Filter to those whose text is 0: elems = elems.filter(function() { return $(this).text() === "0"; }); Get their parent <tr> element: elems = elems.closest('tr'); Then, finally, hide them: elems.hide(); That can, obviously, all be done in one line: $('span.hideRow').filter(function() {return $(this).text() === "0";}).closest('tr').hide();
[ "ux.stackexchange", "0000054523.txt" ]
Q: How to display a lot of filters (cascading and/or not)? I have a dashboard for an internal web application in my company. I have 4 charts and labeled combobox filters related to these charts. The user can select a specific value in the combobox or select all of them (by default). Here is a quick wireframe : download bmml source – Wireframes created with Balsamiq Mockups Some of these filters are cascading ("Domain" -> "Service" -> "Sector"). But the user can select a specific a specific "Service" or "Sector" event if he doesn't know the "Domain". "Sourcing" and "Profiles" are independent and "Line" defines one specif domain, service and sector. I'm a bit confuse with these filters. I don't know how to display them and the cascading effect can create difficult situations for the user, that's why I put a 'reset' button (i.e. back back to the default statement). By the way, my company asks me to add more filters again. Some of them are global and independent (like "Sourcing"), others can cascade again. I also need to add a "Designation" filter, which is the same than "Line" but with another typology (for different users), and may be some checkboxes... Well, I think users will be lost with all these filters and don't know how to properly display them. How can I improve my UI ? Can I use some "filters patterns" ? A: I totally agree with dennislees' comment. What I want to add is, it seems to me that you do not have a clear 'user scenario' or 'set of requirements'. If you ask the analyst, or the person who is making the requests, to prepare a set of scenarios and requirements, then work on it together for 1,5; you will be able reach a clear hierarchy of filters as well as the goals. One more tip, advanced filtering is a good option for this kind of situation. Once you know what your main filters are (around 4-6 filters) then you can group them all, and put the rest in advanced filtering.
[ "stackoverflow", "0006693821.txt" ]
Q: How do you display the code (not output) that .Net T4 generates? We have a set of T4 templates we have just migrated forward to VS 2010 and they compile but are no longer working the same. In order to see what is actually going on under the hood it would be useful to see the temporary cs files that T4 generates to produce the actual T4 conversion. A: As you're now using Visual Studio 2010, you can also change the custom tool on the template from TextTemplatingFileGenerator to TextTemplatingFilePreprocessor temporarily. This will spit out the underlying code directly into your project instead of the regular template output. A: If you set <#@ template debug="true"#> then the generated code will be left in your temp directory. On my Windows 7 system, that's C:\Users\John Saunders\AppData\Local\Temp.
[ "stackoverflow", "0040628525.txt" ]
Q: Allow broswer to download images from Google Cloud Storage? I have a compute engine and google cloud storage work together. The compute engine has a tomcat running allow browsers to load a page and get the images from the google cloud storage. How could i allow the html page (generated by the servlet) to download several images from the google cloud storage where the images are not public shared?? What i expect is when the broswers downloaded the html page then it will request the images directly from the cloud storage, but how can i allow the broswer to do it without making the images public sharable? Thanks A: This is tricky but possible. If you want to manage some sort of authorization scheme for who can and cannot view GCS images, you'll need a service which can vend short-term, signed URLs to parties that your service decides are authorized. You then embed the URLs in the image tags of your dynamically-generated HTML pages, or you fetch the URLs from the server with JavaScript. The gcloud-java library has a signURL method for generating such a URL. Another option would be to simply obfuscate the image URLs to something unguessable and rotate them every so often.
[ "math.stackexchange", "0001469521.txt" ]
Q: Curves with constant curvature and constant torsion Describe all curves in $\mathbb{R}^3$ which have constant curvature $κ > 0$ and constant torsion $τ$. Any ideas what we can do to describe all such curves? Do we have to use the formulas of the curvature and of the torsion? A: HINT: If you don't want to solve the matrix differential equation, I recommend that you get a second-order differential equation for the principal normal $n$. You should know solutions of this by sight (at least, component by component). A: As had been explained, you may choose to either solve the differential equation given by Frenet's identities in the space of matrices, or do the smart trick suggested by Ted Shiffrin; I shall choose the latter approach. For my typing convenience, I shall also omit all the "mathhb" formatting, therefore the normal will just be $n$. Also, since $t$ is the tangent, I shall use $s$ for the time parameter on the curve. Starting with $\ddot n = - (k^2 + \tau ^2)n$, we shall approach it in the usual way: first we consider its associated algebraic equation $\lambda ^2 = -(k^2 + \tau ^2)$, which has the roots $\pm \Bbb i \sqrt{k^2 + \tau ^2}$. Next, we know from the general theory of linear equations that this gives two fundamental solutions to the above equation, namely $u \sin rs$ and $v \cos rs$ where $r^2 = k^2 + \tau ^2$ and $u,v \in \Bbb R ^3$ (note that $r \ne 0$ because $k>0$ by assumption). Therefore, $n(s) = u \sin rs + v \cos rs$ for some constant vectors $u,v \in \Bbb R ^3$. May $u,v \in \Bbb R ^3$ be really arbitrary? Not quite: note that $n(0) = v$ and since $\| n (s) \| = 1 \ \forall s$ (the curve is parametrized by arc-length and the Frenet frame is taken to be orthonormal), then $\| v \| = 1$. Next, if you derive this once, you get $\dot n (0) = ru$; on the other hand, $\dot n (0) = -k t(0) + \tau b (0)$, so $r u = -k t(0) + \tau b (0)$, so $r^2 \| u \| ^2 = \| -k t(0) + \tau b (0) \| ^2 = k^2 \| t (0) \| ^2 - 2 k \tau \langle t(0), b(0) \rangle + \tau ^2 \| v \| ^2$. Since $\| t \| = \| b \| = 1$ and $\langle t, b \rangle = 0$, the last expression is exactly $k^2 + \tau ^2 = r^2$, which implies $\| u \| = 1$. Finally, $\| n \| ^2 = 1$ implies $\| u \| ^2 \sin ^2 rs + 2 \sin rs \cos rs \langle u, v \rangle + \| v \| ^2 \cos ^2 rs = 1$ which, taking into consideration all of the above, implies $\langle u, v \rangle = 0$. To conclude, $u$ and $v$ must be orthogonal, and of length $1$. Next, if your curve is $s \mapsto x(s) \in \Bbb R ^3$ ($x$ is a vector, not the first coordinate of a vector!), then using the equation $\dot t = k n$ and the fact that $t = \dot x$, you will get $\ddot x = kn = k (u \sin rs + v \cos rs)$, that you will have to integrate twice. Integrating once gives $\dot x = -\dfrac k r u \cos rs + \dfrac k r v \sin rs + w$, with $w \in \Bbb R ^3$, and integrating once more gives $x = - \dfrac k {r^2} u \sin rs - \dfrac k {r^2} v \cos rs + ws + x_0$, with $x_0 \in \Bbb R^3$. Similarly to the discussion about $u$ and $v$, may $w$ be arbitrary? No, it may not: first, $\langle t, n \rangle = 0$ implies $\langle w, u \sin rs + v \cos rs \rangle = 0 \ \forall s$, which implies that $w \perp \text{span} \{u, v \}$. Second, using this and the fact that $\| \dot x \| ^2 = \| t \| ^2 = 1$ implies that $\| w \| = \dfrac {| \tau |} r$. There is no constraint, on the other hand, on $x_0$. If $\tau = 0$ (so your curve is a plane curve), after a possible orthogonal transformation you may take $u = (-1, 0, 0)$ and $v = (0, -1, 0)$, so your curve will look like $x(s) = (\dfrac k {r^2} \sin rs, \dfrac k {r^2} \cos rs, 0) + x_0$ which, after a translation by $x_0$ will have the final nice form $x(s) = (\dfrac k {r^2} \sin rs, \dfrac k {r^2} \cos rs, 0)$, so it will be a circle. If $\tau \ne 0$, since $\{ -u, -v, w \frac r {\ |\tau| }\}$ have been shown to form an orthonormal frame (in fact, we have worked with $u$ and $v$, but absorbing a minus sign into them doesn't change orthonormality), after a possible orthogonal transformation you may take them to form the familiar frame $\{ (1, 0, 0), (0, 1, 0), (0, 0, 1) \}$, in which case you curve looks like $x(s) = (\dfrac k {r^2} \sin rs, \dfrac k {r^2} \cos rs, \frac {| \tau |} r s) + x_0$. If you also translate your curve by $x_0$ (again, this doesn't change your curve), it will have the final nice form $x(s) = (\dfrac k {r^2} \sin rs, \dfrac k {r^2} \cos rs, s\dfrac { |\tau | } r)$, which is a helix. Note that this equation reduces to the one of the circle for $\tau \to 0$. Therefore, the only curves that satisfy your problem are circles and helices. (Had you allowed $k=0$ too, you would have also obtained (segments of) straight lines).
[ "stackoverflow", "0030441844.txt" ]
Q: image overlay with ffmpeg runs the script indefinitely I really tried hard, I did not succeed, so I am asking here. I wanted to have an overlay image (jpg) with text on video (mp4; 15 secs) and have fade-in and fade-out for the overlayed image (and not the video). I could do this with the follwing command, but it hangs after after reaching 451 frames. After this the "drop" (shown in the output; drop=1451) starts increasing and the process never finishes. ffmpeg -i video.mp4 -loop 1 -i overlay.jpg -filter_complex \ "[1] drawtext=fontfile=$fontfile:text='TESTING TEXT':fontcolor=white@1.0:fontsize=46:x=0:y=0 [t0]; [t0] fade=in:st=0:d=3 [t1]; [0][t1] overlay=0:900:enable='between(t,0,15)'" \ -codec:a copy output.mp4 Output: frame= 451 fps=8.8 q=-1.0 Lsize= 4790kB time=00:00:14.98 bitrate=2619.0kbits/s dup=75 drop=1451 Please help. Thanks. A: Option 1 Your image input is looping indefinitely. Add shortest=1 to your overlay to force the output to terminate when the shortest input terminates: overlay=0:900:enable='between(t,0,15)':shortest=1 Option 2 Remove -loop 1.
[ "stackoverflow", "0027650832.txt" ]
Q: Cannot receive broadcast in Activity from LocalBroadcastManager in IntentService it is very simple code to use broadcast between Activity and IntentService. The MainActivity starts SyncService (which is an IntentService), the SyncService broadcasts messages and MainActivity should receive the messages from SyncService (by using BroadcastReceiver). but it is strange that the MainActivity cannot get any message from SyncService. Somehow if I call LocalBroadcastManager to broadcast message directly in MainActivity (onCreate() method), the receiver can get the message. is it because of the different context to initialize LocalBroadcastManager? or there is any other problem? thanks! Relavant code in MainActivity: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter statusIntentFilter = new IntentFilter(AppConstants.BROADCAST_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, statusIntentFilter); final Intent intent = new Intent(this, SyncService.class); this.startService(intent); this.sendMessage(); } private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Get extra data included in the Intent String message = intent.getStringExtra("message"); Log.d("receiver", "Got message: " + message); } }; Relevant code in SyncService: public class SyncService extends IntentService { private static final String TAG = "SyncService"; public SyncService() { super("SyncService"); mBroadcaster = new BroadcastNotifier(this); } @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "Handle intent"); mBroadcaster.broadcastIntentWithState(AppConstants.STATE_ACTION_STARTED); mBroadcaster.broadcastIntentWithState(AppConstants.STATE_ACTION_COMPLETE); Log.d(TAG, "Finish intent"); } private BroadcastNotifier mBroadcaster; } Relavent code in BroadcastNotifier: private LocalBroadcastManager mBroadcaster; public BroadcastNotifier(Context context) { // Gets an instance of the support library local broadcastmanager Log.d(TAG, "Start to create broadcast instance with context: " + context); mBroadcaster = LocalBroadcastManager.getInstance(context); } public void broadcastIntentWithState(int status) { Intent localIntent = new Intent(AppConstants.BROADCAST_ACTION); // The Intent contains the custom broadcast action for this app //localIntent.setAction(); // Puts the status into the Intent localIntent.putExtra(AppConstants.EXTENDED_DATA_STATUS, status); localIntent.addCategory(Intent.CATEGORY_DEFAULT); // Broadcasts the Intent mBroadcaster.sendBroadcast(localIntent); } A: Remove addCategory() from broadcastIntentWithState(). That is not normally used with any sort of broadcasts (system or local), and your IntentFilter is not filtering on category.
[ "stackoverflow", "0035643858.txt" ]
Q: How to check that input string could not be reduced to start symbol in PLY? I'm using PLY to create a parser for a programming language. The problem is that the parser returns None even if it has not reduced the input string to the starting symbol. Short Example to demonstrate the problem Starting symbol: program Input: {+ def p_program(p): 'program : LBRACE PLUS RBRACE' pass Here, the parser should return some kind of error that EOF was reached and the string could not be reduced. Instead, it just sends None to p_error() which is standard for signalling EOF. How do I get to know that the stack could not be reduced and EOF was reached? Additional details from parser.out state 1 (0) S' -> program . state 2 (1) program -> LBRACE . PLUS RBRACE PLUS shift and go to state 3 state 3 (1) program -> LBRACE PLUS . RBRACE RBRACE shift and go to state 4 state 4 (1) program -> LBRACE PLUS RBRACE . $end reduce using rule 1 (program -> LBRACE PLUS RBRACE .) A: If p_error is called with None, then you know that the input could not be reduced to the start symbol because a premature EOF was found. p_error is only called if there is an error; with a correctly written grammar, it will not be called if the parse succeeded by reducing to the start symbol.
[ "stackoverflow", "0001843356.txt" ]
Q: Non transparent image in transparent block logo_area { background-color: #d9e670; filter:alpha(opacity=25); opacity:0.25; } and another div: #logo_image { background: url(../images/logo.png) no-repeat center 50%; } <div id="logo_area"> <div id="logo_image"></div> </div> Of course, logo_image is transparent too. Could I make it untrensparent in transparent block? A: I don't think so. I am not sure if it's possible to bring it to 100% transparent if the container isn't. However, what you can do is put it outside the block, such as: <div id="logo_image"></div> <div id="logo_area"> </div> Then on the logo image block, add: #logo_area { position: absolute; height: x; width: y; } So it should sit on top of the logo area div, but not be part of it. You may need to set the height of the logo area though, as the logo image will not cause it to stretch.
[ "stackoverflow", "0041120985.txt" ]
Q: Sinch Sms Verification 2.0.3 SDK Swift 3 Hi Im using Sinch sms verification to sign up users in my app but after updating my code to swift 3 (and sinch sdk currently 2.0.3), Im getting the following error Use of unresolved identifier 'SINPhoneNumberUtil' Use of unresolved identifier 'SINPhoneNumberFormat' Use of undeclared type 'SINPhoneNumber' That the code who was working with previous SDK and Swift 2 if (result.success){ let phoneUtil = SINPhoneNumberUtil() do { let defaultRegion = DeviceRegion.currentCountryCode() let phoneNum: SINPhoneNumber = try phoneUtil.parse(self.phoneNumber.text!, defaultRegion: defaultRegion) let formattedString: String = try phoneUtil.formatNumber(phoneNum, format: SINPhoneNumberFormat.E164)//format(phoneNumber, numberFormat: .E164) self.formattedNumToPass = formattedString print(formattedString) } catch let error as NSError { print(error.localizedDescription) } self.performSegue(withIdentifier: "enterPin", sender: sender); } I saw there were some changes in the SinchVerification reference docs : http://download.sinch.com/docs/verification/ios/latest/reference-swift/html/index.html but so far I didnt succeed to make the right changes.. Thanks for your help! A: As I read in the link you attached in your question SIN prefix was dropped so to fix the errors that you're facing just remove it from your code like this. if (result.success) { let phoneUtil = SharedPhoneNumberUtil() do { let defaultRegion = DeviceRegion.currentCountryCode() let phoneNum: PhoneNumber = try phoneUtil.parse(self.phoneNumber.text!, defaultRegion: defaultRegion) let formattedString: String = try phoneUtil.formatNumber(phoneNum, format: PhoneNumberFormat.e164) //format(phoneNumber, numberFormat: .E164) self.formattedNumToPass = formattedString print(formattedString) } catch let error as NSError { print(error.localizedDescription) } self.performSegue(withIdentifier: "enterPin", sender: sender); }
[ "stackoverflow", "0060737917.txt" ]
Q: How to apply build.gradle properties from custom standalone plugin to project that applies that plugin I have many projects that are using same dependencies and plugins and so on. I've prepared standalone Gradle plugin to avoid doing it in all projects, but I faced one problem. Let's say that all my projects are using com.gorylenko.gradle-git-properties My plugin is able to apply git-properties plugin to project that applies my plugin - that's good, but I want also add some properties for this plugin to target project, I mean something like this: gitProperties { dateFormat = 'yyyy-MM-dd HH:mm:ss' dateFormatTimeZone = 'Europe/Warsaw' keys = [ 'git.branch', 'git.commit.id.abbrev', 'git.commit.time', 'git.dirty', 'git.commit.message.short' ] } Question: How to add this properties to target build.gradle? It is possible that target project can reuse properties from plugin build.gradle or something? A: When your plugin configures the project in question and applies the com.gorylenko.gradle-git-properties, you will have to configure the extension contributed by the underlying plugin. Given that this plugin registers an extension of type GitPropertiesPluginExtension, you need to get access to it and then can configure it (code in Java): // After adding the plugin GitPropertiesPluginExtension gitExtension = project.getExtensions().getByType(GitPropertiesPluginExtension.class); gitExtension.keys = // Your list of keys
[ "wordpress.stackexchange", "0000237308.txt" ]
Q: Can a shortcode function this way Post body: [paragraph value="1"]text text text[/paragraph] [paragraph value="2"]moretext moretext moretext[/paragraph] Desired result: You are reading paragraph 1: text text text You are reading paragraph 2: moretext moretext moretext Can that be achieve using the above structure cause I couldn't figure out how to do it using the examples at: https://codex.wordpress.org/Shortcode_API Can you have enclosing shortcodes and values in them or are these 2 different shortcode types? A: Yes. That result can be achieved by single shortcode function. Here is your code- function paragraph_shortcode( $atts, $content = null ) { $pull_atts = shortcode_atts( array( 'value' => 0 ), $atts ); return 'You are reading paragraph ' . wp_kses_post( $pull_atts[ 'value' ] ) . ': ' . do_shortcode($content); } add_shortcode( 'paragraph', 'paragraph_shortcode' ); It'll work as you expected. Just input your data as you described- [paragraph value="1"]text text text[/paragraph] [paragraph value="2"]moretext moretext moretext[/paragraph] An d you'll get your desired output.
[ "stackoverflow", "0004934677.txt" ]
Q: Printing tens of pages in Silverlight freezes the computer we have a Silverlight 4 app that prints a multi-page report. When the number of pages exceeds 20 or 30 (depending on the computer), the printing completely blocks the computer and users are unable to use it. That is due to the huge print job size - each page takes about 170MB, so a 10 page document results in nearly 2gig! In a comment from the page http://wildermuth.com/2009/11/27/Silverlight_4_s_Printing_Support (see comment by Marshall Agnew from December 3, 2009) I found that "Silverlight Printing does currently allow users to specify Color/Grayscale, Orientation and Resolution(DPI)..." However, I am unable to find any info as to how this is done. We are printing a black and white document, text only, so grayscale (or even black&white, if that were possible) would be fine with us. Thanks for any help on how to decrease the size of the print job or find an alternative solution to printing multi-page reports in SL4. Jan A: The problem is that silverlight print raw image bytes by rendering images from XAML. Not optimized at all. Try generate XPS or PDF files from your client and allow the user to save it before print. XPS are relatively easy to generate because they use XAML. http://msdn.microsoft.com/en-us/library/ms771669.aspx
[ "mathoverflow", "0000265652.txt" ]
Q: $2^\omega$ vs $({\omega+1})^\omega$ It is easy to see that there is a surjective lattice homomorphism $s:({\omega+1})^\omega \to 2^\omega$ (construction see after the horizontal line below). Is there a surjective lattice homomorphism $s:2^\omega \to ({\omega+1})^\omega$? Assign to every $f\in ({\omega+1})^\omega$ the map $s(f)\in 2^\omega$ defined by setting for every $n\in\omega$: $\big(s(f)\big)(n) = 0$ if $f(n) = 0$ and $\big(s(f)\big)(n) = 1$ if $f(n)>0 $. A: No. The lattice $2^\omega$ is complemented, but the lattice $\omega+1$ is not complemented. Since a homomorphic image of a complemented lattice is complemented, there is no surjective lattice homomorphism from $2^\omega$ to $\omega+1.$ Equivalently, there is no surjective lattice homomorphism from $2^\omega$ to $(\omega+1)^\omega.$ Likewise, there is no surjective lattice homomorphism from $2^\omega$ to $3,$ although there is a surjective lattice homomorphism from $\omega+1$ to $3.$
[ "stackoverflow", "0025700017.txt" ]
Q: Data inserted in atomic transaction persists even after rollback I am trying to implement this atomic transaction in django and am following this example from the docs. But changes are found to persist despite rollback. I've searched for similar questions and most common cause seems to be catching integrity error inside atomic block, but I am not doing that. Following is my django code: def get_lead_alert_data(params): with transaction.atomic(): with acquire_lead_lock(): caller = params['caller'] via = params['via'] called = params['called'] leadphone = LeadsPhone.objects.filter(phone_number=caller, brokerage__isnull=True).first() if leadphone: lead_id = leadphone.lead_id else: lead_id = create_lead_from_inbound_call(caller, called) created, requirement = get_or_create_requirement_from_inbound_call(via, lead_id) picking_agent = Users.objects.get(phone_mobile=called) if created: RequirementAssignment.objects.create(requirement=requirement, agent=picking_agent) assigned_to = picking_agent.user_name else: assigned_requirement = RequirementAssignment.objects.filter(brokerage__active=True, requirement=requirement).first() #There will be only one such requirement if not assigned_requirement.agent: assigned_requirement.agent = picking_agent assigned_requirement.save() assigned_to = assigned_requirement.agent.user_name if assigned_requirement else 'nobody' return {'lead_id': lead_id, 'assigned_to': assigned_to, 'picking_by': picking_agent.user_name} I also checked resulting logs in mysql and it is indeed calling a rollback, yet the changes persist. 3043 Connect root@localhost on reserve_db_2 3043 Query SET NAMES utf8 3043 Query set autocommit=0 3043 Query set autocommit=1 3043 Query SET SQL_AUTO_IS_NULL = 0 3043 Query set autocommit=0 3043 Query lock table person write, leads write, leads_phones write, leads_emails write, requirements write, tele_phones read 3043 Query SELECT `leads_phones`.`id`, `leads_phones`.`lead_id`, `leads_phones`.`phone_number`, `leads_phones`.`brokerage_id`, `leads_phones`.`created` FROM `leads_phones` WHERE (`leads_phones`.`phone_number` = '9899696089' AND `leads_phones`.`brokerage_id` IS NULL) ORDER BY `leads_phones`.`id` ASC LIMIT 1 3043 Query INSERT INTO `person` (`user_id`, `fullname`, `mobile_no`, `fb_location`, `fb_email`, `fb_aboutme`, `fb_avatar`, `goog_email`, `goog_avatar`, `uploaded_avatar`, `first_name`, `last_name`, `description`, `address`, `is_admin`, `reviewer_badge`, `title`, `phone_home`, `phone_work`, `phone_other`, `phone_fax`, `status`, `address_street`, `address_city`, `address_region_id`, `address_country`, `address_postalcode`, `created`, `last_updated`, `created_by`, `modified_by`, `deleted`) VALUES (NULL, '', NULL, '', '', '', '', '', '', '', '', '', '', '', NULL, '1ST TIME REVIEWER', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2014-09-06 11:12:03', '2014-09-06 11:12:03', '', NULL, 0) 140906 16:40:05 3043 Query INSERT INTO `leads` (`id`, `date_entered`, `date_modified`, `modified_user_id`, `created_by`, `description`, `deleted`, `assigned_user_id`, `salutation`, `first_name`, `middle_name`, `last_name`, `title`, `department`, `do_not_call`, `primary_email_address`, `secondary_email_address`, `phone_home`, `phone_mobile`, `phone_work`, `phone_other`, `phone_fax`, `primary_address_street`, `primary_address_city`, `primary_address_state`, `primary_address_postalcode`, `primary_address_country`, `alt_address_street`, `alt_address_city`, `alt_address_state`, `alt_address_postalcode`, `alt_address_country`, `converted`, `refered_by`, `lead_source_description`, `status`, `status_description`, `reports_to_id`, `residence_phone`, `citizenship`, `primary_address_street_by_agent`, `office_location`, `owned_rented`, `owned_rented_by_agent`, `unique_id`, `reason_for_status_change`, `annual_income`, `annual_income_by_agent`, `designation`, `executive_level`, `executive_level_by_agent`, `present_company`, `website`, `lead_type_fav`, `lead_type_c`, `facebook_url`, `linkedin_url`, `twitter_url`, `google_plus_url`, `assigned_user_date`, `worked_by_tele`, `worked_by_sales`, `off_campaign_id`, `activity_done`, `activity_completed`, `queue_name`, `queue_description`, `history_notes`, `lead_category`, `trans_type`, `potential`, `referral_remark`, `referral_name`, `referral_no`, `referral_email`, `primary_secondary_lead`, `met_face_to_face`, `met_site_visit`, `met_final_negotiation`, `total_met`, `is_duplicate`, `is_duplicate_date`, `queue_abort_remark`, `referer_url`, `landing_url`, `leadpage_url`, `lead_projects`, `lead_projects_ids`, `lead_max_budget`, `lead_source`, `person_id`, `brokerage_id`, `lead_parent_id`) VALUES ('1440bb40-4f8a-4f87-917f-6aca0c758711', NULL, NULL, NULL, '', NULL, 0, '', NULL, NULL, NULL, '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', NULL, NULL, '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 315601, NULL, NULL) 3043 Query INSERT INTO `leads_phones` (`lead_id`, `phone_number`, `brokerage_id`, `created`) VALUES ('1440bb40-4f8a-4f87-917f-6aca0c758711', '9899696089', NULL, '2014-09-06 11:12:03') 3043 Query SELECT `tele_phones`.`id`, `tele_phones`.`source_id`, `tele_phones`.`project_id`, `tele_phones`.`locality_id`, `tele_phones`.`cluster_id`, `tele_phones`.`city_id` FROM `tele_phones` WHERE `tele_phones`.`id` = '3314892' LIMIT 21 3043 Query INSERT INTO `requirements` (`id`, `req_unique_id`, `lead_id`, `user_id`, `name`, `date_entered`, `date_modified`, `created_by`, `modified_user_id`, `assigned_user_id`, `deleted`, `req_type`, `category`, `bhk`, `unit_type`, `construction_phase`, `main_entrance_facing`, `balcony_facing`, `furnish_state`, `plc`, `locality`, `cluster`, `city`, `region`, `project`, `plot_area`, `super_area`, `price_sft_syd`, `price`, `total_price`, `cash_in_hand`, `need_loan`, `description`, `is_active_req`) VALUES ('63494d0d-88f8-44f5-816c-af4bb5ec439e', NULL, '1440bb40-4f8a-4f87-917f-6aca0c758711', NULL, '', NULL, NULL, '', '', '', NULL, '', '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, 1, 1, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, 1) 3043 Query unlock tables 3043 Query rollback 3043 Query set autocommit=1 A: Ohk, I checked out mysql docs. Looks like unlocking tables implicitly causes a commit if there are any locked tables, which there are in my case. Will have to find a workaround.
[ "stackoverflow", "0004830466.txt" ]
Q: Regular Expression to get full string if it doesn't contain a specific character? I need help with a regular expression that will find matches in the strings below: myDOG_test myCAT_test Basically, I want to return 'DOG' or 'CAT' from these paths. Then I have similar strings (all start with 'my') that don't contain the underscore AFTER the value I want, and in that case I just want to return the FULL string -- in a match group. myCentralReports myDEMO3 This is the REGEXP that I have so far: .*?my(.*?)\_.* This correctly puts CAT & DOG in the matching group, but I'm having problems matching the other 2 strings. Obviously I left the hardcoded underscore in there just to show you what I started with -- but I need to modify this for the other case. Any help is appreciated! Thanks. A: '/\smy(.+?)[_|\s]/' This will get anything between a whitespace character followed by "my", and the next trailing underscore or whitespace character. try it out.
[ "languagelearning.stackexchange", "0000001985.txt" ]
Q: Are there any online resources for practicing spoken Esperanto? There are already a number of resources online to help learners improve their Esperanto reading, writing and aural comprehension, such as Duolingo, but I want to increase my confidence in speaking Esperanto. Can anyone recommend any online resources that will allow me to converse in real-time with other Esperanto speakers and/or learners? A: Telegram is a messaging application that allows you to send voice recordings. There is an active community of Esperanto speakers in Telegram, and they can correct your pronunciation if you ask them too. It is also a great place to ask people for a real-time conversation. For this, you can use programs such as Skype, Google Hangouts, appear.in and Discord. Many programs exist and some of them do not require to download something or to create an account. A: There seems to be an Esperanto group in Second Life that meet regularly and use the program's voice chat for conversations. Esperantujo en Dua Vivo A: You can buy spoken lessons with several Esperanto tutors with italki: Find a Teacher.
[ "stackoverflow", "0048612957.txt" ]
Q: Dynamic Keyed Each? Can keyed each blocks have a dynamic key, using the value of a component property? For example: {{#each items as item @{componentPropertyExpression}}} <div>{{item.stuff}}</div> {{/each}} A: Not currently — there's a discussion around it though: https://github.com/sveltejs/svelte/issues/703
[ "stackoverflow", "0030956188.txt" ]
Q: In Javascript how do I automatically set properties to null if they don't exist? I have a Javascript class (using John Resig's approach) that I create an instance of and pass an args object, like so: var myCucumber = new Cucumber({ size: 'small' organic: true }) Within the class itself, it references many properties on the args object. However none of the properties are meant to be mandatory, so there may be some missing ones at times, which causes "property is undefined" errors. To remedy this, I do the following: args.size = args.size || null; args.organic = args.organic || false; args.colour = args.colour || null; args.origin = args.origin || null; It seems kind of annoying to have to do this for each property that may get used throughout the class. Is there a clean way to assume that any property of args will be null if it hasn't been passed in when an instance of the class was created? A: I suggest addding a function to handle values in the expected way. Example: Cucumber.prototype._args = function(attr) { return this.args[attr] || null; } // Then you may use it to access values as follows: this._args('size');
[ "stackoverflow", "0013368663.txt" ]
Q: Destructors and shutdown functions when exiting by Ctrl+C in PHP-CLI If I use Ctrl+C to exit a PHP script running in CLI, neither the shutdown functions, nor the destructors of instantiated objects, nor any output buffers are handled. Instead the program just dies. Now, this is probably a good thing, since that's what Ctrl+C is supposed to do. But is there any way to change that? Is it possible to force Ctrl+C to go through the shutdown functions? More specifically, this is about serialising and saving data on exiting of the script, so it can be reloaded and resumed the next time the script runs. Periodically saving the data could work, but would still lose everything from the last save onward. What other options are there? A: Obviously PCNTL is *nix only, but ... You can register handlers for all the individual signals for a more robust solution, but specifically to do something when a CTL+C interrupt is encountered: <?php declare(ticks = 1); pcntl_signal(SIGINT, function() { echo "Caught SIGINT\n"; die; }); while (true) { // waiting for your CTRL+C }
[ "stackoverflow", "0044591518.txt" ]
Q: Filtering out faint sobel filter lines? I'm using skimage to creator a sobel filter image similar to this... I was wondering is there a way to sharpen this sobel filter image? To say, remove the white lines that are more faint like for example the faint lines behind the air balloons? I used Skimage to do this, but I can get access to other things like OpenCV. My code specifically is... from skimage.filters import sobel elevation_map = sobel(img) plt.imshow(elevation_map, cmap=plt.get_cmap('gray')) A: Maybe a bit late but the simplest way to remove faint pixels is to apply a threshold to the image. It can be done like this (with a threshold of 50 for instance) elevation_map[elevation_map < 50] = 0 You can adjust the threshold to get more of less dark gray pixels set to 0.
[ "meta.stackoverflow", "0000393883.txt" ]
Q: Recruiters can see my real name It seems that recruiters can see my real name on the jobs section. This is pretty weird and unexpected. How do you remove it? Where is it warned about? A: When you go to your Jobs profile there are two fields Display Name Profile Name These are described as such: Display Name: How you appear to other users on the Stack Overflow Q&A Network. Profile Name: How you appear to employers, your private Teams, and to other users when you share your Developer Story. To change these: Go to Jobs Click Developer Profile Click Edit next to your profile picture (it only appears on mouse over) Modify one or both the fields listed above A recruiter sees the following. After this header, they see the "Traditional View" of your Developer Story (at least I do, I can't remember if I changed that from the Story view at one point or not). The blacked out fields, in order from top to bottom: Full Name (from the settings above) Current job title (supplied in your developer story) Location (supplied in your developer profile) URL to personal site (supplied in your profile)
[ "stackoverflow", "0021534422.txt" ]
Q: Binding Drop Down List from Code behind using C# I am trying to bind drop-down box from code behind, but I am getting a compilation error: 'System.Web.UI.WebControls.SqlDataSource' does not contain a definition for 'DataSource' I have tried to figure out but cannot seem to fix this issue. <asp:DropDownList ID="MYDDL" Width="300px" DataTextField="PRJ_TITLE" AutoPostBack="true" DataValueField="PRJ_ID" runat="server"> </asp:DropDownList> Here is my function: private void Bind_DD() { String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myCon"].ConnectionString; SqlConnection con2 = new SqlConnection(strConnString); SqlDataAdapter sda = new SqlDataAdapter(); SqlCommand cmd1 = new SqlCommand("SELECT ID, PRJ_TITLE FROM myTable"); cmd1.Connection = con2; con2.Open(); myDDL.DataSource = cmd1.ExecuteReader(); myDDL.DataTextField = "PRJ_TITLE"; myDDL.DataValueField = "ID"; myDDL.DataBind(); con2.Close(); } A: So it looks like you are possibily a bit mixed up about sql data connections as there are many ways to do them. I elected to do a databing via the sqlDataAdapter to DataTable. Additionally make sure you do not have any elements in your markup that have a asp:SqlDataSource anywhere in your markup. private void Bind_DD() { DataTable dt = new DataTable(); using(SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString)) { con2.Open(); SqlCommand cmd1 = new SqlCommand("SELECT ID, PRJ_TITLE FROM myTable",con2); SqlDataAdapter sda = new SqlDataAdapter(cmd1); sda.Fill(dt); } myDDL.DataSource = dt; myDDL.DataTextField = "PRJ_TITLE"; myDDL.DataValueField = "ID"; myDDL.DataBind(); }
[ "softwareengineering.stackexchange", "0000294071.txt" ]
Q: How to abstract from a display? I'm building an embedded text editor consisting of a keyboard, an LCD display and a PIC32 microcontroller, to be programmed in C. The application should look, for example, like the GNU nano editor. The display is 40x16 characters big. I'm currently wondering what would be a good abstraction from the display. We could conceptualise a simple terminal as follows: typedef struct { char* content; // Current and past content void (*update)(Terminal); // Update function } Terminal; void append(Terminal, char*); // Append to content & execute update function void discard(Terminal, int); // Discard last n characters & execute update f. By adding a function pointer to the Terminal type, we basically have a model and a view. The Terminal can be controlled by the append() and discard() functions. With this Terminal we could make a simple terminal with stdin and stdout. However, that's not enough for a nano-like editor, where text can be inserted and removed anywhere on the screen, not just at the end of the current data. I have now made up the following type: typedef struct { unsigned short rows, columns, // Screen size first_visible_row, first_visible_column, // Left-top coordinates cursor_x, cursor_y; // Cursor coordinates char* content; // Current and off-screen content void (*update)(Screen); // Update function } Screen; This Screen holds off-screen content as well, and its visible section is determined by its left-top coordinates. This makes scrolling easier. But, functions to write to this screen at some position would be complicated, because there is no direct relationship between a position in content and its coordinates on the actual display. An easier to work with type would hold an array of rows char arrays, for different lines on the screen. Then, content would be an array of char arrays, i.e. char** content. Basically, I'm asking if there are problems with my suggested approach and if there is an easier approach. To sum up, here are some of the requirements for the screen: Should be easy to scroll in It should be possible to add and remove text at any point on the screen A: You might benefit from a double buffer concept where you store lines longer than the display into a larger structure and a zoomed in 40 * 16 array that can move up or down with display events. Provide offset pointers to each start of row and end is determined so arrows move around larger area. Limit shifting to min max. Then cut and paste is line by line segment copy. Multi line area copies would be the hardest to track, you could limit to window to start. Buffer area into and out of file is a single write at the end of operations. Display is a custom per string operation.
[ "stackoverflow", "0015350477.txt" ]
Q: Memory leak when using strings < 128KB in Python? Original title: Memory leak opening files < 128KB in Python? Original question I see what I think is a memory leak when running my Python script. Here is my script: import sys import time class MyObj(object): def __init__(self, filename): with open(filename) as f: self.att = f.read() def myfunc(filename): mylist = [MyObj(filename) for x in xrange(100)] len(mylist) return [] def main(): filename = sys.argv[1] myfunc(filename) time.sleep(3600) if __name__ == '__main__': main() The main function calls myfunc() which creates a list of 100 objects that each open and read a file. After returning from myfunc(), I'd expect memory from the 100-item list and from reading the file to be freed since they are no longer referenced. However, when I check the memory usage using the ps command, the Python process uses about 10,000 KB more memory than a Python process run from a script with lines 12 and 13 commented out. The strange thing is that the memory leak (if that's what it is) only seems to occur for files <128KB in size. I created a bash script to run this script with files ranging in size from 1KB to 200KB and the memory increase stopped when the files size hit 128KB. Here is the bash script: #!/bin/bash echo "PID RSS S TTY TIME COMMAND" > output.txt for i in `seq 1 200`; do python debug_memory.py "data/stuff_${i}K.txt" & pid=$! sleep 0.1 ps -e -O rss | grep $pid | grep -v grep >> output.txt kill $pid done Here is the output of the bash script: PID RSS S TTY TIME COMMAND 28471 5552 S pts/16 00:00:00 python debug_memory.py data/stuff_1K.txt 28477 5656 S pts/16 00:00:00 python debug_memory.py data/stuff_2K.txt 28483 5756 S pts/16 00:00:00 python debug_memory.py data/stuff_3K.txt 28488 5852 S pts/16 00:00:00 python debug_memory.py data/stuff_4K.txt 28494 5952 S pts/16 00:00:00 python debug_memory.py data/stuff_5K.txt 28499 6052 S pts/16 00:00:00 python debug_memory.py data/stuff_6K.txt 28505 6156 S pts/16 00:00:00 python debug_memory.py data/stuff_7K.txt 28511 6256 S pts/16 00:00:00 python debug_memory.py data/stuff_8K.txt 28516 6356 S pts/16 00:00:00 python debug_memory.py data/stuff_9K.txt 28522 6452 S pts/16 00:00:00 python debug_memory.py data/stuff_10K.txt 28527 6552 S pts/16 00:00:00 python debug_memory.py data/stuff_11K.txt 28533 6656 S pts/16 00:00:00 python debug_memory.py data/stuff_12K.txt 28539 6756 S pts/16 00:00:00 python debug_memory.py data/stuff_13K.txt 28544 6852 S pts/16 00:00:00 python debug_memory.py data/stuff_14K.txt 28550 6952 S pts/16 00:00:00 python debug_memory.py data/stuff_15K.txt 28555 7056 S pts/16 00:00:00 python debug_memory.py data/stuff_16K.txt 28561 7156 S pts/16 00:00:00 python debug_memory.py data/stuff_17K.txt 28567 7252 S pts/16 00:00:00 python debug_memory.py data/stuff_18K.txt 28572 7356 S pts/16 00:00:00 python debug_memory.py data/stuff_19K.txt 28578 7452 S pts/16 00:00:00 python debug_memory.py data/stuff_20K.txt 28584 7556 S pts/16 00:00:00 python debug_memory.py data/stuff_21K.txt 28589 7652 S pts/16 00:00:00 python debug_memory.py data/stuff_22K.txt 28595 7756 S pts/16 00:00:00 python debug_memory.py data/stuff_23K.txt 28600 7852 S pts/16 00:00:00 python debug_memory.py data/stuff_24K.txt 28606 7952 S pts/16 00:00:00 python debug_memory.py data/stuff_25K.txt 28612 8052 S pts/16 00:00:00 python debug_memory.py data/stuff_26K.txt 28617 8152 S pts/16 00:00:00 python debug_memory.py data/stuff_27K.txt 28623 8252 S pts/16 00:00:00 python debug_memory.py data/stuff_28K.txt 28629 8356 S pts/16 00:00:00 python debug_memory.py data/stuff_29K.txt 28634 8452 S pts/16 00:00:00 python debug_memory.py data/stuff_30K.txt 28640 8556 S pts/16 00:00:00 python debug_memory.py data/stuff_31K.txt 28645 8656 S pts/16 00:00:00 python debug_memory.py data/stuff_32K.txt 28651 8756 S pts/16 00:00:00 python debug_memory.py data/stuff_33K.txt 28657 8856 S pts/16 00:00:00 python debug_memory.py data/stuff_34K.txt 28662 8956 S pts/16 00:00:00 python debug_memory.py data/stuff_35K.txt 28668 9056 S pts/16 00:00:00 python debug_memory.py data/stuff_36K.txt 28674 9156 S pts/16 00:00:00 python debug_memory.py data/stuff_37K.txt 28679 9256 S pts/16 00:00:00 python debug_memory.py data/stuff_38K.txt 28685 9352 S pts/16 00:00:00 python debug_memory.py data/stuff_39K.txt 28691 9452 S pts/16 00:00:00 python debug_memory.py data/stuff_40K.txt 28696 9552 S pts/16 00:00:00 python debug_memory.py data/stuff_41K.txt 28702 9656 S pts/16 00:00:00 python debug_memory.py data/stuff_42K.txt 28707 9756 S pts/16 00:00:00 python debug_memory.py data/stuff_43K.txt 28713 9852 S pts/16 00:00:00 python debug_memory.py data/stuff_44K.txt 28719 9952 S pts/16 00:00:00 python debug_memory.py data/stuff_45K.txt 28724 10052 S pts/16 00:00:00 python debug_memory.py data/stuff_46K.txt 28730 10156 S pts/16 00:00:00 python debug_memory.py data/stuff_47K.txt 28739 10256 S pts/16 00:00:00 python debug_memory.py data/stuff_48K.txt 28746 10352 S pts/16 00:00:00 python debug_memory.py data/stuff_49K.txt 28752 10452 S pts/16 00:00:00 python debug_memory.py data/stuff_50K.txt 28757 10556 S pts/16 00:00:00 python debug_memory.py data/stuff_51K.txt 28763 10656 S pts/16 00:00:00 python debug_memory.py data/stuff_52K.txt 28769 10752 S pts/16 00:00:00 python debug_memory.py data/stuff_53K.txt 28774 10852 S pts/16 00:00:00 python debug_memory.py data/stuff_54K.txt 28780 10952 S pts/16 00:00:00 python debug_memory.py data/stuff_55K.txt 28786 11052 S pts/16 00:00:00 python debug_memory.py data/stuff_56K.txt 28791 11152 S pts/16 00:00:00 python debug_memory.py data/stuff_57K.txt 28797 11256 S pts/16 00:00:00 python debug_memory.py data/stuff_58K.txt 28802 11356 S pts/16 00:00:00 python debug_memory.py data/stuff_59K.txt 28808 11452 S pts/16 00:00:00 python debug_memory.py data/stuff_60K.txt 28814 11556 S pts/16 00:00:00 python debug_memory.py data/stuff_61K.txt 28819 11656 S pts/16 00:00:00 python debug_memory.py data/stuff_62K.txt 28825 11752 S pts/16 00:00:00 python debug_memory.py data/stuff_63K.txt 28831 11852 S pts/16 00:00:00 python debug_memory.py data/stuff_64K.txt 28836 11956 S pts/16 00:00:00 python debug_memory.py data/stuff_65K.txt 28842 12052 S pts/16 00:00:00 python debug_memory.py data/stuff_66K.txt 28847 12152 S pts/16 00:00:00 python debug_memory.py data/stuff_67K.txt 28853 12256 S pts/16 00:00:00 python debug_memory.py data/stuff_68K.txt 28859 12356 S pts/16 00:00:00 python debug_memory.py data/stuff_69K.txt 28864 12452 S pts/16 00:00:00 python debug_memory.py data/stuff_70K.txt 28871 12556 S pts/16 00:00:00 python debug_memory.py data/stuff_71K.txt 28877 12652 S pts/16 00:00:00 python debug_memory.py data/stuff_72K.txt 28883 12756 S pts/16 00:00:00 python debug_memory.py data/stuff_73K.txt 28889 12856 S pts/16 00:00:00 python debug_memory.py data/stuff_74K.txt 28894 12952 S pts/16 00:00:00 python debug_memory.py data/stuff_75K.txt 28900 13056 S pts/16 00:00:00 python debug_memory.py data/stuff_76K.txt 28906 13156 S pts/16 00:00:00 python debug_memory.py data/stuff_77K.txt 28911 13256 S pts/16 00:00:00 python debug_memory.py data/stuff_78K.txt 28917 13352 S pts/16 00:00:00 python debug_memory.py data/stuff_79K.txt 28922 13452 S pts/16 00:00:00 python debug_memory.py data/stuff_80K.txt 28928 13556 S pts/16 00:00:00 python debug_memory.py data/stuff_81K.txt 28934 13652 S pts/16 00:00:00 python debug_memory.py data/stuff_82K.txt 28939 13752 S pts/16 00:00:00 python debug_memory.py data/stuff_83K.txt 28945 13852 S pts/16 00:00:00 python debug_memory.py data/stuff_84K.txt 28951 13952 S pts/16 00:00:00 python debug_memory.py data/stuff_85K.txt 28956 14052 S pts/16 00:00:00 python debug_memory.py data/stuff_86K.txt 28962 14152 S pts/16 00:00:00 python debug_memory.py data/stuff_87K.txt 28967 14256 S pts/16 00:00:00 python debug_memory.py data/stuff_88K.txt 28973 14352 S pts/16 00:00:00 python debug_memory.py data/stuff_89K.txt 28979 14456 S pts/16 00:00:00 python debug_memory.py data/stuff_90K.txt 28984 14552 S pts/16 00:00:00 python debug_memory.py data/stuff_91K.txt 28990 14652 S pts/16 00:00:00 python debug_memory.py data/stuff_92K.txt 28996 14756 S pts/16 00:00:00 python debug_memory.py data/stuff_93K.txt 29001 14852 S pts/16 00:00:00 python debug_memory.py data/stuff_94K.txt 29007 14956 S pts/16 00:00:00 python debug_memory.py data/stuff_95K.txt 29012 15052 S pts/16 00:00:00 python debug_memory.py data/stuff_96K.txt 29018 15156 S pts/16 00:00:00 python debug_memory.py data/stuff_97K.txt 29024 15252 S pts/16 00:00:00 python debug_memory.py data/stuff_98K.txt 29029 15360 S pts/16 00:00:00 python debug_memory.py data/stuff_99K.txt 29035 15456 S pts/16 00:00:00 python debug_memory.py data/stuff_100K.txt 29040 15556 S pts/16 00:00:00 python debug_memory.py data/stuff_101K.txt 29046 15652 S pts/16 00:00:00 python debug_memory.py data/stuff_102K.txt 29052 15756 S pts/16 00:00:00 python debug_memory.py data/stuff_103K.txt 29057 15852 S pts/16 00:00:00 python debug_memory.py data/stuff_104K.txt 29063 15952 S pts/16 00:00:00 python debug_memory.py data/stuff_105K.txt 29069 16056 S pts/16 00:00:00 python debug_memory.py data/stuff_106K.txt 29074 16152 S pts/16 00:00:00 python debug_memory.py data/stuff_107K.txt 29080 16256 S pts/16 00:00:00 python debug_memory.py data/stuff_108K.txt 29085 16356 S pts/16 00:00:00 python debug_memory.py data/stuff_109K.txt 29091 16452 S pts/16 00:00:00 python debug_memory.py data/stuff_110K.txt 29097 16552 S pts/16 00:00:00 python debug_memory.py data/stuff_111K.txt 29102 16652 S pts/16 00:00:00 python debug_memory.py data/stuff_112K.txt 29108 16756 S pts/16 00:00:00 python debug_memory.py data/stuff_113K.txt 29113 16852 S pts/16 00:00:00 python debug_memory.py data/stuff_114K.txt 29119 16952 S pts/16 00:00:00 python debug_memory.py data/stuff_115K.txt 29125 17056 S pts/16 00:00:00 python debug_memory.py data/stuff_116K.txt 29130 17156 S pts/16 00:00:00 python debug_memory.py data/stuff_117K.txt 29136 17256 S pts/16 00:00:00 python debug_memory.py data/stuff_118K.txt 29141 17356 S pts/16 00:00:00 python debug_memory.py data/stuff_119K.txt 29147 17452 S pts/16 00:00:00 python debug_memory.py data/stuff_120K.txt 29153 17556 S pts/16 00:00:00 python debug_memory.py data/stuff_121K.txt 29158 17656 S pts/16 00:00:00 python debug_memory.py data/stuff_122K.txt 29164 17756 S pts/16 00:00:00 python debug_memory.py data/stuff_123K.txt 29170 17856 S pts/16 00:00:00 python debug_memory.py data/stuff_124K.txt 29175 17952 S pts/16 00:00:00 python debug_memory.py data/stuff_125K.txt 29181 18056 S pts/16 00:00:00 python debug_memory.py data/stuff_126K.txt 29186 18152 S pts/16 00:00:00 python debug_memory.py data/stuff_127K.txt 29192 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_128K.txt 29198 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_129K.txt 29203 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_130K.txt 29209 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_131K.txt 29215 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_132K.txt 29220 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_133K.txt 29226 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_134K.txt 29231 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_135K.txt 29237 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_136K.txt 29243 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_137K.txt 29248 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_138K.txt 29254 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_139K.txt 29260 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_140K.txt 29265 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_141K.txt 29271 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_142K.txt 29276 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_143K.txt 29282 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_144K.txt 29288 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_145K.txt 29293 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_146K.txt 29299 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_147K.txt 29305 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_148K.txt 29310 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_149K.txt 29316 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_150K.txt 29321 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_151K.txt 29327 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_152K.txt 29333 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_153K.txt 29338 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_154K.txt 29344 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_155K.txt 29349 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_156K.txt 29355 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_157K.txt 29361 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_158K.txt 29366 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_159K.txt 29372 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_160K.txt 29378 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_161K.txt 29383 5460 S pts/16 00:00:00 python debug_memory.py data/stuff_162K.txt 29389 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_163K.txt 29394 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_164K.txt 29400 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_165K.txt 29406 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_166K.txt 29411 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_167K.txt 29417 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_168K.txt 29423 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_169K.txt 29428 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_170K.txt 29434 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_171K.txt 29439 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_172K.txt 29445 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_173K.txt 29451 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_174K.txt 29456 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_175K.txt 29463 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_176K.txt 29483 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_177K.txt 29489 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_178K.txt 29496 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_179K.txt 29501 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_180K.txt 29507 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_181K.txt 29512 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_182K.txt 29518 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_183K.txt 29524 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_184K.txt 29529 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_185K.txt 29535 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_186K.txt 29541 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_187K.txt 29546 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_188K.txt 29552 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_189K.txt 29557 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_190K.txt 29563 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_191K.txt 29569 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_192K.txt 29574 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_193K.txt 29580 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_194K.txt 29586 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_195K.txt 29591 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_196K.txt 29597 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_197K.txt 29602 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_198K.txt 29608 5456 S pts/16 00:00:00 python debug_memory.py data/stuff_199K.txt 29614 5452 S pts/16 00:00:00 python debug_memory.py data/stuff_200K.txt Can someone explain what is happening? Why do I see an increase in memory usage when using files <128KB? My full test environment is located here: https://github.com/saltycrane/debugging-python-memory-usage/tree/50f73358c7a84a504333ce9c4071b0f3537bbc0f I am running Python 2.7.3 on Ubuntu 12.04. UPDATE 1 This issue is not specific to working with files <128K in size. I get the same results setting the object attribute to a value the same size as was read from the file. Here is the updated code: import sys import time class MyObj(object): def __init__(self, size_kb): self.att = ' ' * int(size_kb) * 1024 def myfunc(size_kb): mylist = [MyObj(size_kb) for x in xrange(100)] len(mylist) return [] def main(): size_kb = sys.argv[1] myfunc(size_kb) time.sleep(3600) if __name__ == '__main__': main() Running this script gives similar results. The updated test environment is located here: https://github.com/saltycrane/debugging-python-memory-usage/tree/59b7ff61134dfc11c4195e9201b2c1728ed4fcce UPDATE 2 I simplified my test script further by: 1. removing the class and simply creating a list of strings 2. removing myfunc() and using del to delete the mylist object import sys import time def main(): size_kb = sys.argv[1] mylist = [] for x in xrange(100): mystr = ' ' * int(size_kb) * 1024 mylist.append(mystr) del mylist time.sleep(3600) if __name__ == '__main__': main() My simplified script also gives similar results to the original. However, if I don't create a separate string variable, I don't see an increase in memory. Here is the script that does not create an increase in memory: import sys import time def main(): size_kb = sys.argv[1] mylist = [] for x in xrange(100): mylist.append(' ' * int(size_kb) * 1024) del mylist time.sleep(3600) if __name__ == '__main__': main() The updated test environment is located here: https://github.com/saltycrane/debugging-python-memory-usage/tree/423ca6a50dccbe32572a9d0dea1068ddcb06663b More questions: Can someone else reproduce my results? Is the increase in memory seen by ps expected? Hints about what is happening I discovered some interesting information about "free lists" that seem like they could be related to this issue: Why doesn't Python release the memory when I delete a large object? How can I explicitly free memory in Python? Python Memory Management — Theano v0.6rc3 documentation From the last link: To speed-up memory allocation (and reuse) Python uses a number of lists for small objects. Each list will contain objects of similar size Indeed: if an item (of size x) is deallocated (freed by lack of reference) its location is not returned to Python’s global memory pool (and even less to the system), but merely marked as free and added to the free list of items of size x. If small objects memory is never freed, then the inescapable conclusion is that, like goldfishes, these small object lists only keep growing, never shrinking, and that the memory footprint of your application is dominated by the largest number of small objects allocated at any given point. UPDATE 3 I oversimplified the code in Update 2. Adding the line del mystr at the end of the script freed the memory. (See: https://github.com/saltycrane/debugging-python-memory-usage/blob/dd058e4774802cae7cbfca520fb835ea46b645e8/debug_memory_leaks.py) I updated the script to be sufficiently complicated to demonstrate the issue. The issue still exists in the following code. The latest code/environment is located here: https://github.com/saltycrane/debugging-python-memory-usage/tree/fc0c8ce9ba621cb86b6abb93adf1b297a7c0230b import gc import sys import time def main(): size_kb = sys.argv[1] mylist = [] for x in xrange(100): mystr = ' ' * int(size_kb) * 1024 mydict = {'mykey': mystr} mylist.append(mydict) del mystr del mydict del mylist gc.collect() time.sleep(3600) if __name__ == '__main__': main() I also ran the script is some other environments. The strange result was running from within a clean virtualenv. In this case, the memory dropoff occurred at 260KB instead of 128KB. See https://github.com/saltycrane/debugging-python-memory-usage/tree/52fbd5d57ff45affdcd70623ddb74fa1f1ffbbc2 Environments: Ubuntu 12.04 64-bit, system Python 2.7.3: original run Ubuntu 12.04 64-bit, Python 3.3.0 compiled from source: similar results Scientific Linux 6 64-bit, Python 2.6.6: similar results Ubuntu 12.04 64-bit, Python 2.7.3 from a virtualenv: memory dropoff occurs at 260KB instead of 128KB More references: http://revista.python.org.ar/2/en/html/memory-fragmentation.html http://www.evanjones.ca/python-memory.html http://mail.python.org/pipermail/python-dev/2004-October/049480.html (Note: this is from 2004) http://mail.python.org/pipermail/python-dev/2006-March/061991.html http://www.evanjones.ca/memoryallocator/ http://www.evanjones.ca/memory-allocator.pdf http://hg.python.org/releasing/2.7.3/file/7bb96963d067/Objects/obmalloc.c After reading some of these, I see a reference to an "arena size" of 256KB. Maybe that is related? UPDATE 4 (MOSTLY SOLVED) schlenk uncovered the reason the memory usage drops off at 128KB. 128KB is the point at which "memory allocation functions" (malloc?) use mmap instead of increasing the program break using sbrk. Interestingly, the threshold can be changed via an environment variable. I ran a test setting the MALLOC_MMAP_THRESHOLD_ environment variable to different values and the dropoff in memory usage matched that value. See here for results: https://github.com/saltycrane/debugging-python-memory-usage/blob/97d93cd165a139a6b6f96720de63a92561dd2f05/output_debug_memory_leaks.py.txt I would still like to know if it expected behavior for my script to leak memory for string values < 128KB. A few more links: mallopt(3) - Linux manual page (from schlenk) Python memory management and TCMalloc | Pushing the Web Re: Set x to to None and del x doesn't release memory in python 2.7.1 (HPUX 11.23, ia64) « python-list « ActiveState List Archives Issue 3526: Customized malloc implementation on SunOS and AIX - Python tracker Make the mmap/brk threshold in malloc dynamic to improve performance Note: According to the last two links, there is a performance (speed) hit for using mmap instead of sbrk. A: You might simply hit the default behaviour of the linux memory allocator. Basically Linux has two allocation strategies, sbrk() for small blocks of memory and mmap() for larger blocks. sbrk() allocated memory blocks cannot easily be returned to the system, while mmap() based ones can (just unmap the page). So if you allocate a memory block larger than the value where the malloc() allocator in your libc decides to switch between sbrk() and mmap() you see this effect. See the mallopt() call, especially the MMAP_THRESHOLD (http://man7.org/linux/man-pages/man3/mallopt.3.html). Update To answer your extra question: yes, it is expected that you leak memory that way, if the memory allocator works like the libc one on Linux. If you used Windows LowFragmentationHeap instead, it would probably not leak, similar on AIX, depending on which malloc is configured. Maybe one of the other allocators (tcmalloc etc.) also fix such issues. sbrk() is blazingly fast, but has issues with memory fragmentation. CPython cannot do much about it, as it does not have a compacting garbage collector, but simple reference counting. Python offers a few methods to reduce the buffer allocations, see for example the blog post here: http://eli.thegreenplace.net/2011/11/28/less-copies-in-python-with-the-buffer-protocol-and-memoryviews/ A: I would look into garbage collection. It may be that larger files are triggering garbage collection more frequently, but the small files are being freed but collectively staying at some threshold. Specifically, call gc.collect() and then call gc.get_referrers() on the object to hopefully reveal what is keeping an instance is around. See the Python doc here: http://docs.python.org/2/library/gc.html?highlight=gc#gc.get_referrers Update: The issue relates to garbage collection, namespace, and reference counting. The bash script you posted is giving a fairly narrow view of the garbage collector's behaviour. Try a larger range and you will see patterns in how much memory certain ranges will take. For example, change the bash for loop for a larger range, something like: seq 0 16 2056. You noticed the memory usage was reduced if you del mystr because you are removing any references left to it. Similar results would likely happen if you limited the mystr variable to it's own function like so: def loopy(): mylist = [] for x in xrange(100): mystr = ' ' * int(size_kb) * 1024 mydict = {x: mystr} mylist.append(mydict) return mylist Rather than using bash scripts, I think you could get more useful information using a memory profiler. Here are a couple examples using Pympler. This first version is similar to your code from Update 3: import gc import sys import time from pympler import tracker tr = tracker.SummaryTracker() print 'begin:' tr.print_diff() size_kb = sys.argv[1] mylist = [] mydict = {} print 'empty list & dict:' tr.print_diff() for x in xrange(100): mystr = ' ' * int(size_kb) * 1024 mydict = {x: mystr} mylist.append(mydict) print 'after for loop:' tr.print_diff() del mystr del mydict del mylist print 'after deleting stuff:' tr.print_diff() collected = gc.collect() print 'after garbage collection (collected: %d):' % collected tr.print_diff() time.sleep(2) print 'took a short nap after all that work:' tr.print_diff() mylist = [] print 'create an empty list for some reason:' tr.print_diff() And the output: $ python mem_test.py 256 begin: types | # objects | total size ======================= | =========== | ============= list | 957 | 97.44 KB str | 951 | 53.65 KB int | 118 | 2.77 KB wrapper_descriptor | 8 | 640 B weakref | 3 | 264 B member_descriptor | 2 | 144 B getset_descriptor | 2 | 144 B function (store_info) | 1 | 120 B cell | 2 | 112 B instancemethod | -1 | -80 B _sre.SRE_Pattern | -2 | -176 B tuple | -1 | -216 B dict | 2 | -1744 B empty list & dict: types | # objects | total size ======= | =========== | ============ list | 2 | 168 B str | 2 | 97 B int | 1 | 24 B after for loop: types | # objects | total size ======= | =========== | ============ str | 1 | 256.04 KB list | 0 | 848 B after deleting stuff: types | # objects | total size ======= | =========== | =============== list | -1 | -920 B str | -1 | -262181 B after garbage collection (collected: 0): types | # objects | total size ======= | =========== | ============ took a short nap after all that work: types | # objects | total size ======= | =========== | ============ create an empty list for some reason: types | # objects | total size ======= | =========== | ============ list | 1 | 72 B Notice after the for loop the total size for the str class is 256 KB, essentially the same as the argument I passed to it. After explicitly removing the reference to mystr in del mystr the memory is freed. After this, the garbage has already been picked up so there's no further reduction after gc.collect(). The next version uses a function to create a different namespace for the string. import gc import sys import time from pympler import tracker def loopy(): mylist = [] for x in xrange(100): mystr = ' ' * int(size_kb) * 1024 mydict = {x: mystr} mylist.append(mydict) return mylist tr = tracker.SummaryTracker() print 'begin:' tr.print_diff() size_kb = sys.argv[1] mylist = loopy() print 'after for loop:' tr.print_diff() del mylist print 'after deleting stuff:' tr.print_diff() collected = gc.collect() print 'after garbage collection (collected: %d):' % collected tr.print_diff() time.sleep(2) print 'took a short nap after all that work:' tr.print_diff() mylist = [] print 'create an empty list for some reason:' tr.print_diff() And finally the output from this version: $ python mem_test_2.py 256 begin: types | # objects | total size ======================= | =========== | ============= list | 958 | 97.53 KB str | 952 | 53.70 KB int | 118 | 2.77 KB wrapper_descriptor | 8 | 640 B weakref | 3 | 264 B member_descriptor | 2 | 144 B getset_descriptor | 2 | 144 B function (store_info) | 1 | 120 B cell | 2 | 112 B instancemethod | -1 | -80 B _sre.SRE_Pattern | -2 | -176 B tuple | -1 | -216 B dict | 2 | -1744 B after for loop: types | # objects | total size ======= | =========== | ============ list | 2 | 1016 B str | 2 | 97 B int | 1 | 24 B after deleting stuff: types | # objects | total size ======= | =========== | ============ list | -1 | -920 B after garbage collection (collected: 0): types | # objects | total size ======= | =========== | ============ took a short nap after all that work: types | # objects | total size ======= | =========== | ============ create an empty list for some reason: types | # objects | total size ======= | =========== | ============ list | 1 | 72 B Now, we don't have to clean up the str, and I think this example shows why using functions are a good idea. Generating code where there's one big chunk in one namespace is really preventing the garbage collector from doing it's job. It will not come into your house and start assuming things are trash :) It has to know that things are safe to collect. That Evan Jones link is very interesting btw.
[ "stackoverflow", "0035721320.txt" ]
Q: How split date in this line? I have some problem with parse some information from String line. In this example, I would like to work with the line 2011-08-28 19:02:30. I have a lot of lines for this template. How to parse this date? Thanks [47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://example.com Thanks all. Here is my solution. private Date parseDate(String line) { line = line.replaceAll("\\s+", " ").trim(); String[] masWords = line.split(" "); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(masWords[3] + " " + masWords[4]); } catch (ParseException e) { e.printStackTrace(); } return date; } A: i'd do it like that: String[] s1 = "[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX".split(" "); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for(int i = 1; i< s1.length ; i++ ){ try { Date date = format.parse(s1[i-1]+" "+s1[i]); System.out.println("Date found: "+s1[i-1]+" "+s1[i]); break; } catch (ParseException e) { continue; } } Split the String loop through the String Array cast to date until you found a valid date. if the you know the date is always on the same place in the string you can do it much easier by you cast: String[] s1 = "[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX".split(" "); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.parse(s1[6]+" "+s1[7]); A: You need to normalize your string by removing the extra spaces... () Regex can do that fast and easy), then split the string, concatenate the elements of the string that you need for building a date, parse those to a Date object Woala... a snippet for this: String chain = "[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX"; chain = chain.replaceAll("\\s+", " ").trim(); System.out.println(chain); String[] var = chain.split(" "); for (String string : var) { System.out.println(string); } String string = var[3] + " " + var[4]; DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = format.parse(string); System.out.println(date);
[ "stackoverflow", "0013671536.txt" ]
Q: how to build an accumulator array in matlab I'm very new to matlab so sorry if this is a dumb question. I have to following matrices: im = imread('image.jpg'); %<370x366 double> [y,x] = find(im); %x & y both <1280x1 double> theta; %<370x366 double> computed from gradient of image I can currently plot points one at a time like this: plot(x(502) + 120*cos(theta(y(502),x(502))),y(502) + 120*sin(theta(y(502),x(502)))); But what I want to do is some how increment an accumulator array, I want to increment the location of acc by 1 for every time value for that location is found. So if x(502) + 120*cos(theta(y(502),x(502))),y(502) + 120*sin(theta(y(502),x(502)) = (10,10) then acc(10,10) should be incremented by 1. I'm working with a very large data set so I want to avoid for-loops and use something like this: acc = zeros(size(im)); %increment value when point lands in that location acc(y,x) = acc(x + 120*cos(theta(y,x)),y + 120*sin(theta(y,x)),'*b')) + 1; It would be nice if the 120 could actually be another matrix containing different radius values as well. A: Do i = find(im); instead of [y,x] = find(im) wthis will give you linear indice of non zero values Also, create a meshgrid [x,y] = meshgrid(1:366,1:370) Now you can index both coordinated and values linearly, for example x(520) is 520-th point x coordinate im(520) is 520-th point gray value theta(520) is 520-th gradient value So, now you can just plot it: plot(x(i) + 120*cos(theta(i)),y(i) + 120*sin(theta(i)),'b*'); x(i) means a column of i-th values x(i) + 120*cos(theta(i)) means a column of results ACCUMULATING I think in this case it is ok to loop for accumulating: acc=zeros(size(im)); for ii=1:length(i) xx=round(x(ii) + 120*cos(theta(ii))); yy=round(y(ii) + 120*sin(theta(ii))); acc(xx,yy)=acc(xx,yy)+1; end;
[ "stackoverflow", "0048913344.txt" ]
Q: Angular 5 adding html content dynamically I have following angular to add dynamically loaded content: main.html <div class="top"> <ng-template #main></ng-template> </div> main.ts import { Component, ViewChild, ComponentFactoryResolver, ViewContainerRef } from '@angular/core'; @Component({ selector: 'page-main_page', templateUrl: 'main_page.html' }) export class main_page { @ViewChild('main', { read: ViewContainerRef }) entry: ViewContainerRef; data: any; constructor(public resolver: ComponentFactoryResolver){ }; ngOnInit(){ this.getDynamicREST().then((res)=>{ this.data = res; //Where it is a html markup from php server: <div class="sample"> Example </div> const factory = this.resolver.resolveComponentFactory(this.data); this.entry.createComponent(factory); }) }; } In the getDynamicRest(), I am getting a html markup from php server such as : <div class="sample"> Example </div> However I am getting an error "Error: No component factory found for <div class="sample"> Example </div>" Any suggestions would be much appreciated. A: The ComponentFactoryResolver's resolveComponentFactory method accepts an Angular Component. In your case, you are injecting HTML into your template, not a component. To inject HTML, save it in a variable and use the DomSanitizer to either sanitize it or bypass the security check: export class main_page { data: SafeHtml; constructor(private sanitizer: DomSanitizer) {} ngOnInit(){ this.getDynamicREST().then((res)=> { this.data = this.sanitizer.sanitize(res); /* OR */ this.data = this.sanitizer.bypassSecurityTrustHtml(res); }) }; } Then, in your template: <div class="top"> <div [innerHtml]="data"></div> </div>
[ "stackoverflow", "0041765762.txt" ]
Q: select first character from each word within a list of scraped data Ive been struggling with abbreviating some data scraped using bs4. I'm trying abbreviate the output from: import urllib.request from bs4 import BeautifulSoup url = "http://www.bbc.co.uk/weather/en/2644037/?day1" page = urllib.request.urlopen(url) soup = BeautifulSoup(page, "html5lib") weekWeather = soup.find('div', {'class':'daily-window'}) wD = [x.text for x in weekWeather.findAll('span', {'class':'description blq-hide'})] The output is a list... ['South South Westerly', 'South Westerly', 'Southerly', 'Southerly', 'Southerly'] which I want to abbreviate to ['SSW', 'SW', 'S', 'S', 'S'] My first plan was to use split() and then select all upper(), then I tried using map to iterate over each word, and select the first character, but I only ever get the first letter back of each element (i.e. [S, S, S, S, S] I have a feeling it's because of the way the data is being returned?? Any pointers would be great, Thanks. A: In the simplest form, you can split by space via .split() and get the first character of every word: ["".join([item[0] for item in x.text.split()]) for x in weekWeather.select('span.description.blq-hide')] which would return: ['SSW', 'SW', 'S', 'S', 'S']
[ "stackoverflow", "0015234935.txt" ]
Q: Using Meteor's Template.rendered for google maps I am using the following code: Template.categories.rendered = function() { var map = new GMaps({ div: '#map_canvas', lat: -12.043333, lng: -77.028333 }); } to execute the Gmaps.js plugin - and it works, everytime I Submit a form, the layout gets re-rendered and my google maps get a re-paint too. I also used constant to try to isolate it... And isolate.. Nothing. (it's not inside a template) {{#constant}} <div id="map_canvas"></div> {{/constant}} I tried changing Template.categories.rendered to Template.categories.created but I got a bunch of errors. I was hoping 'created' only gets executed once.. edit I made a new template 'maps' and separated the forms form the map but I'm afraid this is not a viable solution as I want to communicate between the map and the form.. notably I want to get the latitude and longitude and automatically fill in a field... A: Try putting your map in a seperate template e.g <template name="categories"> {{>map}} {{>other_form_with_submit_button}} </template> So you put your map in the <template name="map"> <div id="map_canvas></div> </template> <template name="other_form_with_submit_button"> .. your form data </template> You should still be able to communicate to the map like normal, the DOM doesn't even notice much of the difference Template.other_form_with_submit_button.events({ 'submit' : function() { var lat = "-12.043333", var lng = "-77.028333"; var map = new GMaps({ div: '#map_canvas', lat: -12.043333, lng: -77.028333 }); } } Similarly while moving the map you can attach a listener and have it change the textbox like you wish: Template.map.rendered = function() { var map = new GMaps({ div: '#map_canvas', lat: -12.043333, lng: -77.028333 }); //Im not sure what you're using to get the location but this is the example if moving the center could be used google.maps.event.addListener(map, 'center_changed', function() { $("#lat").val(map.getPosition().lat()); $("#lng").val(map.getPosition().lng()); } });
[ "stackoverflow", "0021293554.txt" ]
Q: Show content if there's a `conversation_id` I have a messaging system set up so when a new message is created a conversation_id will be created for any replies associated with the message's id. The conversation_id is supposed to match the message's id. The question I have is how can I show every messages.body with the current conversation id? I am trying to create a threaded messaging system. Here's a example: I sent a message out that created message id 5 and no conversation id (The code I created does not supply a conversation id to the original message). I replied to message id 5 and had a conversation that created message ids 8, 9, 10. Those three message ids have a conversation id of 5. When user views message id 8...in the view it should also show message id 5, 9, and 10 since it's part of the conversation and they have conversation_id as 5 (with the exception of message id 5, no conversation_id shows for it since it's the original message). Controller: def show @new_message = Message.new @message = Message.find(params[:id]) @message.readingmessage if @message.recipient == current_user end A: I'd suggest a conversation model so you can have a has_many relationship. In this case your problem would be easily solved and the code would make more sense. If you're reluctant to do that, you can always fetch all the messages with same conversation_id: @messages = Message.where(conversation_id: params[:conversation_id]).order(created_at: :desc)} GL & HF
[ "worldbuilding.stackexchange", "0000115383.txt" ]
Q: Cyborg adaptation to a high pressure environment I'm currently working on a science fiction comic about humans marooned on an alien world for generations. This world is slightly larger and more metallic than earth with greater gravity a higher percentage of oxygen (I was thinking similar levels to the Carboniferous period here on earth 35-40%) and 3-4 earth atmospheres of pressure at sea level and a more comfortable level higher up where most humans live in domed habitats and can move around outside for limited periods with some protection. Though I'm really flexible on all those numbers if they don't work or aren't actually possible. My question is related to the people moving between higher and lower levels of pressure to scavenge materials and war with the locals. How much pressure is too much? how quickly could they move between these levels? how long could they survive in the lowlands with and without equipment? and what other unforeseen issues could I have missed? Mainly I want to know if these issues could be resolved with cybernetic modification (particularly modifications that make them repugnant to the unmodified) to allow for a lower level of protective equipment at all pressures. I remember reading peter watts Rifters trilogy in which the deep sea divers were modified to remove all their internal pockets of gas at will and store them in a canister, presumably so nothing could rupture under the pressure. Would something that extreme be viable or necessary? and more important would switching it on while shirtless be unsettling and cool looking? Thanks for taking the time to read this and sorry for any errors or faux pas on my part I'm not good with words. Please be gentle, its my first time. A: The bends. Decompression sickness (DCS; also known as divers' disease, the bends...) describes a condition arising from dissolved gases coming out of solution into bubbles inside the body on depressurisation. DCS most commonly refers to problems arising from underwater diving decompression (i.e., during ascent), but may be experienced in other depressurisation events such as emerging from a caisson, flying in an unpressurised aircraft at altitude, and extravehicular activity from spacecraft. DCS and arterial gas embolism are collectively referred to as decompression illness. Since bubbles can form in or migrate to any part of the body, DCS can produce many symptoms, and its effects may vary from joint pain and rashes to paralysis and death. Going into a high pressure atmosphere drives gas under pressure into solution within our blood. Then when a diver returns to normal atmospheric pressure the gas comes out of solution. Bubbles form in tissues and cause trouble where they do - stroke is the worst thing but these bubbles can cause holes in bones, tissue damage, etc. This is why divers must decompress slowly on ascent. The pressure changes your human experience on this world put them at risk for the bends. I propose your cybernetic humans are modified such that an ascent they can outgas pressured bubbles quickly and in a controlled manner, through the lungs. This outgassing of pressurized gas is the same thing that happens if a bottle of soda is shaken and then opened. This is how it would look for a human too - gouts of pinkish foam spurting from nose and mouth.
[ "stackoverflow", "0052676615.txt" ]
Q: Wget Linux command is downloading files with Read Permissions for only sudo users - how to give Read permissions to all users? I am running Ubuntu 16.04 and I am programming in PHP. Here is my problem: I have a need to use the wget linux command to download all files from a website. So I am using PHP's shell_exec() function to execute the command: $wgetCommand = "wget --recursive --page-requisites --convert-links $url 2>&1"; $wgetCommandOutput = shell_exec($wgetCommand); This command downloads all files and folders from a website, recursively, to the current working directory (unless otherwise specified). The problem is that when these files and folders are downloaded, I do not have permissions to read them programmatically after that. But if I do something like sudo chmod 777 -R path/to/downloaded/website/directory after they are downloaded with the wget command and before they are read programmatically, they are read just fine and everything works. So I need a way to download folders and files from a website using wget command and they should have read permissions for all users, not just sudo. How can I achieve that? A: This sounds like a umask issue with the user running the PHP script. Normally, Ubuntu would have a default umask of 0002. This would create a file with (-rw-rw-r--). From the console you can check and set the umask for the PHP user via: $umask And inside the PHP script, do a <?php umask() If you are on a running webserver, it would, however be better to alter the files permissions of the downloaded files afterwards, via <?php chmod() The reason is, that the umask handles file creation for all files - not just your script.
[ "stackoverflow", "0015892940.txt" ]
Q: Getting a lists of times in Python from 0:0:0 to 23:59:59 and then comparing with datetime values I was working on code to generate the time for an entire day with 30 second intervals. I tried using DT.datetime and DT.time but I always end up with either a datetime value or a timedelta value like (0,2970). Can someone please tell me how to do this. So I need a list that has data like: [00:00:00] [00:00:01] [00:00:02] till [23:59:59] and needed to compare it against a datetime value like 6/23/2011 6:38:00 AM. Thanks! A: Is there a reason you want to use datetimes instead of just 3 for loops counting up? Similarly, do you want to do something fancy or do you want to just compare against the time? If you don't need to account for leap seconds or anything like that, just do it the easy way. import datetime now = datetime.datetime.now() for h in xrange(24): for m in xrange(60): for s in xrange(60): time_string = '%02d:%02d:%02d' % (h,m,s) if time_string == now.strftime('%H:%m:%S'): print 'you found it! %s' % time_string Can you give any more info about why you are doing this? It seems like you would be much much better off parsing the datetimes or using strftime to get what you need instead of looping through 60*60*24 times.
[ "stackoverflow", "0018542025.txt" ]
Q: I always get warning when I add text or button in Eclipse I am a new Android Developer and I downloaded and installed Eclipse using the xdatv steps on How to Build an Android App Part 1: Setting up Eclipse and Android SDK Here is how I installed it: First I download the SDK. (It contains the SDK and Eclipse in the same .rar file.) I extracted the files(SDK and Eclipse) in one folder. I opened Eclipse and added the browsed folder where I extracted the SDK and Eclipse files as the Workspace. And I opened the SDK to download the SDK version I chose Android 2.3.3 (API 10). I opened Eclipse and went to the Help category and I chose Install New software. I added that link http://dl-ssl.google.com/android/eclipse/ and checked the Developer tool and NDK Plugin, then I downloaded them. And before I start to create an Android app, I check in the Workspace setting if the SDK location is correct in the folder where sdk and eclipse in/sdk folder. Finally when I started to create an app, I tried to add a button or text, but I always get a warning when I add a button [I8N]Hardcoded string "button", should use @string resource and I got the same warning on the text. I searched for answer for my problem and I found I did the same thing that they did (I added @string/ on this code android:text="@string/button" /> on the button and also in the text code). And I added on strings.xml these codes: <string name="button">Button</string> <string name="Testtext">Test text</string> The warning disappeared but there is something annoying me -- it always shows @string in the button and the text in the graphical layout: I think that it must always be that when I add text or a button it automatically adds the @string and in the strings.xml adds the these codes <string name="my_string">Your Text!</string>. I just want know what the wrong thing that I did to get this warning and why it doesn't add these codes automatically in the .xml files and how to fix that. Thanks A: I think that it must always be that when I add text or a button it automatically adds the @string and in the strings.xml adds the these codes Your Text! NO (atleast in Eclipse thats not the case) why it doesn't add these codes automatically in the .xml files In Eclipse no automatic addition of code in strings.xml is done. You have to add them manually. As far as your warning is Graphical Layout is concerned :- You have correctly done mapping of those srings in strings.xml. Just follow the below steps. make sure ids are exact as mentioned in strings.xml Save-all. Select your project and click F5 to Refreash. Clean and build your project. Your Couldn't resolve resourses --- error will be gone.. Check on emulator or a real devices.
[ "diy.stackexchange", "0000198105.txt" ]
Q: Water heater straps too short. Replace straps? Get extension? The water heater is already installed in a narrow cabinet. So there is no easy access behind it without taking it out: I could get 3 additional inches by making the fold around both brackets a little shorter. But even then I would still be 3 inches short. Have four questions on how to bring this up to California code: Can I use some extensions to get to 6 inches? Are there brackets with a longer foot? Can I simply use ridiculously long bolt? Can I just replace the left side strap with a regular galvanized hanger strap to still be up to code? P.S. The bottom strap is fine. If I would try really hard, then I could maybe reach the upper left bolt as there is slightly more clearance. The bracket looks like this: A: If you haven't got access to replace the strap, I'd just replace the bolt with a piece of threaded rod and a couple of washers/nuts. They won't lie flat to the brackets, but since this is just for stability, they don't need to go tight so this shouldn't matter. The above is obviously assuming that you can run a straight line between the holes on the two brackets, but it does look like this is possible from the picture.
[ "stackoverflow", "0011688705.txt" ]
Q: How to use DropDownList.SelectedIndex from datasource? I have an ASP.NET Wizard for registration. In step 1, I have few controls that goes into table dbo.Emp. In this step1, I have couple of DropDownList that is binded from code-behind from different table called dbo.Emptype. However, while inserting the form to table dbo.Emp, I am getting following error- Insert Error:Error converting data type nvarchar to numeric. I do not know for which control it is telling it for. But there is a statement here- cmd.Parameters.AddWithValue("@EmpType",DropDownList1.SelectedIndex); cmd.Parameters.AddWithValue("@DeptID", DropDownList3.SelectedIndex); I want the INT values that is associated with items in EmpType to be inserted into the table. DropDownList1 is binded to the table called Dbo.EmpType (TypeID (PK- AutoIncrement)| Type) So, when a user drops down that control and select value, I need DataValueField (i.e TypeID) to get inserted into the table. What do I do? This is my bind class. public void dropdowntype() { SqlConnection myConn = new SqlConnection(@"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True"); SqlCommand myCmd = new SqlCommand( "SELECT Type, TypeID FROM EmpType", myConn); myConn.Open(); SqlDataReader myReader3 = myCmd.ExecuteReader(); //Set up the data binding. Emp_type.DataSource = myReader3; Emp_type.DataTextField = "Type"; Emp_type.DataValueField = "TypeID"; Emp_type.DataBind(); //Close the connection. myConn.Close(); myReader3.Close(); } protected void Page_Load(object sender, EventArgs e) { if (!(Page.IsPostBack)) { dropdownDept(); dropdowntype(); dropdownskills(); } } A: If you need the data value feild from your dropdown then use this statement cmd.Parameters.AddWithValue("@EmpType",DropDownList1.SelectedValue); cmd.Parameters.AddWithValue("@DeptID",DropDownList3.SelectedValue); You are currently selecting the index of the dropdown.
[ "stackoverflow", "0003506964.txt" ]
Q: MPMediaPickerController in one view and the MPMediaPlayback in another view. How to? Basically I have a three view stack. In the last view I got a MPMediaPickerController that lets the user pick a song from his/her library. The song is to be played later from the first view. How can I tell the player (in the first view) what should be played? One possibility would be to send a notification and include the MPMediaItemCollection as the object maybe? Is this a/the correct way or do you have other smarter suggestions? A: I ended up using NSNotification and attaching the MediaItemCollection as userInfo.
[ "stackoverflow", "0052126435.txt" ]
Q: Selenium Python Extracting text after .click() Good day everyone, I am having much trouble attempting to click on an element on a website, and after that extracting the text that results from the click. Another consideration is that this code has to be robust enough to loop. In the modified webpage source code below, id='atelno80112862' is how i identify the element to click. After clicking, the phone number I want "(65) 6890 6333" replaces the text "Call" on the webpage. Afterwards, id='telno80112862' is how I identify the text i want to pull. <div id="ctl00_ContentPlaceHolder1_dgrdCompany_ctl02_idContact"> <a style="display: inline; width: 100px; cursor: pointer; cursor: hand;" id='atelno80112862' onclick="showElement('telno80112862');" title='(65) 6890 6333'> <img src="/images/call_icon.jpg" />CALL</a> <a style="display: none; width: 100px;" id='telno80112862' href="tel:(65) 6890 6333">(65) 6890 6333</a> On to my code(i've modified it to zero in on the problem areas): for j in range(2 ,10): path5 = "ctl00_ContentPlaceHolder1_dgrdCompany_ctl0{0}_idContact".format(j) path6 = "//a[contains(@id,'atel')]" path7 = "//a[@id='telno80112862']" try: phone = driver.find_element_by_id(path5) phone_num = phone.find_element_by_xpath(path6).click() phone_info = phone.find_element_by_xpath(path7) except: print("ERROR: NO PHONE NUMBER") This works partially, and when i loop i get this for each iteration: (65) 6890 6333 ERROR: NO PHONE NUMBER The first problem is why am i getting the except output too? The second problem is that i am unable to improve the robustness of path7. It only works if i provide the exact relative xpath. Ive tried using partial xpath "//a[(contains(@id,'telno')]" but doesnt seem to work. Any help would be greatly appreciated. Cheers! A: Code below get all company names and phone numbers on one page. companies = driver.execute_script('return [...document.querySelectorAll("a[id$=Hyperlink4],a[id^=telno]")].map((e,i) => e.innerText.trim())') print(companies) for i in range(0, len(companies), 2): print('{0} : {1}'.format(companies[i], companies[i+1]))
[ "stackoverflow", "0026070001.txt" ]
Q: HttpClient freezes on the GetStringAsync method I have this c# MVC code and it works fine with the GetAsync and GetPost methods, but when using GetStringAsync, it freezes up at the line: version = await client.GetStringAsync("/API/Version"); Driver code: Task<string>[] tasks = new Task<string>[count]; for (int i = 0; i < count; i++) { tasks[i] = MyHttpClient.GetVersion(port, method); } Task.WaitAll(tasks); string[] results = new string[tasks.Length]; for(int i=0; i<tasks.Length; i++) { Task<string> t = (Task<string>)(tasks[i]); results[i] = (string)t.Result; } HttpCilent code: public static async Task<string> GetVersion(int port, string method) { try { var client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:" + port); string version = null; if (method.ToUpper().Equals("GETSTR")) { version = await client.GetStringAsync("/API/Version"); } else if (method.ToUpper().Equals("GET")) { HttpResponseMessage res = client.GetAsync("/API/Version").Result; version = res.Content.ReadAsStringAsync().Result; } else if (method.ToUpper().Equals("POST")) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("name", "jax") }); HttpResponseMessage res = client.PostAsync("/API/Version", content).Result; version = res.Content.ReadAsStringAsync().Result; } client.Dispose(); return version; } catch (Exception ex) { return "Error: " + ex.Message; } } } Any ideas why? A: Generally, you shouldn't mix async/await with .Result and .Wait(). First the fix to the GetVersion method: public static async Task<string> GetVersion(int port, string method) { try { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:" + port); if (method.ToUpper().Equals("GETSTR")) { return await client.GetStringAsync("/API/Version") .ConfigureAwait(false); } else if (method.ToUpper().Equals("GET")) { var res = await client.GetAsync("/API/Version").ConfigureAwait(false); return await res.Content.ReadAsStringAsync().ConfigureAwait(false); } else if (method.ToUpper().Equals("POST")) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("name", "jax") }); var res = await client.PostAsync("/API/Version", content) .ConfigureAwait(false); return await res.Content.ReadAsStringAsync().ConfigureAwait(false); } } } catch (Exception ex) { return "Error: " + ex.Message; } } All I've done here is replace the <task>.Result calls with await <task>. For each await, the portion of the method following the await will be registered as a continuation of the Task being awaited -- if and when each await expression is encountered -- instead of blocking the thread in the case of .Result. Now in your calling code you need to do the same thing: var tasks = new Task<string>[count]; for (int i = 0; i < count; i++) { tasks[i] = MyHttpClient.GetVersion(port, method); } var results = new string[tasks.Length]; for (int i = 0; i < tasks.Length; i++) { results[i] = await tasks[i]; } Or more simply: var tasks = new Task<string>[count]; for (int i = 0; i < count; i++) { tasks[i] = MyHttpClient.GetVersion(port, method); } var results = await Task.WhenAll(tasks);
[ "ai.stackexchange", "0000011313.txt" ]
Q: Reinforcement Learning with more actions than states I have read a lot about RL recently. As far as I understood, most RL applications have much more states than there are actions to choose from. I am thinking about using RL for a problem where I have got a lot of actions to choose from, but only very few states. To give a handy example: The algo should render (for whatever reason) a sentence with three words. I always want to have a sentence with three words, but I have many words to choose from. After choosing the words, I get some sort of reward. Are RL algorithms an efficient way to solve this? I am thinking about using policy gradients with an ε-greedy algorithm to explore a lot of the possible actions before exploiting the knowledge gained. A: As far as I understood, most RL applications have much more states than there are actions to choose from. Yes, this is quite common, but in no way required by the underlying theory of Markov Decision Processes (MDPs). The most extreme version of the opposite thing - with one state (or effectively no state, as state is not relevant) - are k-armed bandit problems, where an agent tries to find a single best long-term action in general from a selection of actions. These problems typically would not use RL algorithms such as Q-learning or policy-gradients. However, that is partly because they are described with different goals in mind (e.g. minimising "regret" or simply gaining as much reward as possible during the learning process), and RL algorithms will work to solve them, albeit less efficiently than algorithms designed to work on bandit problems directly. I am thinking about using RL for a problem where I have got a lot of actions to choose from, but only very few states. That should work, provided your problem is still a MDP. That means for instance that the state evolves according to rules depending on which action was taken in which starting state. If the state evolution is instead arbitrary or random, then you may have a contextual bandit problem instead. There is an important difference here between: a large number of entirely different actions, each with different results, which need enumeration and have to be explored separately and a large action space due to measurable values which are part of an action, such as how much force to apply in a motor The former will require lots of exploration, since any specific combination of action and state could be the ideal. With the latter, you can use that fact that numerical values that are similar will often give similar results, which will make generalisation via function approximation (e.g. neural networks) work efficiently in your favour. The algo should render (for whatever reason) a sentence with three words. I always want to have a sentence with three words, but I have many words to choose from. After choosing the words, I get some sort of reward This seems more like the first bullet-point above, although that may depend if a natural language model could be applied for example. E.g. if "This is good" and "This is great" would produce similar rewards in a specific state, then there is maybe some benefit to generalisation, although I am not quite sure where you would fit this knowledge - possibly in a generator for a sentence vector as the "raw" action and then have a LSTM-based language model produce the actual action from that vector, similar to seq2seq translation models. Are RL algorithms an efficient way to solve this? Yes, but whether or not it is the most efficient will depend on other factors, such as: Whether the environment is stochastic or deterministic with regard to both reward and state progression. Whether state progression is key to obtaining the best rewards in the long term (e.g. there is some "goal" or "best" state that can only be reached by a certain route). What the actual size of the MDP is $|\mathcal{S}| \times |\mathcal{A}|$. Small MDPs can be fully enumerated, allowing you to estimate action values in a simple table. If you have 10 states and 1,000,000 discrete actions, with no real pattern of actions mapping to results, then a big 10 million entry table will actually be reasonably efficient. Competitive algorithms to RL here might be global search and optimisation ones, such as genetic algorithms. The more arbitrary and deterministic your environment is, the more likely it is that an exhaustive search will find your optimal policy faster than RL. I am thinking about using policy gradients with an ε-greedy algorithm to explore a lot of the possible actions before exploiting the knowledge gained. This should be fine. Exploration here is definitely important, but finding the sweet spot for the right amount of it will be hard, and depend on other traits of the environment. You may want to use something like upper confidence bound action selection or simply optimistic initial values, in order to ensure exploration does not miss certain actions. An epsilon greedy approach will miss a certain fraction of actions over time, and the expectation of that fraction grows smaller progressively more slowly, so it may be possible to miss an important action for a long time if you rely on being able to randomly select it. To give a handy example: The algo should render (for whatever reason) a sentence with three words. I always want to have a sentence with three words, but I have many words to choose from. After choosing the words, I get some sort of reward. I would consider modelling this as sequences of 3 actions, each of which chooses a word, with the state being a start token (whatever the state you already have) plus the sentence so far, and on every 3 words the environment is consulted to reset the state to the next start token and to gather a reward (rewards for interim steps would be zero). Doing this immediately makes the state space much larger than the action space, as your state includes history of up to two actions. If you had 10 different start states, and 100 word choices, then your state space would be 101,010 and action space 100. This will fit available designs of RL algorithms, and allow for learning some internal language modelling if it is relevant. It will reduce your need to model sentence construction outside of the agent. Most importantly, if "good" or "bad" sentences tend to start or end with certain words, and you use function approximation, then the algorithm may discover combinations more efficiently than iterating over all sentences as if they were completely independent.
[ "stackoverflow", "0017491364.txt" ]
Q: Knockoutjs Custom bindig with jQueryUI Dialog I'm trying to make a custom binding based on this code, http://jsfiddle.net/rniemeyer/WpnTU/ , Mine after a field checkbox is selected then open a jQueryUI dialog. Here is the code: http://jsfiddle.net/superjohn_2006/UFEg6/ , another question is it posible to acomplish this without a template. <table> <tbody data-bind="foreach: records"> <tr data-bind="foreach: fields"> <th align="left"> <input type="checkbox" data-bind="checked: chkedValue" /><span data-bind=" text: field"></span> </th> </tr> <tr data-bind="foreach: fields"> <th align="left"><a data-bind="click: $root.addFormatting" href="#">Add Formatting</a></th> </tr> <tr data-bind="foreach: row"> <td data-bind="text: value"></td> </tr> </tbody> </table> <div id="details" data-bind="jqDialog: { autoOpen: false, resizable: false, modal: true }, template: { name: 'editTmpl', data: selectedField }, openDialog: selectedField"> </div> <script id="editTmpl" type="text/html"> <p> <label>Selected Field: </label> <span data-bind="value: field" /> </p> <button data-bind="jqButton: {}, click: $root.accept">Accept</button> <button data-bind="jqButton: {}, click: $root.cancel">Cancel</button> </script> **The model // custom binding ko.bindingHandlers.jqDialog = { init: function(element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()) || {}; // initialize a jQuery UI dialog $(element).dialog(options); // handle disposal ko.utils.domNodeDisposal.addDisposeCallback(element, function() { $(element).dialog("destroy"); }); } }; //custom binding handler that opens/closes the dialog ko.bindingHandlers.openDialog = { update: function(element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); if (value) { $(element).dialog("open"); } else { $(element).dialog("close"); } } }; //custom binding to initialize a jQuery UI button ko.bindingHandlers.jqButton = { init: function(element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()) || {}; //handle disposal ko.utils.domNodeDisposal.addDisposeCallback(element, function() { $(element).button("destroy"); }); $(element).button(options); } }; var resultsData = [ { fields: [{ field: "Field1", chkedValue: false }, { field: "Field2", chkedValue: false }] }, { row: [{ value: "1" }, { value: "True" }] }, { row: [{ value: "2" }, { value: "False" }] } ]; var TableModel = function (records) { var self = this; self.records = ko.observableArray(ko.utils.arrayMap(records, function (record) { return { fields: ko.observableArray(record.fields), row: ko.observableArray(record.row) }; })); self.selectedField = ko.observable(); self.addFormatting = function (formatToAdd) { self.selectedField(); }; }; this.accept = function() { }, this.cancel = function() { } ko.applyBindings(new TableModel(resultsData)); A: the following couple of lines need to be changed. span data-bind="value: field" for: span data-bind="text: $data.field" and, self.selectedField(); for: self.selectedField(formatToAdd); modified code is in the same jsFiddle, jus add: /1/ to the end of the url address.
[ "stackoverflow", "0006477856.txt" ]
Q: How to add attributes to option tags in django ? I have to add title attribute to options of the ModelChoiceField. Here is my admin code for that: class LocModelForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(LocModelForm,self).__init__(*args,**kwargs) self.fields['icons'] = forms.ModelChoiceField(queryset = Photo.objects.filter(galleries__title_slug = "markers")) self.fields['icons'].widget.attrs['class'] = 'mydds' class Meta: model = Loc widgets = { 'icons' : forms.Select(attrs={'id':'mydds'}), } class Media: css = { "all":("/media/css/dd.css",) } js=( '/media/js/dd.js', ) class LocAdmin(admin.ModelAdmin): form = LocModelForm I can add any attribute to select widget, but i don't know how to add attributes to option tags. Any idea ? A: First of all, don't modify fields in __init__, if you want to override widgets use Meta inner class, if you want to override form fields, declare them like in a normal (non-model) form. If the Select widget does not do what you want, then simply make your own. Original widget uses render_option method to get HTML representation for a single option — make a subclass, override it, and add whatever you want. class MySelect(forms.Select): def render_option(self, selected_choices, option_value, option_label): # look at the original for something to start with return u'<option whatever>...</option>' class LocModelForm(forms.ModelForm): icons = forms.ModelChoiceField( queryset = Photo.objects.filter(galleries__title_slug = "markers"), widget = MySelect(attrs = {'id': 'mydds'}) ) class Meta: # ... # note that if you override the entire field, you don't have to override # the widget here class Media: # ... A: I had a similar problem, where I needed to add a custom attribute to each option dynamically. But in Django 2.0, the html rendering was moved into the Widget base class, so modifying render_option no longer works. Here is the solution that worked for me: from django import forms class CustomSelect(forms.Select): def __init__(self, *args, **kwargs): self.src = kwargs.pop('src', {}) super().__init__(*args, **kwargs) def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): options = super(CustomSelect, self).create_option(name, value, label, selected, index, subindex=None, attrs=None) for k, v in self.src.items(): options['attrs'][k] = v[options['value']] return options class CustomForm(forms.Form): def __init__(self, *args, **kwargs): src = kwargs.pop('src', {}) choices = kwargs.pop('choices', ()) super().__init__(*args, **kwargs) if choices: self.fields['custom_field'].widget = CustomSelect(attrs={'class': 'some-class'}, src=src, choices=choices) custom_field = forms.CharField(max_length=100) Then in views, render a context with {'form': CustomForm(choices=choices, src=src)} where src is a dictionary like this: {'attr-name': {'option_value': 'attr_value'}}. A: Here's a class I made that inherits from forms.Select (thanks to Cat Plus Plus for getting me started with this). On initialization, provide the option_title_field parameter indicating which field to use for the <option> title attribute. from django import forms from django.utils.html import escape class SelectWithTitle(forms.Select): def __init__(self, attrs=None, choices=(), option_title_field=''): self.option_title_field = option_title_field super(SelectWithTitle, self).__init__(attrs, choices) def render_option(self, selected_choices, option_value, option_label, option_title=''): print option_title option_value = forms.util.force_unicode(option_value) if option_value in selected_choices: selected_html = u' selected="selected"' if not self.allow_multiple_selected: # Only allow for a single selection. selected_choices.remove(option_value) else: selected_html = '' return u'<option title="%s" value="%s"%s>%s</option>' % ( escape(option_title), escape(option_value), selected_html, forms.util.conditional_escape(forms.util.force_unicode(option_label))) def render_options(self, choices, selected_choices): # Normalize to strings. selected_choices = set(forms.util.force_unicode(v) for v in selected_choices) choices = [(c[0], c[1], '') for c in choices] more_choices = [(c[0], c[1]) for c in self.choices] try: option_title_list = [val_list[0] for val_list in self.choices.queryset.values_list(self.option_title_field)] if len(more_choices) > len(option_title_list): option_title_list = [''] + option_title_list # pad for empty label field more_choices = [(c[0], c[1], option_title_list[more_choices.index(c)]) for c in more_choices] except: more_choices = [(c[0], c[1], '') for c in more_choices] # couldn't get title values output = [] for option_value, option_label, option_title in chain(more_choices, choices): if isinstance(option_label, (list, tuple)): output.append(u'<optgroup label="%s">' % escape(forms.util.force_unicode(option_value))) for option in option_label: output.append(self.render_option(selected_choices, *option, **dict(option_title=option_title))) output.append(u'</optgroup>') else: # option_label is just a string output.append(self.render_option(selected_choices, option_value, option_label, option_title)) return u'\n'.join(output) class LocModelForm(forms.ModelForm): icons = forms.ModelChoiceField( queryset = Photo.objects.filter(galleries__title_slug = "markers"), widget = SelectWithTitle(option_title_field='FIELD_NAME_HERE') )
[ "salesforce.stackexchange", "0000101624.txt" ]
Q: Multiple email attachment failure I have below code to send multiple email attachments in a single email which is throwing below error. Can some one please tell me what's wrong here? Code Snippet Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment(); if(getSelectedSize() > 0) { if(recordtypes.contains('ABS_Compliance_Incidents_abv')) { PageReference pdf = Page.CompIncidentTransactionsAttachment; pdf.getParameters().put('Ids',Ids ); // pdf.setRedirect(true);//false Blob b = pdf.getContent(); efa.setFileName('ComplianceIncidentReport.pdf'); efa.setBody(b); } //email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); if(recordtypes.contains('Sample_Compliance_Incidents_abv')) { PageReference pdf1 = Page.CompIncidentTransactionsAttachmentSample; pdf1.getParameters().put('Ids',Ids ); // pdf1.setRedirect(true);//false Blob b1 = pdf1.getContent(); // Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment(); efa1.setFileName('SampleIncidentReport.pdf'); efa1.setBody(b1); } Integer interSample=[select count() from Compliance_Incident_abv__c where Id =:Ids1 and Recordtype.developername='Sample_Compliance_Incidents_abv']; Integer interABS=[select count() from Compliance_Incident_abv__c where Id =:Ids1 and Recordtype.developername='ABS_Compliance_Incidents_abv']; if(interSample==0) {email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});} else if(interABS==0) {email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});}*/ else { email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa,efa1}); } } // Sets the paramaters of the email email.setSubject(Subject); email.setToAddresses( toAddresses ); if(ccAddresses.size() > 0 && ccAddresses[0] != null && ccAddresses[0] != '') { //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, toAddresses + ' ' + ccAddresses + ccAddresses.size() + toAddresses.size())); email.setCCAddresses( ccAddresses ); } email.setPlainTextBody( Body); Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); sendEmail=true;//Control viz of Send btn. ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'Your Email has been successfully Sent')); Error System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, No body supplied for the file attachment.: [fileAttachments] A: There can be one reason: 1. Record Types are not matching in if. Try below sample code. List<Messaging.EmailFileAttachment> efaList = new List<Messaging.EmailFileAttachment>(); if(getSelectedSize() > 0) { if(recordtypes.contains('ABS_Compliance_Incidents_abv')) { Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); PageReference pdf = Page.CompIncidentTransactionsAttachment; pdf.getParameters().put('Ids',Ids ); // pdf.setRedirect(true);//false Blob b = pdf.getContent(); efa.setFileName('ComplianceIncidentReport.pdf'); efa.setBody(b); efaList.add(efa); Integer interABS=[select count() from Compliance_Incident_abv__c where Id =:Ids1 and Recordtype.developername='ABS_Compliance_Incidents_abv']; if(interABS==0) { email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); } } if(recordtypes.contains('Sample_Compliance_Incidents_abv')) { PageReference pdf1 = Page.CompIncidentTransactionsAttachmentSample; pdf1.getParameters().put('Ids',Ids ); // pdf1.setRedirect(true);//false Blob b1 = pdf1.getContent(); Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); efa.setFileName('SampleIncidentReport.pdf'); efa.setBody(b1); Integer interSample=[select count() from Compliance_Incident_abv__c where Id =:Ids1 and Recordtype.developername='Sample_Compliance_Incidents_abv']; if(interSample==0) { email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); } } } // Sets the paramaters of the email email.setSubject(Subject); email.setToAddresses( toAddresses ); if(ccAddresses.size() > 0 && ccAddresses[0] != null && ccAddresses[0] != '') { //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, toAddresses + ' ' + ccAddresses + ccAddresses.size() + toAddresses.size())); email.setCCAddresses( ccAddresses ); } email.setPlainTextBody( Body); Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); sendEmail=true;//Control viz of Send btn. ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'Your Email has been successfully Sent'));
[ "stackoverflow", "0052802922.txt" ]
Q: How to read stream+json responses from Vuejs? I use axios http client in vuejs application and this code: axios.get('http://localhost:8081/pets') .then(response => { this.pets = response.data; }) If server return simple "application/json" conten, then all fine. But i want read "application/stream+json" for each row separately. For example: axios.get('http://localhost:8081/pets') .then(response => { this.pets.push(response.data) }) But this code (as expected) does not work. A: I solved this problem with SSE: let es = new EventSource('http://localhost:8081/pets'); es.addEventListener('message', event => { let data = JSON.parse(event.data); this.pets.push(data); }, false);
[ "stackoverflow", "0045965444.txt" ]
Q: Match length of two Python lists I have two Python lists of different length. One may assume that one of the lists is multiple times larger than the other one. Both lists contain the same physical data but captured with different sample rates. My goal is to downsample the larger signal such that it has exactly as much data points as the smaller one. I came up with the following code which basically does the job but is neither very Pythonic nor capable of handling very large lists in a performant way: import math a = [1,2,3,4,5,6,7,8,9,10] b = [1,4.5,6.9] if len(a) > len(b): div = int(math.floor(len(a)/len(b))) a = a[::div] diff = len(a)-len(b) a = a[:-diff] else: div = int(math.floor(len(b)/len(a))) b = b[::div] diff = len(b)-len(a) b = b[:-diff] print a print b I would appreciated if more experienced Python users could elaborate alternative ways to solve this task. Any answer or comment is highly appreciated. A: Here's a shortened version of the code (not necessarily better performance): a = [1,2,3,4,5,6,7,8,9,10] b = [1,4.5,6.9] order = 0 # To determine a and b. if len(b) > len(a): a, b = b, a # swap the values so that 'a' is always larger. order = 1 div = len(a) / len(b) # In Python2, this already gives the floor. a = a[::div][:len(b)] if order: print b print a else: print a print b Since you're ultimately discarding some of the latter elements of the larger list, an explicit for loop may increase performance, as then you don't have to "jump" to the values which will be discarded: new_a = [] jump = len(b) index = 0 for i in range(jump): new_a.append(a[index]) index += jump a = new_a
[ "stackoverflow", "0026538416.txt" ]
Q: WELL PRNG not working?(maybe) I am trying to use a specific implementation of the WELL PRNG, supposedly better than the original. link to the code However I am having some trobles with it. No matter how I seed it, it just outputs the same numbers. I think that I am probably just using it wrong, but have not been able to figure out my mistake. Unfortunately the source of the PRNG is completely opaque to me. My code: #include <iostream> #include <WELL44497a_new.h> void pause() { std::string dummy; std::cout << "Press enter to continue..."; std::getline(std::cin, dummy); } int main(int argc, char** argv) { using std::cout; using std::cin; using std::endl; cout<<"Hello"<<endl; pause(); unsigned int rngseed; cout<<"Input RNG seed:"; cin>>rngseed; cout<<"The RNG seed is:"; cout<<rngseed<<endl; pause(); InitWELLRNG44497(&rngseed); int i=1; for (i;i<100;i++){ unsigned long rngtest=WELLRNG44497(); cout<<rngtest<<endl; } pause(); return 0; } A: Based on the comment squeamish-ossifrage I have revised the code. The following code appears to work: ... cin>>rngseed; cout<<"The RNG seed is:"; cout<<rngseed<<endl; pause(); unsigned int rngseed_arr[1391]; int i=0; for (i;i<1391;i++){ rngseed_arr[i]=rngseed+i; } InitWELLRNG44497(rngseed_arr); i=1; ...
[ "webmasters.stackexchange", "0000078792.txt" ]
Q: What is the use case for Fax links in a webpage? I've used tel: and mailto: to link to a phone number or email but how and why would I use fax: linking in a webpage? We currently take orders via fax. What would be the flow for a customer who clicks the fax link on our webpage expecting to fax in an order? Is it even worth using? I would think that the user would need some kind of desktop faxing software which at that point most users would just give up and use email. <a href=“fax:number”>number</a> What's the use case for this link type? A: Computers, mobiles and tablets can send fax's with software, its just like sending an email, it was added to rfc2086 15 years ago but it never took off and as far as I know no major browsers support href="fax:" they do however support href="tel:" that can be used just the same to send a fax using software. 2.3 "fax" URL scheme The URL syntax is formally described as follows (the definition reuses nonterminals from the above definition). For the basis of this syntax, see [RFC2303] and [RFC2304]. fax-url = fax-scheme ":" fax-subscriber fax-scheme = "fax" fax-subscriber = fax-global-phone / fax-local-phone fax-global-phone = "+" base-phone-number [isdn-subaddress] [t33-subaddress] [post-dial] *(area-specifier / service-provider / future-extension) fax-local-phone = 1*(phonedigit / dtmf-digit / pause-character) [isdn-subaddress] [t33-subaddress] [post-dial] area-specifier *(area-specifier / service-provider / future-extension) t33-subaddress = ";tsub=" 1*phonedigit The fax: URL is very similar to the tel: URL. The main difference is that in addition to ISDN subaddresses, telefaxes also have an another type of subaddress, see section 2.5.8.
[ "stackoverflow", "0024289842.txt" ]
Q: Query done by SQL showing same results multiple times (multiple copies of same record in query) I've got a query being made via an SQL statement. I'm getting the correct results, just each result is repeated 4 times in the query. I'm confused as to why I am getting 4 copies of the same result. Here is my code for the form: Dim strTables As String Private Sub btnFollowUpQs_Click() If (btnFollowUpQs.Value = True) Then Set db = CurrentDb() Set rs = db.OpenRecordset(btnFollowUpQs.Caption) Dim fld As DAO.Field For Each fld In rs.Fields Me.lstVariablesFollowUpQs.AddItem (fld.Name) Next Set fld = Nothing db.Close strTables = strTables + "," + btnFollowUpQs.Caption Else lstVariablesFollowUpQs.RowSource = "" strTables = Replace(strTables, "," + btnFollowUpQs.Caption, "") End If Debug.Print strTables End Sub Private Sub btnBaseline_Click() If (btnBaseline.Value = True) Then Set db = CurrentDb() Set rs = db.OpenRecordset(btnBaseline.Caption) Dim fld As DAO.Field For Each fld In rs.Fields Me.lstVariablesBaseline.AddItem (fld.Name) Next Set fld = Nothing db.Close strTables = strTables + "," + btnBaseline.Caption Else lstVariablesBaseline.RowSource = "" strTables = Replace(strTables, "," + btnBaseline.Caption, "") End If Debug.Print strTables End Sub Private Sub btnTreatments_Click() If (btnTreatments.Value = True) Then Set db = CurrentDb() Set rs = db.OpenRecordset(btnTreatments.Caption) Dim fld As DAO.Field For Each fld In rs.Fields Me.lstVariablesTreatments.AddItem (fld.Name) Next Set fld = Nothing db.Close strTables = strTables + "," + btnTreatments.Caption Else lstVariablesTreatments.RowSource = "" strTables = Replace(strTables, "," + btnTreatments.Caption, "") End If Debug.Print strTables End Sub Private Sub btnQuestionnaires_Click() If (btnQuestionnaires.Value = True) Then Set db = CurrentDb() Set rs = db.OpenRecordset(btnQuestionnaires.Caption) Dim fld As DAO.Field For Each fld In rs.Fields Me.lstVariablesQuestionnaires.AddItem (fld.Name) Next Set fld = Nothing db.Close strTables = strTables + "," + btnQuestionnaires.Caption Else lstVariablesQuestionnaires.RowSource = "" strTables = Replace(strTables, "," + btnQuestionnaires.Caption, "") End If Debug.Print strTables End Sub Private Function createSQL(ByRef lstCtrl As Control, v() As String) As String Dim count As Integer count = 0 With lstCtrl For Each varSelected In .ItemsSelected If Not IsNull(varSelected) Then Dim sel As String sel = (lstCtrl.Column(0, varSelected)) strSQL = strSQL + sel & " " & v(count) & " AND " End If count = count + 1 Next End With createSQL = strSQL End Function Private Sub btnBuildQuery_Click() If Left(strTables, 1) = "," Then strTables = Right(strTables, Len(strTables) - 1) End If Dim tables() As String tables = Split(strTables, ",") Dim strSQL As Variant strSQL = "SELECT * FROM " & strTables & " WHERE " For Each Table In tables Dim values() As String Select Case Table Case "tblPatientHistoryBaseline" values = Split(txtSearchValueBaseline, ",") strSQL = strSQL + createSQL(lstVariablesBaseline, values) Case "tblQuestionnaires" values = Split(txtSearchValueQuestionnaires, ",") strSQL = strSQL + createSQL(lstVariablesQuestionnaires, values) Case "tblTreatments" values = Split(txtSearchValueTreatments, ",") strSQL = strSQL + createSQL(lstVariablesTreatments, values) Case "tblFollowUpQs" values = Split(txtSearchValueFollowUpQs, ",") strSQL = strSQL + createSQL(lstVariablesFollowUpQs, values) End Select Next strSQL = Left(strSQL, Len(strSQL) - 5) Debug.Print (strSQL) Dim qdf As QueryDef Set qdf = CurrentDb.CreateQueryDef("qry" & txtQueryName, strSQL) DoCmd.OpenQuery qdf.Name End Sub Here's what the query returns: LastName FirstName ID Visit Line Georgia 1234567 0 Line Georgia 1234567 0 Line Georgia 1234567 0 Line Georgia 1234567 0 Doe Jane 0123456 0 Doe Jane 0123456 0 Doe Jane 0123456 0 Doe Jane 0123456 0 Here's a sample SQL that I've generated: SELECT * FROM tblQuestionnaires, tblPatientHistoryBaseline WHERE Visit = 0 AND LastName Like '*e*' I'm guessing its something wrong with my SQL but I cannot figure out what. Thanks! 'EDIT----------------- LastName is from tblPatientHistoryBaseline, Visit is from tblQuestionnaires A: You are not specifying how tblQuestionnaires is related to tblPatientHistoryBaseline? A proper JOIN would probably fix this: SELECT * FROM tblQuestionnaires AS q INNER JOIN tblPatientHistoryBaseline AS ph ON q.ID = ph.ID WHERE Visit = 0 AND LastName Like '*e*' I am not quite sure which table the fields are coming from in your select. The above query may still produce duplicates if there are multiple records in either table. If that is the case you could add the DISTINCT statement to the query and specify the field you need: SELECT DISTINCT LastName, FirstName, ph.ID, Visit FROM tblQuestionnaires AS q INNER JOIN tblPatientHistoryBaseline AS ph ON q.ID = ph.ID WHERE Visit = 0 AND LastName Like '*e*' EDIT: SELECT DISTINCT ph.ID, q.fieldname, ph.fieldname, t.fieldname, f.fieldname FROM tblQuestionnaires AS q INNER JOIN tblPatientHistoryBaseline AS ph ON q.ID = ph.ID INNER JOIN tblTreatments AS t ON t.ID = ph.ID INNER JOIN tblFollowUp AS f ON f.ID = ph.ID WHERE Visit = 0 AND LastName Like '*e*'
[ "unix.stackexchange", "0000447519.txt" ]
Q: Has anyone tried to write a shell that fixes errexit (`set -e`)? errexit (set -e) is often suggested as a way to make simple scripts more robust. However, it is generally regarded as a horrible trap by anyone who has seen how it behaves in more complex scripts, in particular with functions. And a very similar problem can be seen with subshells. Take the following example, adapted from https://stackoverflow.com/questions/29926013/exit-subshell-on-error ( set -o errexit false true ) && echo "OK" || echo "FAILED"; The trap here is that shells show "OK", and not "FAILED".[*] While the behaviour of set -e in specific cases has historically varied in unfortunate ways, shells available on a modern distribution claim to follow the POSIX shell standard, and testing showed the same behaviour ("OK") for all of the following: bash-4.4.19-2.fc28.x86_64 (Fedora) busybox-1.26.2-3.fc27.x86_64 (Fedora) dash 0.5.8-2.4 (Debian 9) zsh 5.3.1-4+b2 (Debian 9) posh 0.12.6+b1 (Debian 9) ksh 93u+20120801-3.1 (Debian 9). Question Is there any technical reason why you can't write a shell with similar features to POSIX sh, except that it prints FAILED for the above code? I hope that it would also change set -e so that top-level && expressions which return false are considered fatal. https://serverfault.com/a/847016/133475 And hopefully it would have some nicer idiom to use with grep. set -e # print matching lines, but it's not an error if there are no matches in the file ( set +e grep pattern file.txt RET=$? [[ $RET == 0 || $RET == 1 ]] || exit $RET ) I guess I also assume arithmetic statements (let builtin) would be redefined in some way that avoids implicitly coercing their numeric value to a true/false exit status. Is there an example of a shell which does any of this? I don't mind looking at something with a different syntax from Bourne. I'm interested in something which is compact, when writing short "glue" scripts, but which also has a compact strategy for detecting errors. I don't like using && as a statement separator, if it means accidentally omitting a statement separator will cause errors to be silently ignored. [*] EDIT. This is perhaps not a perfect example to use. Discussion suggests that a better example would be to move the set -o errexit above the subshell. AFAICT this is very similar to the test case (false; echo foo) || echo bar; echo \ $? from the table here, which says that it would show "foo" (and then "0") on the original Bourne shell and most of its descendents. The exceptions are "hist.ash" and bash 1.14.7. When you add set -e inside the subshell - (set -e; false; echo foo) || echo bar; echo \ $? - there are two additional exceptions, "SVR4 sh sun5.10" and dash-0.3.4. For the spirit of my question, I suppose having set -e inside the subshell was a distraction. My main interest is in an idiom where you use set -e at the top of the script, and it also applies to subshells (which is already the POSIX behaviour). Jörg Schilling suggests that the Bourne shell from original Unix would print "FAILED" for the example I used in this question, that he has ported this shell to POSIX as "osh" in schilytools, and that this result has been verified as of release 2018-06-11. Perhaps this is based on 1) set -e being inside the subshell and 2) "SVR4 sh sun5.10". "osh" is "based on the OpenSolaris sources and thus based on SVR4 and SVID3". Or perhaps there is some horrifying additional variance caused by adding && echo "OK" in between the subshell and || echo "FAILED". I don't think the schily shell answers my question. You could use subshells for functions (use ( in place of { to run the function in a subshell), and start every subshell with set -e. However, using subshells introduces the limitation that you cannot modify global variables. At least, I have yet to see anyone defend this as a general purpose coding style. A: The POSIX standard (c.f. -e) is clearer than the Bash manual about the errexit shell option. When this option is on, when any command fails (for any of the reasons listed in Consequences of Shell Errors or by returning an exit status greater than zero), the shell immediately shall exit, as if by executing the exit special built-in utility with no arguments, with the following exceptions: The failure of any individual command in a multi-command pipeline shall not cause the shell to exit. Only the failure of the pipeline itself shall be considered. The -e setting shall be ignored when executing the compound list following the while, until, if, or elif reserved word, a pipeline beginning with the ! reserved word, or any command of an AND-OR list other than the last. If the exit status of a compound command other than a subshell command was the result of a failure while -e was being ignored, then -e shall not apply to this command. This requirement applies to the shell environment and each subshell environment separately. For example, in: set -e; (false; echo one) | cat; echo two the false command causes the subshell to exit without executing echo one; however, echo two is executed because the exit status of the pipeline (false; echo one) | cat is zero. Clearly, the sample code is equivalent to the following pseudocode. ( LIST; ) && COMMAND || COMMAND The exit status of the list is zero because: the errexit shell option is ignored. the return status is the exit status of the last command specified in the list, here true. Therefore, the second part of the AND list is executed: echo "OK".
[ "meta.askubuntu", "0000017137.txt" ]
Q: Editor wars aside, can we use sudo nano when talking to non-experts? TL;DR: when posting a solution could you please standardize any editors to something that firstly comes with vanilla Ubuntu, and secondly, is simple to use, regardless of your personal preferences. I just installed Ubuntu 17.04 for my daughter. It couldn't connect to wifi during installation, so had to install via Ethernet, and after installation during troubleshooting I found this question, which turns out is an easy fix. Problem was, they chose gksu gedit to edit the file,which is no longer native to vanilla Ubuntu, with other problems involved for 64-bit OS A seasoned user may automatically replace gksu gedit with sudo vi without any thought,but I'm not one. I tried vi,gedit,etc; then had to google how to close vi. Laugh all you like. On the other hand, I approve of gedit as a suitably Windows user-level editor, but if it can't be elevated using sudo, it's no good either. A: We should absolutely not be recommending the use of gedit as root (through gksu or worse, sudo) to any user, professional or otherwise. See my answer here for reasoning, as well as a similar thread regarding the "dropping" of gksudo. Anything that requires the use of root is probably something that requires caution to be exercised. Therefore, it would be appropriate to add friction to the process. I would hope that new (and therefore inexperienced) users would be far more cautious when they're in the "spooky scary command line," mostly because it is scary. One wrong move causes an entire system to break in potentially fascinating ways. To that regard, nano is basically the friendliest text editor on the command line, and is more or less perfect for this sort of operation. After users get their feet wet and start to understand what's going on, they'll start reading sudo nano /path/to/file as "open /path/to/file as root in a terminal" and they'll choose their own editor appropriately. While sudoedit/sudo -e is a good tool, it's also giving the user a complicated choice of "what do any of these things mean, and what should I choose?" which would also add unnecessary overhead in questions that may not apply in all cases ("choose 1 to use this editor" - after first-run, this isn't a choice). In my opinion, it's best to just use sudo nano, user-experience be (intentionally) damned. Once the user has more knowledge of how Ubuntu works, they'll be comfortable enough to know that nano really means "insert your favorite editor here." A: sudoedit should be the preferred choice for command-line editors if you want to remain agnostic. That lets the user choose on first-run. The problem with this approach is it forces the user into a terminal. Many new users are deeply uncomfortable with something they perceive an archaic 80s technology. That's why so many of the answers suggest ramping gedit (which does ship with standard Ubuntu) up to root. And gksu gedit works here. $ dpkg -S $(which gksu) gksu: /usr/bin/gksu $ cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=17.04 DISTRIB_CODENAME=zesty DISTRIB_DESCRIPTION="Ubuntu 17.04" $ apt policy gksu gksu: Installed: 2.0.2-9ubuntu1 Candidate: 2.0.2-9ubuntu1 Version table: *** 2.0.2-9ubuntu1 500 500 http://gb.archive.ubuntu.com/ubuntu zesty/universe amd64 Packages 100 /var/lib/dpkg/status
[ "stackoverflow", "0020367794.txt" ]
Q: Difference between RACAble(), RACObserve() and RACBind() in Reactive Cocoa I'm new to Reactive Programming. I have gone through the documentation of Reactive Cocoa but couldn't realize the differences between RACAble(), RACObserve() and RACBind(). Please, help ,me in understanding the aspects by some example code snippets. I think the RACAble() is replaced with RACObserve() with some options/arguments. If I am not correct then please correct me in this regard. Is RACObserve() skip: similar to RACAble()? A: I think one big source of confusion here is that 3 months ago the ReactiveCocoa team released v2.0, which had quite a few breaking changes. This was a great release - and has some amazing features, but it does mean that much of the information you will find on the web is now out-dated. To your specific points: RACAble has been replaced with RACObserve RACBind has been replaced with RACChannelTo RACObserve is used to create a signal from an object and a keypath, in other words it allows you to take regular properties and 'lift' them into the ReactiveCocoa world. It is a handy replacement for KVO. RACChannelTo provides a mechanism for two-way binding. In other words you can keep two properties synchronised. A good example of this is if you want to have a property in your view controller, or some model class, bound to a property on a UIKit control. Another macro you will probably come across is RAC, this provides one-way binding. In other words it will set the value of the given property based on the latest value from a signal.
[ "stackoverflow", "0003313005.txt" ]
Q: How to put a UILabel ontop of a UIToolbar? I have a UILabel that shows a character count as the user types into a textfield. Currently it is sitting behind a translucent UIToolbar. I would like the UILabel to be ontop of the UIToolbar. How can I accomplish this? A: I would add it to the UIToolbar's items as a UIBarButtomItem. Instantiate it with [[UIBarButtonItem alloc] initWithCustomView:myLabel].
[ "stackoverflow", "0050592397.txt" ]
Q: fade animation on a slider not working (CSS3 and html5 only) I am a beginner in CSS3 and HTML5, and right now I'm trying to create a HTML5 and CSS3 website in order to code a PSD mock-up. The problem came once I started with the slider. Normally it should be a carousel slider with 2 images, a progress bar in the bottom and an animation to make it work in a loop. So, first I have created a main div with two other divs inside containing radio inputs, that way I could get the next and previous arrows working in order to pass from one slide to another. Then, in my css file, I've created the @keyframes with the opacity effect to proceed with the fade animation. Unfortunately this is not working as I thought, just the arrows but not the fade animation. Could someone help me and have a look at my code? I'll really appreciate it! HERE IS MY HTML5 CODE: @keyframes click{ 0%{ opacity:.4;} 100%{opacity:1;} } @keyframes fade{ 0% {opacity:1} 45% { opacity: 1} 50% { opacity: 0} 95% {opacity:0} 100% { opacity: 1} } @keyframes fade2{ 0% {opacity:0} 45% { opacity: 0} 50% { opacity: 1} 95% { opacity: 1 } 100% { opacity:0} } #i1, #i2{ display: none;} .slider{ width: 100%; height: 550px; margin: 20px auto; position: rela } #first, #second{ position: absolute; width: 100%; height: 100%; } .previous{ width: 35px; height: 70px; position: absolute; top:40%; left:0; background-color: rgba(70, 70, 70,0.6); border-radius: 0px 50px 50px 0px; } .next{ width: 35px; height: 70px; position: absolute; top:40%; right: 0; background-color: rgba(70, 70, 70,0.6); border-radius: 50px 0px 0px 50px; } .prev:hover, .next:hover{ transition: .3s; background-color: rgba(99, 99, 99, 1); } .fas.fa-chevron-left{ position: absolute; left : 0; top: 30%; margin-left: 5px; color: #fff; font-size: 30px; } .fas.fa-chevron-right{ position: absolute; right: 0; top: 30%; margin-right: 5px; color: white; font-size: 30px; } .slider div#first { background: url('img1.jpg') no-repeat center; background-size: cover; animation:fade 30000s infinite linear; -webkit-animation:fade 30000s infinite linear; } .slider div#second{ background: url('img2.jpg') no-repeat center; background-size: cover; animation: fade2 30000ms infinite linear; -webkit-animation: fade2 30000ms infinite linear; } .slide{z-index:-1;} #i1:checked ~ #first, #i2:checked ~ #second {z-index: 10; animation: click 1s ease-in-out;} <body> <div class="slider"> <input type="radio" id="i1" name="images" checked /> <input type="radio" id="i2" name="images" /> <div class="slide" id="first"> <h1>WEBAGENCY: L'AGANCE DE TOUS <br> VOS PROJETS !</h1> <p>Vous avez un projet ? La WebAgency vous aide à les realiser !</p> <label class="previous" for="i2"><i class="fas fa-chevron-left"></i></label> <label class="next" for="i2"><i class="fas fa-chevron-right"></i></label> </div> <div class="slide" id="second"> <label class="previous" for="i1"><i class="fas fa-chevron-left"></i></label> <label class="next" for="i1"><i class="fas fa-chevron-right"></i></label> </div> </div> </body> A: Unfortunately, I'm not sure if it's possible to combine: Progress in the bottom Working buttons on the sides Auto-advance Just using CSS/HTML. You need to store your state as radio buttons, but if you advance using a linear animation, what will happen if the user wants to go back? How do you synchronize the state? You CAN have both progress and working buttons. I have made an example based on your code on how to achieve that, with ability to add 2+ slides. .radio { display: none; } .slider { width: 100%; height: 175px; position: absolute; left: 0; top: 0; } .slider__slide { position: absolute; width: 100%; height: 100%; opacity: 0; pointer-events: none; transition: 1s opacity; } .slider__slide:nth-of-type(1) { background: IndianRed; } .slider__slide:nth-of-type(2) { background: Cornsilk; } .slider__slide:nth-of-type(3) { background: PaleTurquoise; } .button { width: 35px; height: 70px; position: absolute; top: 40%; background-color: rgba(70, 70, 70, 0.6); } .button--previous { left: 0; border-radius: 0px 50px 50px 0px; } .button--next { right: 0; border-radius: 50px 0px 0px 50px; } .button:hover { transition: 0.3s; background-color: rgba(99, 99, 99, 1); } .radio:nth-of-type(1):checked ~ .slider__slide:nth-of-type(1), .radio:nth-of-type(2):checked ~ .slider__slide:nth-of-type(2), .radio:nth-of-type(3):checked ~ .slider__slide:nth-of-type(3){ opacity: 1; pointer-events: auto; } .progress { margin: 0; padding: 0; position: absolute; top: 175px; left: 0; right: 0; text-align: center; list-style-type: none; } .progress__item { position: relative; display: inline-block; margin: 1px; border: 3px solid black; width: 16px; height: 16px; } .radio:nth-of-type(1):checked ~ .progress .progress__item:nth-of-type(1):before, .radio:nth-of-type(2):checked ~ .progress .progress__item:nth-of-type(2):before, .radio:nth-of-type(3):checked ~ .progress .progress__item:nth-of-type(3):before{ position: absolute; top: 2px; right: 2px; bottom: 2px; left: 2px; content: ''; background: black; } .fas.fa-chevron-left { position: absolute; left: 0; top: 30%; margin-left: 5px; color: #fff; font-size: 30px; } .fas.fa-chevron-right { position: absolute; right: 0; top: 30%; margin-right: 5px; color: white; font-size: 30px; } <body> <div class="slider"> <input id="i1" class="radio" name="images" type="radio" checked /> <input id="i2" class="radio" name="images" type="radio" /> <input id="i3" class="radio" name="images" type="radio" /> <div class="slider__slide"> <h1>FIRST SLIDE</h1> <p>First Subtitle</p> <label class="button button--previous" for="i3"><i class="fas fa-chevron-left"></i></label> <label class="button button--next" for="i2"><i class="fas fa-chevron-right"></i></label> </div> <div class="slider__slide"> <h1>SECOND SLIDE</h1> <p>Second Subtitle</p> <label class="button button--previous" for="i1"><i class="fas fa-chevron-left"></i></label> <label class="button button--next" for="i3"><i class="fas fa-chevron-right"></i></label> </div> <div class="slider__slide"> <h1>THIRD SLIDE</h1> <p>Third Subtitle</p> <label class="button button--previous" for="i2"><i class="fas fa-chevron-left"></i></label> <label class="button button--next" for="i1"><i class="fas fa-chevron-right"></i></label> </div> <div class="progress"> <label class="progress__item" for="i1"></label> <label class="progress__item" for="i2"></label> <label class="progress__item" for="i3"></label> </div> </div> </body>
[ "stackoverflow", "0012480564.txt" ]
Q: Android ActionbarSherlock Customization I'm working on a application that has a different appearance depending on the result of an API call. This call returns a set of data, also containing information about the appearance of the app. Since I get this information on the run, I cant edit styles.xml to design the ActionBarSherlock I'm using. What is was wondering, is there a way to customize the ActionBar solely from code? I mean more than the icon, title or background. But textcolors and menuitems and so on. A: do something like the following where actionbar is a layout with a bunch of buttons that you can restyle programatically //ActionBar Functions protected void initActionBar() { // Inflate the custom view for action bar View customNav = LayoutInflater.from(this).inflate(R.layout.actionbar, null); // Attach to the action bar getSupportActionBar().setCustomView(customNav); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); setActionBar(); }
[ "stackoverflow", "0010660167.txt" ]
Q: Creating a tree using json from a list/table Let’s say I have table/list like this n=3 in this case, but n can be as unlimited. groupid answerid1 answerid2 answerid(n) 1 3 6 8 1 3 6 9 1 4 7 2 5 and i want to create a parent/child tree json output like this using java.(I have been using GSON) { data: [ { groupid: 1, children: [ { answerid1: 1, children: [ { answerid2:3, children: [ { answerid3:6, children: [ {answerid4: 8}, {answerid4: 9} ] } }, { answerid2: 4, children: [ {answerid3:7} ] } ] }, { groupid1: 2, children: [ { answerid2: 5} ] } ] } what would be the code/steps to do so. i have looked through lots of tags but mostly people are printing the output and not recursively build a hashmap/ArrayList for GSON to parse adn write to API. one other point each id has other data associated with it that will have to be included in the json output. for instance instead of {groupid:1} would need to this {groupid:1, text=toyota}. any help is greatly appreciated as i am fairly new to java as i come from SAS background. I get data like this (just a matrix of list) Toyota, Gas, Compact, Corolla Toyota, Gas, Compact, Camry Toyota, Hybrid, Compact, Prius Honda, Gas, Compact, Civic If needed I can REFORMAT THE DATA into two tables parentId parText answerId 1 Toyota 1 1 Toyota 2 1 Toyota 3 2 Honda 4 answerId level answerTextid answerText 1 1 1 Gas 1 2 2 Compact 1 3 3 Corolla 2 1 1 Gas 2 2 2 Compact 2 3 4 Camry … Then I need to make it a tree(nested output like the JSON shows with parent/children - just like if you were creatign a file system directory) one other thign i would like to do is for each car have mileage as a varialbe ({answerid3:4, text=Corolla, mileage=38}. but also if i traverse up the tree give an average mile for the branch. Like say at branch Toyota, Gas, Compact the mileage would be avg(Camry, Corolla) the output is a little off, i am looking for something like this. if no children then no children arraylist, and attrbutes are part of one object (hashmap) {"data":[{"id":1,"children": [{"id": 2,"children": [{"id": 3 ,"children": [{"id": 4,"name":"Prius"}],"name":"Compact"}],"name":"Hybrid"}, {"id":5,"children": [{"id":3,"children": [{"id":7,"MPG":38, "name":"Corolla"}, {"id":8,"MPG":28,"name":"Camry"}],"name":"Compact"}],"name":"Gas"}],"name":"Toyota"}, {"id":9, "children": [{"id":10,"children": [{"id":3 ,"children": [{"id":11 ,"name":"Civic"}],"name":"Compact"}],"name":"Gas"}],"name":"Honda"}]} A: You should create classes to model your data, in the structure you require. You are basically wanting to build a hierarchical structure from some row based data, this is quite like an XML document, which might be an appropriate solution. But you got me hooked so I played about with what I had before and came up with this: public class Test { public static void main(String[] args) { // hierarchical data in a flattened list String[][] data = { {"Toyota", "Gas", "Compact", "Corolla"}, {"Toyota", "Gas", "Compact", "Camry"}, {"Toyota", "Hybrid", "Compact", "Prius"}, {"Honda", "Gas", "Compact", "Civic"} }; TreeManager treeManager = new TreeManager(); for(String[] row : data) { // build the path to our items in the tree List<String> path = new ArrayList<String>(); for(String item : row) { // add this item to our path path.add(item); // will add it unless an Item with this name already exists at this path treeManager.addData(treeManager, path); } } treeManager.getData(data[0]).putValue("MPG", 38); treeManager.getData(data[1]).putValue("MPG", 28); Gson gson = new Gson(); System.out.println(gson.toJson(treeManager)); } /** * This base class provides the hierarchical property of * an object that contains a Map of child objects of the same type. * It also has a field - Name * */ public static abstract class TreeItem implements Iterable<TreeItem>{ private Map<String, TreeItem> children; private String name; public TreeItem() { children = new HashMap<String, TreeItem>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public void addChild(String key, TreeItem data) { children.put(key, data); } public TreeItem getChild(String key) { return children.get(key); } public boolean hasChild(String key) { return children.containsKey(key); } @Override public Iterator<TreeItem> iterator() { return children.values().iterator(); } } /** * This is our special case, root node. It is a TreeItem in itself * but contains methods for building and retrieving items from our tree * */ public static class TreeManager extends TreeItem { /** * Will add an Item to the tree at the specified path with the value * equal to the last item in the path, unless that Item already exists */ public void addData(List<String> path) { addData(this, path); } private void addData(TreeItem parent, List<String> path) { // if we're at the end of the path - create a node String data = path.get(0); if(path.size() == 1) { // unless there is already a node with this name if(!parent.hasChild(data)) { Group group = new Group(); group.setName(data); parent.addChild(data, group); } } else { // pass the tail of this path down to the next level in the hierarchy addData(parent.getChild(data), path.subList(1, path.size())); } } public Group getData(String[] path) { return (Group) getData(this, Arrays.asList(path)); } public Group getData(List<String> path) { return (Group) getData(this, path); } private TreeItem getData(TreeItem parent, List<String> path) { if(parent == null || path.size() == 0) { throw new IllegalArgumentException("Invalid path specified in getData, remainder: " + Arrays.toString(path.toArray())); } String data = path.get(0); if(path.size() == 1) { return parent.getChild(data); } else { // pass the tail of this path down to the next level in the hierarchy return getData(parent.getChild(data), path.subList(1, path.size())); } } } public static class Group extends TreeItem { private Map<String, Object> properties; public Object getValue(Object key) { return properties.get(key); } public Object putValue(String key, Object value) { return properties.put(key, value); } public Group () { super(); properties = new HashMap<String, Object>(); } } } I think this meets most of the requirements you've mentioned so far, although I left out the averaging of the MPG values as an exercise for the reader (I've only got so much time...). This solution is very generic - you may want more concrete sub-classes that better describe your data model (like Manufacturer, Type, Model), as you will then be able to hang more useful methods off them (like calculating averages of fields in child objects) , and you wouldn't have to deal with the properties as a collection of Objects, but you then get more complicated code initialising your data structure from the list. Note - this is not production ready code, I've just provided it as an example of how you might go about modelling your data in Java. If you are new to not only Java but Object Orientated Programming then you should read up on the subject. The code I have written here is not perfect, I can already see ways it could be improved. Learning to write good quality object orientated code takes time and practice. Read up on Design Patterns and Code Smells .
[ "stackoverflow", "0001126169.txt" ]
Q: What causes EventMachine::ConnectionNotBound? I'm new to EventMachine, so I'm not sure what this means. I'm getting this exception: EventMachine::ConnectionNotBound recieved ConnectionUnbound for an unknown signature: ef93a97d4d6441cb80d30fe2313d7de73 The program is fairly complicated, so I can't really explain everything that might have led up to it. All I need is a pointer towards what to look for. The error doesn't seem to be documented (looking at http://eventmachine.rubyforge.org/). A: I have had this exception raised when some other unhandled exception was raised in the initialize method of a subclass of EventMachine::Connection. Check that the arity of your subclass initialize method is correct and that the initialize method is running without errors. A: Usually, those errors occur in initialize or post_init. The first thing you should do is add rescue inside your callbacks to find out what actually is causing that error. def initialize(*args) ... super rescue Exception ... end def post_init ... super rescue Exception ... end
[ "stackoverflow", "0009162423.txt" ]
Q: Why crash if I release the NSIndexSet parameter passed to insertSections:withRowAnimation: I've wrote some code to batch delete/insert sections and cells from/into a table view. But I encountered a problem I can't understand. My codes are as follow NSMutableArray *deleteIndexPaths = [[NSMutableArray alloc] initWithCapacity:1]; NSMutableArray *insertIndexPaths = [[NSMutableArray alloc] initWithCapacity:1]; NSIndexSet *insertSections = [[NSIndexSet alloc] initWithIndex:kDeleteSection]; NSArray *insertDeleteIndexPaths = [[NSArray alloc] initWithObjects:[NSIndexPath indexPathForRow:0 inSection:kDeleteSection], nil]; /// init deleteIndexPaths and insertIndexPaths [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationRight]; [self.tableView insertSections:insertSections withRowAnimation:UITableViewRowAnimationRight]; [self.tableView insertRowsAtIndexPaths:insertDeleteIndexPaths withRowAnimation:UITableViewRowAnimationRight]; [self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade]; [self.tableView endUpdates]; [insertSections release]; [deleteIndexPaths release]; //[insertSections release]; // If uncommented it, program will crash. [insertDeleteIndexPaths release]; As the comment on the code, if I uncomment the statement [insertSections release];, the program will crash. Why? I can't find the answer. A: Because you are releasing it twice: **[insertSections release];** [deleteIndexPaths release]; **//[insertSections release]; // If uncommented it, program will crash.**
[ "stackoverflow", "0005116421.txt" ]
Q: require_once :failed to open stream: no such file or directory I have this testing code in "PAGE A": <?php require_once('../mysite/php/classes/eventManager.php'); $x=new EventManager(); $y=$x->loadNumbers(); ?> "eventManager.php" has inside a require_once: <?php require_once('../includes/dbconn.inc'); class EventManager {...} ?> My folders structure is this: mysite/php/classes folder and includes folder If i test PAGE A in a browser i receive: Warning: require_once(../includes/dbconn.inc) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\mysite\php\classes\eventManager.php on line 3 Fatal error: require_once() [function.require]: Failed opening required '../includes/dbconn.inc' (include_path='.;C:\php5\pear') in C:\wamp\www\mysite\php\classes\eventManager.php on line 3 where is the error? Thanks Luca A: You will need to link to the file relative to the file that includes eventManager.php (Page A) Change your code from require_once('../includes/dbconn.inc'); To require_once('../mysite/php/includes/dbconn.inc'); A: The error pretty much explains what the problem is: you are trying to include a file that is not there. Try to use the full path to the file, using realpath(), and use dirname(__FILE__) to get your current directory: require_once(realpath(dirname(__FILE__) . '/../includes/dbconn.inc')); A: this will work as well require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/mysite/php/includes/dbconn.inc');
[ "math.stackexchange", "0002091867.txt" ]
Q: Quasi-newton methods: Understanding DFP updating formula In Nocedal/Wright Numerical Optimization book at pages 138-139 the approximate Hessian $B_k$ update for the quasi-Newton method: (DFP method) $$B_{k+1} = \left(I-\frac{y_ks_k^T}{y_k^Ts_k}\right)B_k\left(I-\frac{s_ky_k^T}{y_k^Ts_k}\right)+ \frac{y_ky_k^T}{y_k^Ts_k}\tag{1}$$ is explained as the solution to the problem: $$\min_B\|B-B_k\|_{F,W} \\ \text{subject to}~B=B^T,~Bs_k=y_k \tag{2}$$ for which $\|A\|_{F,W}$ is the weighted Frobenius norm : $$\|A\|_{F,W} = \|W^{1/2}AW^{1/2}\|_F$$ for $W$ being any symmetric matrix satisfying the relation $Wy_k=s_k$ How can I prove that $B_{k+1}$ given by equation (1) is the solution to the problem (2)? A: This answer goes basically along the lines of my answer about BFGS update. Introduce the short notations $$ \min\|\underbrace{W^{1/2}B_kW^{1/2}}_{\hat B_k}-\underbrace{W^{1/2}BW^{1/2}}_{\hat B}\|_F $$ \begin{align} Wy_k=s_k\quad&\Leftrightarrow\quad \underbrace{\color{red}{W^{-1/2}}Wy_k}_{\hat y_k}=\underbrace{\color{red}{W^{-1/2}}s_k}_{\hat s_k}\quad\Leftrightarrow\quad \hat y_k=\hat s_k,\tag{1}\\ Bs_k=y_k\quad&\Leftrightarrow\quad \underbrace{\color{blue}{W^{1/2}}B\color{red}{W^{1/2}}}_{\hat B}\underbrace{\color{red}{W^{-1/2}}s_k}_{\hat s_k}=\underbrace{\color{blue}{W^{1/2}}y_k}_{\hat y_k}\quad\Leftrightarrow\quad \hat B\hat s_k=\hat y_k.\tag{2} \end{align} Then the problem becomes $$ \min\|\hat B_k-\hat B\|_F\quad\text{subject to }\hat B\hat s_k=\hat s_k. $$ The optimization variable $\hat B$ has the given eigenvector with the given eigenvalue, hence, it is convenient to introduce the new orthonormal basis $$ U=[u\ |\ u_\bot] $$ where $u$ is the normalized eigenvector $\hat s_k$, i.e. $$ u=\frac{\hat s_k}{\|\hat s_k\|}\tag{3}, $$ and $u_\bot$ is any orthonormal complement to $u$. Then $u^T\hat Bu=u^Tu=1$ and $u_\bot^T\hat Bu=u_\bot^Tu=0$, and the operator matrices in the new basis take the form \begin{align} U^T\hat B_kU-U^T\hat BU&=\begin{bmatrix}u^T\\ u_\bot^T\end{bmatrix}\hat B_k\begin{bmatrix}u & u_\bot\end{bmatrix}-\begin{bmatrix}u^T\\ u_\bot^T\end{bmatrix}\hat B\begin{bmatrix}u & u_\bot\end{bmatrix}=\\ &=\begin{bmatrix}\color{blue}{u^T\hat B_ku} & \color{blue}{u^T\hat B_ku_\bot}\\\color{blue}{u_\bot^T\hat B_ku} & \color{red}{u_\bot^T\hat B_ku_\bot}\end{bmatrix}-\begin{bmatrix}\color{blue}{1} & \color{blue}{0}\\\color{blue}{0} & \color{red}{u_\bot^T\hat Bu_\bot}\end{bmatrix}. \end{align} Since the Frobenius norm is unitary invariant (as it depends on the singular values only) we have \begin{align} \|\hat B_k-\hat B\|_F^2&=\|U^T(\hat B_k-\hat B)U\|_F^2= \left\|\begin{bmatrix}\color{blue}{u^T\hat B_ku-1} & \color{blue}{u^T\hat B_ku_\bot}\\\color{blue}{u_\bot^T\hat B_ku} & \color{red}{u_\bot^T\hat B_ku_\bot-u_\bot^T\hat Bu_\bot}\end{bmatrix}\right\|_F^2=\\ &=\color{blue}{(u^T\hat B_ku-1)^2+\|u^T\hat B_ku_\bot\|_F^2+\|u_\bot^T\hat B_ku\|_F^2}+\color{red}{\|u_\bot^T\hat B_ku_\bot-u_\bot^T\hat Bu_\bot\|_F^2} \end{align} The blue part cannot be affected by optimization, and to minimize the Frobenius norm, it is clear that we should make the red part zero, that is, the optimal solution satisfies $$ \color{red}{u_\bot^T\hat Bu_\bot}=\color{red}{u_\bot^T\hat B_ku_\bot}. $$ It gives the optimal solution to be \begin{align} \hat B&=U\begin{bmatrix}\color{blue}1 & \color{blue}0\\\color{blue}0 & \color{red}{u_\bot^T\hat B_ku_\bot}\end{bmatrix}U^T=\begin{bmatrix}u & u_\bot\end{bmatrix}\begin{bmatrix}1 & 0\\0 & u_\bot^T\hat B_ku_\bot\end{bmatrix}\begin{bmatrix}u^T \\ u_\bot^T\end{bmatrix}=uu^T+u_\bot u_\bot^T\hat B_ku_\bot u_\bot^T=\\ &=uu^T+(I-uu^T)\hat B_k(I-uu^T) \end{align} where we used the following representation for the projection operator to the complement of $u$ $$ I=UU^T=\begin{bmatrix}u & u_\bot\end{bmatrix}\begin{bmatrix}u^T \\ u_\bot^T\end{bmatrix}=uu^T+u_\bot u_\bot^T\quad\Leftrightarrow\quad u_\bot u_\bot^T=I-uu^T. $$ Changing variables back to the original ones is straightforward via (1), (2), (3) $$ B=W^{-1/2}\hat BW^{-1/2}=W^{-1/2}uu^TW^{-1/2}+(I-W^{-1/2}uu^TW^{1/2})B_k(I-W^{1/2}uu^TW^{-1/2}) $$ where \begin{align} \|\hat s_k\|^2&=\hat s_k^T\hat s_k=\hat y_k^T\hat s_k=y_k^Ts_k,\\ uu^T&=\frac{\hat s_k^T\hat s_k}{\|\hat s_k\|^2}=\frac{\hat y_k\hat y_k^T}{y_k^Ts_k}=W^{1/2}\frac{y_ky_k^T}{y_k^Ts_k}W^{1/2},\\ W^{-1/2}uu^TW^{-1/2}&=\frac{y_ky_k^T}{y_k^Ts_k},\\ W^{1/2}uu^TW^{-1/2}&=\frac{Wy_ky_k^T}{y_k^Ts_k}=\frac{s_ky_k^T}{y_k^Ts_k}. \end{align}
[ "stackoverflow", "0017695198.txt" ]
Q: Differences between constructor syntax and assignment syntax for primitive type initialisation Reading some code written by a coworker I stumbled on the use of constructor syntax to initialize a primitive type variable. Ie something like below: #include <iostream> int main() { using namespace std; // initialized using assignement syntax (copy initialisation) int titi = 20; cout << "titi=" << titi << "\n"; // got 20 in titi, it works // initialized using constructor syntax (direct initialization) int toto(10); cout << "toto=" << toto << "\n"; // got 10 in toto, it works } My natural tendency would be to stick with the assignement syntax, as it is the historical one and it's a no brainer, and there is obvious compatibility issues (consructor syntax won't qualify as valid C). Still I wonder if there is any other non obvious difference between the two syntax ? If they are actually meaning the same thing ? And what are the pros and cons of one or the other form considering for instance future maintenance/code evolution issues or readability issues ? A: For simple types such as int, there is no difference. For class types, what you call "constructor syntax" is known as direct initialization, and what you call "assignment syntax" as copy initialization. You cannot use copy initialization unless the class supports copy, so the tendency is to prefer direct initialization (with the caveat that then one must worry about the most vexing parse problem). Some people then argue in favor of the direct initialization syntax everywhere, on grounds of homogeneity: use the same format everywhere.
[ "serverfault", "0000894072.txt" ]
Q: SQLPlus: Execute SQL scripts located on database server machine Is there a possibility to execute an SQL script that is located on the database server using SQLPlus? For example, if I execute @@?/rdbms/admin/awrrpti.sql the SQL file located on the client machine is used (if existent). Can I tell SQLPlus to look the script up on the server itself (without SSHing into the remote machine)? A: Short answer: no, you cannot. sqlplus is a client application, it has no way to access the server's filesystem.
[ "stackoverflow", "0058582588.txt" ]
Q: How to remove rows with non-integer values from pandas series of dtype object? A dataframe based on a survey about candy has a column for the survey taker's age. Currently, the dtype of this column is object. Some of the values in this column are integers, some are strings (ex. 50+, too old for this). How to delete rows that have strings? Most solutions I've tried haven't worked or only apply to entire dataframes. As shown in the code below, I've tried using inequalities, converting the column to int and removing null values, and keeping only rows with values that are in a certain subset. df = df[(df['Age'] >= 3) & (df['Age'] <= 100)] df = df[pd.to_numeric(df.Age, errors='coerce').notnull()] df = df.dropna(subset = ['Age']) df = df.convert_objects(convert_numeric=True).dropna() a=[] for i in range(2,101): a.append(i) df = df[~df.Age.isin(a)] I usually get "'>=' not supported between instances of 'str' and 'int'" or an unchanged dataframe. A: Try this: mport pandas as pd df=pd.DataFrame({"age": ["45", "50+", "34 ", "34 years", "too old"], "xyz":[1,4,7,3,6]}) print(df) df.drop(df.index[df["age"].apply(lambda x: not (x.strip().isnumeric()))], axis=0, inplace=True) print(df) Output: age xyz 0 45 1 1 50+ 4 2 34 7 3 34 years 3 4 too old 6 age xyz 0 45 1 2 34 7 [Program finished]
[ "stackoverflow", "0051770893.txt" ]
Q: Vue.js Why 2 objects are linked? I have two data objects called items and itemsOrg var vm = new Vue({ el: '#divVM', mixins: [mix], data: { items: [], itemsOrg:[], // .... }, When the page loads, I make an AJAX call to fetch data from MySQL table and assign it to items and itemsOrg object. function getMustacheVariables() { $.ajax({ type: "POST", url: "adminAjax.php", data: { actionID: 'GET_DATA', }, dataType: "json", success: function(data) { vm.items= data; vm.itemsOrg = data; } // ... However, when I update Vm.items, vm.itemsOrg is also automatically updated and don't know why these the two are linked. Here is a snapshot of console.log vm.items[0]["key"] "agent" vm.itemsOrg[0]["key"] "agent" vm.items[0]["key"] = "new_key" "new_key" vm.itemsOrg[0]["key"] "new_key" vm.itemsOrg[0]["key"] = "updated_key" "updated_key" vm.items[0]["key"] "updated_key" Is there a reason that these two objects are linked? I even tried assigning vm.items to vm.itemsOrg using vm.items.slice() as well as push() but the two objects are always linked. I appreciate any help. A: After playing with your example I noticed that we can simplify your AJAX fetched object as data = { 0: { key: 'agent'} and it has this property data[0] assigned to a reference of the object { key: 'agent'} (data can be called a nested object) So it seems that even if you're copying the data object with Object.assign you'll still have every referenced object in it. As said here : But be aware that this makes a shallow copy only. Nested objects are still copied as references. So you have two options that would work without JQuery: 1. Using JSON.parse and JSON.stringify like JSON.parse(JSON.stringify(data)) to stringify then parse your object 2. Making a loop to manually deep copy the object (as in the outdated answer of the thread referenced above) And if using JQuery you can write jQuery.extend(true ,{}, data) with the deep option set to true
[ "stackoverflow", "0002751250.txt" ]
Q: Which version of Python should be used? I'm starting a new Python web project. With most frameworks, everyone rushes to the latest version, however, it seems that this is not as true for Python 3.x. Which version of Python should brand new projects use? A: A lot of 3rd party Python modules still require Python 2.x (numpy, scipy for example). If you will use any of those, or if you don't yet know what modules you need and want to keep your options open then stick with Python 2.x for now. If you know that all the modules you need work with Python 3.x then go with that.
[ "askubuntu", "0001070984.txt" ]
Q: Cannot open terminal on Ubuntu 18.04 Recently I installed Ubuntu 18.04 and so far everything was great but yesterday it started to be weird. Issues I found so far: terminal won't open after reboot, but when I log out and then log in it works sound is not working (tried few things but still no luck) cannot open nautilus What I did before it started to act weirdly was that I have installed Chrome Remote Desktop and added google account to online accounts. I cannot figure out how to fix this and is it related to chrome remote desktop. I will appreciate any kind of help! A: Once you install the Chrome Remote Desktop, all the windows are opened in a virtual desktop/workspace (which you can connect to remotely). The audio is also routed to the same desktop/workspace. After logging out of the current session and logging back in, you assume control over the current active session and everything seems to work. If you want a quick solution to get your system working, just switch to a different virtual desktop (CtrlAltF4) and enter sudo apt-get autoremove chrome-remote-desktop after logging in to your account on the virtual desktop. To resume back on the gnome session, use CtrlAltF2. Alternatively, MDMower provided a great answer on configuring your Chrome Remote Desktop installation here: https://superuser.com/questions/778028/configuring-chrome-remote-desktop-with-ubuntu-gnome-14-04/#answer-850359
[ "stackoverflow", "0036398489.txt" ]
Q: MDX Query with parameters with multiples values and null value I work with a SSAS Cube and Datazen (dashboard creator). I've a data view (for the valueCode 'AZE') with 3 parameters: AgeClassCode: 'AGE01', 'AGE02', 'AGE03', ... StatutCode: 'A', 'B', 'C', 'D', ... NiveauCode: 'X', 'Y', 'W', ... With this query, when I use multiple values or just one value for each, it works. But I would like that the query returns all values for a parameter when the parameter's value is null. I've tested ISEMPTY(@param), ISEMPTY(STRTOSET(@param)), ... but that returns this error: An mdx expression was expected. An empty expression was specified. This query works for one or more values: SELECT NON EMPTY { [Measures].[Value], [Measures].[PreviousValueYear], [Measures].[PreviousValueReportMonth] } ON COLUMNS, NON EMPTY { NONEMPTY ( [EntiteFederal].[ServiceCode].[ServiceCode].ALLMEMBERS * [EntiteFederal].[EntiteCode].[EntiteCode].ALLMEMBERS * [ReportMonth].[ReportMonth].[ReportMonth].ALLMEMBERS * [T].[Year].[Year].ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( { [ValueType].[ValueCode].&[AZE] } ) ON COLUMNS FROM ( SELECT ( STRTOSET('{{ @AgeClassCode }}') ) ON COLUMNS FROM ( SELECT ( STRTOSET('{{ @NiveauCode }}') ) ON COLUMNS FROM ( SELECT ( (STRTOSET('{{ @StatutCode }}') ) ON COLUMNS FROM [MyCube] ) ) ) ) WHERE ( IIF( STRTOSET('{{ @StatutCode }}').Count = 1, STRTOSET('{{ @StatutCode }}'), [Statut].[StatutCode].currentmember ), IIF( STRTOSET('{{ @NiveauCode }}').Count = 1, STRTOSET('{{ @NiveauCode }}'), [Niveau].[NiveauCode].currentmember ), IIF( STRTOSET('{{ @AgeClassCode }}').Count = 1, STRTOSET('{{ @AgeClassCode }}'), [AgeClass].[AgeClassCode].currentmember ), [ValueType].[ValueCode].&[AZE] ) What do I have to change? EDIT: To test the strtoset() , the good solution is the isError() A: When using strToSet or strToMember you need to supply a string that represents valid mdx so for example these are ok: strToSet("[AgeClassCode].[AgeClassCode].members") strToMember("[AgeClassCode].[AgeClassCode].[AGE01]") This isn't valid as NULL isn't a string, or something that represents mdx: strToSet(NULL) So if in your client you'd like NULL to represent all members then somehow you need to transform the NULL to a string "[AgeClassCode].[AgeClassCode].members" before it hits strToSet.
[ "stackoverflow", "0007217802.txt" ]
Q: JW Player load HD plugin locally I've been trying to get the HD plugin to load locally using the jw embedder code. I know you need to use the full URL for local plugins but I can't get the parameters to work. Also do you need the hd.js file loaded as well? Does some one have an example they can share of this in action? This does not work. plugins: {hd:"http://www.mysite.com/swf/files/hd.swf" { file:"http://www.mysites.com/vid/file.mp4", fullscreen: false,state: true }, }, A: You are doing it the wrong way, here is how to do it. You don't need to specify "hd: <the url>", just the url is enough if you want to serve the file locally. plugins: { "http://www.example.com/swf/files/hd.swf": { file: "http://www.example.com/vid/file.mp4", fullscreen: false, state: true } }
[ "math.stackexchange", "0000746857.txt" ]
Q: Find the probability that you have three of a kind after you pick 5 cards from a regular 52-card deck. How would I go about finding this? I was thinking that, since this is a permutation, you would have 52!/(52-5!)? But how would that account for 3 of a kind? A: There are $\binom{52}{5}$ five-card hands. They are all equally likely. We now count the favourables, the three of a kind hands. The kind we have $3$ of can be chosen in $\binom{13}{1}$ ways. For each of these choices, there are $\binom{4}{3}$ ways to choose the actual $3$ cards. Now we must count the number of ways to choose the "useless" cards. The two different kinds that we have one each of can be chosen in $\binom{12}{2}$ ways. For each of these ways, the actual cards of the chosen kinds can be chosen in $\binom{4}{1}\binom{4}{1}$ ways. Thus the number of favourables is $\binom{13}{1}\binom{4}{3}\binom{12}{2}\binom{4}{1}\binom{4}{1}$. For the probability, divide by $\binom{52}{5}$. Remark: The following is an alternate approach to count the number of ways to choose the useless cards. There are $\binom{48}{2}$ ways to choose $2$ cards from the $48$ cards that are not of the kind we have $3$ of. But some of these choices give us $2$ of the same kind, giving us a full house, a very good hand. So we must subtract the number of ways in which we get $2$ of a kind. The kind can be chosen in $\binom{12}{1}$ ways, and the actual cards in $\binom{4}{2}$ ways. So the number of ways to choose the useless cards is $\binom{48}{2}-\binom{12}{1}\binom{4}{2}$.
[ "worldbuilding.stackexchange", "0000011842.txt" ]
Q: How do I explain that crystals/gems and precious metals are magical Within my setting, there are magical items. These magical items are created by affixing runes onto them. These rune are drawn with metal thread from various precious metals: copper, silver, gold, platinum etc. The runes are then instructions for magic, with the precious metals having innately a lot of Mana in them. Here is where I need help. Right now, I justify the precious metals as being magical due to them having a generally similar properties. Be that as it may, feel free to include your own reasoning for precious metals being magical. However, I really want there to be magical crystals/gemstones. How should I then explain, in a way that is internally consistent, so that precious and expensive materials are highly magical? Notes: The method of drawing metals into thread and writing with them to form runes is entirely inspired by the Masterwork Dwarf Fortress mod. I want materials that are precious and expensive in real life, except petroleum, to be magical, not the other way around of random magical materials being expensive because it is magical. While the precious metals are used in the form of runes, I would imagine that the gemstones/crystals would be simply placed on it, and it is carved with the same runes as the metals are drawn, and then it is magical as well In other words, what do crystals, gemstones, and precious metals have in common? A: Since metals are operating in a different system than gems, out makes sense to say they contain different mechanics. When you talked about weaving runes with metal, the first thing that sprung to mind was electrical circuitry. Metal runes are basically inscribed circuits that provide magical integrated hardware! Gold, silver, and platinum are just the best magical semiconductors... Gems are a little trickier. According to your post, they get inscribed but not inlaid. There are many gemstones and crystals that are semiprecious or common that would presumably have no magical properties, like quartz, salt, and amethyst. So it can't be pure crystalline structure. What else? Well, all precious stones form under deep heat and pressure, mostly volcanic conditions. The earth's core is a massive magical source, and the deeper down a gem is formed, the more ambient magic is absorbed into its crystalline structure! Surface formations like salt and geodes would have little inherent magic. Precious veined metals (rather than ores) are too amorphous to retain magic in their lodes, but are still attuned to magic which is how they can be woven into runes. These runes create effects by drawing magic from the ambient surroundings: the more magical the area, the more powerful the spell. Precious gems work in the opposite manner: they are magical super capacitors and generators. Carving a rune into them allows you to control the external flow if magic. The larger the gem and the more flawless the crystalline structure, the more magical capacity the gem has and the more powerful it is. So you have two complementing methods: woven metal runes generate magic from channeling external energies, precious gems from internal energies trapped during crystal formation further down toward the magical core of the planet. Update: With this system, you can have a REALLY crafty crafter who inscribes gems with runes and then weaves metallic runes AROUND them - the gold concentrating the magic of the gem even further! Perhaps by focusing the magical energies into coherence this creates a "magical laser?" Might it cause a feedback loop and result in a huge explosion? There are all sorts of ways to go with this one, though I pity the poor sod who's the first to try it out... They'll probably spend months scraping him off the walls... A: The key is Patterns. All crystals and gemstones have repeated geometric patterns as part of their internal structure. You can decide that that structure is necessary or enhances magic. As a side effect, a more valuable crystal/gemstone means a better, more repeated pattern with fewer flaws. So you can justify more expensive stones being better for magic. Precious metals are trickier. It is possible to put patterns into metal with repeated smithing - that's part of what makes forged objects stronger - but there's no obvious reason why gold would be better than say, bronze or iron for that purpose. There are a few things you could use, but they're a bit weaker: Affinities - you could say that certain metals associate with different types of magic for Reasons. Say gold with fire, silver with darkness, etc - you get the idea. Numerology - do some pseudoscience with the periodic table and figure out some special associations with the atomic number of the precious metals that common ones don't share. Then you can decide that that makes them special. Shared Magic - maybe each metal on the planet has a total amount of magic, shared between all parts of that metal. Let's call this 1 Big Magic Unit (BMU). So all the gold on the planet = 1 BMU = all the iron on the planet in terms of magical potential. But because there's say, only 1/4th as much gold, that means each ounce of gold has 4 times more magic than each ounce of iron. Edit: I realize now that you already have something for precious metals, but figure I'll leave the second section in since it doesn't hurt anything.
[ "stackoverflow", "0058526630.txt" ]
Q: Volley Library giving error 500 on post request I have the following code that I am using to save data into a mysql database; private void save(final String orderId, final String client, final String name, final String Seller, final String amount, final String quantity, final double longi, final double lat, final String location, final ProgressDialog progressDialog) { String URL_ORDER = "https://foodfuzz.co.ke/foodfuzzbackend/market/orders/order.php"; StringRequest orderStringRequest = new StringRequest(Request.Method.POST, URL_ORDER, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject orderObject = new JSONObject(response); String orderSuccess = orderObject.getString("success"); if(orderSuccess.equals("1")){ Toast.makeText(CheckOutActivity.this,"Order Placed Successfully " , Toast.LENGTH_SHORT).show(); pay.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); progressDialog.dismiss(); Toast.makeText(CheckOutActivity.this,"Unable to place order " + e.toString(), Toast.LENGTH_SHORT).show(); pay.setEnabled(true); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(CheckOutActivity.this,"Error placing order " + error.toString(), Toast.LENGTH_SHORT).show(); pay.setEnabled(true); } }){ protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("orderId",orderId); params.put("name", name); params.put("client", client); params.put("seller", Seller); params.put("amount", amount); params.put("quantity",quantity); params.put("longitude",String.valueOf(longi)); params.put("latitude",String.valueOf(lat)); params.put("location",location); return params; } }; RequestQueue orderRequestQueue = Volley.newRequestQueue(this); orderRequestQueue.add(orderStringRequest); } My problem is that I get the error code 500 when I make a post request. The following is the actual error logged on logcat BasicNetwork.performRequest: Unexpected response code 500 for https://foodfuzz.co.ke/foodfuzzbackend/market/orders/order.php This is the php code that is on the server at the stated url <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { require_once '../db/connector.php'; $orderId = mysqli_real_escape_string($conn, $_POST['orderId']); $client = mysqli_real_escape_string($conn, $_POST['client']); $product = mysqli_real_escape_string($conn, $_POST['name']); $seller = mysqli_real_escape_string($conn, $_POST['seller']); $amount = mysqli_real_escape_string($conn, $_POST['amount']); $quantity = mysqli_real_escape_string($conn, $_POST['quantity']); $longi = mysqli_real_escape_string($conn, $_POST['longitude']); $lati = mysqli_real_escape_string($conn, $_POST['latitude']); $loc = mysqli_real_escape_string($conn, $_post['location']); $status = 1; $sql = "INSERT INTO tbl_orders (orderid, client, product, seller, amount, quantity, longitude, latitude, deliveryloc, status) VALUES ('$orderId', '$client', '$product', '$seller', '$amount', '$quantity', '$longi', '$lati', '$loc', '$status')"; if (mysqli_query($conn, $sql)) { $result["success"] = "1"; $result["message"] = "success"; echo json_encode($result); mysqli_close($conn); } else { $result["success"] = "0"; $result["message"] = "error"; echo json_encode($result); mysqli_close($conn); } } The code works on postman without any error. What could I be doing wrong A: This error is normally caused by errors in your code, first it is good to check if your php script is error free and the other codes as well. In my case the post data was not matching the table columns.
[ "serverfault", "0000143605.txt" ]
Q: Encrypt uploaded pdf files with mcrypt and php I'm currently set up with a CentOS box that utilizes mcrypt to encrypt/decrypt data to/from the database. In my haste, I forgot that I also need a solution to encrypt files (primarily pdf, with a xls and txt file here and there). Is there a way to utilize mcrypt to encrypt uploaded pdf files? I understand the possibility of file_get_contents() with txt; is a similar solution available for other formats? Thanks! A: I know this question has an accepted answer but the cleanest way to do this would be to use an encryption stream filter. The page on the PHP manual has full details so I won't duplicate any code here but it seems to be the simplest way of achieving this. You attach a stream filter to the file handle resource and data is transparently encrypted or decrypted as it is read from or written to the file. Best of all this uses the mcrypt library to do all of this.
[ "stats.stackexchange", "0000028041.txt" ]
Q: Pros/cons of estimating parameters for missing observations? Some people are playing a game online. Every time a person plays, a new game board is generated randomly. On generation of a new board, the player can also choose a special weapon. (The choice of weapon does not affect the board generation.) Over time, observed data are like this: player weapon win 3 5 0 # player 3 used weapon 5 and lost 4 2 1 # player 4 used weapon 2 and won 8 1 1 # player 8 used no weapon and won To find out if some players are better with some weapons, and others with other weapons, I've modeled this as a Bayesian logistic regression: $logit(Pr(Win=1)) = \alpha_{p,w}$ $\alpha_{p,w} \sim N(\mu_{w},\sigma^2)$ So, $\mu_w$ is the effect of weapon $w$ across all players, and $\alpha_{p,w}$ is the effect of player $p$ with weapon $w$. Because this is a Bayesian model, the prior for $\alpha_{p,w}$ is $\mu_w$, so in theory, I can estimate $\alpha_{p,w}$ for all combinations of $p$ and $w$ even if some players never use some weapons. (JAGS will do this with nested for loops over players and weapons, for example.) But is that a bad idea? Also, is there a special name for this kind of model? P.S. Please edit the title and tags if you can make it clearer. A: No, it is not a bad idea. However, when you look at the posterior distributions for $\alpha_{p,w}$ you will see you haven't learned all that much about those $p,w$ combinations for which you have no data; they'll still be centered at 0, with a spread that's determined largely by the $p,w$ combinations for which you do have data (and the rest by your prior). You will have learned how spread out they might be, however, which may be good enough for your purposes. I'd suggest a reformulation of your model to include a player effect: $\text{logit} (\text{P}(\text{Win})) = \mu_0 + \alpha_p + \gamma_w + \delta_{p,w}$ where $\mathbb{E}\alpha_p = \mathbb{E}\gamma_w = \mathbb{E}\delta_{p,w} = 0$ in your priors. $\gamma_w$ is the weapon effect and $\delta_{p,w}$ is the player-weapon interaction. This would be called something like a two-factor logistic model with an interaction term.
[ "stackoverflow", "0038903043.txt" ]
Q: How to trigger an event only when the user ctrl click the lower half of a button? I want to implement some secret features in my application and they can only be invoked by ctrl left click the lower half of a button. Is this possible to implement in WPF? I tried to create a demo app and debugging doesn't show me the cursor position information in the click event handler. Below is my test code. Any ideas? <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="255.284" Width="313.918"> <Grid> <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="81,89,0,0" VerticalAlignment="Top" Width="158" Height="49" Click="button_Click"/> </Grid> </Window> using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { // <----- set break point here, can't find cursor info in e and sender } } } A: You can use the MouseUp or MouseDown events, which both give you the mouse position in the event arguments, as well as which mouse button was pressed. Mouse up is triggered when the mouse button is lifted while inside the button, while mouse down (can you guess?) when it's pressed down while inside the button. EDIT : I just checked the details for MouseDown and you'll have to use Point p = e.GetPosition(yourButton); to get the position of the mouse relative to the button (you can replace yourButton by any control to get the mouse position relative to it)
[ "stackoverflow", "0016815328.txt" ]
Q: Invalid attempt to read when no data is present error I have a function whose sole purpose is to fetch some data when a button is pressed and it's called multiple times. This is the function code: Function GetData2(ByVal clientNo As Integer) As List(Of SocioInfo) Dim theResults2 = New List(Of SocioInfo) Dim connStr = "Data Source=localhost;Initial Catalog=testdb;Integrated Security=True;MultipleActiveResultSets=true" Using conn = New SqlConnection(connStr) Dim sql = "SELECT [FirstName], [LastName] FROM [CustInfo] Where ([NumCuenta] = @SocioNum)" Dim sql2 = "SELECT [AcctName], [AcctNum], [NewAcct], [Balance] From [ACCT_NEW] Where ([AcctNum] = @SocioNum)" Dim sqlCmd = New SqlCommand(sql, conn) Dim sqlCmd2 = New SqlCommand(sql2, conn) sqlCmd.Parameters.AddWithValue("@SocioNum", CDbl(txtInput.Text)) sqlCmd2.Parameters.AddWithValue("@SocioNum", CDbl(txtInput.Text)) conn.Open() Dim rdr = sqlCmd.ExecuteReader Dim rdr2 = sqlCmd2.ExecuteReader While rdr.Read theResults2.Add(New SocioInfo With { .Nombre = rdr.GetString(0), .LastName = rdr.GetString(1) }) End While While rdr2.Read theResults2.Add(New SocioInfo With { .CuentaName = rdr.GetString(0), .AcctNum = rdr.GetValue(1), .AcctFull = rdr2.GetValue(2), .Balance = rdr2.GetValue(3) }) End While End Using Return theResults2 End Function I am not 100% sure if this is the best way to do this (basically need to get data from two different tables). Thing is, while Rdr shows me no error, Rdr2 just blows in the face. The exception is this: Invalid attempt to read when no data is present. A: In the second loop you are trying to use the first SqlDataReader but this is not possible because the first loop has already reached the end of the input data. If you need joined data between the two tables a better approach is to use just one query using the JOIN operator. This query works assuming that each customer in the CustInfo table has one account in the ACCT_NEW table Dim sql = "SELECT c.FirstName, c.LastName, a.AcctName, a.AcctNum, a.NewAcct, a.Balance " & _ "FROM CustInfo c INNER JOIN ACCT_NEW a ON a.AcctNum = c.NumCuenta " & _ "WHERE NumCuenta = @SocioNum " Using conn = New SqlConnection(connStr) Dim sqlCmd = New SqlCommand(sql, conn) sqlCmd.Parameters.AddWithValue("@SocioNum", CDbl(txtInput.Text)) conn.Open() Dim rdr = sqlCmd.ExecuteReader While rdr.Read theResults2.Add(New SocioInfo With { .Nombre = rdr.GetString(0), .LastName = rdr.GetString(1) .CuentaName = rdr.GetString(2), .AcctNum = rdr.GetValue(3), .AcctFull = rdr.GetValue(4), .Balance = rdr.GetValue(5) }) End While End Using
[ "stackoverflow", "0015582648.txt" ]
Q: Custom site search by category I want to create a simple search for a site that I'm working on. I have items in my db that all hold a specific category id and can optionally be linked to multiple tags. I would like to take whatever search terms come in and query the category.name and tag.name fields to find the items that match those terms. I'm looking for advice on how to create an efficient/quick query that does this AND orders the results by the items that match closest(most matches) Here's a quick version of my relevant tables: item id | category | title | description category id | name | parentId tag id | name | uses item_tag itemId | tagId A: I still didn't entirely understand what you want. Well, here's a first version for us to discuss. I suggest you to create a view as the following: CREATE OR REPLACE VIEW `search_view` AS SELECT i.id AS `item_id`, i.title AS `item_title`, c.id AS `cat_id`, c.name AS `cat_name`, t.id AS `tag_id`, t.name AS `tag_name` FROM item AS i LEFT OUTER JOIN item_tag AS it ON (i.id = it.itemId) LEFT OUTER JOIN tag AS t ON (it.tagId = t.id) LEFT OUTER JOIN category AS c ON (i.category = c.id) WHERE ((t.id IS NOT NULL) OR (c.id IS NOT NULL)); And then you query from the view using something near SELECT *, ( IF(tag_name like ?, 2, 0) + IF(cat_name like ?, 4, 0) + IF(item_title like ?, 1, 0) ) AS `priority` FROM search_view GROUP BY item_id ORDER BY SUM(priority); No tests in the code above. Report any problems you have [first edition] You use PHP, don't you? Well, you can normalize your queries using PHP string functions; one way is to replace every occurrence of ',' by '|', remove extra spaces and perform the following query: [I'll give an example using @VAR (actually you'll replace it with your input string)] SET @VAR = 'notebook|samsung'; SELECT *, ( IF (tag_name REGEXP CONCAT('.*(', @VAR, ').*'), 2, 0) + IF (cat_name REGEXP CONCAT('.*(', @VAR, ').*'), 4, 0) + IF (item_title REGEXP CONCAT('.*(', @VAR, ').*'), 1, 0) ) AS `priority` FROM search_view ORDER BY priority DESC; This time I tested. Yes, you can use MySQL functions, something about REPLACE(REPLACE(@VAR,' ',''), ',', '|'). But I recommend you to do it in PHP (or java, python etc).
[ "stackoverflow", "0006518012.txt" ]
Q: Why does TObjectList.Clear not free objects? I just noticed that var ObjList : TObjectList <TMyObject>; ... ObjList := TObjectList <TMyObject>.Create (True); ObjList.Add (TMyObject.Create); ObjList.Clear; does not free the object. Looking at the source code it seems that no cnRemoved notification is triggered in Clear (inherited from TList <T>). My question: Is this intentional? Is there any reason why one does not want to get these notifications in the case of Clear? Or can this be considered as a bug in the collection classes? EDIT Turns out that a I put the line inherited Create; on the top of TMyObject destructor, which was supposed to go into the constructor. This is why I got memory leaks reported that looked like the TObjectList was not freeing the items. And a look at the source convinced me (I was trapped by the Count property). Thanks for your help anyway! A: The list frees owned objects when you call .Clear. You've got a testing error. The code sample below, written on Delphi XE, displays this: Calling CLEAR Object deleted. Object deleted. After CLEAR. Press ENTER to free L and Exit. The code in TList<T>.Clear is deceiving, because Count is actually a property. Look at SetCount(), then look at DeleteRange() and you'll see the code for Notify(oldItems[i], cnRemoved) at the end of the DeleteRange procedure. program Project3; {$APPTYPE CONSOLE} uses SysUtils, Generics.Collections; type TDelObject = class public destructor Destroy;override; end; { TDelObject } destructor TDelObject.Destroy; begin WriteLn('Object deleted.'); inherited; end; var L:TObjectList<TDelObject>; begin L := TObjectList<TDelObject>.Create(True); L.Add(TDelObject.Create); L.Add(TDelObject.Create); WriteLn('Calling CLEAR'); L.Clear; WriteLn('After CLEAR. Press ENTER to free L and Exit.'); Readln; L.Free; end. A: TList<T>.Clear calls DeleteRange to do the work. The last part of DeleteRange runs around all the items calling Notify passing cnRemoved. Your analysis of the code is thus incorrect. The cnRemoved notification is duly delivered and owned objects are freed.
[ "stackoverflow", "0038398772.txt" ]
Q: Specify Minimum Password Length in Django Version <= 1.8? Is it possible to enforce a minimum password length if you're using Django 1.8 or under when a user is changing their password? When a user creates their account in my website, I enforce a minimum password length using a custom validator in my signup form. However, when a user wants to change their password, I call Django's auth_views.password_change method which specifies the form and validation criteria used. # account/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ ... url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html'}, name='password_change'), ... ] Since I'm not validating their new password, users will be able to change it to one that doesn't meet my minimum length criteria. Is there any way to do this validation other than monkey-patching? This Stackover question discusses an approach that works, but it's for the situation where you're implementing authentication whereas I'm only allowing an authenticated user to change their existing password. I know Django 1.9 will provide this ability via an AUTH_PASSWORD_VALIDATORS setting but I won't have time to upgrade to 1.9 before my site goes live. A: You can customize the default PasswordChangeForm form and pass password_change_form extra options to view functions through url to point to your CustomPasswordChangeForm form rather the default one. from django.contrib.auth.forms import PasswordChangeForm class CustomPasswordChangeForm(PasswordChangeForm): """ A Custom PasswordChangeForm for minimum password length validation. """ def clean_new_password1(self): """ Validates that the new_password1. """ password = self.cleaned_data.get('new_password1') # Add your custom validation if len(password) < 8: raise ValidationError('Password too short') return password And change the url: from django.conf.urls import url from django.contrib.auth import views as auth_views from _where_ import CustomPasswordChangeForm #import the CustomPasswordChangeFormform urlpatterns = [ ... url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'password_change_form': CustomPasswordChangeForm}, name='password_change'), ... ]
[ "stackoverflow", "0026385100.txt" ]
Q: Rcpp map return I am trying to return a map from c++ to r. My code in c++ is the following (as found in https://github.com/RcppCore/Rcpp/blob/master/inst/unitTests/cpp/wrap.cpp): #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] IntegerVector map_string_int(){ std::map< std::string, int > m ; m["b"] = 100; m["a"] = 200; m["c"] = 300; return wrap(m); } My r code is the following: require(Rcpp) Rcpp::sourceCpp(test.cpp') map_string_int() Although the code compiles without any error, when i call the function, my r session terminates immediately. Any ideas? [EDIT] R version 3.1.1 (2014-07-10) Platform: x86_64-w64-mingw32/x64 (64-bit) locale: [1] LC_COLLATE=Portuguese_Portugal.1252 [2] LC_CTYPE=Portuguese_Portugal.1252 [3] LC_MONETARY=Portuguese_Portugal.1252 [4] LC_NUMERIC=C [5] LC_TIME=Portuguese_Portugal.1252 attached base packages: [1] stats graphics grDevices utils datasets [6] methods base other attached packages: [1] Rcpp_0.11.3 loaded via a namespace (and not attached): [1] tools_3.1.1 A: Decided to try another compiler and it worked! I have installed Rtools compiler (http://cran.r-project.org/bin/windows/Rtools/) after which just changed the system path to point to the bin folders within the Rtools installation folder.
[ "crypto.stackexchange", "0000070458.txt" ]
Q: Key rotation (or other measures) for PASETO v2 "local" I was looking at using PASETO's v2 "local" encryption (XChaCha20-Poly1305) to implement short-lived tokens to share claims between microservices via an untrusted client. PASETO's documentation is strong on its implementation detail, but I'm left with questions at a higher level. Specifically, I want to avoid a scenario where an attacker could breach a key and use it to forge claims. I'm under the impression that the likelihood of an attacker brute forcing a key increases with time and quantity of encrypted data samples, so key rotation seems like a great way to limit both the time and available data related to any single key, as well as to limit the duration which any breached key would be useful for. I see from this answer that the primary purpose of key rotation for symmetric ciphers is to limit the damage that would result if a key was breached (e.g. only the data encrypted by that specific key would be exposed). In our use case, the claims would not contain any sensitive data, so this is not a concern. Is key rotation a valid approach to avoid an attacker being able to forge claims? Is it overkill? Is there something else I should consider? A: Key rotation is important. Besides data breaches, unintentional key disclosure happens. For example by committing an unintended file to a public GitHub repository. Also, people having access to a key today can take a copy of that key when they leave the company. In case of PASETO, brute-forcing the key is not a concern. The key space is ginormous (2^256), so this is infeasible, no matter how much data is collected. If you control all the applications using that key, and you probably do, key rotation should also be fairly easy to implement.
[ "superuser", "0000660417.txt" ]
Q: Does it matter where I plug my power buttons and LED's into my motherboard? I found the System Panel Header, now I just need to plug em' in. A: What you're looking for is the "System Panel Header" on that picture you gave, #16. If you grab the "Quick Install Guide" from http://www.asrock.com/MB/AMD/880GM-LE%20FX/index.us.asp?cat=Manual, you'll find the pinouts for the header on Page 23 (edit: bottom of page 23) (second edit: the picture in question is on page 2 of the quick install guide, since the link was removed.) The two important ones are "PWRBTN" and "RESET". Connect the appropriate button's jumper to the labelled header, and the other side to one of the "GND" pins. PLED/HDLED are for the power and hard drive lights - the jumpers in that bundle of cables should be properly labelled with + and -... just match 'em up.
[ "stackoverflow", "0062512509.txt" ]
Q: Pandas remove row if all values in that row are false I am looking to tidy up some rows in my dataset output = { 'id1': ['False', 'False', 'False', 'False'], 'id2': ['True', 'False', 'False', 'False'], 'id3': ['True', 'False', 'True', 'False'], 'id4': ['True', 'False', 'True', 'True'], } So using the above row 2 contains all false Due to this i wont need to use it so I would just like to remove it newoutput = { 'id1': ['False', 'False', 'False'], 'id2': ['True', 'False', 'False'], 'id3': ['True', 'True', 'False'], 'id4': ['True', 'True', 'True'], } I got as far as checking for rows with false in it output.drop(output[output != False].index, inplace=True) But that just looks at ANY value in row being False and not All A: Use DataFrame.any for test if match at least one True in boolean indexing, so removed only Falses rows Because is used this solution converting to boolean is not necessary: df = df[df.any(axis=1)] A: I constructed df via df = pd.DataFrame(output). You can use >>> df[df.replace({'False': False, 'True': True}).any(1)] id1 id2 id3 id4 0 False True True True 2 False False True True 3 False False False True I strongly suggest using booleans instead of strings to indicate True and False. In that case the solution is a simple reassignment to df[df.any(1)].
[ "stackoverflow", "0006934936.txt" ]
Q: How do I stop this program from calling a non-existant list element? import string ## This part of the code initializes the program by recieving inputs and saving ## them as strings. ## It also currently works! intext = str.lower(raw_input("Please input the text you are going to use. ")) ##print intext instring = str.lower(raw_input("Please input your string. ")) ##print instring inlengthminus = int(raw_input("Please input the number of words you would like before the matched word. ONLY PUT AN INTEGER HERE!")) inlengthplus = int(raw_input("Please input the number of words you would like after the matched word. ONLY PUT AN INTEGER HERE!")) ## This part of the code splits the text into searchable lists. ## It only works when the cases match, which is why the search lists ## convert the text to lowercase. searchtext=str.split(intext) ##print searchtext searchstring=list(instring+1) ##print searchstring ## This is the actual search process. ## It works, mostly. length = len(searchtext) stringlength = len(searchstring) ##print stringlength x=0 for a in range(0,length): print a print searchstring[x] print x if searchstring[x] in searchtext[a]: if (a-inlengthminus)<0: print "You almost caused an error, please pick a number of words before your matched word that won't call text that doesn't exist." break else: print searchtext[a-inlengthminus:a+inlengthplus+1] x+=1 else: pass I don't know how to stop this program from calling a value for searchstring[x] that is greater than the length of searchstring. Is there a way to stop x from causing this overflow error? A: Replace x+=1 With x = (x + 1) % len(searchstring) The modulus operator does division and returns the remainder. So x from 0 up to the length of searchstring, the modulus does nothing (returns itself). If x == the length of searchstring, it "resets" to 0, because there is no remainder when dividing.
[ "tex.stackexchange", "0000420304.txt" ]
Q: Sorry, but "MiKTeX Compiler Driver" did not succeed. FATAL texify - BibTeX failed for some reason I am trying to run some latex files on a new computer. I am using an external hard drive that is a direct copy of my previous computer so the files all should be fine, however I am getting the error: Sorry, but "MiKTeX Compiler Driver" did not succeed. The log file hopefully contains the information to get MiKTeX going again: C:/Users/******/AppData/Local/MiKTeX/2.9/miktex/log/texify.log You may want to visit the MiKTeX project page, if you need help. I have found lots of threads on this, but none of the solutions given have worked for me. I have tried deleting aux files and re-running, I have tried running from command prompt, I have tried uninstalling and reinstalling MiKTeX, I have tried running initexmf --mkmaps --verbose from the command prompt. The log file it directs me too reads as follows: 2018-03-15 11:36:30,425Z INFO texify - starting with command line: "C:\Program Files\MiKTeX 2.9\miktex\bin\x64\texify.exe" --pdf --synctex=1 --clean warwickthesis.tex 2018-03-15 11:36:49,382Z FATAL texify - BibTeX failed for some reason. 2018-03-15 11:36:49,382Z FATAL texify - Info: 2018-03-15 11:36:49,382Z FATAL texify - Source: Programs\MiKTeX\texify\mcd.cpp 2018-03-15 11:36:49,382Z FATAL texify - Line: 1286 I have since tried running just pdflatex - this works but obviously does not create references etc. Running just bibtex does not work and returns this in the blg file: This is BibTeX, Version 0.99dThe top-level auxiliary file: warwickthesis.aux The style file: unsrt.bst Database file #1: library.bib Repeated entry---line 1242 of file library.bib : @article{Takishita2015 : , I'm skipping whatever remains of this entry Repeated entry---line 1396 of file library.bib : @article{Grassie2005 : , I'm skipping whatever remains of this entry Warning--I didn't find a database entry for "Haidemenopoulos2016" Warning--I didn't find a database entry for "Hughes2015" Warning--I didn't find a database entry for "Blitz1997" Warning--I didn't find a database entry for "Bieber1998" Warning--I didn't find a database entry for "Tian2005" Warning--I didn't find a database entry for "Mina1997" Warning--I didn't find a database entry for "Drinkwater2006" Warning--I didn't find a database entry for "Grimberg2006" Warning--I didn't find a database entry for "Edwards2008a" Warning--I didn't find a database entry for "Gros1999" Warning--I didn't find a database entry for "Hughes2014" Warning--I didn't find a database entry for "Honarvar2013" Warning--I didn't find a database entry for "Alvarez-Arenas2013" Warning--I didn't find a database entry for "Kang2017" ... etc (few more of these) Warning--empty journal in Ewert2013 Warning--can't use both author and editor fields in Achenbach1999 Warning--empty journal in Blake1990 Warning--empty note in Thring2018 (There were 2 error messages) This is odd as the references are in my library created by Mendeley and the referencing works fine on a different computer. Any suggestions? A: I also encounter a similar problem. I.E. MiKTeX compiler driver did not succeed. The problem is that I give the LaTeX file a name that with spaces. When I deleted all the spaces in the file name, then everything was fine.
[ "stackoverflow", "0014184529.txt" ]
Q: How to Convert Comma Seperated Column into rows and add counter I am having a table with these values Table : Documents id | document ----|------------- 1 | doc.txt , doc1.txt , doc2.rtf , doc3.docx , doc4.doc 2 | doc.txt 3 | doc.txt , doc1.txt 4 | doc.txt , doc1.txt , doc2.rtf 5 | doc.txt , doc1.txt , doc2.rtf , doc3.docx , doc4.doc 6 | doc.txt , doc1.txt , doc2.rtf , doc3.docx 7 | doc.txt , doc1.txt , doc2.rtf , doc3.docx , doc4.doc 8 | doc.txt , doc1.txt , doc2.rtf 9 | doc.txt , doc1.txt , doc2.rtf , doc3.docx , doc4.doc 10 | doc.txt , doc1.txt SQL FIDDLE SCHEMA I need result like this. Where id = 5 Counter | docs ----|----------- 1 | doc.txt 2 | doc1.txt 3 | doc2.rtf 4 | doc3.docx 5 | doc4.doc Where id = 4 Counter | docs ----|----------- 1 | doc.txt 2 | doc1.txt 3 | doc2.rtf You see i need to explode comma seperated column and count how many values are there. I dont like this schema but i am working on an existing project and can not change it. I need counter to display in the user interface. So counter is necessary too. How can i do that? Also i can not do it on the php end because i am using pyrocms and i need to display it using pyrocms tage which does not allow me to use php in the views. A: Look at this SQL FIDDLE , maybe it is that you want. You must use helper table sequence SELECT * FROM (SELECT S.Id Counter, REPLACE(SUBSTRING(SUBSTRING_INDEX(document, ' , ', S.Id), LENGTH(SUBSTRING_INDEX(document, ' , ', S.Id - 1)) + 1), ' , ', '') docs FROM documents D, sequence S WHERE D.id = 3) A WHERE A.docs <> ''
[ "askubuntu", "0000053444.txt" ]
Q: How can I measure the execution time of a terminal process? I'm trying to measure the execution time of a process that I call via the command line (i.e., I want to find out how long it takes to for the process to finish). Is there any command that I can add to the command calling the process that will achieve this? A: Add time before the command you want to measure. For example: time ls. The output will look like: real 0m0.606s user 0m0.000s sys 0m0.002s Explanation on real, user and sys (from man time): real: Elapsed real (wall clock) time used by the process, in seconds. user: Total number of CPU-seconds that the process used directly (in user mode), in seconds. sys: Total number of CPU-seconds used by the system on behalf of the process (in kernel mode), in seconds. A: For a line-by-line delta measurement, try gnomon. It is a command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long. Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer--that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable. A: You can use time: time ls -R
[ "math.stackexchange", "0003782348.txt" ]
Q: What does $f:\mathbb R \rightarrow \mathbb R$ mean? This is simply a basic notation question: what is the meaning of $$f:\mathbb R \rightarrow \mathbb R$$ I imagine it's some sort of function to do with the set of real numbers, perhaps some sort of mapping. Until now I've only encountered functions of the form $$f(x)=...$$ or $$f:x\mapsto...$$ Thanks in advance. A: It means that the function maps any real number (all real numbers are the domain) to one and only one real number (the codomain is a subset of $\mathbb R$). For example the following notations are valid $f:\mathbb R \rightarrow \mathbb R,\: f(x)=x^3$ $f:\mathbb R \rightarrow \mathbb R,\: f(x)=x^2$ $f:\mathbb R \rightarrow \mathbb R^+_0,\: f(x)=x^2$ $f:\mathbb R^+_0 \rightarrow \mathbb R^+_0,\: f(x)=\sqrt x$ and the following are wrong $f:\mathbb R \rightarrow \mathbb R^+_0,\: f(x)=\sqrt x$ $f:\mathbb R \rightarrow \mathbb R,\: f(x)=\log x$ $f:\mathbb R \rightarrow \mathbb R,\: f(x)=\frac 1x$
[ "stackoverflow", "0057408161.txt" ]
Q: Zend framework 3 tutorial error 404 after setting database : The requested controller could not be mapped to an existing controller class I'm trying Zend framework 3 for a project and I followed the tutorial. The 404 errors occurs after setting the route and controller, exactly at the end of this part : https://docs.zendframework.com/tutorials/getting-started/routing-and-controllers/ The error : A 404 error occurred Page not found. The requested controller could not be mapped to an existing controller class. Controller: Controller\AlbumController (resolves to invalid controller class or alias: Controller\AlbumController) No Exception available I tried some Zend 2 fix but It make it worse. This is my Album\config\module.config.php return [ 'router' => [ 'routes' => [ 'album' => [ 'type' => Segment::class, 'options' => [ 'route' => '/album[/:action[/:id]]', 'constraints' => [ 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+', ], 'defaults' => [ 'controller' => Controller\AlbumController::class, 'action' => 'index', ], ], ], ], ], 'view_manager' => [ 'template_path_stack' => [ 'album' => __DIR__ . '/../view', ], ], ]; Did I missed something? Is it broken? Thanks for helping me. A: Ok thanks to @Ermenegildo I figured it out. The problem was located is Module.php where some dependencies were missing. namespace Album; use Zend\Db\Adapter\AdapterInterface; use Zend\Db\ResultSet\ResultSet; use Zend\Db\TableGateway\TableGateway; use Zend\ModuleManager\Feature\ConfigProviderInterface;