qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
1,892,851
I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame . HINT: birthList is a list of Birth objects. but I will find this exception why? Please help me:( Manager class: ``` public Manager class{ Logger logger = Logger.getLogger(this.getClass().getName()); private static Connection conn = DBManager.getConnection(); private static Admin admin; public static void addToBirthListFromMySQL() throws SQLException { try{ Statement stmt = conn.createStatement(); ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable"); Birth list1; while (rs.next()) { String s1 = rs.getString(2); if (rs.wasNull()) { s1 = null; } String s2 = rs.getString(3); if (rs.wasNull()) { s2 = null; } String s3 = rs.getString(4); if (rs.wasNull()) { s3 = null; } String s4 = rs.getString(5); if (rs.wasNull()) { s4 = null; } String s5 = rs.getString(6); if (rs.wasNull()) { s5 = null; } String s6 = rs.getString(7); if (rs.wasNull()) { s6 = null; } list1 = new Birth(s1, s2, s3, s4, s5, s6); admin.birthList.add(list1); } } catch(SQLException e){ } } ``` My Frame: ``` public class BirthList extends javax.swing.JFrame { private Admin admin; /** Creates new form BirthList */ public BirthList(Admin admin) { initComponents(); this.admin = admin; try { Manager.addToBirthListFromMySQL(); } catch (SQLException ex) { Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex); } fillTable(); } public void fillTable() { String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"}; List<Birth> birth = admin.getBirthList(); Object[][] data = new Object[birth.size()][columNames.length]; for (int i = 0; i < data.length; i++) { Birth birth1 = birth.get(i); data[i][0] = birth1.getName(); data[i][1] = birth1.getFamily(); data[i][2] = birth1.getFatherName(); data[i][3] = birth1.getMotherName(); data[i][4] = birth1.getDateOfBirth(); data[i][5] = birth1.getPlaceOfBirth(); } DefaultTableModel model = new DefaultTableModel(data, columNames); jTable1.setModel(model); } public boolean isCellEditable(int row, int col) { return true; } } ``` stacktrace: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at database.Manager.addToBirthListFromMySQL(Manager.java:272) at AdminGUI.BirthList.(BirthList.java:35) at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127) at AdminGUI.BirthFrame.access$000(BirthFrame.java:21) at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6038) at javax.swing.JComponent.processMouseEvent(JComponent.java:3265) at java.awt.Component.processEvent(Component.java:5803) at java.awt.Container.processEvent(Container.java:2058) at java.awt.Component.dispatchEventImpl(Component.java:4410) at java.awt.Container.dispatchEventImpl(Container.java:2116) at java.awt.Component.dispatchEvent(Component.java:4240) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916) at java.awt.Container.dispatchEventImpl(Container.java:2102) at java.awt.Window.dispatchEventImpl(Window.java:2429) at java.awt.Component.dispatchEvent(Component.java:4240) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160) at java.awt.EventDispatchThread.run(EventDispatchThread.java:121) **line 272 is :admin.birthList.add(list1);** \*\*I also debug my project and the result was : **debug: Listening on javadebug User program running Debugger stopped on uncompilable source code.** \*I also print my object admin with system.out.println(admin) and the result was: classes.Admin@20be79\*
2009/12/12
[ "https://Stackoverflow.com/questions/1892851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124339/" ]
Instead of hunting the root cause in the dark, I think it's better to explain how and why NPE's are caused and how they can be avoided, so that the OP can apply the newly gained knowledge to hunt his/her own trivial problem. Look, object references (the variables) can contain either a fullworthy `Object` or simply *nothing*, which is `null`. ``` SomeObject someObject1 = new SomeObject(); // References something. SomeObject someObject2 = null; // References nothing. ``` Now, if you're trying to access *nothing* (`null`), then you will undoubtely get a `NullPointerException`, simply because `null` doesn't have any variables or methods. ``` someObject1.doSomething(); // Works fine. someObject2.doSomething(); // Throws NullPointerException. ``` Workarounding this is fairly simple. It can be done in basically two ways: either by instantiating it or just by ignoring it. ``` if (someObject2 == null) { someObject2 = new SomeObject(); } someObject2.doSomething(); // No NPE anymore! ``` or ``` if (someObject2 != null) { someObject2.doSomething(); // No NPE anymore! } ``` In case of a NPE, the first line number of the stacktrace points the exact line where the it is been caused. You told literally "line 272 is `admin.birthList.add(list1);`". This line contains **two** places where object references are been accessed/invoked (using the dot `.` operator). The first being `admin.birthList` and the second being `birthList.add(list1)`. It's up to you to find out if one or both caused the NPE. If it is the first invocation, then `admin` is simply `null`. If it is the second invocation, then `birthList` is simply `null`. You can fix it by instantiating it with a fullworthy object. **Edit:** If you have a hard time in determining the root cause (as turns out from comments), then you need to learn debugging. Run a debugger or just do "poor man's debugging" with help of a `System.out.println()` of every variable before accessing/invoking them. First look at line where the NPE is caused. If this is for example ``` admin.birthList.add(list1); ``` then you need to change it as follows to nail down the root cause: ``` System.out.println("admin: " + admin); List<Birth> birthList = admin.birthList; System.out.println("birthList: " + birthList); birthList.add(list1); ``` check if any of them prints `null`. Alternatively you can also do: ``` if (admin == null) throw new NullPointerException("admin is null!"); List<Birth> birthList = admin.birthList; if (birthList == null) throw new NullPointerException("birthList is null!"); birthList.add(list1); ``` you can also separate the individual invocations over separate lines so that you have enough to the line number to know which reference is null. ``` List<Birth> birthList = admin.birthList; // If NPE line points here, then admin is null. birthList.add(list1); // If NPE line points here, then birthList is null. ```
18,814,496
I have a JSON witch looks something like this ``` { "English": "en", "Francais": "fr", "German": "gm" } ``` Now I need to print this data in HTML structure witch looks like this ``` <ul id="links"> <li class="home"> <a href="#"></a> </li> <li class="languages"> <a href="#">EN</a> ------ > FIRST LANGUAGE FROM JSON <ul class="available"> ----> OTHERS <li><a href="#">DE</a></li> <li><a href="#">IT</a></li> <li><a href="#">FR</a></li> </ul> </li> </ul> ``` In javascript I know how to get data and print all data in the same structure but how to do it in structure shown in example ? in Javascript I'm getting data with ``` $.getJSON('js/languages.json', function(data) { console.log(data); /* $.each(data, function(key, val) { console.log(val); });*/ }); ```
2013/09/15
[ "https://Stackoverflow.com/questions/18814496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2590328/" ]
Use [jQuery template](http://plugins.jquery.com/loadTemplate/) to bind the Html. [Some Sample](http://weblogs.asp.net/hajan/archive/2010/12/14/jquery-templates-supported-tags.aspx)
43,177,742
Not sure why my \*ngFor loop is printing nothing out. I have the following code in an html file: ``` <table class="table table-hover"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Company</th> <th>Status</th> </tr> </thead> <tbody> <!-- NGFOR ATTEMPTED HERE -- no content printed --> <ng-template *ngFor="let xb of tempData"> <tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"> <td>{{ xb.name }}</td> <td>{{ xb.email }}</td> <td>{{ xb.company }}</td> <td>{{ xb.status }}</td> </tr> <!-- other content --> </ng-template> </tbody> </table> ``` Then, in my simple component I have the following: ``` import { Component } from '@angular/core'; @Component({ selector: 'my-profile-exhibitors', templateUrl: './profile-exhibitors.component.html', styleUrls: ['./profile-exhibitors.component.scss'] }) export class ProfileExhibitorsComponent { public tempData: any = [ { 'name': 'name1', 'email': 'email1@gmail', 'company': 'company', 'status': 'Complete' }, { 'name': 'name2', 'email': 'email2@gmail', 'company': 'company', 'status': 'Incomplete' } ]; constructor() {} } ``` When I run this code, I get zero output. Even weirder is that when I select the element using debug tools I see this: [![enter image description here](https://i.stack.imgur.com/9Vlch.png)](https://i.stack.imgur.com/9Vlch.png) Looks like it correctly recognizes my object, but then outputs nothing.
2017/04/03
[ "https://Stackoverflow.com/questions/43177742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409312/" ]
I think what you want is ```ts <ng-container *ngFor="let xb of tempData"> ``` or ```ts <ng-template ngFor let-xb [ngForOf]="tempData"> ```
16,883,875
In this code I want to increment `index` to put it to each `yield`ing result. ``` var index=0 for(str <- splitToStrings(text) ) yield { if (index != 0) index += 1 // but index is equal to `0` all the time new Word(str, UNKNOWN_FORM, index ) } ``` Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise?
2013/06/02
[ "https://Stackoverflow.com/questions/16883875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369759/" ]
The `zipWithIndex` method on most sequence-like collections will give you a zero-based index, incrementing with each element: ``` for ((str, index) <- splitToStrings(text).zipWithIndex) yield new Word(str, UNKNOWN_FORM, index) ```
3,115,948
In my iphone app,I want to let the user upload an image to his facebook photo Album and publish a story at the same time.The story's media field contains the uploaded image's url.I successly uploaded the photo and got the result's "link" and "src\_small" property.But when I use FBStreamDialog to publish the story,I got: [![alt text](https://i.stack.imgur.com/kEOVp.png)](https://i.stack.imgur.com/kEOVp.png) (source: [sinaimg.cn](http://ss10.sinaimg.cn/orignal/5d84b24ag89d4c79cbcb9&690)) At last,I find this:[http://developers.facebook.com/live\_status#msg\_625](https://developers.facebook.com/status/dashboard/#msg_625),it says: ``` We no longer allow stream stories to contain images that are hosted on the fbcdn.net domain. The images associated with these URLs aren't always optimized for stream stories and occasionally resulted in errors, leading to a poor user experience. Make sure your stream attachments don't reference images with this domain. You should host the images locally. ``` It seems that I can't finish my job,What's your solution? thanks in advance!
2010/06/25
[ "https://Stackoverflow.com/questions/3115948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355393/" ]
you can't use that picture or the picture from facebook itself you can upload the picture on other servers or upload it to online photo sharing like picasa
37,770,348
I'm really interested in interrupting incremental lists of items created in Rmarkdown with RStudio, to show plots and figures, then retake the list highlighting. This is quite straightforward in Latex, but I couldn't figure out how to achieve the same result using Rmarkdown. Below is some beamer example. ``` --- title: "Sample Document" author: "Author" output: beamer_presentation: fonttheme: structurebold highlight: pygments incremental: yes keep_tex: yes theme: AnnArbor toc: true slide_level: 3 --- # Some stuff 1 ### Some very important stuff - More detail on stuff 1 - More detail on stuff 1 - More detail on stuff 1 # The following chart should appear between the first and second item above ```{r, prompt=TRUE} summary(iris[, "Sepal.Length"]) # Stuff 2 ### There are other kinds of stuff? ```{r, prompt=TRUE} summary(mtcars[, "cyl"]) ``` [![enter image description here](https://i.stack.imgur.com/O0Dz2.png)](https://i.stack.imgur.com/O0Dz2.png) [![enter image description here](https://i.stack.imgur.com/QMKCG.png)](https://i.stack.imgur.com/QMKCG.png) [![enter image description here](https://i.stack.imgur.com/3XtpV.png)](https://i.stack.imgur.com/3XtpV.png) [![enter image description here](https://i.stack.imgur.com/CXieu.png)](https://i.stack.imgur.com/CXieu.png)
2016/06/12
[ "https://Stackoverflow.com/questions/37770348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792000/" ]
first - you do not need the comma in the select, second - ensure that this is the only element with the id of status, third - simply check the $status value in each option and echo selected if it is. ``` echo "<select name = 'status' id = 'status'> <option value='Interested'"; if($status == "Interested"){echo " selected";} echo">Interested</option> <option value='Not Interested' "; if($status == "Not Interested"){echo " selected";} echo">Not Interested</option> </select><br>"; ```
14,789,226
I'm really confused right now. I'm using following code in another project without any problems: ``` public class ReadOnlyTable<T extends Model> implements ReadOnly<T> { protected at.viswars.database.framework.core.DatabaseTable datasource; private boolean debug = true; protected ReadOnlyTable() { initTable(); } protected void reloadDataSource() { initTable(); } private void initTable() { boolean readOnlyClass = false; if (getClass().getSuperclass().equals(ReadOnlyTable.class)) readOnlyClass = true; Class<T> dataClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; ``` The last line will run without problems. Now i made a second project and as i had problems with reading out the Class i tried to do the most simple case possible: ``` public class GenericObject<T> implements IGenericObject<T> { public GenericObject() { init(); } private void init() { Class<T> clazz = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } ``` } This class is instanciated here: ``` GenericObject<String> go = new GenericObject<String>(); ``` In my second example i will always receive following error message: Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType What i am missing?? This drives me crazy. Any help is appreciated!
2013/02/09
[ "https://Stackoverflow.com/questions/14789226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057248/" ]
It is impossible to retrieve `String` from `go`. The type parameter of an object instantiation expression (`new GenericObject<String>()`) is not present anywhere at runtime. This is type erasure. The technique you are trying to use concerns when a *class* or *interface* extends or implements another class or interface with a specific type argument. e.g. `class Something extends GenericObject<String>`. Then it is possible to get this *declaration information* from the class object. This is completely unrelated to what you are doing.
56,924,735
I don't know how to resolve this problem,can someone help me. ``` The following packages have unmet dependencies: testdisk : Depends: libntfs-3g861 E: Unable to correct problems, you have held broken packages. ```
2019/07/07
[ "https://Stackoverflow.com/questions/56924735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10576808/" ]
Can you try after changing your template like this: ``` <ul class="nav navbar-nav"> <li><a [routerLink]='["/search"]'>Search <span class="slider"></span></a></li> <li *ngIf="isLoggedIn$ | async"><a (click)="logout()">Logout</a></li> </ul> ``` Notice the `async` pipe to unwrap the observable value. Notice in the stackblitz example shared by you - Observable value was unwrapped using `async` pipe - ``` <mat-toolbar color="primary" *ngIf="isLoggedIn$ | async as isLoggedIn"> ```
723,613
A practice question for my analysis midterm is as follows: Give an example of a function $f:[a, b] \to\ \mathbb R$ such that $f \in R[a, c] \forall c \in\ [a, b)$ but $$f \notin R[a, b]$$ I can't think of any examples. Any help is much appreciated. Thanks in advance.
2014/03/23
[ "https://math.stackexchange.com/questions/723613", "https://math.stackexchange.com", "https://math.stackexchange.com/users/114014/" ]
$$f(x)=\left\{\begin{array}{ccc}\frac1{1-x}&\mathrm{if}&x\in[0,1)\\0&\mathrm{if}&x=1\end{array}\right.$$
9,246,871
I'm trying to delete the folder `mapeditor` from my Java engine on GitHub here (https://github.com/UrbanTwitch/Mystik-RPG) I'm on Git Bash.. messing around with `rm` and `-rf`but I can't seem to do it. How do I remove `mapeditor` folder from `Mystik-RPG` completely? Thanks.
2012/02/12
[ "https://Stackoverflow.com/questions/9246871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272501/" ]
From the `Mystik-RPG` folder: ``` git rm -rf mapeditor ```
46,787,270
I'm using JavaMail to the handle emails. Subject is encoded in following charset: `Subject: =?x-mac-ce?Q?Wdro=BFenia_znaku_CE?=` How to decode this using a JavaMail.
2017/10/17
[ "https://Stackoverflow.com/questions/46787270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087407/" ]
Windows [seems to use](https://msdn.microsoft.com/en-us/library/ms537500(v=vs.85).aspx) `x-mac-ce` as an alias for `Windows-1250` codepage (matching the CP1250 JDK charset). **JavaMail** maintains a map of "MIME to Java" charset aliases internally, as resolved with the [MimeUtility.javaCharset](http://grepcode.com/file/repo1.maven.org/maven2/javax.mail/mail/1.4.1/javax/mail/internet/MimeUtility.java#MimeUtility.javaCharset%28java.lang.String%29) method, to handle cases like that. Unfortunately there is no [mapping](http://grepcode.com/file/repo1.maven.org/maven2/javax.mail/mail/1.4.1/javax/mail/internet/MimeUtility.java#1210) for `x-mac-ce` (at least as of JavaMail 1.6.0), and (AFAIK) there is no extension API provided, to add it. So the best you can do at the moment is decode the subject line in your application code, like that: ``` MimeUtility.decodeText( m.getSubject().replace("x-mac-ce","CP1250") ) ``` **Test** ``` m.setSubject("=?x-mac-ce?Q?Wdro=BFenia_znaku_CE?="); System.out.printf( MimeUtility.decodeText( m.getSubject().replace("x-mac-ce","CP1250") ) ); >>Wdrożenia znaku CE ``` **Note** I've first incorrectly identified the encoding as [Macintosh Central European encoding](https://en.wikipedia.org/wiki/Macintosh_Central_European_encoding) (`x-MacCentralEurope` Java Charset), which does not fully match CP1250, and seems to be a transposed version of it (i.e. 0xBF matches 0xFB e.t.c.).
10,019,594
I have a database with an email field, and it cycles through the database to grab all the transactions concerning a certain email address. Users putting in lowercase letters when their email is stored with a couple capitals is causing it not to show their transactions. When I modify it to match perfect case with the other emails, it works. How can I modify this so that it correctly compares with the email field and case doesn't matter? Is it going to be in changing how the email gets stored? ``` $result = mysql_query("SELECT * FROM `example_orders` WHERE `buyer_email`='$useremail';") or die(mysql_error()); ``` Thanks ahead of time!
2012/04/04
[ "https://Stackoverflow.com/questions/10019594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871966/" ]
A mixed PHP/MySQL solution: ``` $result = mysql_query(" SELECT * FROM example_orders WHERE LOWER(buyer_email) = '" . strtolower($useremail) . "'; ") or die(mysql_error()); ``` What it does is converting both sides of the comparison to lowercase. This is not very efficient, because the use of `LOWER` will prevent MySQL from using indexes for searching. **A more efficient, pure SQL solution:** ``` $result = mysql_query(" SELECT * FROM example_orders WHERE buyer_email = '$useremail' COLLATE utf8_general_ci; ") or die(mysql_error()); ``` In this case, we are forcing the use of a case-insensitive collation for the comparison. You wouldn't need that if the column had a case-insensitive collation in the first place. Here is how to change the column collation, as suggested by Basti in a comment: ``` ALTER TABLE `example_orders` CHANGE `buyer_email` `buyer_email` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ``` If you choose to do that, you can run the query without `COLLATE utf8_general_ci`.
229,587
Related to the following question but looking for a PyQGIS method: [QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order) --- The following is a simple setup containing a group with three layers. [![Simple setup](https://i.stack.imgur.com/GV5pZ.png)](https://i.stack.imgur.com/GV5pZ.png) The code I use adds a new layer at the **end of this group**: ``` root = QgsProject.instance().layerTreeRoot() group = root.findGroup('Main group') vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory') QgsMapLayerRegistry.instance().addMapLayer(vlayer, False) group.insertChildNode(-1, QgsLayerTreeLayer(vlayer)) ``` [![New layer added at end of group](https://i.stack.imgur.com/kK1Hq.png)](https://i.stack.imgur.com/kK1Hq.png) In the *Layer Order Panel*, the newly added layer is at the end. [![Layer Order Panel](https://i.stack.imgur.com/pbexP.png)](https://i.stack.imgur.com/pbexP.png) --- Is it possible to move this to the top **without moving the layer in the *Layers Panel***?
2017/02/23
[ "https://gis.stackexchange.com/questions/229587", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/25814/" ]
You can set layer order in the `Layer Order Panel` "**manually**" using `QgsLayerTreeCanvasBridge.setCustomLayerOrder()` method, which receives an ordered list of layer ids. For instance (assuming you just loaded `vlayer`): ``` bridge = iface.layerTreeCanvasBridge() order = bridge.customLayerOrder() order.insert( 0, order.pop( order.index( vlayer.id() ) ) ) # vlayer to the top bridge.setCustomLayerOrder( order ) ``` --- To **automatically** move newly added layers to the top of `Layer Order Panel`, you could use the `legendLayersAdded` SIGNAL (this signal is appropriate because it's emitted after the `Layer Order Panel` gets the new layer) from `QgsMapLayerRegistry` and reorder layers in this way: ``` def rearrange( layers ): order = iface.layerTreeCanvasBridge().customLayerOrder() for layer in layers: # How many layers we need to move order.insert( 0, order.pop() ) # Last layer to first position iface.layerTreeCanvasBridge().setCustomLayerOrder( order ) QgsMapLayerRegistry.instance().legendLayersAdded.connect( rearrange ) ``` --- NOTE: Since you're loading your `vlayer` calling `QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)`, that `False` parameter prevents the `legendLayersAdded` SIGNAL from being emitted. So, the automatic approach won't work for your case and you will need to rearrange layers manually (first approach of this answer).
56,194,991
Consider the following numbers: ``` 1000.10 1000.11 1000.113 ``` I would like to get these to print out in python as: ``` 1,000.10 1,000.11 1,000.11 ``` The following transformations almost do this, except that whenever the second digit to the right of the decimal point is a zero, the zero is elided and as a result that number doesn't line up properly. This is my attempt: ``` for n in [1000.10, 1000.11, 1000.112]: nf = '%.2f' %n # nf is a 2 digit decimal number, but a string nff = float(nf) # nff is a float which the next transformation needs n_comma = f'{nff:,}' # this puts the commas in print('%10s' %n_comma) 1,000.1 1,000.11 1,000.11 ``` Is there a way to avoid eliding the ending zero in the first number?
2019/05/18
[ "https://Stackoverflow.com/questions/56194991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9399754/" ]
You want the format specifier `',.2f'`. `,`, as you noted, performs comma separation of thousands, while `.2f` specifies that two digits are to be retained: ``` print([f'{number:,.2f}' for number in n]) ``` Output: ``` ['1,000.10', '1,000.11', '1,000.11'] ```
47,384,766
I know this question has been asked already. However, when I follow the answer given to that question it doesn't work. This is my JS function and the relevant HTML ```js function myFunction() { document.getElementById("submit").innerHTML = "LOADING..."; } ``` ```html <input class="textbox" type="number" id="number"> <button onclick="myFunction(document.getElementById("number").value)" class="Button" >Submit</button> <p id="submit"></p> <script type ="text/javascript" src="../src/index.js"></script> ```
2017/11/20
[ "https://Stackoverflow.com/questions/47384766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7870395/" ]
You have to config your web server to response `index.html` when receive requests like `/place/66bb50b7a5` [vue-router doc](https://router.vuejs.org/en/essentials/history-mode.html) have example configurations for Apache, nginx, IIS... For MAMP (apache): 1. create an file name `.htaccess` in your MAMP `htdocs` folder 2. paste apache configuration from vue-router doc `.htaccess`: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> ```
2,784,323
> > Let $A = \{(x,y): y = \sin(\frac{1}{x}), 0 < x \le 1\}$ Show that the point $(0, \frac {1}{\sqrt{2}})$ is a limit point of $A$ > > > If $p$ is a limit point of $A$, then $\forall\_{\delta>0}, B\_\delta(p) \cap A \neq \emptyset$, so we need to show that definition with $p = (0, \frac {1}{\sqrt{2}})$. My question is how do I proceed to prove this proposition.
2018/05/16
[ "https://math.stackexchange.com/questions/2784323", "https://math.stackexchange.com", "https://math.stackexchange.com/users/477171/" ]
**Hint:** $\left(\frac4\pi,\frac1{\sqrt2}\right)\in A$. And $\left(\frac4{5\pi},\frac1{\sqrt2}\right)\in A$ too.
64,195
If one has built a kasher sukkah, with its own completed skhakh but there is a tree branch that leans against the skhakh, is it still kasher?
2015/09/27
[ "https://judaism.stackexchange.com/questions/64195", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/9045/" ]
There are many details found in the Shulchan Aruch siman 626. If the branch only provides a minority of the shade etc. In one situation having the branch mixed in with the kosher schach is actually beneficial. But according to one opinion in the Shulchan Aruch, one should never under any circumstances have any branch above the schach. If you rule with Ramma or straight Shulchan Aruch will come into play here, so again, see the details there.
69,274
I have disabled the touchscreen on my official 7" display by adding the below line to my /boot/config.txt ``` # disable the touchscreen disable_touchscreen=1 ``` While this works, it also eliminates all ability to programmatically control the display. Everything under /sys/class/backlight disappears. Is there a way to disable the touchscreen that will still allow the control of the rest of the display functions?
2017/07/02
[ "https://raspberrypi.stackexchange.com/questions/69274", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/69672/" ]
If you're using your screen with X server (GUI), then you can simply find its ID in the output of `xinput --list` and disable it with `xinput disable <ID>`. Your touchscreen will still generate input events, but your X server will not forward those events to the applications. You will want to execute the `xinput disable <ID>` command at startup to make the change permanent.
24,681,229
Does anyone know how to associate a floating IP address with a load balancer in a heat template? I can create a load balancer on an instance (or a bunch of instances, but starting small) in heat; and can associate a floating IP address to the load balancer in Horizon, but I can't figure out how to do it through heat.
2014/07/10
[ "https://Stackoverflow.com/questions/24681229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833982/" ]
I just had to find the answer to this question myself. It turns out that the `vip` attribute of an `OS::Neutron::Pool` resource contains a few more keys than are documented [here](http://docs.openstack.org/developer/heat/template_guide/openstack.html#OS::Neutron::Pool-hot). In particular, the `vip` attribute contains a `port_id`, which is the address of the Neutron port associated with this pool. Since we have a Neutron port id, we can use that to associate a floating ip address like this: ``` type: "OS::Neutron::Pool" properties: protocol: HTTP monitors: - {get_resource: monitor} subnet_id: {get_resource: fixed_subnet} lb_method: ROUND_ROBIN vip: protocol_port: 80 lb_floating: type: "OS::Neutron::FloatingIP" properties: floating_network_id: get_param: external_network_id port_id: get_attr: [pool, vip, port_id] ``` That `get_attr` call is getting the `port_id` attribute of the `vip` attribute of the `pool` resource.
21,668,250
I'm trying to make a program that will get the user input of a new file name, create the file, and write to it. It works but it will only write the first word of the string to the file. How can i get it to write the full string? thanks. ``` #include "stdafx.h" #include <fstream> #include <iostream> #include <string> using namespace std; int main() { for (;;) { char *myFile = " "; string f = " "; string w = " "; cout <<"What is the name of the file you would like to write to? " <<endl; cin >>f; ofstream myStream(f,ios_base::ate|ios_base::out); cout <<"What would you like to write to " <<f <<" ? "; cin >>w; myStream <<w; if (myStream.bad()) { myStream <<"A serious error has occured."; myStream.close(); break; } } } ```
2014/02/10
[ "https://Stackoverflow.com/questions/21668250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3150762/" ]
According to [this post](https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin), you should consult [this reference](http://www.cplusplus.com/reference/fstream/fstream/) to use a method like getline(). Also, when you are writing out I recommend that you flush the output (cout.flush()) before ending the program, especially in this case, since I presume you are ending the program with a ctrl-C break. In formulating a suggestion, I will read data into char\*, and convert them to "string" in case you will use them elsewhere in your program. I tested this code in MS Visual C++ Express. ``` #include "stdafx.h" #include <fstream> #include <iostream> #include <string> using namespace std; int main() { for (;;) { char *myFile = new char[200]; // modified this line //added this line char *myInput = new char[200]; string f = " "; string w = " "; cout << "What is the name of the file you would like to write to? " << endl; cin.getline(myFile, 200);//modified this line f = (myFile);//added this line cin.clear(); //added this line ofstream myStream(f, ios_base::ate | ios_base::out); cout << "What would you like to write to " << f << " ? "; cin.getline(myInput, 200);//edited this line w = string(myInput);//added this line myStream << w; myStream.flush();//added this line if (myStream.bad()) { myStream << "A serious error has occured."; myStream.close(); break; } delete myFile; delete myInput; } } ```
31,870
I'm trying to find undirected random graphs $G(V,E)$ with $|V|$ = $d^2$ for $d \in \mathbb{N}$ such that $\forall v \in V: deg(v) = d$. For $d \in 2\mathbb{N} +1$ this trivially is impossible as no such graph exists: The number of incidences (connections between vertices and edges) is given by $|V|\cdot d = d^3 = 8k^3 + 12k^2 + 6k + 1$ (for some $k$). As the number of incidences is always double the number of edges $|E| = d^3/2$ is a contradiction. This argument however, doesn't work for $d \in 2\mathbb{N}$. My first guess was just constructing a random graph would do, however, this can get stuck in a local maximum. For instance in $d = 2$: ``` +---+ example for | / an incomplete | / graph that |/ cannot be + + completed ``` A similar example can be constructed for $d = 4$ leaving up to two unconnectable vertices (essentially by using a 4-HyperCube). I strongly suspect that for each $d$ the number of valid graphs significantly outweigh the number of incomplete graphs, but I would like to know **how likely it is to end up with an incomplete graph**. And if there is a **better way to find these graphs** than the random algorithm above (which could perhaps be fixed by breaking apart incomplete graphs, but that would not be guaranteed to terminate).
2015/06/30
[ "https://cstheory.stackexchange.com/questions/31870", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/1908/" ]
The standard simple way of generating random regular graphs is: * while the degree < d + choose a random perfect matching from the edges still possible to add to the graph + If no matching is possible, restart the process. The problem with this is that the higher edge degree you want, the more likely it is for the algorithm to get stuck. I see many papers limiting themself to $|V|>d^3$, so I don't know if this process will work for you.
34,601,754
JavaScrpt expert, i want if the below script exist in my template coding then my page should redirect to example.com ``` <script> $(document).ready(function(){ $("#wrapper").hide(); }) </script> ``` if the above script exist in my template, then it should redirect to example.com **Attention:** please add some condition in that script like this: ``` <script> $(document).ready(function(){ If //#wrapper is hide $("#wrapper").hide(); //then it should redirected to example.com </script> ``` I hope someone will figure out and will share code with me. thanks.
2016/01/04
[ "https://Stackoverflow.com/questions/34601754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741391/" ]
If you need this functionality somewhere after the bit of code you show, this would work: ``` var $wrapper=$("#wrapper"); if($wrapper.length>0 && !$wrapper.is(':visible')){ // #wrapper exists on the page but is not visible, redirect user window.location.href = "http://example.com"; } ```
15,369,589
i use this script to compress all .txt and .cpi files into the backup folder in separated files with 7zip. After the files are zipped i delete the original files. However this script has a logical flaw. Lets say if the 7zip program fails to run, the files will also get deleted. How can i change the script so that it should not delete the files if they don't get zipped first. Also how can i change this script so it zips files that are older than 7 days? Thanks for your help. @echo off setlocal ``` set _source=C:\test7zip\bak set _dest=C:\test7zip\bak set _wrpath=C:\Program Files\7-Zip if NOT EXIST %_dest% md %_dest% for %%I in (%_source%\*.txt,%_source%\*.cpi) do "%_wrpath%\7z" a "%_dest%\%%~nI.7z" "%%I" & del "%%I" ``` pause
2013/03/12
[ "https://Stackoverflow.com/questions/15369589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2120466/" ]
This is a partial solution to a partial question, but generally you would use: `ORDER BY YEAR(TimeColumn), DATEPART(m, TimeColumn)`
82,435
Is the full version of Quake II free now? If so, where can I find it - I don't see it available on ID's site, even in the Store section. I see that there's a GPL source available. And I recall ID having made other's free as well. Is there an authoritative source?
2012/09/03
[ "https://gaming.stackexchange.com/questions/82435", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/16833/" ]
While id has [open-sourced the *engine*](https://github.com/id-Software/Quake-2), the game itself is not free (as in beer or speech). > > All of the Q2 data files remain copyrighted and licensed under the > original terms, so you cannot redistribute data from the original game, but if > you do a true total conversion, you can create a standalone game based on > this code. > > > This essentially means that you can download the source code, and use it as long as you comply with the terms of the license. Additionally, you can download versions of the Q2 binaries/source that other people have modified or made available, if you so desire. If you want to play the *game,* you'll need the game files from the original disc or some other source. As far as the game is concerned, you can [pick it up on Steam](http://store.steampowered.com/app/2320/?snr=1_7_suggest__13), along with most of the rest of the id library.
2,805,674
I am experiencing problems creating a connection pool in glassfish v3, just for reference i am using the Java EE glassfish bundle. my enviroment vars are as follows ``` Url: jdbc:oracle:thin:@localhost:1521:xe User: sys Password : xxxxxxxx ``` which i think is all i need to make a connection. but i get the following exception ``` WARNING: Can not find resource bundle for this logger. class name that failed: com.sun.gjc.common.DataSourceObjectBuilder SEVERE: jdbc.exc_cnfe_ds java.lang.ClassNotFoundException: oracle.jdbc.pool.OracleDataSource at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at com.sun.gjc.common.DataSourceObjectBuilder.getDataSourceObject(DataSourceObjectBuilder.java:279) at com.sun.gjc.common.DataSourceObjectBuilder.constructDataSourceObject(DataSourceObjectBuilder.java:108) at com.sun.gjc.spi.ManagedConnectionFactory.getDataSource(ManagedConnectionFactory.java:1167) at com.sun.gjc.spi.DSManagedConnectionFactory.getDataSource(DSManagedConnectionFactory.java:135) at com.sun.gjc.spi.DSManagedConnectionFactory.createManagedConnection(DSManagedConnectionFactory.java:90) at com.sun.enterprise.connectors.service.ConnectorConnectionPoolAdminServiceImpl.getManagedConnection(ConnectorConnectionPoolAdminServiceImpl.java:520) at com.sun.enterprise.connectors.service.ConnectorConnectionPoolAdminServiceImpl.getUnpooledConnection(ConnectorConnectionPoolAdminServiceImpl.java:630) at com.sun.enterprise.connectors.service.ConnectorConnectionPoolAdminServiceImpl.testConnectionPool(ConnectorConnectionPoolAdminServiceImpl.java:442) at com.sun.enterprise.connectors.ConnectorRuntime.pingConnectionPool(ConnectorRuntime.java:898) at org.glassfish.admin.amx.impl.ext.ConnectorRuntimeAPIProviderImpl.pingJDBCConnectionPool(ConnectorRuntimeAPIProviderImpl.java:570) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.glassfish.admin.amx.impl.mbean.AMXImplBase.invoke(AMXImplBase.java:1038) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:836) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:761) at javax.management.MBeanServerInvocationHandler.invoke(MBeanServerInvocationHandler.java:288) at org.glassfish.admin.amx.util.jmx.MBeanProxyHandler.invoke(MBeanProxyHandler.java:453) at org.glassfish.admin.amx.core.proxy.AMXProxyHandler._invoke(AMXProxyHandler.java:822) at org.glassfish.admin.amx.core.proxy.AMXProxyHandler.invoke(AMXProxyHandler.java:526) at $Proxy233.pingJDBCConnectionPool(Unknown Source) at org.glassfish.admingui.common.handlers.JdbcTempHandler.pingJdbcConnectionPool(JdbcTempHandler.java:99) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.jsftemplating.layout.descriptors.handler.Handler.invoke(Handler.java:442) at com.sun.jsftemplating.layout.descriptors.LayoutElementBase.dispatchHandlers(LayoutElementBase.java:420) at com.sun.jsftemplating.layout.descriptors.LayoutElementBase.dispatchHandlers(LayoutElementBase.java:394) at com.sun.jsftemplating.layout.event.CommandActionListener.invokeCommandHandlers(CommandActionListener.java:150) at com.sun.jsftemplating.layout.event.CommandActionListener.processAction(CommandActionListener.java:98) at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88) at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:772) at javax.faces.component.UICommand.broadcast(UICommand.java:300) at com.sun.webui.jsf.component.WebuiCommand.broadcast(WebuiCommand.java:160) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:240) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:239) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) WARNING: RAR8054: Exception while creating an unpooled [test] connection for pool [ testingManagmentDataConnection ], Class name is wrong or classpath is not set for : oracle.jdbc.pool.OracleDataSource WARNING: Can not find resource bundle for this logger. class name that failed: com.sun.gjc.common.DataSourceObjectBuilder ``` does anyone have any ideas what i am doing wrong/ what i will have to do to correct this issue, Thanks for your time Jon
2010/05/10
[ "https://Stackoverflow.com/questions/2805674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337609/" ]
Copy the jdbc jar to $glassfish-v3/glassfish/domains/domain1/lib/ext/ and restart glassfish. this should fix the problem.
72,411,979
I'm trying to style a group of images or paragraphs in a certain way, ```css .products { margin: 40px; border-radius: 4px solid black; } ``` ```html <div class="products"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> </div> <div class="products"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> <img src="images/bodybutter1.jpg" style="width 250px; height: 300px; border-radius: 15px;" alt="bodybutter"> </div> ```
2022/05/27
[ "https://Stackoverflow.com/questions/72411979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19210232/" ]
You'll need to target the img tag inside the parent instead of targeting the parent div. See code below: ``` .products img { margin: 40px; border-radius: 4px solid black; } ``` You can use this to reduce code duplication.
24,300
In R, if I set.seed(), and then use the sample function to randomize a list, can I guarantee I won't generate the same permutation? ie... ``` set.seed(25) limit <- 3 myindex <- seq(0,limit) for (x in seq(1,factorial(limit))) { permutations <- sample(myindex) print(permutations) } ``` This produces ``` [1] 1 2 0 3 [1] 0 2 1 3 [1] 0 3 2 1 [1] 3 1 2 0 [1] 2 3 0 1 [1] 0 1 3 2 ``` will all permutations printed be unique permutations? Or is there some chance, based on the way this is implemented, that I could get some repeats? I want to be able to do this without repeats, guaranteed. How would I do that? (I also want to avoid having to use a function like permn(), which has a very mechanistic method for generating all permutations---it doesn't look random.) Also, sidenote---it looks like this problem is O((n!)!), if I'm not mistaken.
2012/03/08
[ "https://stats.stackexchange.com/questions/24300", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/7420/" ]
The question has many valid interpretations. The comments--especially the one indicating permutations of 15 or more elements are needed (15! = 1307674368000 is getting big)--suggest that what is wanted is a *relatively small* random sample, without replacement, of all n! = n\*(n-1)*(n-2)*...\*2\*1 permutations of 1:n. If this is true, there exist (somewhat) efficient solutions. The following function, `rperm`, accepts two arguments `n` (the size of the permutations to sample) and `m` (the number of permutations of size n to draw). If m approaches or exceeds n!, the function will take a long time and return many NA values: it is intended for use when n is relatively big (say, 8 or more) and m is much smaller than n!. It works by caching a string representation of the permutations found so far and then generating new permutations (randomly) until a new one is found. It exploits R's associative list-indexing ability to search the list of previously-found permutations quickly. ``` rperm <- function(m, size=2) { # Obtain m unique permutations of 1:size # Function to obtain a new permutation. newperm <- function() { count <- 0 # Protects against infinite loops repeat { # Generate a permutation and check against previous ones. p <- sample(1:size) hash.p <- paste(p, collapse="") if (is.null(cache[[hash.p]])) break # Prepare to try again. count <- count+1 if (count > 1000) { # 1000 is arbitrary; adjust to taste p <- NA # NA indicates a new permutation wasn't found hash.p <- "" break } } cache[[hash.p]] <<- TRUE # Update the list of permutations found p # Return this (new) permutation } # Obtain m unique permutations. cache <- list() replicate(m, newperm()) } # Returns a `size` by `m` matrix; each column is a permutation of 1:size. ``` The nature of `replicate` is to return the permutations as *column* vectors; *e.g.*, the following reproduces an example in the original question, *transposed*: ``` > set.seed(17) > rperm(6, size=4) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 2 4 4 3 4 [2,] 3 4 1 3 1 2 [3,] 4 1 3 2 2 3 [4,] 2 3 2 1 4 1 ``` Timings are excellent for small to moderate values of m, up to about 10,000, but degrade for larger problems. For example, a sample of m = 10,000 permutations of n = 1000 elements (a matrix of 10 million values) was obtained in 10 seconds; a sample of m = 20,000 permutations of n = 20 elements required 11 seconds, even though the output (a matrix of 400,000 entries) was much smaller; and computing sample of m = 100,000 permutations of n = 20 elements was aborted after 260 seconds (I didn't have the patience to wait for completion). This scaling problem appears to be related to scaling inefficiencies in R's associative addressing. One can work around it by generating samples in groups of, say, 1000 or so, then combining those samples into a large sample and removing duplicates. R experts might be able to suggest more efficient solutions or better workarounds. ### Edit **We can achieve near linear asymptotic performance** by breaking the cache into a hierarchy of two caches, so that R never has to search through a large list. Conceptually (although not as implemented), create an array indexed by the first $k$ elements of a permutation. Entries in this array are lists of all permutations sharing those first $k$ elements. To check whether a permutation has been seen, use its first $k$ elements to find its entry in the cache and then search for that permutation within that entry. We can choose $k$ to balance the expected sizes of all the lists. The actual implementation does not use a $k$-fold array, which would be hard to program in sufficient generality, but instead uses another list. Here are some elapsed times in seconds for a range of permutation sizes and numbers of distinct permutations requested: ``` Number Size=10 Size=15 Size=1000 size=10000 size=100000 10 0.00 0.00 0.02 0.08 1.03 100 0.01 0.01 0.07 0.64 8.36 1000 0.08 0.09 0.68 6.38 10000 0.83 0.87 7.04 65.74 100000 11.77 10.51 69.33 1000000 195.5 125.5 ``` (The apparently anomalous speedup from size=10 to size=15 is because the first level of the cache is larger for size=15, reducing the average number of entries in the second-level lists, thereby speeding up R's associative search. At some cost in RAM, execution could be made faster by increasing the upper-level cache size. Just increasing `k.head` by 1 (which multiplies the upper-level size by 10) sped up `rperm(100000, size=10)` from 11.77 seconds to 8.72 seconds, for instance. Making the upper-level cache 10 times bigger yet achieved no appreciable gain, clocking at 8.51 seconds.) Except for the case of 1,000,000 unique permutations of 10 elements (a substantial portion of all 10! = about 3.63 million such permutations), practically no collisions were ever detected. In this exceptional case, there were 169,301 collisions, but no complete failures (one million unique permutations were in fact obtained). Note that with large permutation sizes (greater than 20 or so), the chance of obtaining two identical permutations even in a sample as large as 1,000,000,000 is vanishingly small. Thus, this solution is applicable primarily in situations where (a) large numbers of unique permutations of (b) between $n=5$ and $n=15$ or so elements are to be generated but even so, (c) substantially fewer than all $n!$ permutations are needed. Working code follows. ``` rperm <- function(m, size=2) { # Obtain m unique permutations of 1:size max.failures <- 10 # Function to index into the upper-level cache. prefix <- function(p, k) { # p is a permutation, k is the prefix size sum((p[1:k] - 1) * (size ^ ((1:k)-1))) + 1 } # Returns a value from 1 through size^k # Function to obtain a new permutation. newperm <- function() { # References cache, k.head, and failures in parent context. # Modifies cache and failures. count <- 0 # Protects against infinite loops repeat { # Generate a permutation and check against previous ones. p <- sample(1:size) k <- prefix(p, k.head) ip <- cache[[k]] hash.p <- paste(tail(p,-k.head), collapse="") if (is.null(ip[[hash.p]])) break # Prepare to try again. n.failures <<- n.failures + 1 count <- count+1 if (count > max.failures) { p <- NA # NA indicates a new permutation wasn't found hash.p <- "" break } } if (count <= max.failures) { ip[[hash.p]] <- TRUE # Update the list of permutations found cache[[k]] <<- ip } p # Return this (new) permutation } # Initialize the cache. k.head <- min(size-1, max(1, floor(log(m / log(m)) / log(size)))) cache <- as.list(1:(size^k.head)) for (i in 1:(size^k.head)) cache[[i]] <- list() # Count failures (for benchmarking and error checking). n.failures <- 0 # Obtain (up to) m unique permutations. s <- replicate(m, newperm()) s[is.na(s)] <- NULL list(failures=n.failures, sample=matrix(unlist(s), ncol=size)) } # Returns an m by size matrix; each row is a permutation of 1:size. ```
43,950,988
I am using ExtJS 6 version. I have panel element and dynamically I am updating panel html as ``` panel.update("<img src=app/resources/first.jpg ></img>"); ``` after updating html, image is not loading. I did `panel.updateLayout();` still image is not loading. Please suggest
2017/05/13
[ "https://Stackoverflow.com/questions/43950988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373142/" ]
If you want the list of lines without the trailing new-line character you can use `str.splitlines()` method, which in this case you can read the file as string using `file_obj.read()` then use `splitlines()` over the whole string. Although, there is no need for such thing when the `open` function is already returned a generator from your lines (you can simply strip the trailing new-line while processing the lines) or just call the `str.strip()` with a `map` to create an iterator of striped lines: ``` with open('dictionary.txt'): striped_lines = map(str.strip, f) ``` But if you just want to count the words as a pythonic way you can use a generator expression within `sum` function like following: ``` with open('dictionary.txt') as f: word_count = sum(len(line.split()) for line in f) ``` Note that there is no need to strip the new lines while you're splitting the line. e.g. ``` In [14]: 'sd f\n'.split() Out[14]: ['sd', 'f'] ``` But if you still want all the words in a list you can use a list comprehension instead of a generator expression: ``` with open('dictionary.txt') as f: all_words = [word for line in f for word in line.split()] word_count = len(all_words) ```
50,008,690
I'm having some trouble implementing the boostrap/js/jquery date picker into my webpage. I am not sure if there is code I am missing or hwaat. These are the includes in the head ``` <!-- Include Required Prerequisites --> <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" /> <!-- Include Date Range Picker --> <script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" /> ``` This is the Mark Up ``` <div class="container"> <div class="well"> <h1><span class="glyphicon glyphicon-calendar"></span></h1> <h3>Choose Your Dates</h3> <input type="text" id="datepicker" value="01/01/2015 - 01/31/2015"/> </div> </div> ``` This is the script ``` <script type="text/javascript"> $(function(){ $(".datepicker").daterangepicker(); }); </script> ``` UPDATE Looks like content loading problem [![console errors](https://i.stack.imgur.com/yiRvA.png)](https://i.stack.imgur.com/yiRvA.png)
2018/04/24
[ "https://Stackoverflow.com/questions/50008690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8569800/" ]
try ``` $("#datepicker").daterangepicker(); ```
1,334,121
I have several Ubuntu servers running on my Windows 2019 Hyper-V however I lost the ISO image. I downloaded `ubuntu-20.04.2-live-server-amd64.iso` and when I create a new VM it bombs every time: [![enter image description here](https://i.stack.imgur.com/wRhUU.png)](https://i.stack.imgur.com/wRhUU.png) What am I doing wrong? I have: * Windows 2019 Server w/24 Cores, 256 GB of RAM, and 4 TB of usable space. * Generation 2, Secure Boot unchecked * 32 GB of RAM * 12 Virtual Processors * 1 TB of hard disk space (tried 25 GB, 125 GB, and 512 GB) * SCSI Controller * All but Guest Services checked. I must have forgotten a step. Any ideas?
2021/04/26
[ "https://askubuntu.com/questions/1334121", "https://askubuntu.com", "https://askubuntu.com/users/1225018/" ]
Use the `numbered` when using `mv` ``` numbered, t make numbered backups ``` [man mv](https://linux.die.net/man/1/mv) `mv --backup=TYPE` with type being 1 of these: * none, off never make backups (even if --backup is given) * numbered, t make numbered backups * existing, nil numbered if numbered backups exist, simple otherwise * simple, never always make simple backups
31,560,712
I am digging for quite a while and I am wondering how do I open an HttpClient connection in Java (Android) and then close the socket(s) right away without getting CLOSE\_WAIT and TIME\_WAIT TCP statuses while I am checking network monitoring tools. What I am doing is (Found this solution on stackoverflow site): ``` String url = "http://example.com/myfile.php"; String result = null; InputStream is = null; StringBuilder sb = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { } Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); ``` After I run this code - The PHP file is executed well, I get the response back to TOAST, BUT - when I analyze the networking environment of my mobile device with external network analyzer tool - I see that the connection(s) stay in CLOSE\_WAIT or/and TIME\_WAIT for about 1 minute and only then they move to CLOSED state. The problem is: I am calling the above function every ~2 to 5 seconds in an infinite loop, which result over time a huge amount of CLOSE\_WAITs and TIME\_WAITs - which affect the overall performance of my Android app, until it gets stuck and useless ! What I want to do is (And need your answer if possible): I wish to really close the connection RIGHT AWAY after I TOAST the response message without any open sockets. No TIME\_WAIT and no CLOSE\_WAIT. No left overs at all - close all communication IMMEDIATELY at the split second that I run code that should do so. I don't need the connection anymore until the next iteration of the loop. How can I accomplish that ? I have in mind that I don't want the application to halt or have poor performance over time, since it should run in a service/stay open forever. I would really appreciate if you could write simple code that work after I do copy-paste. I am new to Java and Android, so I will try to figure out the code that you write, so please keep it as simple as possible. Thanks a lot ! Question asker.
2015/07/22
[ "https://Stackoverflow.com/questions/31560712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5142880/" ]
1. If you want to write " #002s ", Why not write at once? May be the serial device cant identify the control code when you write each character. ``` void Test_Serial::writeDataToSerialPort() { QByteArray input = QString("#002s").toLocal8Bit(); serial->write(input); } ``` 2. And no need for this reading part . ``` serial->waitForReadyRead(100); QByteArray output = serial->readAll(); ui->label_2->setText(output); ``` The `Test_Serial::serialReceived` will be called any way when you have the response from the serial device. 3. And you can catch the error on opening the port by using the `error` `signal` from `QSerialPort` ``` connect(serial,SIGNAL(error(QSerialPort::SerialPortError)),this,SLOT(serialPortError(QSerialPort::SerialPortError))); void Test_Serial::serialPortError(QSerialPort::SerialPortError error) { //Print error etc. } ```
1,387,296
I am using `nl2br()` to convert `\n` characters to the `<br />` tag but I do not want more than one `<br />` tag at a time. For example, `Hello \n\n\n\n Everybody` should become `Hello <br /> Everybody`. How can I do this?
2009/09/07
[ "https://Stackoverflow.com/questions/1387296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169141/" ]
The most direct approach might be to first replace the multiple newlines with one using a simple regular expression: ``` nl2br(preg_replace("/\n+/", "\n", $input)); ```
48,497,134
I have two DataFrames recommendations and movies. Columns rec1-rec3 in recommendations represent movie id from movies dataframe. ``` val recommendations: DataFrame = List( (0, 1, 2, 3), (1, 2, 3, 4), (2, 1, 3, 4)).toDF("id", "rec1", "rec2", "rec3") val movies = List( (1, "the Lord of the Rings"), (2, "Star Wars"), (3, "Star Trek"), (4, "Pulp Fiction")).toDF("id", "name") ``` What I want: ```none +---+------------------------+------------+------------+ | id| rec1| rec2| rec3| +---+------------------------+------------+------------+ | 0| the Lord of the Rings| Star Wars| Star Trek| | 1| Star Wars| Star Trek|Pulp Fiction| | 2| the Lord of the Rings| Star Trek| Star Trek| +---+------------------------+------------+------------+ ```
2018/01/29
[ "https://Stackoverflow.com/questions/48497134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5123568/" ]
We can also use the functions `stack()` and `pivot()` to arrive at your expected output, joining the two dataframes only once. ``` // First rename 'id' column to 'ids' avoid duplicate names further downstream val moviesRenamed = movies.withColumnRenamed("id", "ids") recommendations.select($"id", expr("stack(3, 'rec1', rec1, 'rec2', rec2, 'rec3', rec3) as (rec, movie_id)")) .where("rec is not null") .join(moviesRenamed, col("movie_id") === moviesRenamed.col("ids")) .groupBy("id") .pivot("rec") .agg(first("name")) .show() +---+--------------------+---------+------------+ | id| rec1| rec2| rec3| +---+--------------------+---------+------------+ | 0|the Lord of the R...|Star Wars| Star Trek| | 1| Star Wars|Star Trek|Pulp Fiction| | 2|the Lord of the R...|Star Trek|Pulp Fiction| +---+--------------------+---------+------------+ ```
31,979,254
in my app Im trying to give the user points every time they create an event. I am setting up a PFQuery to retrieve the current score then saving the required points back to the class. My problem is that I can't update the score once it has been created so I need a way to "Update" the current score data with the added score. This is my code: ``` // Give the User Points let saveScore = PFUser.currentUser() var query = PFQuery(className:"User") query.whereKey("score", equalTo: saveScore!) query.findObjectsInBackgroundWithBlock ({ objects, error in if error == nil { // The find succeeded. println("Successfully retrieved \(objects!.count) scores.") // Do something with the found objects if let objects = objects as? [PFObject] { for object in objects { let Score = object["score"] as! String println(object.objectId) let Points = ("100" + Score) saveScore!.setObject(Points, forKey: "score") saveScore!.saveInBackgroundWithBlock { (success: Bool,error: NSError?) -> Void in println("Score added to User."); } } } } else { // Log details of the failure println("Error: \(error!) \(error!.userInfo!)") } }) ``` Can anyone help? Thanks
2015/08/13
[ "https://Stackoverflow.com/questions/31979254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5002014/" ]
Since you already have the current user there's no reason to query it. However you should fetch it if needed to make sure you're working with the latest data. Once fetched set your score variable, add the 100 string and then save the updated score variable, like so: ``` if let currentUser = PFUser.currentUser() { currentUser.fetchIfNeededInBackgroundWithBlock({ (foundUser: PFObject?, error: NSError?) -> Void in // Get and update score if foundUser != nil { let score = foundUser!["score"] as! String let points = "100" + score foundUser!["score"] = points foundUser?.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in if succeeded { println("score added to user") } }) } }) } ```
25,670,647
I have set my GAE web app with all the appropriate endpoints and deployed it locally on my ubuntu pc. I get connected to my home network, I found my computer's local IP, selected the correct port (8888 is the default for GAE web apps) tried to connect (from Chrome and my android device) but no luck. I get `Google Chrome's connection attempt to 192.168.1.2 was rejected. The website may be down, or your network may not be properly configured.` `Error code: ERR_CONNECTION_REFUSED` Where should I look? Is this a GAE, network or Ubuntu issue?
2014/09/04
[ "https://Stackoverflow.com/questions/25670647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583086/" ]
Make sure you set the --address=192.168.1.2 (for java) (--host=192.168.1.2 for python) flag when you startup the app
355,367
I have been using Ubuntu 11.10 on a VMWare for sometime now. I did a lot of customization on it (e.g. remove unity, install my applications etc.). Last week I managed to get another laptop and installed Ubuntu 11.10 on it. I was wondering if it's possible ot make these two Ubuntu system identical, i.e. move everything (settings, applications etc.) from my VM Ubuntu to my laptop Ubuntu.
2012/01/31
[ "https://serverfault.com/questions/355367", "https://serverfault.com", "https://serverfault.com/users/70984/" ]
You can get a list of all installed packages on machine A by running: > > `sudo dpkg --get-selections > packagelist.txt`. > > > On machine B, you can install all those packages by running: > > `sudo dpkg --set-selections < packagelist.txt` > > >
13,930,049
I was wondering if the following is possible to do and with hope someone could potentially help me. I would like to create a 'download zip' feature but when the individual clicks to download then the button fetches images from my external domain and then bundles them into a zip and then downloads it for them. I have checked on how to do this and I can't find any good ways of grabbing the images and forcing them into a zip to download. I was hoping someone could assist
2012/12/18
[ "https://Stackoverflow.com/questions/13930049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1152045/" ]
``` # define file array $files = array( 'https://www.google.com/images/logo.png', 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Wikipedia-logo-en-big.png/220px-Wikipedia-logo-en-big.png', ); # create new zip object $zip = new ZipArchive(); # create a temp file & open it $tmp_file = tempnam('.', ''); $zip->open($tmp_file, ZipArchive::CREATE); # loop through each file foreach ($files as $file) { # download file $download_file = file_get_contents($file); #add it to the zip $zip->addFromString(basename($file), $download_file); } # close zip $zip->close(); # send the file to the browser as a download header('Content-disposition: attachment; filename="my file.zip"'); header('Content-type: application/zip'); readfile($tmp_file); unlink($tmp_file); ``` Note: This solution assumes you have `allow_url_fopen` enabled. Otherwise look into using cURL to download the file.
20,213,739
I am trying to animate a footer section in a webpage, and found out that the jQuery `.animate()` method doesn't 'animate' when using percentages (apparently is a bug still not fixed as of jQuery 1.10.2?). So, as suggested by [another answer on SO](https://stackoverflow.com/questions/6877081/jquery-animate-and-property-values-in-percentage) I should use notation for the parent's height, plus `'px'` to allow jQuery to animate properly. So I tried that, but this breaks the function :/ From my [JS Fiddle](http://jsfiddle.net/zYzT2/), I have this code: ``` $(function () { var open = false; $('#footbutton').click(function () { if (open === false) { $('#footcontent').animate({ height: '100%' }); open = true; } else { $('#footcontent').animate({ height: '0px' }); open = false; } }); }); ``` This works, except, the `#footcontent` div instantly pops open with no animation (but works fine when closing, as I have height set in px). Replacing `height: '100%'` with `height: $('footer').height() +'px'` breaks the function, where for some reason jQuery now sees the parent's height at 0px and cannot make any changes in height. How can the two be different? I've tried replacing `$('footer').height()` with `$(#footcontent).parent().height()` and it's a no-go as well. Surely I'm missing something here or just being dense...it is 4am my time........
2013/11/26
[ "https://Stackoverflow.com/questions/20213739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077783/" ]
Just throwing out ideas there. The current setup looks like this ``` +------------+ +------------+ | CGI |----------->| Apache | | Program |<-----------| Server | +------------+ +------------+ ``` How about something like this ``` +------------+ +------------+ +------------+ | Daemon |--->| CGI |--->| Apache | | Program |<---| Passthru |<---| Server | +------------+ +------------+ +------------+ ``` Basically, move all of the functionality of your current program into a daemon that is launched once at startup. Then create a tiny passthru program for Apache to launch via CGI. The passthru program attaches itself to the daemon using IPC, either shared memory, or sockets. Everything that the passthru program receives on stdin, it forwards to the daemon. Everything that the passthru program receives from the daemon, it forwards to Apache on stdout. That way Apache can launch/kill the passthru program as it pleases, without affecting what you're trying to do on the backend.
51,605,079
I'm playing with co-routines, and they're often described as useful for pipelines. I found a lecture from Berkeley that was very helpful ( <http://wla.berkeley.edu/~cs61a/fa11/lectures/streams.html#coroutines> ), but there's one thing I'm having trouble with. In that lecture, there's a diagram where a pipeline forks, then re-combines later. If order doesn't matter, recombining is easy, the consumer has one yield, but two producers are send()ing to it. But what if order matters? What if I want strict alternation (get a value from left fork, get a value from right fork, lather, rinse, repeat)? Is this possible? Trivial recombine: ``` def producer1(ncr): while True: ncr.send(0) def producer2(ncr): while True: ncr.send(1) def combine(): while True: s=(yield) print(s) chain = combine() chain.__next__() producer1(chain) producer2(chain) ``` I get an output of 0 1 0 1 etc, but I'm pretty sure that's a side effect of scheduling. Is there a way to guarantee the ordering, like a yield-from-1,yield-from-2? To be clear, I know of `yield from` and `__await__`, but I haven't understood them yet.
2018/07/31
[ "https://Stackoverflow.com/questions/51605079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6454568/" ]
This isn't difficult if you "pull" through your pipeline rather than "push": ``` def producer1(): while True: yield 0 def producer2(): while True: yield 1 def combine(*producers): while True: for producer in producers: val = next(producer) print(s) combine(producer1(), producer2()) ``` Should reliably produce alternating 1s and 0s You can also have the final consumer (the thing that does work with each value- printing in this case) work as a receiver with no reference to the producers if you really want: ``` def producer1(): while True: yield 0 def producer2(): while True: yield 1 def combine_to_push(co, *producers): while True: for producer in producers: s = next(producer) co.send(s) def consumer(): while True: val = (yield) print(val) co = consumer() co.__next__() combine_to_push(co, producer1(), producer2()) ```
55,599,038
I have a customers table and an orders table. I want to display the customer and all of his/her order dates on one row, rather than multiple rows. Here is what I have and what I'm looking for: ![Picture of both tables, current results, what i'm looking for](https://i.stack.imgur.com/IQclF.png) Basic code to get results: ``` select customerid, name, orderdate from customer_table c inner join order_table o on c.customerid = o.customerid ```
2019/04/09
[ "https://Stackoverflow.com/questions/55599038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8260859/" ]
this will work at the most you cant show it on different columns having nulls: ``` select customer_id,name,LISTAGG(orderdate, ', ') WITHIN GROUP (ORDER BY orderdate) from(select customerid, name, orderdate from customer_table c inner join order_table o on c.customerid = o.customerid ); ```
20,165,576
I want to add 10 points to each of my students grades with PLSQL. ``` UPDATE AverageView SET AverageModifier = 10 WHERE COURSE_ID = 'INFO101' AND GROUP_ID = 101 AND SEMESTER = 'SUMER14'; ``` So when I try to update the view, I want this trigger activated and I want to use INSTEAD OF UPDATE and modify the real tables. Like this : ``` CREATE OR REPLACE TRIGGER ChangeAverage INSTEAD OF UPDATE ON AverageView FOR EACH ROW BEGIN UPDATE INSCRIPTIONS SET grade = (grade + 10) WHERE COURSE_ID = :NEW.COURSE_ID AND GROUP_ID = :NEW.GROUP_ID AND SEMESTER = :NEW.SEMESTER ; END; / ``` I added a +10 ''manually'' but eventually it will be a just a variable. ``` UPDATE INSCRIPTIONS SET grade = (grade + modifier) .... ``` I think it doesn't work because there is more than one grades to update, and I am stuck there. When I remove the grade and set a static value it ''kind of'' work, but it's setting all the student grades to 10. ``` CREATE OR REPLACE TRIGGER ChangeAverage INSTEAD OF UPDATE ON AverageView FOR EACH ROW BEGIN UPDATE INSCRIPTIONS SET grade = 10 WHERE COURSE_ID = :NEW.COURSE_ID AND GROUP_ID = :NEW.GROUP_ID AND SEMESTER = :NEW.SEMESTER ; END; / ``` Should I use a loop and a cursor ? My inscriptions table looks like this : ``` STUDENT_ID CHAR(12) NOT NULL, COURSE_ID CHAR(12) NOT NULL, GROUP_ID INTEGER NOT NULL, SEMESTER CHAR(12) NOT NULL, REGISTRATION_DATE DATE NOT NULL, GRADE INTEGER, ``` My AverageView is : ``` CREATE OR REPLACE VIEW AverageView AS SELECT COURSE_ID, GROUP_ID, SEMESTER, AVG(GRADE) AS Average FROM Inscriptions GROUP BY COURSE_ID, GROUP_ID, SEMESTER / ``` From what I know of the views, they cant be modified. Instead I modify the inscription table. Lets say my inscriptions table look like this ``` Student A, INFO101, 101, SUMER14, ramdom_date, 70 Student B, INFO101, 101, SUMER14, ramdom_date, 50 ``` My view works perfectly : It outputs an average of 60 for this course. Now, with my trigger, I want to boost the average. ``` UPDATE AverageView SET AverageModifier = 10 WHERE COURSE_ID = 'INFO101' AND GROUP_ID = 101 AND SEMESTER = 'SUMER14'; ``` But from what I know, I cannot modify the content of an view, so I want to add 10 (for now) to every grade in the table inscriptions. So the trigger will result something like that : ``` Student A, INFO101, 101, SUMER14, ramdom_date, 80 Student B, INFO101, 101, SUMER14, ramdom_date, 60 ``` Best regards
2013/11/23
[ "https://Stackoverflow.com/questions/20165576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352575/" ]
Try ``` CREATE OR REPLACE TRIGGER ChangeAverage INSTEAD OF UPDATE ON AverageView FOR EACH ROW BEGIN UPDATE INSCRIPTIONS SET grade = (:old.grade + 10) WHERE COURSE_ID = :NEW.COURSE_ID AND GROUP_ID = :NEW.GROUP_ID AND SEMESTER = :NEW.SEMESTER ; END; / ```
9,271,724
I'm trying to create a function that will check to make sure all the input a user provided is numeric. ``` function wholeFormValid() { var inp = document.getElementsByClassName('userInput'); //userInput is a class name i provide to all my non-hidden input fields. //I have over 20 hidden values (I need to use hidden values to store state in a session). //Wanted to print out what my function is getting. I keep seeing undefined values. var string= "justToInitializeThis"; for(var m in inp) { string = string + " " + inp.value; } alert(string); //Actual function that will be used once I track down the bug. for(var i in inp) { if(inp.value != "") { if(!(/^[0-9]+$/.test(inp.value))) { return false; } } } return true; ``` } The function does get the right input fields back, I can tell from my different pages and they vary in the amount of input a user can give. But what i can't understand is why all my values are returned as null instead of what the user entered. I'm fairly new to HTML & Javascript and just needed a second pair of eyes on this :) Thanks in Advance.
2012/02/14
[ "https://Stackoverflow.com/questions/9271724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/855127/" ]
Use this ``` var inp = document.getElementsByClassName('userInput'); var string= "justToInitializeThis"; for(var i=0; i < inp.length; i++) { string = string + " " + inp[i].value; } alert(string); ``` Same for another loop too
17,279,320
I always use this query in sql server to get Row number in a table: ``` SELECT * FROM (SELECT *, Row_number() OVER( ORDER BY [myidentitycolumn]) RowID FROM mytable) sub WHERE rowid = 15 ``` Now I am working in Access 2010 and this seems to be not working. Is there any replacement for this query in Access?
2013/06/24
[ "https://Stackoverflow.com/questions/17279320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1901125/" ]
MS-Access doesn't support ROW\_NUMBER(). Use TOP 1: ``` SELECT TOP 1 * FROM [MyTable] ORDER BY [MyIdentityCOlumn] ``` If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this: ``` SELECT TOP 1 * FROM ( SELECT TOP 15 * FROM [MyTable] ORDER BY [MyIdentityColumn] ) t ORDER BY [MyIdentityColumn] DESC ```
22,284,380
I am new to reactive programming and confused about composing observables that have dependencies. Here is the scenario: There are two observables **A**, **B**. Observable **A** depends on a value emitted by **B**. (Therefore A needs to observe B). Is there a way to create an Observable **C** that composes **A** and **B**, and emits **V**? I am just looking for pointers in the RxJava [documentation](https://github.com/Netflix/RxJava/wiki).
2014/03/09
[ "https://Stackoverflow.com/questions/22284380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3398673/" ]
You question is a bit vague on how A depends on B so I'll try to give a several examples of how to combine observables. Example - **A** cannot be created without **B** - Use map() ```java public class B { public final int value; public B(int value) { this.value = value; } } public class A { public final B b; public A(B b) { this.b = b; } } public Observable<B> createObservableB() { return Observable.from(new B(0), new B(1), new B(2), new B(3)); } public Observable<A> createObservableA() { return createObservableB() .map(new Func1<B, A>() { @Override public A call(B b) { return new A(b); } }); } ``` Example - Each occurrence of **B** can create zero or more **A** - Use flatMap() ```java public class B { public final int value; public B(int value) { this.value = value; } } public class A { public final int value; public A(int value) { this.value = value; } } public Observable<B> createObservableB() { return Observable.from(new B(0), new B(1), new B(2), new B(3)); } public Observable<A> createObservableA() { return createObservableB() .flatMap(new Func1<B, Observable<? extends A>>() { @Override public Observable<? extends A> call(final B b) { return Observable.create(new Observable.OnSubscribe<A>() { @Override public void call(Subscriber<? super A> subscriber) { for (int i = 0; i < b.value; i++) { subscriber.onNext(new A(i)); } subscriber.onCompleted(); } }); } }); } ``` I'm not exactly sure what you are asking with Observables **C** and **V** so let's look at a few more ways to combine observables. Example - Combine each pair of items emitted by two observables - Use zip() ```java public class A { public final int value; public A(int value) { this.value = value; } } public class B { public final int value; public B(int value) { this.value = value; } } public class C { private final A a; private final B b; public C(A a, B b) { this.a = a; this.b = b; } } public Observable<B> createObservableB() { return Observable.from(new B(0), new B(1), new B(2), new B(3)); } public Observable<A> createObservableA() { return Observable.from(new A(0), new A(1), new A(2), new A(3)); } public Observable<C> createObservableC() { return Observable.zip(createObservableA(), createObservableB(), new Func2<A, B, C>() { @Override public C call(A a, B b) { return new C(a, b); } } ); } ``` Example - Combine the last item of two Observables - Use combineLatest() ```java // Use the same class definitions from previous example. public Observable<C> createObservableC1() { return Observable.combineLatest(createObservableA(), createObservableB(), new Func2<A, B, C>() { @Override public C call(A a, B b) { return new C(a, b); } } ); } ```
53,153,288
So basically what I want to be able to do is to be able to a single property name space that can be overridden by a child of that property's parent. The practical application here is maintaining a Model/View system. Where the views are derived from the same base view class, however some require a more complex model to perform their function. I was wondering if there is a best practice pattern for this since my current approach of just hiding variable namespaces seems too messy. Here's some sample pseudo-code of what I mean: ``` public class ParentPropertyType{ public string bar = "bar"; } public class ChildPropertyType: ParentPropertyType{ public string foo = "foo"; } public class ChildManager:ParentManager { public virtual ChildPropertyType PropertyType {get; set;} } public class ParentManager{ public override ParentPropertyType PropertyType {get; set;} } ... Debug.Log(new ParentManager().PropertyType.foo); ```
2018/11/05
[ "https://Stackoverflow.com/questions/53153288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2941307/" ]
Seems like you should make your `ParentManager`-class generic: ``` public class ChildManager : ParentManager<ChildPropertyType> { } public class ParentManager<T> where T: ParentPropertyType { public T PropertyType { get; set; } } ``` Now you don´t even need `virtual` and `override`, as the property has the correct type depending on the class it is used in. Therefor the following compiles fine, because PropertyType returns an instance of ChildPropertyType: ``` var manager = new ChildManager(); ChildPropertyType c = manager.PropertyType; ```
7,517,885
I wanted to give all of the child's div elements a background-color of parent div. But, as I see, child divs' style overwrite parent's style even though child's did not have that property. For example, ``` <!-- Parent's div --> <div style="background-color:#ADADAD;"> some codes here... <!-- child's div --> <div style="position:absolute;font-size:12px; left:600px;top:100px;"> again some codes... </div> </div> ``` In here, If i delete the style of child div, it works fine. I think my problem may be solved if i did the same thing with external css file also. But, I have already done hundreds of divs exactly like this. So, is there anyway to force parent's style to child style, just for background-color?(new in css)
2011/09/22
[ "https://Stackoverflow.com/questions/7517885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893970/" ]
> > But, as i see, chid divs' style overwrite parent's style even though child's did not have that property. > > > No, they just don't inherit the value by default, so they get whatever value they would otherwise have (which is usually `transparent`). You can (in theory) get what you want with background-color: [inherit](http://www.w3.org/TR/CSS2/cascade.html#value-def-inherit). That has [problems in older versions of IE](https://stackoverflow.com/questions/511066/ie7-css-inherit-problem/511108#511108) though.
422,681
I'm trying to figure out how to integrate one command that updates multiple Aggregates in different contexts in a video game. The components/considerations for my particular design are DDD, CQRS, Ports and Adapters, Event-Driven Architecture, Aggregate+Event Sourcing, and Entity-Component-System. It's a lot to manage, but there are a few cases that can simplify quite a number of the friction points. [![diagram showing interaction between purchase item command and inventory, shop, and wallet contexts](https://i.stack.imgur.com/O7LGC.png)](https://i.stack.imgur.com/O7LGC.png) This diagram kind of illustrates what I'm working with. I have 5 different models, Inventory, Item, Shop, Currency, and Wallet. This is a collaborative, disconnected environment. What I mean by that is, each of these models is designed to not necessarily know about each other, except when necessary. I want these models to be reusable, by unknown third-parties, resulting in other compositions, aside from the ones that I can think of, or the one I'll talk about here. For instance, the Item model doesn't know about the Currency model, or the Wallet model, or the Shop model, or the Inventory model. But, the Inventory deals with storing Items, so it knows about Items. The Shop model knows about assigning prices to Items, so it knows about Items and Currencies. The Wallet model knows about storing and keeping track of money, so it knows about Currencies. Items can be added to a specific Inventory by using an AddItemToInventory command. Money can be removed from a specific Wallet by using a RemoveMoneyFromWallet command. When a Player wants to buy an Item from a Shop, they select the given Item, and if they have enough of the specified type of money in their Wallet, they confirm they want to buy it. At that point, the money is removed from their Wallet, and the specified Item is added to their Inventory. Because this is in a video game, I don't want to create places where duplication can occur. There are two particular cases I want to avoid. * An Item is added to a Player's Inventory, but money is not removed from their Wallet, allowing them to get the Item for free. * Money is removed from a Player's Wallet, but the Item is not added to their Inventory, resulting in lost money. I've been trying to figure out how I can avoid these particular issues. My initial thinking was that this would be managed in a single transaction. The problem though is that these are in different models, different contexts, different Aggregates. Because they are different Aggregates, they shouldn't be updated in the same transaction. Other Aggregates could be updated asynchronously, in my case via published Domain Events. But because they're updated asynchronously, that still leaves open the problems, where items are given, but money isn't taken, or money is taken, and items aren't given. In the diagram, I have the `PurchaseItem` command going into a `???` component. I don't know what it's supposed to be. I didn't want it to be given to the Shop Aggregate, because then the Shop context would have to know about Inventories and Wallets. It knows about Items and Currencies, but it feels improper for it to also know about Inventories and Wallets. The Shop should work in exactly the same way, whether the Item is added to an Inventory, and funds removed from a Wallet; or if the Item is added to a Package, and funds removed in one batch at the end of the day from a Customer Account, or any other combination of things. So more than one Aggregate can't be updated at a time. I'm thinking that either another Aggregate needs to exist somewhere else, which becomes responsible for this interaction. This though would move the Source of Truth to this new Aggregate, making these targeted contexts, sometimes the Source of Truth, sometimes not. More like Eventual Source of Truth. Or, maybe it's acceptable to create a new Aggregate, in a different context, which uses the same Entities and Value Objects of these other contexts. But these other contexts would still own their own data, so it would still be Eventually Consistent. I read in Implementing Domain-Driven Design about a bargain basement Domain Model, where three separate models were used, and a question was posed about whether it makes sense to introduce a new model for the interaction. My problem with that approach is that I still need these other contexts to exist as they are, because third-party developers will use them for completely different purposes. Using Items for Equipment, Money for Quest Rewards, In-game and out-of-game Shops. So I can't just condense these all into a single model, without also forcing those developers to NOT use most of the model that's available. Additionally, all Aggregates in my design are sourced from Events. On the development side, the game developer will create a new Item by assigning a new Item Id. This gets recorded in the game files as an ItemIdAssigned event. Same thing for Currency, Shop, Wallet, Inventory, etc. But once these things are created on the developer side, they're interacted with in completely different ways by the Player. A developer can add an Item to a Shop, a Player can't. A Player can buy an Item from a Shop, a developer can't. This also indicates to me that there are different Aggregates that are at play here that I can't identify. Ones that may be sourced from all, or part, of a different Aggregate's Event Stream. Or that these Aggregates are missing functionality that I haven't been able to understand it's place. How can I model this?
2021/02/24
[ "https://softwareengineering.stackexchange.com/questions/422681", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/161992/" ]
**This answer is based on the presumtion that this is not a hobby project:** Probably that is not what you want to hear , but trying to go at the same time DDD, CQRS, Event Driven Architecture, Event sourcing sounds like a bit of big bite that will lead, either to nowhere, or to a very overengeneered system. If it is a hobby project put it in the description so I will try to answer it. Otherwise my answer is re-think the architecture to have less amount of Buzz words. Pick some concepts of these architectures or just pick one of them and not try to build a system only to test these architectures. I was part once of a project that was trying to utilize at the same time: TDD,CQRS,Event Driven architecture,Behaviour testing and Domain Driven Design and microservice architecture. A project that normaly should take months was year and half in development without visible end because of the added complexity of the different architecture. I find CQRS one of the main sources of overengeneering. I think majority of developers understand very literaly that there MUST BE one read store and one write store which raises multiple problems related to synchronization of two stores. While I have personaly thought that the main principle of CQRS is that you have two different channels and if you actualy have 1 read and 1 write stor or read and write store are the same. As long as you have 2 separate channels all is good.
22,556,020
I am using `Gson` to parse data from Json String. Everything is working fine. But now, Main `Json String` contains Inner Json String and I want that Inner `Json String`'s data. How to get it ? **Check my `Json String`:** ``` [{"Question":"Are you inclined to:","QId":"2","Options":[{"Option":"Argue or debate issues","OptionId":"4"},{"Option":"Avoid arguments","OptionId":"5"},{"Option":"Swutch topics","OptionId":"6"}]}] ``` **Here, I want value of "Options". My Sample code is as below :** ``` PrimaryTest[] testlist = gson.fromJson(result, PrimaryTest[].class); // result is Json String. List<PrimaryTest> lstTest = Arrays.asList(testlist); PrimaryTest objTest = lstTest.get(0); String Question = objTest.getQuestion(); ``` Here, I am getting Question value perfectly but don't know how to get Options value. If I am using same method then It is giving error : `Invalid Json Data`. **PrimaryTest.java Code :** ``` public class PrimaryTest { private String Question; public PrimaryTest(String Question) { this.Question = Question; } public void setQuestion(String Question) { this.Question = Question; } public String getQuestion() { return this.Question; } } ```
2014/03/21
[ "https://Stackoverflow.com/questions/22556020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3234665/" ]
Write your class which include parameter which your JSON string contain so that you can directly parse your string into class object. Your `PrimaryTest` class should contain following members : ``` public class PrimaryTest { private String Question; private int QId; private List<Option> Options; //Getter and Setter methods here } ``` And your `Option` class contain members as shown below : ``` public class Option{ private String Option; private int OptionId; // Getter and Setter methods } ``` Now parse your JSON string in as `PrimaryTest` class and get your `Options` list from getter method of class. Below is the test code : ``` PrimaryTest[] response = gson.fromJson(json, PrimaryTest[].class); List<PrimaryTest> lstTest = Arrays.asList(response); PrimaryTest objTest = lstTest.get(0); List<Option> options = objTest.getOptions(); for(Option option : options){ System.out.println(option.getOption()); } ```
377,189
I'm implementing my own simple database with disk storage, and I'm not sure how to go about modifying and deleting entries. The problem is that as you delete a record from arbitrary position within a file, a "hole" is left there. As you insert a new entry, you may or may not be able to plug it into the hole. Modifying an entry in-place may be possible if the new value is smaller, leaving another hole. Or the new one may be larger, so one has to insert it some place else and delete the old one. Another hole. If implemented like this, the database file starts looking like Swiss cheese after a while. The obvious solution is to run optimization every now and then to compact the file, but that is a tedious and not trivial to implement task as well. For instance, if the file is much larger than the amount of RAM, and you must carefully juggle the records in the file. My question is: are there other approaches to database storage file management? And how do the big database management systems store the data on persistent storage? How do they deal with these problems? I tried Googling but didn't get much info, possibly because I don't even know the right keywords.
2018/08/20
[ "https://softwareengineering.stackexchange.com/questions/377189", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/29016/" ]
The approach you describe is the same which is used, for instance, by SQL Server. With time, the data file grows, and you have to run a maintenance plan in order to [shrink it](https://docs.microsoft.com/en-us/sql/relational-databases/databases/shrink-a-database?view=sql-server-2017) by moving pages from the end of the file to its beginning. The only difference is that you're talking about *records*, while the usual notion is the one of *pages*. Similarly, many file systems have a notion of *fragmentation*, which is eventually solved by performing a *defragmentation* on regular basis. Note that: * If you're creating your own database for learning purposes and shrinking looks too complicated, then maybe you can leave it alone and focus on the things which are fun for your learning project. Just let the file grow over time—it's not like you're expecting to store terabytes of data in a home made database system anyway. * If you're creating your own database because you think you can do a better job compared to all existent database software products, then you may want to reconsider your choice. Note that if relational databases don't fit your needs, you may be better using other types of databases: the ones which store records, the hierarchical ones, the key-value stores, etc.
12,659,035
How to get access to the custom named views instead of giving the same method name in Zend framework 2.0. For Eg: Under index action "return new ViewModel();" will call index.phtml but i want to call an another view here.
2012/09/30
[ "https://Stackoverflow.com/questions/12659035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1608722/" ]
Just call model view with view you want: ``` $model = new ViewModel(); $model->setTemplate('edit'); return $model; ``` More info: <http://framework.zend.com/manual/2.0/en/modules/zend.view.renderer.php-renderer.html>
38,562,968
I know how to dismiss a keyboard, I use this extension: ``` extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } ``` And called `hideKeyboardWhenTappedAround` in `viewDidLoad` But my problem now is I added a `UITextField` to a `navigationBar`, and this extension no longer works! This is how I added the `UITextField`: ``` let textField = UITextField(frame: CGRectMake(0,0,textfieldW,0.8*ram.navigationBarHeight) ) textField.borderStyle = UITextBorderStyle.RoundedRect textField.center.y = centerView.center.y centerView.addSubview(textField) self.navigationItem.titleView = centerView ``` How to dismiss a keyboard brought from a `UITextField` that lurks in a navigation bar? [![enter image description here](https://i.stack.imgur.com/NTwM3.png)](https://i.stack.imgur.com/NTwM3.png)
2016/07/25
[ "https://Stackoverflow.com/questions/38562968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5312361/" ]
Make a reference to this text field, like: ``` var navigationBarField : UITextField? ``` Then initialize it: ``` navigationBarField = UITextField(frame: CGRectMake(0,0,textfieldW,0.8*ram.navigationBarHeight) ) textField.borderStyle = UITextBorderStyle.RoundedRect textField.center.y = centerView.center.y centerView.addSubview(navigationBarField) self.navigationItem.titleView = centerView ``` And when you want to remove keyboard call: ``` navigationBarField?.resignFirstResponder() ```
3,459,990
I have a program that fundamentally requires a lot of memory. However, for some reason java gives me an error when I try to set the max heap space above 1.5GB. That is, running ``` java -Xmx1582m [my program] ``` is okay, but ``` java -Xmx1583m [my program] ``` gives the error ``` Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. ``` I got the same error in both Windows command line and Eclipse. Here are my system configurations: Windows 7 (64-bit) Intel Core 2 Quad CPU Installed RAM: 8.00 GB Java version 1.6.0 It is weird that I can only set 1.5GB memory even though I'm running 64-bit OS with 8 GB RAM. Is there a way to work around this?
2010/08/11
[ "https://Stackoverflow.com/questions/3459990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298724/" ]
The likely case is that while your *operating system* is 64-bit, your JVM is not. Opening a command line and typing `java -version` will give you the verbose version information, which should indicate whether your installed JVM is a 32 or 64-bit build. A 64-bit JVM should have no problem with the higher memory limits.
25,882,522
How can I display result with continue serial number from MySql table using PHP pagination
2014/09/17
[ "https://Stackoverflow.com/questions/25882522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048865/" ]
Try this. It's working for me ``` $pageno = $this->uri->segment(2); // ( $this->uri->segment(2) ) : this is for codeigniter if(empty($pageno) || $pageno == 1){ $srno = 1; } else{ $temp = $pageno-1; $new_temp = $temp.'1'; $srno = (int)$new_temp; } ```
73,271,313
I need to develop a function whereby a type property gets appended to an array if it doesn't exist. So the key will be of type and it should have a value of "dog". Can someone kindly point out how I can iterate over the array to check if the key "type" exists and also provide guidance on how to append {type:"dog"} to the inner array if it doesn't exist. I tried animalArray[0][1]={type:"dog"} but it doesnt seem to work. A typical array of animals will look like this: ``` labelTheDogs( [ {name: 'Obi'}, {name: 'Felix', type: 'cat'} ] ) // should return [ {name: 'Obi', type: 'dog'}, {name: 'Felix', type: 'cat'} ] ```
2022/08/07
[ "https://Stackoverflow.com/questions/73271313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19364797/" ]
This is not a nested array ```js function labelTheDogs(dogs) { dogs.forEach(dog => { if (!dog.type) { dog.type = 'dog' } }) return dogs } const dogs = labelTheDogs( [{ name: 'Obi' }, { name: 'Felix', type: 'cat' } ] ) console.log(dogs) ```
1,662,967
In general, if $X$ is a random variable defined on a probability space $(Ω, Σ, P)$, then the expected value of $X$ is defined as \begin{align} \int\_\Omega X \, \mathrm{d}P = \int\_\Omega X(\omega) P(\mathrm{d}\omega) \end{align} Let $X\_1, X\_2, \dots$ be a sequence of independent random variables identically distributed with probability measure $P$. The empirical measure $P\_n$ is given by \begin{align} P\_n =\frac{1}{n}\sum\_{i=1}^n \delta\_{X\_i} \end{align} Is the following the correct notation for the expectation with respect of the empirical measure? \begin{align} \int\_\Omega X \, \mathrm{d}P\_n = \int\_\Omega X(\omega) P\_n(\mathrm{d}\omega) = \frac{1}{n}\sum\_{i=1}^n X\_i \end{align} **Edit:** What is important for me, is that $P\_n$ is an approximation for $P$. I think $X$ and $X\_1,\dotsc,X\_n$ should map from $(Ω, Σ)$ to some measureable space $(\mathcal{F},\mathscr{F})$.
2016/02/19
[ "https://math.stackexchange.com/questions/1662967", "https://math.stackexchange.com", "https://math.stackexchange.com/users/148666/" ]
It's not correct. The empirical measure isn't a measure on the sample space $\Omega$, it's a (random) measure on $\mathbb{R}$. Notationally, I think most people reserve letters like $P, P\_n$, etc, for measures on $\Omega$, using letters like $\mu, \nu$ for measures on other spaces. So I'd call your empirical measure $\mu\_n$ and then write its mean as $$\int\_{\mathbb{R}} x\,\mu\_n(dx) = \frac{1}{n} \sum\_{i=1}^n X\_i.$$ Note that the left-hand side denotes the integral over $\mathbb{R}$, with respect to the measure $\mu\_n$, of the identity function $f : \mathbb{R} \to \mathbb{R}$ given by $f(x) = x$. The lower-case $x$ is intentional and not a typo.
10,550,398
Editing of controller or any js file of sencha touch application bield from Sencha Architect 2 are editable or not?
2012/05/11
[ "https://Stackoverflow.com/questions/10550398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/861521/" ]
Manually or via the UI? Manually you add a controller and then in the designer view choose CODE and then OVERWRITE. The original is saved (look in the dir structure) Next time open this screen, choose (in the first selector of code view) the VIEW OVERRIDE CODE so that you see your latest work. I work with intellij to edit the file. Then paste it into the field, and it automatically updates both files (there's a .js and an Architect metadata file) Via the UI of course: That's simple. Use the config inspector to select the views models and stores you wish to control. Moshe
50,905
One channel of my split audio is cutting out when the cables are plugged into two devices. I have a computer audio output that I have [this splitter](https://rads.stackoverflow.com/amzn/click/com/B000067RC4) connected to. From the splitter I connect a cable to a standard headset. Then I connect the other cable from the splitter to [this bass amplifier](https://rads.stackoverflow.com/amzn/click/com/B00HWINLAE)'s Input 1/4" jack (with an adapter). This is when the issue occurs. Before I plug into the amp, the headset has sound coming from both ears. After I plug in, all sound stops coming through the right ear of the headset. Unplugging from the amp restores the sound to the right ear. I can't duplicate the output into two separate jacks, so it has to be split from a single one somehow. The behavior is also not limited to that single headset, splitter, or cables. I've tried switching out every part of the setup except for the bass (since I only have one.) I'm sure this is some normal phenomenon, but I can't find anything about it to save my life.
2021/08/24
[ "https://sound.stackexchange.com/questions/50905", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/34185/" ]
Guitar amp input impedance ≅ 1MΩ Headset impedance ≅ 50 - 300Ω Totally mis-matched. However, this doesn't add up to what you're hearing. The amp should be the one suffering lack of signal, though it can make up the gain significantly. Best guess, as your amp is mono, it is shorting one side of the stereo signal, resulting in loss of one side on the headset. In short [pardon the pun] - you really don't want to be doing it that way. Splitters like this really need to be splitting to two very similar devices. You'll need some kind of passive mixer at least to do this even vaguely properly.
41,234,161
Given two `numpy` arrays of `nx3` and `mx3`, what is an efficient way to determine the row indices (counter) wherein the rows are common in the two arrays. For instance I have the following solution, which is significantly slow for not even much larger arrays ``` def arrangment(arr1,arr2): hits = [] for i in range(arr2.shape[0]): current_row = np.repeat(arr2[i,:][None,:],arr1.shape[0],axis=0) x = current_row - arr1 for j in range(arr1.shape[0]): if np.isclose(x[j,0],0.0) and np.isclose(x[j,1],0.0) and np.isclose(x[j,2],0.0): hits.append(j) return hits ``` It checks if rows of `arr2` exist in `arr1` and returns the row indices of `arr1` where the rows match. I need this arrangement to be always sequentially ascending in terms of rows of `arr2`. For instance given ``` arr1 = np.array([[-1., -1., -1.], [ 1., -1., -1.], [ 1., 1., -1.], [-1., 1., -1.], [-1., -1., 1.], [ 1., -1., 1.], [ 1., 1., 1.], [-1., 1., 1.]]) arr2 = np.array([[-1., 1., -1.], [ 1., 1., -1.], [ 1., 1., 1.], [-1., 1., 1.]]) ``` The function should return: ``` [3, 2, 6, 7] ```
2016/12/20
[ "https://Stackoverflow.com/questions/41234161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6345567/" ]
quick and dirty answer ``` (arr1[:, None] == arr2).all(-1).argmax(0) array([3, 2, 6, 7]) ``` --- Better answer Takes care of chance a row in `arr2` doesn't match anything in `arr1` ``` t = (arr1[:, None] == arr2).all(-1) np.where(t.any(0), t.argmax(0), np.nan) array([ 3., 2., 6., 7.]) ``` --- As pointed out by @Divakar `np.isclose` accounts for rounding error in comparing floats ``` t = np.isclose(arr1[:, None], arr2).all(-1) np.where(t.any(0), t.argmax(0), np.nan) ```
684,882
Environment ----------- Operating System: CentOS Linux 8 Virtual Machine running on VMWare Workstation 16 Pro on Windows 11 host. Question -------- I recently had an application lockup while using my VM and I had to power down the VM to recover. When I restarted the VM, I no longer had network access. In Gnome, I lost the network section of the settings application, and if I try to enable the interface using `nmtui` I get `Could not activate connection: Connection 'Host NAT' is not available on device ens160 because device is strictly unmanaged` The device appears in the nmcli status list as type `ethernet` and state `unmanaged`. `ip a` lists the interface with the state UP, but doesn't have an IP address. I tried: * `nmcli device set ens160 managed yes` - No change (still shows unmanaged) * manually editing `ifconfig-ens160` but the settings appear correct * Restarting the Guest OS * Restarting the Host OS One more note: None of the other VMs are showing the same symptoms, so I don't believe its the host OS or the VM configuration. I can't figure out how to restore my interface. Thoughts? Update ------ The interfaces came up when I resumed the VM this morning, so I still don't know what caused it. To answer Alex's questions however: ifcfg-ens160: ``` TYPE=Ethernet PROXY_METHOD=none BROWSER_ONLY=no BOOTPROTO=dhcp DEFROUTE=yes IPV4_FAILURE_FATAL=yes IPV6_DISABLED=yes IPV6INIT=no NAME="Host NAT" UUID=89af5f75-265c-4766-891e-01003ef5a906 DEVICE=ens160 ONBOOT=yes ``` Output of `nmcli con up ens160` ``` Error: unknown connection 'ens160'. ``` Output of `nmcli con up "Host NAT"` ``` Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/7) ```
2022/01/03
[ "https://unix.stackexchange.com/questions/684882", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/96613/" ]
I was able to resolve my issue by suspending the virtual machine and resuming it. I can't quite explain what happened, but it would appear that VMWare changes the state of the network interfaces when suspending a VM and in my case, it wasn't resumed properly. I've had it happen a second time and the suspend/resume approach solved it again.
41,877,490
I'm trying to get the create function to have the user selected values entered into the database. When the create button is pushed, no error is thrown but, the data is not populated. I'm pretty sure my frequency fields are causing the issue but have been unable to come with a solution. There are two different types of frequencies a user can select depending upon their "Notification Name" selection. One selection has 3 separate fields for a numerical value, time frame (week, month etc.), and a before/after selection. The other simply states instantaneous as a static text field. Regardless of which option is chosen the frequency data should be populated into one cell within the database which is then separated using piping where necessary. I'm still pretty new to C# MVC so any help is greatly appreciated. Controller: ``` [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,notificationType1,recipientTypeId,frequency")] NotificationType notificationType) { if (ModelState.IsValid) { db.NotificationType.Add(notificationType); db.SaveChanges(); return RedirectToAction("Create"); } ViewBag.recipientTypeId = new SelectList(db.RecipientType, "Id", "recipientRole", notificationType.recipientTypeId); return View(notificationType); } ``` View ``` @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.notificationType1, "Notification Name", htmlAttributes: new { @class = "control-label col-md-2 helper-format" }) <div class="col-md-10" id="type_selection"> @Html.DropDownList("notificationType1", new List<SelectListItem> { new SelectListItem { Text = "Make a Selection", Value="" }, new SelectListItem { Text = "Incomplete Documents", Value= "Incomplete Documents" }, new SelectListItem { Text = "All Documents Complete", Value = "All Documents Complete" }, new SelectListItem { Text = "Documents Requiring Action", Value = "Documents Requiring Action" } }, new { @class = "helper-format", @id = "value_select", style = "font-family: 'Roboto', Sans Serif;" }) @Html.ValidationMessageFor(model => model.notificationType1, "", new { @class = "text-danger" }) </div> </div> <div class="form-group" id="frequency_group"> @Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-sm-3" id="frequency_group"> @Html.TextBoxFor(model => model.frequency, new { @class = "textbox-width", @placeholder = "42" }) @Html.DropDownList("frequency", new List<SelectListItem> { new SelectListItem { Text = "Day(s)", Value= "| Day"}, new SelectListItem { Text = "Week(s)", Value= "| Week"}, new SelectListItem { Text = "Month(s)", Value= "| Month"} }) @Html.DropDownList("frequency", new List<SelectListItem> { new SelectListItem { Text = "Before", Value= "| Before"}, new SelectListItem { Text = "After", Value= "| After"} }) </div> <p class="col-sm-2" id="psdatetext">The Beginning</p> </div> <div class="form-group" id="freq_instant"> @Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="instant_text"> <p>Instantaneous</p></div> </div> <div class="form-group"> @Html.LabelFor(model => model.recipientTypeId, "Notification For", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("recipientTypeId", new List<SelectListItem> { new SelectListItem { Text = "Me", Value= "Me"}, new SelectListItem { Text = "Account Manager", Value="Account Manager" }, new SelectListItem { Text = "Candidate", Value= "Candidate"}, new SelectListItem { Text = "Recruiter", Value="Recruiter" }, new SelectListItem { Text = "Manager", Value= "Manager"} }) </div> </div> <div class="form-group"> <div class="col-md-offset-1 col-md-10"> <div id="hovercreate"> <button type="submit" value="CREATE" class="btn btn-primary" id="createbtn">CREATE</button> </div> </div> </div> </div> } ``` JS for frequency options ``` @Scripts.Render("~/bundles/jquery") <script type="text/javascript"> $(document).ready(function () { $('#frequency_group').hide() $('#freq_instant').hide() $('#value_select').change(function () { var selection = $('#value_select').val(); $('#frequency_group').hide(); switch (selection) { case 'Incomplete Documents': $('#frequency_group').show(); break; case 'All Documents Complete': $('#frequency_group').show(); break; } }); $('#value_select').on('change', function () { if (this.value == 'Documents Requiring Action') { $("#freq_instant").show(); } else { $("#freq_instant").hide(); } }); }); ```
2017/01/26
[ "https://Stackoverflow.com/questions/41877490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6104319/" ]
Assuming you want the first 10% of rows ordered by Value (desc), you can achieve that by using window functions: ``` select * from ( select ID, Value, COUNT(*) over (partition by ID) as countrows, ROW_NUMBER() over (partition by ID order by Value desc) as rowno from mytable) as innertab where rowno <= floor(countrows*0.1+0.9) order by ID, rowno ``` The floor-thing brings 1 row per 1-10 rows, 2 rows for 11-20 rows and so on.
62,270
I have read the comments from [this question](https://meta.stackexchange.com/questions/62191/questions-getting-closed-too-fast-within-hours-give-it-some-time-to-live) which gave me another proposal. So some people are 'annoyed' if some type of questions are on the front page. Is this a real problem? SO gets a lot of questions that the front page is a moving list. If you want the question out of the front page, have a voting system for moving it instead of closing it. A lot of people do not get the fact that a closed question is basically a signal to users NOT to bother adding more comments or answers to the question. A real DISSERVICE to the poster who is seeking a badly needed answer. A lot of people do not know about re-opening a question or not even care to offer any more help. (Why waste time with a closed questions. Let me run to the new ones) Having a single action, closing, is killing some good questions. Have some other actions like moving questions to another pile or away from the front page. Yeah I know about the bounty system. You lose the points even if you didn't get any answers. It's discouraging to use it unless you really need an answer.
2010/08/25
[ "https://meta.stackexchange.com/questions/62270", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/134444/" ]
A closed question isn't moved off the front page, though, and can be bumped back onto it. Consequently, [a negatively voted question is barred from the front page](https://meta.stackexchange.com/questions/62261/are-edited-questions-no-longer-bumped-to-the-front-page/62262#62262), so we already have a non-closing-based mechanism for removing questions from the front page. For the purpose of front-page-management, I find that the downvotes are good enough and that we don't need to install yet another voting system separate from it.
43,880,219
Probably very simple but got me stumped. I have an overlay menu and some navigation links inside it. What I'd like to do is a simple "slide up" text effect, wherein the text seems to "rise up" from the baseline. It's a commonly seen effect, and I have achieved it playing with line-height and a super simple animation. The jQuery: basically, the idea is that when somebody clicks on the menu icon, the text appears AS it slides up. **The problem: the effect "works", however, when I open the menu, the text actually appears for a split second BEFORE the effect kicks in.** HTML: ``` <ul> <li><span>Hello</span></li> <li><span>Dog</span></li> </ul> ``` CSS: ``` li { overflow: hidden; line-height: 1; } .reveal { display: block; animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 0.5s; } @keyframes reveal { 0% { transform: translate(0, 100%); } 100% { transform: translate(0, 0); } } ``` JQUERY: ``` $(document).ready(function() { $('button').click(function () { //make overlay appear $('li span').addClass('reveal'); //adds the animation to the text }); }); ``` This [jsFiddle](https://jsfiddle.net/m4rbot/v7qvdu46/) will show you the effect I'm going for and the problem. Note: the code is super broken, I just need help with the effect itself. I understand why it happens: I'm telling the browser to translate the text 100% AFTER it has already appeared on screen, without hiding it first. How do I hide the text until the animation kicks in? Nothing I've tried has worked. I just want the text to be invisible UNTIL it slides up into view. What am I doing wrong?
2017/05/09
[ "https://Stackoverflow.com/questions/43880219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7459478/" ]
You can use `animation-fill-mode: forwards` to maintain the end state of the animation. And then translate the starting state: ``` span{ transform: translate(0, 100%); } .reveal { display: block; animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 0.5s forwards; } ```
1,166,068
The **Perron Frobenius theorem** states: > > Any square matrix $A$ with positive entries has a unique eigenvector with > positive entries (up to a multiplication by a positive scalar), and > the corresponding eigenvalue has multiplicity one and is strictly > greater than the absolute value of any other eigenvalue. > > > --- So I **tempted fate** using this matrix: $$ A =\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$$ I find my eigenvalues to be $\lambda\_1 = 0, \lambda\_2 = 2$ Now I find my eigenvector, taking $v\_{11} = 1$, $v\_{21} = 1$ I find $v\_1 = \begin{bmatrix} v\_{11} & v\_{12} \end{bmatrix}$ = $\begin{bmatrix} 1 & -1 \end{bmatrix}$ $v\_1 = \begin{bmatrix} v\_{21} & v\_{22} \end{bmatrix}$ = $\begin{bmatrix} 1 & 1 \end{bmatrix}$ **This verifies the Perron-Frobenius theorem.** --- Now what is the great implication that every positive square matrix has a real eigenvector with an eigenvalue that is the largest of all eigenvalues? Can someone show me an application of this theorem?
2015/02/26
[ "https://math.stackexchange.com/questions/1166068", "https://math.stackexchange.com", "https://math.stackexchange.com/users/105951/" ]
The Perron-Frobenius theorem is used in Google's Pagerank. It's one of the things that make sure that the algorithm works. [Here](http://www.math.pku.edu.cn/teachers/yaoy/Fall2011/lecture07.pdf) it's explained why the the theorem is useful, you have a lot of information with easy explanations on Google.
64,918,101
My primary `nav li` elements shift downwards whenever I hover over them. I thought this was due to use of margin causing this, but I am still receiving this issue after removing margin use, and I'm not sure what it is. I know it's most likely something simple. Any help would be appreciated. Thank you. ```css /*primary nav bar*/ .primarynav { background-color: #ffffff; border: solid 1px #f76f4d; position: relative; height: 50px; width: 1430px; top: 10px; } .primarynav ul { position: relative; padding-bottom: 10px; text-decoration: none; padding-left: 100px; } .primarynav a { position: relative; display: inline-block; text-decoration: none; color: #fd886b; width: 115px; height: 50px; padding: 17px 0px 0px 0px; font-weight: bold; border: 1px solid orangered; } /*primary navigation effects*/ /*.primarynav a:hover::before { background-color: #fd886b; } */ .primarynav a:hover { color: white; background-color: #fd886b; border: 2px solid orangered; border-radius: 3px; } .mainnavigation li { display: inline-block; bottom: 51px; padding-top: 50px; text-align: center; position: relative; font-size: 15px; left: 200px; } ``` ```html <header class="primarynav"> <div class="primaryContainer"> <!-- Main top of page navigation --> <nav alt="worldmainnavigation"><!-- Main navigation buttons on the top of the page (6) --> <ul class= "mainnavigation"> <li><a href="Index.php">Home</a></li> <li><a href="#">Items</a></li> <li><a href="#">Categories</a></li> <li><a href="#">Favourites</a></li> <li><a href="#">Deals</a></li> <li><a href="#">List An Item</a></li> </ul> </nav> </div> </header> ```
2020/11/19
[ "https://Stackoverflow.com/questions/64918101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14390214/" ]
This: ``` if [ "$1" == "" ] ``` should be changed to: ``` if [ -z "$1" ] ``` `-z` is true if the string is zero length. `==` is used with `[[ ]]` while `=` is used with `[ ]`. You can read more about bash string comparison in [How to Compare Strings in Bash](https://linuxize.com/post/how-to-compare-strings-in-bash/).
43,276,990
I'm trying to write a code to do the following: 1. Using text-to-columns,the data should get divided in different columns. The data in Cells A1-A8 is like this: [![enter image description here](https://i.stack.imgur.com/uqIgn.png)](https://i.stack.imgur.com/uqIgn.png) This data should appear in different columns.
2017/04/07
[ "https://Stackoverflow.com/questions/43276990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7832343/" ]
When you log in or log out from child component, emit 'login' or 'logout' event respectively. ``` <template> <div id="app"> <router-view name='login' @login="login=true"></router-view> <router-view name='header' @logout="login=false"></router-view> <keep-alive v-if="login"> <router-view name='write'></router-view> </keep-alive> <router-view name='management'></router-view> <router-view name='account'></router-view> <router-view name='statistics'></router-view> <router-view name='view'></router-view> <router-view name='password'></router-view> </div> </template> <script> export default { name: 'app', data () { return { login: true } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 0; height: 100%; } </style> ```
6,360,499
What does @propert(retain) do? it doesn't actually retain my object by my tests: ``` id obj = getObjectSomehow(); NSLog(@"%d", [obj retainCount]); propertyWithRetain = obj; NSLog(@"%d", [obj retainCount]); // output: // 1 // 1 ``` How can I make a property that will really retain the object?
2011/06/15
[ "https://Stackoverflow.com/questions/6360499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362589/" ]
You're not using your property there, that's why it's not retaining! Try this : ``` id obj = getObjectSomehow(); NSLog(@"%d", [obj retainCount]); self.propertyWithRetain = obj; // Note the self. :) NSLog(@"%d", [obj retainCount]); ``` Using `self.` will use the property. Just using the variable name won't. --- EDIT especially for @bbum (who raises a very fair point in the comments) Don't rely on using retainCount - you don't know what else has retained your object and you don't know if some of those retains are actually scheduled autoreleases so it's usually a misleading number :)
19,104
When making a roll on Majesty to Awe people, is a Vampire permitted to make use of the +2 (or +4) social bonus for the merit of being exceptionally attractive?
2012/11/29
[ "https://rpg.stackexchange.com/questions/19104", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/5649/" ]
Yes. ---- Unless explicitly forbidden, Merits (like Striking Looks) do apply to Discipline rolls.
12,866,808
How do I use regex to convert ``` 11111aA$xx1111xxdj$%%` ``` to ``` aA$xx1111xxdj$%% ``` So, in other words, I want to remove (or match) the FIRST grouping of `1`'s.
2012/10/12
[ "https://Stackoverflow.com/questions/12866808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140811/" ]
Depending on the language, you should have a way to replace a string by regex. In Java, you can do it like this: ``` String s = "11111aA$xx1111xxdj$%%"; String res = s.replaceAll("^1+", ""); ``` The `^` "anchor" indicates that the beginning of the input must be matched. The `1+` means a sequence of one or more `1` characters. Here is a [link to ideone](http://ideone.com/MhsdN) with this running program. The same program in C#: ``` var rx = new Regex("^1+"); var s = "11111aA$xx1111xxdj$%%"; var res = rx.Replace(s, ""); Console.WriteLine(res); ``` ([link to ideone](http://ideone.com/fGilt)) In general, if you would like to make a match of anything only at the beginning of a string, add a `^` prefix to your expression; similarly, adding a `$` at the end makes the match accept only strings at the end of your input.
189,588
I've been led to believe that for single variable assignment in T-SQL, `set` is the best way to go about things, for two reasons: * it's the ANSI standard for variable assignment * it's actually faster than doing a SELECT (for a single variable) So... ``` SELECT @thingy = 'turnip shaped' ``` becomes ``` SET @thingy = 'turnip shaped' ``` But how fast, is *fast*? Am I ever really going to notice the difference?
2008/10/09
[ "https://Stackoverflow.com/questions/189588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
SET is faster on single runs. You can prove this easily enough. Whether or not it makes a difference is up to you, but I prefer SET, since I don't see the point of SELECT if all the code is doing is an assignment. I prefer to keep SELECT confined to SELECT statements from tables, views, etc. Here is a sample script, with the number of runs set to 1: ``` SET NOCOUNT ON DECLARE @runs int DECLARE @i int, @j int SET @runs = 1 SET @i = 0 SET @j = 0 DECLARE @dtStartDate datetime, @dtEndDate datetime WHILE @runs > 0 BEGIN SET @j = 0 SET @dtStartDate = CURRENT_TIMESTAMP WHILE @j < 1000000 BEGIN SET @i = @j SET @j = @j + 1 END SELECT @dtEndDate = CURRENT_TIMESTAMP SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS SET @j = 0 SET @dtStartDate = CURRENT_TIMESTAMP WHILE @j < 1000000 BEGIN SELECT @i = @j SET @j = @j + 1 END SELECT @dtEndDate = CURRENT_TIMESTAMP SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS SET @runs = @runs - 1 END ``` RESULTS: Run #1: SET\_MILLISECONDS 5093 SELECT\_MILLISECONDS 5186 Run #2: SET\_MILLISECONDS 4876 SELECT\_MILLISECONDS 5466 Run #3: SET\_MILLISECONDS 4936 SELECT\_MILLISECONDS 5453 Run #4: SET\_MILLISECONDS 4920 SELECT\_MILLISECONDS 5250 Run #5: SET\_MILLISECONDS 4860 SELECT\_MILLISECONDS 5093 **Oddly, if you crank the number of runs up to say, 10, the SET begins to lag behind.** Here is a 10-run result: SET\_MILLISECONDS 5140 SELECT\_MILLISECONDS 5266 SET\_MILLISECONDS 5250 SELECT\_MILLISECONDS 5466 SET\_MILLISECONDS 5220 SELECT\_MILLISECONDS 5280 SET\_MILLISECONDS 5376 SELECT\_MILLISECONDS 5280 SET\_MILLISECONDS 5233 SELECT\_MILLISECONDS 5453 SET\_MILLISECONDS 5343 SELECT\_MILLISECONDS 5423 SET\_MILLISECONDS 5360 SELECT\_MILLISECONDS 5156 SET\_MILLISECONDS 5686 SELECT\_MILLISECONDS 5233 SET\_MILLISECONDS 5436 SELECT\_MILLISECONDS 5500 SET\_MILLISECONDS 5610 SELECT\_MILLISECONDS 5266
445,436
A block is suspended from a string; does the gravitational force do any work on it?
2018/12/06
[ "https://physics.stackexchange.com/questions/445436", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/215172/" ]
Work is performed when the point of application of a force travels through a distance in the direction of the force. An object suspended by a string in a gravitational field experiences the force of gravity but if it does not move, then no work is being done on it.
45,648,411
I am working on a windows application where I get value of a string called 'strData' from a function which has '\' in it. I want to split that string by '\' but I don't know why 'Split' function is not working. ``` string strData= "0101-0000046C\0\0\0"; //This Value comes from a function string[] strTemp = strData.Split('\\'); return strTemp[0]; ``` The Value of 'strTemp[0]' is still "0101-0000046C\0\0\0". Please Help me
2017/08/12
[ "https://Stackoverflow.com/questions/45648411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6529025/" ]
Your data is interpreted as a non-escaped string: this means all your `\0` in your code file get resolved to the ascii-char with the value of 0 (value-zero-char). In your case you finally have to replace the value-zero-char like this: `strData = strData.Replace("\0", "0\\");` then it works. **Explanation:** this replaces the value-zero-char with a number-zero-char and a backslash. As said you either have to escape the source string to `xxx\\0` or write an `@`-sign in front of the string- declaration like this: `var x = @"xxx";` (only theoretically, second method does not work here because you said you get the value from a function). This does in both cases normally solve your issue.
25,450,780
I'm having a strange issue with a permanent redirection in PHP. Here's the code I'm using: ``` if ($_SERVER['HTTP_HOST'] != 'www.mydomain.ca') { header("HTTP/1.1 301 Moved Permanently"); $loc = "http://www.mydomain.ca".$_SERVER['SCRIPT_NAME']; header("Location: ".$loc); exit; } ``` So, the home page, referenced either by www.myolddomain.ca or www.myolddomain.ca/index.php both work but every other page on the site fails to redirect. I've spent a couple of hours looking at this from all the angles I know and can't fathom it. Does anyone have any idea what the issue could be? As a note, I've tried this without the 301 header too and get the same issue.
2014/08/22
[ "https://Stackoverflow.com/questions/25450780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300171/" ]
If you have a ftp-account to the server, you can create a .htaccess file and let it handle the requests. Just create a file named `.htaccess` in the root-folder of your site and post the code, changed to your desired pattern(s) ``` Options +FollowSymLinks RewriteEngine on RewriteCond {HTTP_HOST} ^yourdomain.com RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L] ``` If you want to do it fix via `PHP`, I would create a `redirect.php` and include it on every site you need it. Hard to tell if this is the best solution, it is a bit depending on your way of layouting and structuring.
43,741
I'm building a piece of software which will have a filtering system that involves multiple flags. The complication is that each flag has three possible states: 1. On 2. Off 3. N/A (i.e. It can't be applied, for whatever reason) Here's my current plan: ![enter image description here](https://i.stack.imgur.com/xPbFC.png) So the "Size" and "Weight" flags are "on", "Height" is off and "Lid Width" is N/A (None of the products actually have a lid). Clicking each box toggles the flag, unless it is N/A. However this method has it's limitations: One of which is that it relies on colour, preventing use by colour-blind users. I could use checkboxes instead, but they take longer to read and absorb when there are a lot visible at once. N.B. The software will *only* be used by a small selection of experts for many hours a day. So it is less important for it to be easy to learn, and more important for it to be quick to use and visually clear what's going on at all times.
2013/08/15
[ "https://ux.stackexchange.com/questions/43741", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/11647/" ]
Suggested solution: ![enter image description here](https://i.stack.imgur.com/bgc2R.png) > > How should I visually represent multiple three-state flags? The > complication is that each flag has three possible states > > > Means there are only two states "on/off" for the component, but component itself can be disabled or enabled. So it is enough to have two state switch. ![enter image description here](https://i.stack.imgur.com/fbxlS.png) Having that understanding it is possible to throw switch away and use ordinary check-boxes instead (preferred solution). ![enter image description here](https://i.stack.imgur.com/mXqQY.png)
67,585,943
I don't know what's wrong here, all I'm trying to do is to open this file, but it says it can't find such a file or directory, however as I have highlighted on the side, the file is right there. I just want to open it. I have opened files before but never encountered this. I must have missed something, I checked online, and seems like my syntax is correct, but I don't know. I get the same error when I try with "alphabetical\_words" which is just a text file. [![enter image description here](https://i.stack.imgur.com/qllVh.png)](https://i.stack.imgur.com/qllVh.png)
2021/05/18
[ "https://Stackoverflow.com/questions/67585943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054031/" ]
When [open()](https://docs.python.org/3/library/functions.html#open) function receives a relative path, it looks for that file relative to the current working directory. In other words: relative to the current directory from where the script is run. This can be any arbitrary location. I guess what you want to do is look for `alphabetical.csv` file relative to the script location. To do that use the following formula: ```py from pathlib import Path # Get directory of this script THIS_DIR = Path(__file__).absolute().parent # Get path of CSV file relative to the directory of this script CSV_PATH = THIS_DIR.joinpath("alphabetical.csv") # Open the CSV file using a with-block with CSV_PATH.open(encoding="utf-8") as csvfile: pass # Do stuff with opened file ```
112,725
I've heard much about bitcoin maximalism. As I've googled it, a bitcoin maximalist is a person who believe that the only real cryptocurrency would really be needed in the future is the bitcoin. Is this correct? Can someone explain it in simple language to me and also the root causes of this belief? Why would some people believe that bitcoin is the only cryptocurrency ever man would need? Thanks in advance.
2022/03/04
[ "https://bitcoin.stackexchange.com/questions/112725", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/101040/" ]
I think your question might be opinion-based and therefore off-topic on this site, but I'll still try to give a helpful answer. Bitcoin maximalists believe that bitcoin is the only cryptocurrency worth holding, studying and/or building upon. That belief comes from any of these and/or related claims (with varying degrees of verifiability): * Bitcoin is the only cryptocurrency that is truly decentralized. (Its creator is unknown and has not been involved with the project for many years, and there is no central authority saying what the protocol changes should be.) * Bitcoin is the only cryptocurrency that is distributed fairly. (There was no pre-sale for insiders, no pre-mine, everyone had the opportunity to mine right from the start.) * Any claimed improvements brought by other cryptocurrencies can be implemented in bitcoin as well if they are shown to be useful. * Bitcoin has the most proof of work going into it, making it the "most secure" chain.
258,812
I want to plot the waveform of an audiosnippet. Since I am working in matlab I exported my audiofile as csv with two columns (n, in). Of course this produces a huge file of about 40MB for my 1 000 000 datapoints. When I now try to plot this using pgf latex will run into a memory error. ``` TeX capacity exceeded, sorry [main memory size=5000000]. ...=in,col sep=comma] {audio.csv}; ``` Here is the code I am using to plot: ``` \begin{tikzpicture} \begin{axis}[width = 18cm, height=6cm,grid=both,xlabel={$n$},ylabel={$x(n)$},ymin=-1, ymax=1,minor y tick num=1,xmin=0, xmax=1000000] \addplot[color=niceblue] table[x=n,y=in,col sep=comma] {audio.csv}; \end{axis} \end{tikzpicture} ``` My first try was to reduce the filesize by only using every 128th datapoint. But this way I lose "interesting" datapoints, like the peaks. This makes my plot look incorrect. Does anyone have an idea how to get a nice plot for my waveform?
2015/08/05
[ "https://tex.stackexchange.com/questions/258812", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/83229/" ]
Perhaps you can reduce the number of points by only plotting the envelope of the waveform. Im not certain if that would suffice for your waveform, but you can use Matlab to extract the envelope from the waveform; <http://mathworks.com/help/signal/ug/envelope-extraction-using-the-analytic-signal.html>
33,311,725
With the new Codeigniter 3.0 version what authentication libraries do you use? * [Flexi auth](http://haseydesign.com/flexi-auth/) was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old `ci_sessions` schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though. * [Community auth](http://community-auth.com/) has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly. * [Tank Auth](https://konyukhov.com/soft/tank_auth/) was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. [Questions about its compatibility](https://github.com/TankAuth/Tank-Auth/issues/74) with CI 3.0 were asked but no airplanes in the horizon so far. * [DX Auth](https://github.com/eyoosuf/DX-Auth/issues) is an old authentication library and as I can see on its github repository, there are some [attempts to migrate it](https://github.com/iwatllc/DX-Auth) on CI 3.0 but I haven't been able personally to test any of them. So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter? Update for the down votes ========================= [This post about Authentication libraries](https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter?rq=1) in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that.
2015/10/23
[ "https://Stackoverflow.com/questions/33311725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219806/" ]
don't let the down votes get ya down. check out Ion Auth <https://github.com/benedmunds/CodeIgniter-Ion-Auth> take a look at the read me, you will have to rename two files for codeigniter 3. otherwise you can see that there are recent changes to the lib. the author Ben Edmunds is one of the four developers on the new codeigniter council. <http://www.codeigniter.com/help/about>
2,863,587
Given $x\_0 \ldots x\_k$ and $n$, Define $$f(Q)=\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$. Note that $$\sum\_{Q=0}^{n\*k} f(Q)=(\sum\_{i=0}^{k}x\_i)^n$$ which comes from the multinomial expansion. I was wondering how to calculate $\sum\_{Q=0}^{n\*k} Q\cdot f(Q)$. I've checked several small cases, and it seems that $\sum\_{Q=0}^{n\*k} Q\cdot f(Q) = n(\sum\_{i=0}^{k}x\_i)^{n-1}(\sum\_{i=0}^{k}ix\_i)$, but I'm not sure how to prove that.
2018/07/26
[ "https://math.stackexchange.com/questions/2863587", "https://math.stackexchange.com", "https://math.stackexchange.com/users/376930/" ]
You can calculate the generating function instead. Define $$ \begin{aligned} F(X,Y)&= \sum\_{n=0}^\infty X^n\sum\_{Q=0}^\infty Y^Q \sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}\\ &=\sum\_{n=0}^\infty X^n\sum\_{Q=0}^\infty Y^Q \sum\_{n\_0, \cdots, n\_k\geq 0} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k} \delta\left(n-\sum\_{j=0}^k n\_j\right) \delta\left(Q-\sum\_{j=0}^k jn\_j\right)\\ &= \sum\_{n\_0, \cdots, n\_k\geq 0} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k} X^{\sum\_j n\_j} Y^{\sum\_j jn\_j}\\ &=\prod\_{m=0}^k \exp(x\_m XY^m) \end{aligned} $$ where by $\delta(Z)$ I mean the Kronecker delta equating $Z=0$. What you are looking for the $n!$ times the coefficient of $X^nY^Q$ in the expansion of $F(X,Y)$ (in other words, $(Q!)^{-1}\partial\_X^n \partial\_Y^Q F\mid\_{X=Y=0}$).
53,022,575
I'm trying to write a regex in php to split the string to array. The string is ``` #000000 | Black #ffffff | White #ff0000 | Red ``` there can or cannot be space between the character and ``` | ``` so the regex needs to work with ``` #000000|Black #ffffff|White #ff0000|Red ``` For the second type of string this works. ``` $str = preg_split('/[\s]+/', $str); ``` How can I modify it to work with the first and second both strings? Edit: Final output needs to be ``` Array ( [0] => Array ( [0] => #000000 [1] => Black ) [1] => Array ( [0] => #ffffff [1] => White ) [2] => Array ( [0] => #ff0000 [1] => Red) ) ```
2018/10/27
[ "https://Stackoverflow.com/questions/53022575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10519464/" ]
From <https://firebase.google.com/docs/android/setup> it looks like 16.0.4 is latest version ``` com.google.firebase:firebase-core:16.0.4 ```
67,122,003
> > **Task:** According to the Taylor Series of sin(x) calculate with using a double function named **mysin** pass it to a double variable. Take a x value from user and use the mysin function to calculate sin(x). > > > [![Sin()x Tyler Series Formula](https://i.stack.imgur.com/elqSV.png)](https://i.stack.imgur.com/elqSV.png) > > > Problem is program gives me wrong value of sin(x). I have been trying to solve that issue about 4 hours but couldn't find it. Is it because of sin(x) function or have I missed something in my code? **My Code:** ``` #include <stdio.h> double mysin(double x) { double value = x; double sum = x; int neg_pos = 1; int fac = 1; int counter = 0; while(1) { neg_pos *= -1; fac += 2; value = value/(fac*(fac-1)); value = value*x*x*neg_pos; sum += value; //printf("Hello"); counter++; if (counter == 100) break; } return sum; } int main() { double number; scanf("%lf",&number); printf("%g",mysin(number)); //printf("%g",number); } ```
2021/04/16
[ "https://Stackoverflow.com/questions/67122003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14886767/" ]
The problem is that you're multiplying by `neg_pos` each step, which toggles between +1 and -1. That means the terms change sign only half the time, whereas they should change sign each time. The fix is to just multiply by -1 each time rather than `neg_pos`. Here's a working, slightly-simplified form of your program that calculates sin for a range of numbers from 0 to 3, showing the stdlib calculation to compare. ``` #include <math.h> #include <stdio.h> double mysin(double x) { double value = x; double sum = x; int fac = 1; for (int counter = 0; counter < 100; counter++) { fac += 2; value = -value*x*x/fac/(fac-1); sum += value; } return sum; } int main() { for (double x = 0.0; x < 3.0; x += 0.1) { printf("%g: %g %g\n", x, mysin(x), sin(x)); } } ``` You can also avoid the separate `fac` and `counter` variables, perhaps like this: ``` double mysin(double x) { double term=x, sum=x; for (int f = 0; f < 100; f++) { term = -term*x*x/(2*f+2)/(2*f+3); sum += term; } return sum; } ```
1,399,204
Please help in Solving the Trigonometric Equation: $$\cos^2x - \sin^2x = \cos3x$$
2015/08/16
[ "https://math.stackexchange.com/questions/1399204", "https://math.stackexchange.com", "https://math.stackexchange.com/users/262417/" ]
$$\begin{align\*} \cos^2x-\sin^2x &= \cos3x\\ \cos2x &= \cos3x\\ 2x &= 2\pi n\pm 3x\\ x &= 2\pi n \text{ or } x=\frac{2\pi n}{5} \end{align\*}$$ where $n\in\mathbb Z$. @ThomasAndrews: The second case includes the first case. $2\pi n=\frac{2\pi(5n)}5$.
4,642,372
Working over the real line, I am interested in the integral of the form $$ I := \int\_a^b dx \int\_a^x dy f(y) \delta'(y), $$ where $a < 0 < b < \infty$, $f$ is some smooth test function with compact support such that $(a,b) \subset supp(f)$, and $\delta$ is the usual Dirac delta "function". At first, when attempting to evaluate this integral, I naively used that $\delta'(f) = -\delta(f')=-f'(0)$ so that the above integral would evaluate to $(a-b) f'(0)$. However, looking at it more closely, the result $\delta'(f) = -\delta(f')$ which can be attributed to "integration by parts", is really only working if the integration is actually over the support of $f$. This is not the case for the first integral. Instead, I modified the relation such that $$ I = \int\_a^b dx \left( [f(y) \delta(y)]\_a^x - \int\_a^x dyf'(y) \delta(y) \right)= \int\_a^b dx \left(f(x) \delta(x) - f'(0) \right) = f(0) + (a-b) f'(0). $$ Is this the correct way to do this? I simply generalised the "integration by parts" rule. Is there a rigourous explanation why this is the correct answer?
2023/02/19
[ "https://math.stackexchange.com/questions/4642372", "https://math.stackexchange.com", "https://math.stackexchange.com/users/604598/" ]
To expand a first-order theory to a second-order theory conservatively (i.e. without adding new first-order definable sets) you have to add a sort for every "definition-scheme". I.e. a sort for every partitioned formula $\varphi(x;y)$. The canonical expansion of a first-order structure $M$ has, beside the domain of the home sort $M$, a domain for each sort $\varphi(x;y)$ that contains (as elements) the sets $\varphi(U;b)$ where $U$ is a large saturated extension of $M$ and $b∈ M^y$. In the language of of $M$ is expanded with the membership relations. --- You find the construction above, with all the gory details, in the Section 13.2 (*The eq-expansion*) of [these notes](https://github.com/domenicozambella/creche/raw/master/PDF/creche.pdf). In the notes a second-order expansion is used to construct (a version of) Shelah's $T^{\rm eq}$. If I understand it well, this comes close to the expansion you are proposing, only much tamer form the model-theoretic point of view.
47,486
I have a friction damping system which is exited by a harmonic force FE (depicted on the left side). Is there a way to convert the friction damper to a linear or nonlinear damper, such that the damping at a given excitement frequency is equal? I am only considering sliding friction. A reasonable approximation would be sufficient as well. Any papers or articles on the topic would also be highly appreciated. [![enter image description here](https://i.stack.imgur.com/YkzOK.png)](https://i.stack.imgur.com/YkzOK.png)
2021/09/29
[ "https://engineering.stackexchange.com/questions/47486", "https://engineering.stackexchange.com", "https://engineering.stackexchange.com/users/25247/" ]
In general this is impossible, because for a given value of $F\_e$, the friction damper dissipates a fixed amount of energy per cycle of vibration *independent of the vibration frequency.* This is (nonlinear) *hysteretic* damping, not (nonlinear) *viscous* damping. The only way to approximate this with a viscous damper would be to make $C$ a function of both the $F\_e$ and the frequency $\omega$, which won't produce a useful equation of motion except in the special case where the machine only operates at one fixed frequency $\omega$. Aside from that issue, a general way to make the approximation is to model one cycle of the stick-slip motion of the friction damper and find the energy dissipated during the cycle. Then choose $C$ to dissipate the same amount of energy. For a simple slip-stick damper you can do this from first principles, though the details are messy, and you need the complete equation of motion of the system - you haven't specified how the mass and/or stiffness are connected to the damper. A more general approach is to use the so-called Harmonic Balance Method to produce a numerical approximation. There are many variations on the basic idea (and many research papers describing them!) but one implementation is the NLVib function in Matlab.
43,621,532
I'm trying to release a Xamarin.Forms application, but when I change to release in the configuration for the Android project and build I get the following error: ``` Java.Interop.Tools.Diagnostics.XamarinAndroidException: error XA2006: Could not resolve reference to 'System.Int32 Xamarin.Forms.Platform.Resource/String::ApplicationName' (defined in assembly 'Syncfusion.SfChart.XForms.Android, Version=13.2451.0.29, Culture=neutral, PublicKeyToken=null') with scope 'Xamarin.Forms.Platform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. When the scope is different from the defining assembly, it usually means that the type is forwarded. ---> Mono.Cecil.ResolutionException: Failed to resolve System.Int32 Xamarin.Forms.Platform.Resource/String::ApplicationName at Mono.Linker.Steps.MarkStep.MarkField(FieldReference reference) at Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction) at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body) at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method) at Mono.Linker.Steps.MarkStep.ProcessQueue() at Mono.Linker.Steps.MarkStep.Process() at Mono.Linker.Steps.MarkStep.Process(LinkContext context) at MonoDroid.Tuner.MonoDroidMarkStep.Process(LinkContext context) at Mono.Linker.Pipeline.Process(LinkContext context) at MonoDroid.Tuner.Linker.Process(LinkerOptions options, LinkContext& context) at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res) --- End of inner exception stack trace --- at Java.Interop.Tools.Diagnostics.Diagnostic.Error(Int32 code, Exception innerException, String message, Object[] args) at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res) at Xamarin.Android.Tasks.LinkAssemblies.Execute() at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() XamarinCRM.Android ```
2017/04/25
[ "https://Stackoverflow.com/questions/43621532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The same error message occurred with me. I was able to solve it like this: Right-click the **Android Project > Properties > Android Options > Linker**, and then choose the "None" option in the **Linking** property.
7,581,534
The following linq ``` var subjectMarks = (from DataRow row in objDatatable.Rows select Convert.ToDecimal(row["EXM_MARKS"])).Sum(); ``` throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc. How can I get the sum of only numeric ones out of them?
2011/09/28
[ "https://Stackoverflow.com/questions/7581534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769091/" ]
Add `where` clause that filters out the records that cannot be parsed as decimals. Try: ``` decimal dummy; var subjectMarks = (from DataRow row in objDatatable.Rows where decimal.TryParse(row["EXM_MARKS"], out dummy) select Convert.ToDecimal(row["EXM_MARKS"])).Sum(); ```
53,124
What I understand of these two terms is that: Paratope is a portion of antibody that recognises and binds to specific antigen. Idiotype is an antigenic determinant of antibody formed of CDRs that have specificity for a particular epitope. Some authors call the antibodies recognising a particular epitope an idiotype. Well the CDRs, they actually form the paratope so is it right to say the CDR that acts as an paratope also forms the idiotypic determinant/ idiotype ?
2016/11/04
[ "https://biology.stackexchange.com/questions/53124", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/16460/" ]
I have read that the unique amino acid sequence of the VH and VL domains of a given antibody can function not only as an antigen-binding site but also as a set of antigenic determinants. the idiotypic determinants are generated by the confomation of the heavy- and light-chain variable region. Each individual antigenic determinant of the variable region is referred to as an idiotope. In some cases an idiotope may be the actual antigen-binding site (The paratope), and in some cases an idiotope may comprise variable region sequences OUTSIDE of the antigen-binding site. Therefore, each antibody will present multiple idiotopes, and the sum of the individual idiotopes is called the IDIOTYPE of the antibody. I hope that had been helpful
20,129,762
In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method ``` Iterator<T> iterator() ``` So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case. When I want to iterate over a Stream using a foreach loop, I have to do something like ``` public static Iterable<T> getIterable(Stream<T> s) { return new Iterable<T> { @Override public Iterator<T> iterator() { return s.iterator(); } }; } for (T element : getIterable(s)) { ... } ``` Am I missing something here?
2013/11/21
[ "https://Stackoverflow.com/questions/20129762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938782/" ]
People have already asked the same [on the mailing list](http://mail.openjdk.java.net/pipermail/lambda-dev/2013-March/008876.html) ☺. The main reason is Iterable also has a re-iterable semantic, while Stream is not. > > I think the main reason is that `Iterable` implies reusability, whereas `Stream` is something that can only be used once — more like an `Iterator`. > > > If `Stream` extended `Iterable` then existing code might be surprised when it receives an `Iterable` that throws an `Exception` the > second time they do `for (element : iterable)`. > > >
15,470,452
I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video? I have search about background task & background thread ,IOS only support music in background (Not video) <http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html> here is some discussion about play video in background 1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0> 2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html> But there are many apps in AppStore, that play video in Background like Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2> SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8>
2013/03/18
[ "https://Stackoverflow.com/questions/15470452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647942/" ]
This method supports all the possibilities: * Screen locked by the user; * List item * Home button pressed; As long as you have an instance of AVPlayer running iOS prevents auto lock of the device. First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element. Then put in your AppDelegate.m into **- (BOOL)application:(UIApplication \*)application didFinishLaunchingWithOptions:(NSDictionary \*)launchOptions:** these methods ``` [[AVAudioSession sharedInstance] setDelegate: self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; ``` and **#import < AVFoundation/AVFoundation.h >** Then in your view controller that controls AVPlayer ``` -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder]; } ``` and ``` - (void)viewWillDisappear:(BOOL)animated { [mPlayer pause]; [super viewWillDisappear:animated]; [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; [self resignFirstResponder]; } ``` then respond to the ``` - (void)remoteControlReceivedWithEvent:(UIEvent *)event { switch (event.subtype) { case UIEventSubtypeRemoteControlTogglePlayPause: if([mPlayer rate] == 0){ [mPlayer play]; } else { [mPlayer pause]; } break; case UIEventSubtypeRemoteControlPlay: [mPlayer play]; break; case UIEventSubtypeRemoteControlPause: [mPlayer pause]; break; default: break; } } ``` Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out). When you control the reproduction of the video (I have play methods) set ``` [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; ``` and the corresponding method to be invoked that will launch a timer and resume the reproduction. ``` - (void)applicationDidEnterBackground:(NSNotification *)notification { [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01]; } ``` Its works for me to play video in Backgorund. Thanks to all.
48,421,109
I am having problem installing a custom plugin in Cordova. ``` plugman -d install --platform android --project platforms\android --plugin plugins\PrintName ``` error: ``` Cannot read property 'fail' of undefined TypeError: Cannot read property 'fail' of undefined at C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\cordova-lib\src\plugman\fetch.js:168:18 at _fulfilled (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:787:54) at self.promiseDispatch.done (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:816:30) at Promise.promise.promiseDispatch (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:749:13) at C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:509:49 at flush (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:108:17) at _combinedTickCallback (internal/process/next_tick.js:131:7) at process._tickCallback (internal/process/next_tick.js:180:9) at Function.Module.runMain (module.js:686:11) at startup (bootstrap_node.js:187:16) ```
2018/01/24
[ "https://Stackoverflow.com/questions/48421109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268945/" ]
What I ended up having to do is uninstall plugman 2.0 ``` npm remove -g plugman ``` Then I install plugman version 1.5.1 ``` npm install -g [email protected] ``` Then I could finally add plugins to the project.
546,205
I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards. However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV. Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general?
2021/09/27
[ "https://stats.stackexchange.com/questions/546205", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/79469/" ]
I can't say with 100% certainty, but I can give you my two cents. Let's start with the difference in philosophy between statistics (as practised in the books mentioned) and machine learning. The former is (usually, but not always) concerned with some sort of inference. There is usually a latent parameter, like the sample mean or the effect of a novel drug, which requires estimation as well as a statement on the precision of the estimate. The latter (usually, but not always) eschews estimating anything except the conditional mean (be it a regression or a probability in the case of some classification models). Thus "model selection" in each context means something slightly different by virtue of having different goals. Cross validation is a means of selecting models by means of estimating their generalization error. It is, therefore, primarily a tool for predictive modelling. But statistics (again usually, but always) is not concerned with generalization error as much as it is concerned with parsimony (for example), hence statistics don't use CV to select models. Prediction from a statisticians point of view is not absent of cross validation. Indeed, Frank Harrell's *Regression Modelling Strategies* mentions the technique, but that book is primarily concerned with the development of predictions models for use in the clinic.
22,119,487
I need to implement a 1024bit math operations in C .I Implemented a simple BigInteger library where the integer is stored as an array "typedef INT UINT1024[400]" where each element represent one digit. It turned up to be so slow so i decided to implement the BigInteger using a 1024bit array of UINT64: "typedef UINT64 UINT1024[16]" so for example the number : 1000 is represented as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1000}, 18446744073709551615 as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xFFFFFFFFFFFFFFFF} and 18446744073709551616 as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}. I started wih writing the function to convert a char array number to an UINT1024 and an UINT1024 to a char array, it worked with numbers <= 0xFFFFFFFFFFFFFFFF. Here's what i did: ``` void UINT1024_FROMSTRING(UIN1024 Integer,const char szInteger[],UINT Length) { int c = 15; UINT64 Result = 0,Operation,Carry = 0; UINT64 Temp = 1; while(Length--) { Operation = (szInteger[Length] - '0') * Temp; Result += Operation + Carry; /*Overflow ?*/ if (Result < Operation || Temp == 1000000000000000000) { Carry = Result - Operation; Result = 0; Integer[c--] = 0; Temp = 1; } else Carry = 0; Temp *= 10; } if (Result || Carry) { /* I DONT KNOW WHAT TO DO HERE ! */ } while(c--) Integer[c] = 0;} ``` So please how can i implement it and is it possible to implement it using UINT64 for speed or just to stick with each array element is a digit of the number which is very slow for 1024bit operations. PS: I can't use any existing library ! Thanks in advance ! --- **Update** Still can't figure out how to do the multiplication. I am using this function: ``` void _uint128_mul(UINT64 u,UINT64 v,UINT64 * ui64Hi,UINT64 * ui64Lo) { UINT64 ulo, uhi, vlo, vhi, k, t; UINT64 wlo, whi, wt; uhi = u >> 32; ulo = u & 0xFFFFFFFF; vhi = v >> 32; vlo = v & 0xFFFFFFFF; t = ulo*vlo; wlo = t & 0xFFFFFFFF; k = t >> 32; t = uhi*vlo + k; whi = t & 0xFFFFFFFF; wt = t >> 32; t = ulo*vhi + whi; k = t >> 32; *ui64Lo = (t << 32) + wlo; *ui64Hi = uhi*vhi + wt + k; } ``` Then ``` void multiply(uint1024_t dUInteger,uint1024_t UInteger) { int i = 16; UINT64 lo,hi,Carry = 0; while(i--) { _uint128_mul(dUInteger[i],UInteger[15],&hi,&lo); dUInteger[i] = lo + Carry; Carry = hi; } } ``` I really need some help in this and Thanks in advance !
2014/03/01
[ "https://Stackoverflow.com/questions/22119487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2627770/" ]
You need to implement two functions for your UINT1024 class, multiply by integer and add integer. Then for each digit you convert, multiply the previous value by 10 and add the value of the digit.
4,259,334
Will XCode installer automatically update my old version or do I need to uninstall old one first? Sorry, sort of newbie to Mac development. Going fine with Xcode 3.2.4, but new version is out as of today.
2010/11/23
[ "https://Stackoverflow.com/questions/4259334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483163/" ]
The new Xcode installer will normally overwrite the older version for you automatically
3,321,511
Prove that the area bounded by the curve $y=\tanh x$ and the straight line $y=1$, between $x=0$ and $x=\infty$ is $\ln 2$ $\int^\infty \_0 (1-\tanh x) \mathrm{dx}= \biggr[x-\ln (\cosh x)\biggr]^\infty\_0\\\infty - \ln(\cosh \infty)+1$ How do I get $\ln 2$ because the line and curve intersect at infinity?
2019/08/12
[ "https://math.stackexchange.com/questions/3321511", "https://math.stackexchange.com", "https://math.stackexchange.com/users/455866/" ]
You need to evaluate the limit $$\lim\_{x\rightarrow \infty} (x - \ln(\cosh(x)))$$ Note that $$e^{\ln(\cosh(x)) -x} = e^{-x} \cosh(x) = \frac{1}{2}(1 + e^{-2x})\rightarrow \frac{1}{2}$$ Therefore $$\lim\_{x\rightarrow \infty} (x - \ln(\cosh(x))) = -\ln(1/2) = \ln(2)$$ Hence $$\int\_0^\infty (1-\tanh(x))dx = \lim\_{y\rightarrow \infty} [x - \ln(\cosh(x))]\_{x=0}^{x=y} = \ln(2) $$
6,454,460
I am using Oracle and I have modified code on some triggers and a package. When I run the script file which modifies the code and try to do an update on a table (which fires the trigger) I am getting Existing State of Package discarded I am getting a bunch of error ``` ORA-04068: ORA-04061: ORA-04065: ORA-06512:--Trigger error -- line 50 ORA-04088: ``` This error is happening only the first time. Any inputs to avoid this would be greatly appreciated. Thank you!
2011/06/23
[ "https://Stackoverflow.com/questions/6454460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529866/" ]
serially\_reusable only makes sense for constant package variables. There is only one way to avoid this error and maintain performance (reset\_package is really not a good option). Avoid any package level variables in your PL/SQL packages. Your Oracle's server memory is not the right place to store state. If something really does not change, is expensive to compute and a return value from a function can be reused over and over without recomputation, then DETERMINISTIC helps in that regard example: DON'T DO THIS: varchar2(100) cached\_result; ``` function foo return varchar2 is begin if cached_result is null then cached_result:= ... --expensive calc here end if; return cached_result; end foo; ``` DO THIS INSTEAD ``` function foo return varchar2 DETERMINISTIC is begin result:=... --expensive calc here return result; end foo; ``` Deterministic tells Oracle that for a given input, the result does not change, so it can cache the result and avoid calling the function. If this is not your use case and you need to share a variable across sessions, use a table, and query it. Your table will end up in the buffer cache memory if it is used with any frequency, so you get the in memory storage you desire without the problems of session variables
38,664,135
I need to make a function which will add to the beginning date 3 days and if it's 3 then it shows alert. ``` $beginDate = 2016-07-29 17:14:43 (this one is from sql table format) $dateNow = date now if $beginDate + 3 days (72h) is >= $dateNow then echo "It's been three days from..." ``` It seems to be simple but I have hard time to make it work with strtotime() and date() functions. How to code this in PHP?
2016/07/29
[ "https://Stackoverflow.com/questions/38664135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4591630/" ]
you can try Smaf.tv, the free cross-platform JS SDK and command line tool, with which you can build and package TV apps with one code base for LG WebOS, Samsung Smart TV (Orsay) & Tizen, Android TV and Amazon Fire TV. Disclaimer: I am part of the Smaf.tv team, but honestly I believe it fits your objective
66,986,409
In my `df` below, I want to : 1. identify and flag the outliers in `col_E` using z-scores 2. separately explain how to identify and flag the outliers using z-scores in two or more columns, for example `col_D` & `col_E` See below for the dataset ``` import pandas as pd from scipy import stats # intialise data of lists df = { 'col_A':['P0', 'P1', 'P2', 'P4', 'P5'], 'col_B':[1,1,1,1,1], 'col_C':[1,2,3,5,9], 'col_D':[120.05, 181.90, 10.34, 153.10, 311.17], 'col_E':[110.21, 191.12, 190.21, 12.00, 245.09 ], 'col_F':[100.22,199.10, 191.13,199.99, 255.19], 'col_G':[140.29, 291.07, 390.22, 245.09, 4122.62], } # Create DataFrame df = pd.DataFrame(df) # Print the output. df ``` Desired: flag all outliers in `col_D` first and then `col_D` and `col_E` secondly (Note: In my image below `10.34` and `12.00` were randomly highlighted) Q1 [![enter image description here](https://i.stack.imgur.com/vVnsZ.png)](https://i.stack.imgur.com/vVnsZ.png) Attempt: ``` #Q1 exclude_cols = ['col_A','col_B','col_C','col_D','col_F','col_G'] include_cols = ['col_E'] # desired column def flag_outliers(s, exclude_cols): if s.name in exclude_cols: print(s.name) return '' else: s=df[(np.abs(stats.zscore(df['col_E'])) > 3)] # not sure of this part of the code return ['background-color: yellow' if v else '' for v in indexes] df.style.apply(lambda s: flag_outliers(s, exclude_cols), axis=1, subset=include_cols) #Q2 exclude_cols = ['col_A','col_B','col_C','col_F','col_G'] include_cols = ['col_D','col_E'] # desired columns def flag_outliers(s, exclude_cols): if s.name in exclude_cols: print(s.name) return '' else: s=df[(np.abs(stats.zscore(df['col_E'])) > 3)] # not sure of this part of the code return ['background-color: yellow' if v else '' for v in indexes] df.style.apply(lambda s: flag_outliers(s, exclude_cols), axis=1, subset=include_cols) ``` Thanks!
2021/04/07
[ "https://Stackoverflow.com/questions/66986409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14488413/" ]
I assume the following meanings to demonstrate a broader range of usage. * Q1 stands for calculating a single column * Q2 stands for calculating over multiple columns pooled together. If Q2 is meant to calculated on multiple columns separately, then you can simply loop your Q1 solution over multiple columns, which should be trivial so I will omit such situation here. Keys ==== * Q1 is quite straightforward as one can return a list of values by list comprehension. * Q2 is a little bit complicated because the z-score would be applied over a DataFrame subset (i.e. `axis=None` must be used). According to the [official docs](https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Building-styles), when applying style over a DataFrame, the returning object must also be a DataFrame with the same index and columns as the subset. This is what caused the reshaping and DataFrame construction artifacts. Single Column (Q1) ================== Note that `z=3` is lowered to `1.5` for demonstration purpose. # desired column include\_cols = ['col\_E'] ``` # additional control outlier_threshold = 1.5 # 3 won't work! ddof = 0 # degree of freedom correction. Sample = 1 and population = 0. def flag_outliers(s: pd.Series): outlier_mask = np.abs(stats.zscore(s, ddof=ddof)) > outlier_threshold # replace boolean values with corresponding strings return ['background-color: yellow' if val else '' for val in outlier_mask] df.style.apply(flag_outliers, subset=include_cols) ``` **Result** [![enter image description here](https://i.stack.imgur.com/cE5Vo.png)](https://i.stack.imgur.com/cE5Vo.png) Multiple Column Pooled (Q2, Assumed) ==================================== Q2 == ``` include_cols = ['col_D', 'col_E'] # desired columns outlier_threshold = 1.5 ddof = 0 def flag_outliers(s: pd.DataFrame) -> pd.DataFrame: outlier_mask = np.abs(stats.zscore(s.values.reshape(-1), axis=None, ddof=ddof)) > outlier_threshold # prepare the array of string to be returned arr = np.array(['background-color: yellow' if val else '' for val in outlier_mask], dtype=object).reshape(s.shape) # cast the array into dataframe return pd.DataFrame(arr, columns=s.columns, index=s.index) df.style.apply(flag_outliers, axis=None, subset=include_cols) ``` **Result** [![enter image description here](https://i.stack.imgur.com/yDFMK.png)](https://i.stack.imgur.com/yDFMK.png)
41,590,518
I'd like to return the rows which qualify to a certain condition. I can do this for a single row, but I need this for multiple rows combined. For example 'light green' qualifies to 'XYZ' being positive and 'total' > 10, where 'Red' does not. When I combine a neighbouring row or rows, it does => 'dark green'. Can I achieve this going over all the rows and not return duplicate rows? ``` N = 1000 np.random.seed(0) df = pd.DataFrame( {'X':np.random.uniform(-3,10,N), 'Y':np.random.uniform(-3,10,N), 'Z':np.random.uniform(-3,10,N), }) df['total'] = df.X + df.Y + df.Z df.head(10) ``` [![enter image description here](https://i.stack.imgur.com/9kL6Z.png)](https://i.stack.imgur.com/9kL6Z.png) EDIT; Desired output is 'XYZ'> 0 and 'total' > 10
2017/01/11
[ "https://Stackoverflow.com/questions/41590518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7168104/" ]
Here's a try. You would maybe want to use `rolling` or `expanding` (for speed and elegance) instead of explicitly looping with `range`, but I did it that way so as to be able to print out the rows being used to calculate each boolean. ``` df = df[['X','Y','Z']] # remove the "total" column in order # to make the syntax a little cleaner df = df.head(4) # keep the example more manageable for i in range(len(df)): for k in range( i+1, len(df)+1 ): df_sum = df[i:k].sum() print( "rows", i, "to", k, (df_sum>0).all() & (df_sum.sum()>10) ) rows 0 to 1 True rows 0 to 2 True rows 0 to 3 True rows 0 to 4 True rows 1 to 2 False rows 1 to 3 True rows 1 to 4 True rows 2 to 3 True rows 2 to 4 True rows 3 to 4 True ```
14,898,987
I have an MySQL statement that performs an inner `SELECT` and returns the result as a pseudo column. I’d like to use the result of this pseudo column in my `WHERE` clause. My current SQL statement looks like this: ``` SELECT product.product_id, product.range_id, product.title, product.image, product.image_text, product.friendly_url, attribute.comfort_grade_id, category.category_id, category.category AS category_name, category.friendly_url AS category_friendly_url, (SELECT price_now FROM product_bedding_sizes AS size WHERE size.product_id = product.product_id ORDER BY size.price_now ASC LIMIT 1) AS price FROM products AS product LEFT JOIN categories AS category ON product.category_id = category.category_id LEFT JOIN product_bedding_attributes AS attribute ON product.product_id = attribute.product_id $where $order LIMIT ?,? ``` However, I get the following error message when running the query: > > #1054 - Unknown column 'price' in 'where clause' > > > How can I get around this and actually use the value of `price` in my `WHERE` clause?
2013/02/15
[ "https://Stackoverflow.com/questions/14898987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102205/" ]
The `WHERE` clause is evaluated before the `SELECT` clause, so it doesn't say the alias name. You have to do the filter by the `WHERE` clause in an outer query like this: ``` SELECT * FROM ( SELECT product.product_id, product.range_id, product.title, product.image, product.image_text, product.friendly_url, attribute.comfort_grade_id, category.category_id, category.category AS category_name, category.friendly_url AS category_friendly_url, (SELECT price_now FROM product_bedding_sizes AS size WHERE size.product_id = product.product_id ORDER BY size.price_now ASC LIMIT 1) AS price FROM ... ) AS sub WHERE price = ... <--- here it can see the price alias. ``` See this for more details: * [**My SQL Query Order of Operations**](http://www.bennadel.com/blog/70-SQL-Query-Order-of-Operations.htm). --- **Or:** You can join that table, instead of a correlated subquery like this: ``` SELECT product.product_id, product.range_id, product.title, product.image, product.image_text, product.friendly_url, attribute.comfort_grade_id, category.category_id, category.category AS category_name, category.friendly_url AS category_friendly_url, size.price_now FROM products AS product LEFT JOIN ( SELECT product_id, MIN(price_now) AS price FROM product_bedding_sizes GROUP BY product_id ) AS size ON size.product_id = product.product_id LEFT JOIN categories AS category ON product.category_id = category.category_id LEFT JOIN product_bedding_attributes AS attribute ON product.product_id = attribute.product_id $where price = ----; ```
52,989,218
I have a one dimensional array of objects and each object has an id and an id of its parent. In the initial array I have each element can have at most one child. So if the array looks like this: ``` {id: 3, parent: 5}, {id: 5, parent: null}, {id: 6, parent: 3}, {id: 1, parent: null}, {id: 4, parent: 7}, {id: 2, parent: 1}, {id: 7, parent: 2} ``` I need it to look similar to this: ``` {id: 5, parent: null, children: [ {id: 3, parent: 5}, {id: 6, parent: 3} ]}, {id: 1, parent: null, children: [ {id: 2, parent: 1}, {id: 7, parent: 2}, {id: 4, parent: 7}, ]} ``` I think the way I did it uses too much loops. Is there a better way? ```js let items = [ {id: 3, parent: 5}, {id: 5, parent: null}, {id: 6, parent: 3}, {id: 1, parent: null}, {id: 4, parent: 7}, {id: 2, parent: 1}, {id: 7, parent: 2} ]; let itemsNew = []; items = items.map(function(x){ return {id: x.id, parent: x.parent, children: []}; }); // new array with parents only for(let i=items.length-1; i>=0; i--){ if(items[i].parent == null){ itemsNew.push(items[i]); items.splice(i, 1); } } for(let i=0; i<itemsNew.length; i++){ let childIndexes = findChildAll(itemsNew[i].id); // sort the indexes so splicing the array wont misplace them childIndexes.sort(function(a,b){ return b-a; }); for(let j=0; j<childIndexes.length; j++){ itemsNew[i].children.push(items[childIndexes[j]]); items.splice(childIndexes[j], 1); } } // returns an array of indexes of all the element's children and their children function findChildAll(parentId){ for(let i=0; i<items.length; i++){ if(items[i].parent == parentId){ let resultArray = findChildAll(items[i].id); // is the result as an array add it to the index if(resultArray) return [i].concat(resultArray); // otherwise return just this index return [i]; } } } console.log(itemsNew); ```
2018/10/25
[ "https://Stackoverflow.com/questions/52989218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3007853/" ]
For me, I ended up just editing the snippet itself. I'm sure I will need to do this every time there is an update and I'm not sure of a better permanent fix outside of creating a user-defined snippet. My quick and dirty fix was to edit the file... > > %USERPROFILE%.vscode\extensions\ms-dotnettools.csharp-1.23.8\snippets\csharp.json > > > Then look for the following section (found mine around line 53)... ``` "Console.WriteLine": { "prefix": "cw", "body": [ "System.Console.WriteLine($0);" ], "description": "Console.WriteLine" }, ``` Then just change... ``` "System.Console.WriteLine($0);" ``` To... ``` "Console.WriteLine($0);" ``` Save, then restart VSCode and test the `cw` snippet.
8,531,269
How to Create a `View` with all days in year. `view` should fill with dates from JAN-01 to Dec-31. How can I do this in Oracle ? If current year have 365 days,`view` should have 365 rows with dates. if current year have 366 days,`view` should have 366 rows with dates. I want the `view` to have a single column of type `DATE`.
2011/12/16
[ "https://Stackoverflow.com/questions/8531269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029088/" ]
This simple view will do it: ``` create or replace view year_days as select trunc(sysdate, 'YYYY') + (level-1) as the_day from dual connect by level <= to_number(to_char(last_day(add_months(trunc(sysdate, 'YYYY'),11)), 'DDD')) / ``` Like this: ``` SQL> select * from year_days; THE_DAY --------- 01-JAN-11 02-JAN-11 03-JAN-11 04-JAN-11 05-JAN-11 06-JAN-11 07-JAN-11 08-JAN-11 09-JAN-11 10-JAN-11 11-JAN-11 ... 20-DEC-11 21-DEC-11 22-DEC-11 23-DEC-11 24-DEC-11 25-DEC-11 26-DEC-11 27-DEC-11 28-DEC-11 29-DEC-11 30-DEC-11 31-DEC-11 365 rows selected. SQL> ``` The date is generated by applying several Oracle date functions: * `trunc(sysdate, 'yyyy')` gives us the first of January for the current year * `add_months(x, 11)` gives us the first of December * `last_day(x)` gives us the thirty-first of December * `to_char(x, 'DDD')` gives us the number of the thirty-first of December, 365 this year and 366 next. * This last figure provides the upper bound for the row generator `CONNECT BY LEVEL <= X`