qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
60,118,300
How can I optimize the processing of strings?
2020/02/07
[ "https://Stackoverflow.com/questions/60118300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3931559/" ]
Your problem is you are making n copies of t and concatenating them. This is a simple approach, but quite expensive - it turns what could be an O(n) solution into an O(n2) one. Instead, just check each char of s: ``` for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != t.charAt(i % t.length())) { return -1: } } ```
Just a remark: in general working with char[] is much faster than working with String. (but nowhere near as convenient) And make your variables `final` when they are final. (it makes no difference to performance, but aids understanding) Anyway, this might do it: ``` import java.util.Arrays; class Result { public static int findSmallestDivisor(final String s, final String t) { final int lenS = s.length(); final int lenT = t.length(); /* * Get Length & Chars of shortest & longest Strings... */ final int lenShort; final int lenLong; final char[] charsShort; final char[] charsLong; if (lenS < lenT) { lenShort = lenS; charsShort = s.toCharArray(); lenLong = lenT; charsLong = t.toCharArray(); } else { lenShort = lenT; charsShort = t.toCharArray(); lenLong = lenS; charsLong = s.toCharArray(); } /* * Get the Factor & exit if there's a remainder... */ final int factor = lenLong / lenShort; final int factorRem = lenLong % lenShort; if (factorRem != 0) { return -1; } /* * Try all possible divisors... */ for (int d=1; d <= lenShort; d++) { final int n = lenShort / d; final int nRem = lenShort % d; if (nRem != 0) { continue; } final char[] dChars = Arrays.copyOf(charsShort, d); final char[] dCharsMultipliedShort = multiplyChars(dChars, n); final char[] dCharsMultipliedLong = multiplyChars(dCharsMultipliedShort, factor); if (Arrays.equals(charsShort, dCharsMultipliedShort) && Arrays.equals(charsLong, dCharsMultipliedLong )) { return d; } } return -1; } private static char[] multiplyChars(final char[] a, final int n) { // if (n == 0) { // Necessary: otherwise ArrayIndexOutOfBoundsException in getChars(...) // return new char[] {}; // (n is never 0) // } if (n == 1) { // Optional: optimisation return a; } final int aLength = a.length; final char[] charsMultiplied = new char[aLength * n]; System.arraycopy(a, 0, charsMultiplied, 0, aLength); // Fill in 1st occurrence /* * Copy 1st occurrence to the remaining occurrences... */ for (int i = 1; i < n; i++) { System.arraycopy(charsMultiplied, 0, charsMultiplied, i*aLength, aLength); } return charsMultiplied; } } ```
60,118,300
How can I optimize the processing of strings?
2020/02/07
[ "https://Stackoverflow.com/questions/60118300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3931559/" ]
Your problem is you are making n copies of t and concatenating them. This is a simple approach, but quite expensive - it turns what could be an O(n) solution into an O(n2) one. Instead, just check each char of s: ``` for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != t.charAt(i % t.length())) { return -1: } } ```
* Do not make new strings, but use String.regionMatches. * Use String.length and modulo % == 0. * The smallest substring of t can be done using the same method. Coding: * new String(string) ist **never** needed. * String += is slow. Better use StringBuilder. No code to not spoil your coding.
30,802,667
I have several documents, that have a title: 1. -> "Just some Word 13 from year 2015" 2. -> "Just some Word 13 from year 2011" 3. -> "Just some Word 13 from year 2012" 4. -> "Just some Word 13 from year 2014" 5. -> "Just some Word 13 from year 2013" When searching for 13 i'm expecting number 5 to be the first result because 13 is exists twice. Field is multiValued="true". My fieldtype for indexing looks like this: ``` <analyzer type="index"> <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[(&quot;)(,:;!?)]" replacement=""/> <tokenizer class="solr.WhitespaceTokenizerFactory"/> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.ReverseStringFilterFactory"/> <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="30" side="front"/> <filter class="solr.ReverseStringFilterFactory"/> </analyzer> ```
2015/06/12
[ "https://Stackoverflow.com/questions/30802667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153948/" ]
It doesn't sound quite right to have one test depending on an another test to define and export a variable. Set the global variable inside `onPrepare()` using `global`: ``` onPrepare: function() { global.caseNumber = moment().format('YYYYMMDD-HHmmss-SS'); }, ``` Then, you'll have `caseNumber` as a global variable across all the tests.
There's no need to use globals. You can make it more readable by creating your own module and requiring it: ``` //test/lib/homepage.js var moment = require('moment'); module.exports = { caseNumber: moment().format('YYYYMMDD-HHmmss-SS'), getContent: function () { //another example of reuse return element(by.css('body')); }); }; //test/homepage.spec.js var page = require('./lib/homepage'); describe('Homepage', function() { it('should display correct date', function () { expect(page.getContent()).toContain(page.caseNumber); }); }); ```
41,202,508
I've tried every option explained step by step [here](https://stackoverflow.com/questions/6760115/importing-a-github-project-into-eclipse) [and here:](https://stackoverflow.com/questions/29245924/import-java-project-from-github-to-eclipse) [and here](https://stackoverflow.com/questions/8070017/how-to-import-a-git-non-eclipse-java-project-into-eclipse) And I can't get it to work. What I want to do is pick [this project:](https://github.com/Simmetrics/simmetrics) , however it may be done (I've tried both through maven and git), and use its code in eclipse. And what I mean by that, is that I get to the point of seeing the folders in eclipse, but I can't create packages since it's not a java project, and if I mess up the code on the files that appear, it doesn't give me a warning nor in general interacts with said code. So I guess I'm missing some piece of knowledge and I don't know where else to look for it. **What should I do to use that project in my eclipse, and create my own code that calls and uses the classes and methods from said project?** Thank you in advance.
2016/12/17
[ "https://Stackoverflow.com/questions/41202508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204260/" ]
Yes, I found the similar issue, it seems to me `react-addons-perf` only work on `react`, for `react native` project, you can use `RCTRenderingPerf` which is a built-in tool in `react native` lib. My react native version is `"react-native": "^0.45.1"` `import PerfMonitor from 'react-native/Libraries/Performance/RCTRenderingPerf';` Start measurements ``` PerfMonitor.toggle(); PerfMonitor.start(); ``` Stop measurements and print Results ``` PerfMonitor.stop(); ``` You do not need to explicitly call print method to print the results, `stop()` already covered that. You can verify it by running: ``` ... _setIndex(idx){ PerfMonitor.toggle(); PerfMonitor.start(); this.setState({index:idx}) } componentDidUpdate(){ PerfMonitor.stop(); } render() { return ( <View style={styles.container}> <Text>Welcome to react-native {helloWorld()}</Text> <Text>Open up App.js to start working on your app!</Text> <Text>Changes you make will automatically reload.</Text> <Text>Shake your phone to open the developer menu.</Text> <Button title="click me to see profiling in console log" onPress={()=> this._setIndex(2)}/> </View> ); } ... ``` Make sure `Remote Debug JS` is on, then you can see the results on chrome console.
Did you try enabling the performance monitor in the dev menu by clicking on Show Perf Monitor? [Example](https://imgur.com/a/al87N)
55,594,929
It is only a simple question but shouldn't a label stay inside of it's nested frame when you use sticky ? In my code it only stays in the parent frame. If it is normal do you have a solution ? I have tried looking the documentation but I didn't find anything which could help. ``` from tkinter import * from tkinter import ttk root = Tk() root.title("Tk test") root.geometry("800x800") frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400").grid(row=0, column=0, rowspan=1, columnspan=1) frame_2 = ttk.Frame(frame_1, relief="sunken", height="200", width="200").grid(row=0, column=0, rowspan=1, columnspan=1) label_1 = ttk.Label(frame_2, text="Text").grid(row=0, column=0, sticky="N, E") root.mainloop() ``` Expected result : The label stays inside of it's frame which is nested inside the parent frame. Actual results : It only stays inside the parent frame
2019/04/09
[ "https://Stackoverflow.com/questions/55594929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10695357/" ]
The `.grid(...)` function returns `None`. Therefore, when you do ``` frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400").grid(row=0, column=0, rowspan=1, columnspan=1) ``` you assign `None` to `frame_1`. And the same goes for `frame_2` and `label_1`. Because `frame_1 == None`, calling `ttk.Frame(frame_1, ...)` is actually the same as `ttk.Frame(None, ...)`. Therefore, you're not passing a master, which defaults to having the root window as the master. Again, the same goes for the creation of `label_1`. The fix is to split the creation and placement of the widgets to two separate lines: ``` from tkinter import * from tkinter import ttk root = Tk() root.title("Tk test") root.geometry("800x800") frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400") frame_1.grid(row=0, column=0, rowspan=1, columnspan=1) frame_2 = ttk.Frame(frame_1, relief="sunken", height="200", width="200") frame_2.grid(row=0, column=0, rowspan=1, columnspan=1) label_1 = ttk.Label(frame_2, text="Text") label_1.grid(row=0, column=0, sticky="N, E") root.mainloop() ```
add .pack() at the end of each line where you define frame\_1, frame\_2 and label\_1
5,377,732
After reading [an article on REST](http://www.ibm.com/developerworks/java/library/j-grails09168/index.html) ("Restful Grails"), I have gotten the impression that it is not possible to truly conform to a REST style in a service that demands a lot of parameters. Is this so? All the examples I have seen so far seem to imply that true REST style services are "parameterless". Using parameters would be RPC-ish and not truly RESTful. To be more specific, say we have a service that returns graph data for stock prices, and this service needs to know the start date, end date, the currency, stock name, and whatever else might be applicable. In any case, at least 4-5 parameters are needed to retrieve the information needed. I would imagine the URL to be something like this : /stocks/YAHOO?startDate="2008-09-01"&endDate=... ("YAHOO" is here a made-up stock name). Would this really be REST or is this more RPC-like, what the author of the aforementioned article calls "GETful" (i.e. just low ceremony rpc)?
2011/03/21
[ "https://Stackoverflow.com/questions/5377732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200987/" ]
Feel free to use as many parameters as you need to identify the resource you wish to access. REST doesn't care.
Why would you think it is not possible? Google uses REST for their charts api, and they take alot of params: <http://chart.apis.google.com/chart?cht=bvg&chs=350x300&chd=t:20,35,10&chxr=1,0,40&chds=0,40&chco=FF0000|FFA000|00FF00&chbh=65,0,35&chxt=x,y,x&chxl=0:|High|Medium|Low|2:||Task+Priority||&chxs=2,000000,12&chtt=Tasks+on+my+To+Do+list&chts=000000,20&chg=0,25,5,5>
5,377,732
After reading [an article on REST](http://www.ibm.com/developerworks/java/library/j-grails09168/index.html) ("Restful Grails"), I have gotten the impression that it is not possible to truly conform to a REST style in a service that demands a lot of parameters. Is this so? All the examples I have seen so far seem to imply that true REST style services are "parameterless". Using parameters would be RPC-ish and not truly RESTful. To be more specific, say we have a service that returns graph data for stock prices, and this service needs to know the start date, end date, the currency, stock name, and whatever else might be applicable. In any case, at least 4-5 parameters are needed to retrieve the information needed. I would imagine the URL to be something like this : /stocks/YAHOO?startDate="2008-09-01"&endDate=... ("YAHOO" is here a made-up stock name). Would this really be REST or is this more RPC-like, what the author of the aforementioned article calls "GETful" (i.e. just low ceremony rpc)?
2011/03/21
[ "https://Stackoverflow.com/questions/5377732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200987/" ]
You can see the querystring as a filter on the resource you are GETing. Here, your resource is the stock prices of yahoo. Doing a GET on that resource give you all the available data, or the most recents. The query string filter the prices you want. Content negociation allow you to change the representation, e.g. a png graph, a csv file, and so on. To add a price, simply POST a representation (e.g. CSV) to the same resource. The "restfulness" is not realy in the URL itself, since URIs are obscures to client, but in the way you interact with resources themselves identified by their URI
Why would you think it is not possible? Google uses REST for their charts api, and they take alot of params: <http://chart.apis.google.com/chart?cht=bvg&chs=350x300&chd=t:20,35,10&chxr=1,0,40&chds=0,40&chco=FF0000|FFA000|00FF00&chbh=65,0,35&chxt=x,y,x&chxl=0:|High|Medium|Low|2:||Task+Priority||&chxs=2,000000,12&chtt=Tasks+on+my+To+Do+list&chts=000000,20&chg=0,25,5,5>
5,377,732
After reading [an article on REST](http://www.ibm.com/developerworks/java/library/j-grails09168/index.html) ("Restful Grails"), I have gotten the impression that it is not possible to truly conform to a REST style in a service that demands a lot of parameters. Is this so? All the examples I have seen so far seem to imply that true REST style services are "parameterless". Using parameters would be RPC-ish and not truly RESTful. To be more specific, say we have a service that returns graph data for stock prices, and this service needs to know the start date, end date, the currency, stock name, and whatever else might be applicable. In any case, at least 4-5 parameters are needed to retrieve the information needed. I would imagine the URL to be something like this : /stocks/YAHOO?startDate="2008-09-01"&endDate=... ("YAHOO" is here a made-up stock name). Would this really be REST or is this more RPC-like, what the author of the aforementioned article calls "GETful" (i.e. just low ceremony rpc)?
2011/03/21
[ "https://Stackoverflow.com/questions/5377732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200987/" ]
You can see the querystring as a filter on the resource you are GETing. Here, your resource is the stock prices of yahoo. Doing a GET on that resource give you all the available data, or the most recents. The query string filter the prices you want. Content negociation allow you to change the representation, e.g. a png graph, a csv file, and so on. To add a price, simply POST a representation (e.g. CSV) to the same resource. The "restfulness" is not realy in the URL itself, since URIs are obscures to client, but in the way you interact with resources themselves identified by their URI
Feel free to use as many parameters as you need to identify the resource you wish to access. REST doesn't care.
9,687,883
I have a simple spring web application that only has spring mvc and spring roo setup. For some reason on all of my old app instances, when I uploaded this sample application, it always gets a "hanging/exceeded time" error in the logs. Even in the case of basic spring mvc setup. The logs I've seen are below. I am a bit confused since the same application was working previously until today, and now even the simple deployments to google app engine are returning a 500 error. Any help would be appreciated, but I just want to see if this is an issue people are seeing with spring mvc specifically or with the latest google app engin sdk?: ``` Uncaught exception from servlet com.google.apphosting.runtime.HardDeadlineExceededError: This request (c22ac44effde64c8) started at 2012/03/13 15:39:52.285 UTC and was still executing at 2012/03/13 15:40:54.889 UTC. at com.google.appengine.runtime.Request.process-c22ac44effde64c8(Request.java) at java.util.zip.ZipFile.read(Native Method) at java.util.zip.ZipFile.access$1200(ZipFile.java:57) at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:476) at java.util.zip.ZipFile$1.fill(ZipFile.java:259) at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158) at sun.misc.Resource.getBytes(Resource.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:273) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory.createApplicationContext(SpringTilesApplicationContextFactory.java:55) ```
2012/03/13
[ "https://Stackoverflow.com/questions/9687883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266930/" ]
If you don't want two view controllers, just create a separate delegate for each scroll view. Make it an `NSObject` which conforms to `UIScrollViewDelegate` and create it at the same time as the scroll view. Seems to combine the results you seek: one view controller, but encapsulated scroll view code.
You could have a base controller class that handles the common functionality. Each different controller can inherit from this and override with their specific functionality as required. Aka [the template pattern](http://en.wikipedia.org/wiki/Template_method_pattern) **Edit** To expand. You say you want only one view controller. So you should create a separate class to handle the individual functionality. The View Controller has a base class pointer which gets swapped around according to the current view. In pseudo code : ``` class BaseFunctionality -(void) handleDidScroll {} end class ScrollViewAFunctionality : BaseFunctionality -(void) handleDidScroll { // Lots of interesting technical stuff... } end class ScrollViewBFunctionality : BaseFunctionality -(void) handleDidScroll { // Lots of interesting technical stuff... } end class TheViewController : UIViewController BaseFunctionality *functionality; -(void) swapViews { // Code to swap views [this.functionality release]; if (view == A) this.functionality = [[ScrollViewAFunctionality alloc] init] else if ( view == B) this.functionality = [[ScrollViewBFunctionality alloc] init] } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [this.functionality handleDidScroll]; } end ```
347,170
Unfortunately the printer being used to print envelopes uses a LPR port which can only be attached to an old machine running Windows 98. The rest of the systems in the network are running Windows 7 and need to have the ability to send print jobs to Windows 98 print server. Are there any alternatives? Unfortunately Linux is not an option as there are no known drivers for the printer unless this does not matter. If there any no alternatives, what should be secured on the network and the print server so that it is not susceptible to viruses, unauthorized access, etc? The network does not run off a domain as they only have 5 computers.
2011/10/16
[ "https://superuser.com/questions/347170", "https://superuser.com", "https://superuser.com/users/79947/" ]
Get a [USB-to-parallel](http://www.google.com/search?q=usb%20to%20parallel%20adapter) adapter, it's around $7. Connect this printer with this adapter to any computer running Windows. HP LaserJet drivers are available for modern Windows versions too. ![USB to Parallel](https://i.stack.imgur.com/W9JOk.jpg) This is what one vendor says about their adapter: > > Add a DB25 parallel port to your desktop or laptop PC through USB. The ICUSB1284D25 6 ft USB to DB25 parallel printer adapter cable turns an available USB port on a host PC into a DB25 female parallel port - allowing you to connect a DB25 printer to the computer as if the necessary parallel port was built-on. A cost-effective and reliable solution, the USB to DB25 adapter saves the expense of replacing a parallel printer for the sake of USB capability. > > >
D-Link makes a parallel print server that plugs directly into the parallel port on the printer. You plug a network cable into it, and access it as a standard TCP/IP LPR port. We've been using one on our old hp LaserJet 4100 series printer that was used as the mainline printer back when printer built-in networking was a little over priced. We purchased the LPT Port print server to get the printer off the Domain Server to quit wasting server clock cycles on spooling a shared printer when the workstations could do a better job of it and communicate directly to the printer. The lj-4100 outlasted the hp LJ4250dtn with built-in print server that replaced it and is still plugging away over in Accounts Payable with this nifty D-Link device plugged into its parallel port. I think the current iteration is D-Link DP-301P or something similar.
2,352,890
If $\dim E = n$ and the normal operator $A\colon E \rightarrow E$ has $n$ distinct eigenvalues, how do I show that $A$ is self adjoint?
2017/07/09
[ "https://math.stackexchange.com/questions/2352890", "https://math.stackexchange.com", "https://math.stackexchange.com/users/462216/" ]
This is asking you to prove that a normal operator with $n$ distinct realeigenvalues over a vector space of dimension $n$ is self-adjoint. $A = EDE^\*$ Therefore $A^\* = (EDE^\*)\* = (E^\*)^\*(D^\*)E^\*= ED^\*E^\*$. $\bar{D} = D^\*$ and as $D$ is real $\bar{D} = D$. So $A^\* = EDE^\* = A$.
Since $A$ has all distinct eigenvalues, if some other operator $S$ commutes with it, then it's a polynomial of it. Choose an basis such that the matrix $M$ of $A$ is diagonal, and define an operator $U\_M$ on the space of matrices where $U\_M(B) = MB - BM$. Letting $E\_{ij}$ be a unit matrix ($1$ in the $(i,j)$ slot and $0$ elsewhere), we see that $U\_M(E\_{ij}) = (A\_{ii} - A\_{jj})E\_{ij}$, which you can verify directly. This is equal to $0$ iff $i=j$, since the eigenvalues of $A$ are distinct, so $\dim(\ker(U\_M)) = M$. Now, we know that the set of polynomials in $M$ clearly is a subspace of $U\_M$. Thing is, since $M$ has all distinct eigenvalues, its minimal polynomial equals its characteristic polynomial, and thus has degree $n$. This means that the space of polynomials in $M$ also has dimension $n$, so that it is equal to $\ker(U\_M)$. By the above and because $A$ is normal, we know that $A^\*$ is a polynomial in $A$. Thus, $\langle Ax,y\rangle = \langle x,p(A)y\rangle$ where $p$ is some polynomial. This implies that $\langle (A-I)x,(I-p(A))y\rangle = 0$ for any $x$ and $y$. In particular, take $x=y$. So, by this, we also know that $\langle (I-p(A))x,(A-I)x\rangle = 0$, implying that $\langle (A-p(A))x,(A-p(A))x\rangle = \|(A-p(A))x\|^2 = 0$ for all $x$, so that $A = p(A)$. So then $A$ is self-adjoint. This is probably an odd way of doing it, I just kinda think like that. The other answer is more direct once you have the spectral theorem for normal operators.
25,980,263
Basically im a xlst newbie and have been tasked with working on some changes to a large xls file that handles the transformation of movies metadata for the german market. The xls file looks something like this: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:str="http://exslt.org/strings" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect" xmlns:xalan="http://xml.apache.org/xslt" exclude-result-prefixes="xalan str"> <xsl:output method="xml" indent="yes" xalan:indent-amount="4"/> <xsl:strip-space elements="*"/> <xsl:template match="/metadata"> <xsl:variable name="featureID" select="substring(mpm_product_id, 7, string-length(mpm_product_id))"/> <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" /> <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> <Metadata> <some values...> <xsl:for-each select="genres/genre"> <Genre> <xsl:choose> <!-- Mappings for German Genres --> <xsl:when test="/metadata/base/territory_code='DE'"> <xsl:choose> <xsl:when test=".= 'Action'">Action und Abenteuer</xsl:when> <xsl:when test=".= 'Adventure'">Action und Abenteuer</xsl:when> <xsl:when test=".= 'Animation'">Zeichentrick</xsl:when> <xsl:when test=".= 'Anime'">Zeichentrick</xsl:when> <xsl:when test=".= 'Bollywood'">Bollywood</xsl:when> <xsl:when test=".= 'Classics'">Drama > Klassiker</xsl:when> <xsl:when test=".= 'Comedy'">Komödie</xsl:when> <xsl:when test=".= 'Concert Film'">Musik</xsl:when> <xsl:when test=".= 'Crime'">Kriminalfilm > Drama</xsl:when> <xsl:when test=".= 'Drama'">Drama</xsl:when> <xsl:when test=".= 'Fantasy'">Drama > Sci-Fi und Fantasy</xsl:when> <xsl:when test=".= 'Foreign'">International</xsl:when> <xsl:when test=".= 'Horror'">Kriminalfilm > Horror</xsl:when> <xsl:when test=".= 'Independent'">Independentfilm &amp; Arthouse</xsl:when> <xsl:when test=".= 'Japanese Cinema'">International > Japan</xsl:when> <xsl:when test=".= 'Jidaigeki'">International > Japan</xsl:when> <xsl:when test=".= 'Kids &amp; Family'">Kinderfilm > Familie</xsl:when> <xsl:when test=".= 'Music Documentary'">Musik > Dokumentation</xsl:when> <xsl:when test=".= 'Music Feature Film'">Musik</xsl:when> <xsl:when test=".= 'Musicals'">Musik > Musical</xsl:when> <xsl:when test=".= 'Mystery'">Drama > Mystery</xsl:when> <xsl:when test=".= 'Nonfiction - Documentary'">Dokumentation</xsl:when> <xsl:when test=".= 'Regional Indian'">International > Indien &amp; Pakistan</xsl:when> <xsl:when test=".= 'Romance'">Drama > Romanze</xsl:when> <xsl:when test=".= 'Science Fiction'">Science Fiction und Fantasy</xsl:when> <xsl:when test=".= 'Short Films'">Independentfilm &amp; Arthouse > Experimentalfilm</xsl:when> <xsl:when test=".= 'Special Interest'">Hobby</xsl:when> <xsl:when test=".= 'Sports'">Sport</xsl:when> <xsl:when test=".= 'Thrillers'">Thriller</xsl:when> <xsl:when test=".= 'Tokusatsu'">International > Japan</xsl:when> <xsl:when test=".= 'Urban'">Drama > Alltag</xsl:when> <xsl:when test=".= 'Westerns'">Western</xsl:when> <xsl:otherwise> <xsl:value-of select="." /> </xsl:otherwise> </xsl:choose> </xsl:when> </xsl:choose> </Genre> </xsl:for-each> <More values...> </Metadata> </xsl:template> ``` Issue being when the genres are transformed we end with duplicate values for example when the input contains the elements ``` <genres> <genre>Comedy</genre> <genre>Adventure</genre> <genre>Action</genre> </genres> ``` After transformation we have ``` <Genre>Komödie</Genre> <Genre>Action und Abenteuer</Genre> <Genre>Action und Abenteuer</Genre> ``` I have tried looking for some solution for this but i have not reached the solution and any help would be appreciated. Edit for clarification: What i need is to eliminate the duplicate genre elements from the output. Those elements can be not adjacent to each other and we cant run the output through a second transformation as we cant modify the code of the service that handles this. Thanks
2014/09/22
[ "https://Stackoverflow.com/questions/25980263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4051655/" ]
Header: ``` #define LITERAL "Hello, world" extern char const literal[sizeof LITERAL]; ``` One source file: ``` char const literal[] = LITERAL; ``` There's still no guarantee that any particular compiler/linker only make one copy of the string literal (but it does guarantee the requirement that `&literal[0]` is the same in all units).
don't u want ``` const char * const LITERAL="foo"; ```
25,980,263
Basically im a xlst newbie and have been tasked with working on some changes to a large xls file that handles the transformation of movies metadata for the german market. The xls file looks something like this: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:str="http://exslt.org/strings" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect" xmlns:xalan="http://xml.apache.org/xslt" exclude-result-prefixes="xalan str"> <xsl:output method="xml" indent="yes" xalan:indent-amount="4"/> <xsl:strip-space elements="*"/> <xsl:template match="/metadata"> <xsl:variable name="featureID" select="substring(mpm_product_id, 7, string-length(mpm_product_id))"/> <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" /> <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> <Metadata> <some values...> <xsl:for-each select="genres/genre"> <Genre> <xsl:choose> <!-- Mappings for German Genres --> <xsl:when test="/metadata/base/territory_code='DE'"> <xsl:choose> <xsl:when test=".= 'Action'">Action und Abenteuer</xsl:when> <xsl:when test=".= 'Adventure'">Action und Abenteuer</xsl:when> <xsl:when test=".= 'Animation'">Zeichentrick</xsl:when> <xsl:when test=".= 'Anime'">Zeichentrick</xsl:when> <xsl:when test=".= 'Bollywood'">Bollywood</xsl:when> <xsl:when test=".= 'Classics'">Drama > Klassiker</xsl:when> <xsl:when test=".= 'Comedy'">Komödie</xsl:when> <xsl:when test=".= 'Concert Film'">Musik</xsl:when> <xsl:when test=".= 'Crime'">Kriminalfilm > Drama</xsl:when> <xsl:when test=".= 'Drama'">Drama</xsl:when> <xsl:when test=".= 'Fantasy'">Drama > Sci-Fi und Fantasy</xsl:when> <xsl:when test=".= 'Foreign'">International</xsl:when> <xsl:when test=".= 'Horror'">Kriminalfilm > Horror</xsl:when> <xsl:when test=".= 'Independent'">Independentfilm &amp; Arthouse</xsl:when> <xsl:when test=".= 'Japanese Cinema'">International > Japan</xsl:when> <xsl:when test=".= 'Jidaigeki'">International > Japan</xsl:when> <xsl:when test=".= 'Kids &amp; Family'">Kinderfilm > Familie</xsl:when> <xsl:when test=".= 'Music Documentary'">Musik > Dokumentation</xsl:when> <xsl:when test=".= 'Music Feature Film'">Musik</xsl:when> <xsl:when test=".= 'Musicals'">Musik > Musical</xsl:when> <xsl:when test=".= 'Mystery'">Drama > Mystery</xsl:when> <xsl:when test=".= 'Nonfiction - Documentary'">Dokumentation</xsl:when> <xsl:when test=".= 'Regional Indian'">International > Indien &amp; Pakistan</xsl:when> <xsl:when test=".= 'Romance'">Drama > Romanze</xsl:when> <xsl:when test=".= 'Science Fiction'">Science Fiction und Fantasy</xsl:when> <xsl:when test=".= 'Short Films'">Independentfilm &amp; Arthouse > Experimentalfilm</xsl:when> <xsl:when test=".= 'Special Interest'">Hobby</xsl:when> <xsl:when test=".= 'Sports'">Sport</xsl:when> <xsl:when test=".= 'Thrillers'">Thriller</xsl:when> <xsl:when test=".= 'Tokusatsu'">International > Japan</xsl:when> <xsl:when test=".= 'Urban'">Drama > Alltag</xsl:when> <xsl:when test=".= 'Westerns'">Western</xsl:when> <xsl:otherwise> <xsl:value-of select="." /> </xsl:otherwise> </xsl:choose> </xsl:when> </xsl:choose> </Genre> </xsl:for-each> <More values...> </Metadata> </xsl:template> ``` Issue being when the genres are transformed we end with duplicate values for example when the input contains the elements ``` <genres> <genre>Comedy</genre> <genre>Adventure</genre> <genre>Action</genre> </genres> ``` After transformation we have ``` <Genre>Komödie</Genre> <Genre>Action und Abenteuer</Genre> <Genre>Action und Abenteuer</Genre> ``` I have tried looking for some solution for this but i have not reached the solution and any help would be appreciated. Edit for clarification: What i need is to eliminate the duplicate genre elements from the output. Those elements can be not adjacent to each other and we cant run the output through a second transformation as we cant modify the code of the service that handles this. Thanks
2014/09/22
[ "https://Stackoverflow.com/questions/25980263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4051655/" ]
Since C++17 you can write in the header: ``` inline char const thing[] = "foo"; ``` which meets all the criteria. *Note:* `inline` variables have external linkage unless explicitly declared as `static`. The rule about `const` variables defaulting to internal linkage only applies to non-inline variables.
don't u want ``` const char * const LITERAL="foo"; ```
25,980,263
Basically im a xlst newbie and have been tasked with working on some changes to a large xls file that handles the transformation of movies metadata for the german market. The xls file looks something like this: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:str="http://exslt.org/strings" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect" xmlns:xalan="http://xml.apache.org/xslt" exclude-result-prefixes="xalan str"> <xsl:output method="xml" indent="yes" xalan:indent-amount="4"/> <xsl:strip-space elements="*"/> <xsl:template match="/metadata"> <xsl:variable name="featureID" select="substring(mpm_product_id, 7, string-length(mpm_product_id))"/> <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" /> <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> <Metadata> <some values...> <xsl:for-each select="genres/genre"> <Genre> <xsl:choose> <!-- Mappings for German Genres --> <xsl:when test="/metadata/base/territory_code='DE'"> <xsl:choose> <xsl:when test=".= 'Action'">Action und Abenteuer</xsl:when> <xsl:when test=".= 'Adventure'">Action und Abenteuer</xsl:when> <xsl:when test=".= 'Animation'">Zeichentrick</xsl:when> <xsl:when test=".= 'Anime'">Zeichentrick</xsl:when> <xsl:when test=".= 'Bollywood'">Bollywood</xsl:when> <xsl:when test=".= 'Classics'">Drama > Klassiker</xsl:when> <xsl:when test=".= 'Comedy'">Komödie</xsl:when> <xsl:when test=".= 'Concert Film'">Musik</xsl:when> <xsl:when test=".= 'Crime'">Kriminalfilm > Drama</xsl:when> <xsl:when test=".= 'Drama'">Drama</xsl:when> <xsl:when test=".= 'Fantasy'">Drama > Sci-Fi und Fantasy</xsl:when> <xsl:when test=".= 'Foreign'">International</xsl:when> <xsl:when test=".= 'Horror'">Kriminalfilm > Horror</xsl:when> <xsl:when test=".= 'Independent'">Independentfilm &amp; Arthouse</xsl:when> <xsl:when test=".= 'Japanese Cinema'">International > Japan</xsl:when> <xsl:when test=".= 'Jidaigeki'">International > Japan</xsl:when> <xsl:when test=".= 'Kids &amp; Family'">Kinderfilm > Familie</xsl:when> <xsl:when test=".= 'Music Documentary'">Musik > Dokumentation</xsl:when> <xsl:when test=".= 'Music Feature Film'">Musik</xsl:when> <xsl:when test=".= 'Musicals'">Musik > Musical</xsl:when> <xsl:when test=".= 'Mystery'">Drama > Mystery</xsl:when> <xsl:when test=".= 'Nonfiction - Documentary'">Dokumentation</xsl:when> <xsl:when test=".= 'Regional Indian'">International > Indien &amp; Pakistan</xsl:when> <xsl:when test=".= 'Romance'">Drama > Romanze</xsl:when> <xsl:when test=".= 'Science Fiction'">Science Fiction und Fantasy</xsl:when> <xsl:when test=".= 'Short Films'">Independentfilm &amp; Arthouse > Experimentalfilm</xsl:when> <xsl:when test=".= 'Special Interest'">Hobby</xsl:when> <xsl:when test=".= 'Sports'">Sport</xsl:when> <xsl:when test=".= 'Thrillers'">Thriller</xsl:when> <xsl:when test=".= 'Tokusatsu'">International > Japan</xsl:when> <xsl:when test=".= 'Urban'">Drama > Alltag</xsl:when> <xsl:when test=".= 'Westerns'">Western</xsl:when> <xsl:otherwise> <xsl:value-of select="." /> </xsl:otherwise> </xsl:choose> </xsl:when> </xsl:choose> </Genre> </xsl:for-each> <More values...> </Metadata> </xsl:template> ``` Issue being when the genres are transformed we end with duplicate values for example when the input contains the elements ``` <genres> <genre>Comedy</genre> <genre>Adventure</genre> <genre>Action</genre> </genres> ``` After transformation we have ``` <Genre>Komödie</Genre> <Genre>Action und Abenteuer</Genre> <Genre>Action und Abenteuer</Genre> ``` I have tried looking for some solution for this but i have not reached the solution and any help would be appreciated. Edit for clarification: What i need is to eliminate the duplicate genre elements from the output. Those elements can be not adjacent to each other and we cant run the output through a second transformation as we cant modify the code of the service that handles this. Thanks
2014/09/22
[ "https://Stackoverflow.com/questions/25980263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4051655/" ]
Header: ``` #define LITERAL "Hello, world" extern char const literal[sizeof LITERAL]; ``` One source file: ``` char const literal[] = LITERAL; ``` There's still no guarantee that any particular compiler/linker only make one copy of the string literal (but it does guarantee the requirement that `&literal[0]` is the same in all units).
Since C++17 you can write in the header: ``` inline char const thing[] = "foo"; ``` which meets all the criteria. *Note:* `inline` variables have external linkage unless explicitly declared as `static`. The rule about `const` variables defaulting to internal linkage only applies to non-inline variables.
63,870,080
I was trying to use the top level in the project and saw that it was necessary to change the module from tscofnig to esnext or system, but for some reason my ts-node's error. And I already put the type: module I tried to use the flag: --experimental-modules but the error still does not know how to solve. package.json: ``` { "name": "micro-hr", "version": "1.0.0", "main": "index.js", "license": "MIT", "type": "module", "scripts": { "commit": "git-cz", "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored", "start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts", "start:debug": "node start --debug --watch", "start:prod": "node dist/index.ts", "test": "jest", "lint": "eslint --fix", "lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts", "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n" }, "devDependencies": { "@babel/cli": "^7.11.5", "@babel/core": "^7.11.5", "@babel/node": "^7.10.5", "@babel/preset-env": "^7.11.5", "@babel/preset-typescript": "^7.10.4", "@commitlint/cli": "^9.1.2", "@commitlint/config-conventional": "^9.1.2", "@types/bcryptjs": "^2.4.2", "@types/cookie-parser": "^1.4.2", "@types/cors": "^2.8.7", "@types/express": "^4.17.8", "@types/helmet": "^0.0.48", "@types/jest": "^26.0.13", "@types/node": "^14.6.4", "@types/pino": "^6.3.0", "@types/pino-http": "^5.0.5", "@types/supertest": "^2.0.10", "@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/parser": "^4.0.1", "babel-plugin-module-resolver": "^4.0.0", "commitizen": "^4.2.1", "cz-conventional-changelog": "^3.3.0", "eslint": "^7.8.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", "eslint-config-standard": "^14.1.1", "eslint-import-resolver-typescript": "^2.3.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", "husky": "^4.2.5", "jest": "^26.4.2", "pino-pretty": "^4.2.0", "prettier": "^2.1.1", "supertest": "^4.0.2", "ts-jest": "^26.3.0", "ts-node": "^9.0.0", "ts-node-dev": "^1.0.0-pre.62", "tsconfig-paths": "^3.9.0", "tscpaths": "^0.0.9", "typescript": "^4.0.2" }, "dependencies": { "amqplib": "^0.6.0", "assert": "^2.0.0", "bcryptjs": "^2.4.3", "class-transformer": "^0.3.1", "cors": "^2.8.5", "dotenv": "^8.2.0", "envalid": "^6.0.2", "express": "^4.17.1", "extendable-error": "^0.1.7", "helmet": "^4.1.0", "nabbitmq": "^1.0.0", "pg": "^8.3.3", "pino": "^6.5.1", "pino-http": "^5.2.0", "reflect-metadata": "^0.1.13", "spt-rabbit-helpers": "^1.0.6", "tsyringe": "^4.3.0", "typeorm": "^0.2.25" }, "config": { "commitizen": { "path": "cz-conventional-changelog" } } } ``` tsconfig: ``` { "compilerOptions": { "target": "es2020", "module": "esnext", "allowJs": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "strictPropertyInitialization": false, "moduleResolution": "node", "baseUrl": "./src", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "typeRoots": ["node_modules/@types", "@types"] }, "include": ["src", "__tests__"], "exclude": ["node_modules"] } ``` main: ``` import 'reflect-metadata'; import express from 'express'; import { RabbitServer } from 'spt-rabbit-helpers'; import validateEnv from 'utils/validateEnvs'; import { RabbitMqConnectionFactory, ConsumerFactory, PublisherFactory, RabbitMqConnection, } from 'nabbitmq'; import { container, singleton } from 'tsyringe'; const factory = new RabbitMqConnectionFactory(); factory.setUri('amqp://localhost:5672'); const ConsumerConnection = await factory.newConnection(); const PublisherConnection = await factory.newConnection(); container.registerInstance('Consumer_Connection', ConsumerConnection); container.registerInstance('Publisher_Connection', PublisherConnection); ```
2020/09/13
[ "https://Stackoverflow.com/questions/63870080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13102905/" ]
To run ts-node (or plain node for that matter) you need to use `"module": "commonjs", "target": "ES2017"`, otherwise the `import`/`export` statements are illegally placed in an IIFE. So I would suggest using another file called *node.tsconfig.json* with the following contents: ```json { "extends": "./tsconfig.json", "compilerOptions": { "target": "ES2017" // For NodeJS 8 compat, see https://www.typescriptlang.org/tsconfig#target for more info } } ``` And then run ts-node with `--project ./node.tsconfig.json`
I had the same issue and I fixed it by changing the `module` in `tsconfig.json` to `commonjs` and removing the `module` key in `package.json`: ```js // tsconfig.json { "module": "CommonJS", } ```
63,870,080
I was trying to use the top level in the project and saw that it was necessary to change the module from tscofnig to esnext or system, but for some reason my ts-node's error. And I already put the type: module I tried to use the flag: --experimental-modules but the error still does not know how to solve. package.json: ``` { "name": "micro-hr", "version": "1.0.0", "main": "index.js", "license": "MIT", "type": "module", "scripts": { "commit": "git-cz", "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored", "start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts", "start:debug": "node start --debug --watch", "start:prod": "node dist/index.ts", "test": "jest", "lint": "eslint --fix", "lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts", "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n" }, "devDependencies": { "@babel/cli": "^7.11.5", "@babel/core": "^7.11.5", "@babel/node": "^7.10.5", "@babel/preset-env": "^7.11.5", "@babel/preset-typescript": "^7.10.4", "@commitlint/cli": "^9.1.2", "@commitlint/config-conventional": "^9.1.2", "@types/bcryptjs": "^2.4.2", "@types/cookie-parser": "^1.4.2", "@types/cors": "^2.8.7", "@types/express": "^4.17.8", "@types/helmet": "^0.0.48", "@types/jest": "^26.0.13", "@types/node": "^14.6.4", "@types/pino": "^6.3.0", "@types/pino-http": "^5.0.5", "@types/supertest": "^2.0.10", "@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/parser": "^4.0.1", "babel-plugin-module-resolver": "^4.0.0", "commitizen": "^4.2.1", "cz-conventional-changelog": "^3.3.0", "eslint": "^7.8.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", "eslint-config-standard": "^14.1.1", "eslint-import-resolver-typescript": "^2.3.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", "husky": "^4.2.5", "jest": "^26.4.2", "pino-pretty": "^4.2.0", "prettier": "^2.1.1", "supertest": "^4.0.2", "ts-jest": "^26.3.0", "ts-node": "^9.0.0", "ts-node-dev": "^1.0.0-pre.62", "tsconfig-paths": "^3.9.0", "tscpaths": "^0.0.9", "typescript": "^4.0.2" }, "dependencies": { "amqplib": "^0.6.0", "assert": "^2.0.0", "bcryptjs": "^2.4.3", "class-transformer": "^0.3.1", "cors": "^2.8.5", "dotenv": "^8.2.0", "envalid": "^6.0.2", "express": "^4.17.1", "extendable-error": "^0.1.7", "helmet": "^4.1.0", "nabbitmq": "^1.0.0", "pg": "^8.3.3", "pino": "^6.5.1", "pino-http": "^5.2.0", "reflect-metadata": "^0.1.13", "spt-rabbit-helpers": "^1.0.6", "tsyringe": "^4.3.0", "typeorm": "^0.2.25" }, "config": { "commitizen": { "path": "cz-conventional-changelog" } } } ``` tsconfig: ``` { "compilerOptions": { "target": "es2020", "module": "esnext", "allowJs": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "strictPropertyInitialization": false, "moduleResolution": "node", "baseUrl": "./src", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "typeRoots": ["node_modules/@types", "@types"] }, "include": ["src", "__tests__"], "exclude": ["node_modules"] } ``` main: ``` import 'reflect-metadata'; import express from 'express'; import { RabbitServer } from 'spt-rabbit-helpers'; import validateEnv from 'utils/validateEnvs'; import { RabbitMqConnectionFactory, ConsumerFactory, PublisherFactory, RabbitMqConnection, } from 'nabbitmq'; import { container, singleton } from 'tsyringe'; const factory = new RabbitMqConnectionFactory(); factory.setUri('amqp://localhost:5672'); const ConsumerConnection = await factory.newConnection(); const PublisherConnection = await factory.newConnection(); container.registerInstance('Consumer_Connection', ConsumerConnection); container.registerInstance('Publisher_Connection', PublisherConnection); ```
2020/09/13
[ "https://Stackoverflow.com/questions/63870080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13102905/" ]
To run ts-node (or plain node for that matter) you need to use `"module": "commonjs", "target": "ES2017"`, otherwise the `import`/`export` statements are illegally placed in an IIFE. So I would suggest using another file called *node.tsconfig.json* with the following contents: ```json { "extends": "./tsconfig.json", "compilerOptions": { "target": "ES2017" // For NodeJS 8 compat, see https://www.typescriptlang.org/tsconfig#target for more info } } ``` And then run ts-node with `--project ./node.tsconfig.json`
If you are using `React`, "commonjs" can not be set for TypeScript. **tsconfig.json** ``` { "compilerOptions": { "module": "esnext" } } ``` **package.json** ``` { "type": "module", "scripts": { "tsnode": "node --loader ts-node/esm --no-warnings" }, "dependencies": { "ts-node": "^10.4.0" } } ``` **hello.ts** ``` import * as os from "os" console.log("os", os); ``` Two ways to execute the TypeScript file: * `node --loader ts-node/esm --no-warnings hello.ts` * `npm run tsnode hello.ts`
63,870,080
I was trying to use the top level in the project and saw that it was necessary to change the module from tscofnig to esnext or system, but for some reason my ts-node's error. And I already put the type: module I tried to use the flag: --experimental-modules but the error still does not know how to solve. package.json: ``` { "name": "micro-hr", "version": "1.0.0", "main": "index.js", "license": "MIT", "type": "module", "scripts": { "commit": "git-cz", "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored", "start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts", "start:debug": "node start --debug --watch", "start:prod": "node dist/index.ts", "test": "jest", "lint": "eslint --fix", "lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts", "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n" }, "devDependencies": { "@babel/cli": "^7.11.5", "@babel/core": "^7.11.5", "@babel/node": "^7.10.5", "@babel/preset-env": "^7.11.5", "@babel/preset-typescript": "^7.10.4", "@commitlint/cli": "^9.1.2", "@commitlint/config-conventional": "^9.1.2", "@types/bcryptjs": "^2.4.2", "@types/cookie-parser": "^1.4.2", "@types/cors": "^2.8.7", "@types/express": "^4.17.8", "@types/helmet": "^0.0.48", "@types/jest": "^26.0.13", "@types/node": "^14.6.4", "@types/pino": "^6.3.0", "@types/pino-http": "^5.0.5", "@types/supertest": "^2.0.10", "@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/parser": "^4.0.1", "babel-plugin-module-resolver": "^4.0.0", "commitizen": "^4.2.1", "cz-conventional-changelog": "^3.3.0", "eslint": "^7.8.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", "eslint-config-standard": "^14.1.1", "eslint-import-resolver-typescript": "^2.3.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", "husky": "^4.2.5", "jest": "^26.4.2", "pino-pretty": "^4.2.0", "prettier": "^2.1.1", "supertest": "^4.0.2", "ts-jest": "^26.3.0", "ts-node": "^9.0.0", "ts-node-dev": "^1.0.0-pre.62", "tsconfig-paths": "^3.9.0", "tscpaths": "^0.0.9", "typescript": "^4.0.2" }, "dependencies": { "amqplib": "^0.6.0", "assert": "^2.0.0", "bcryptjs": "^2.4.3", "class-transformer": "^0.3.1", "cors": "^2.8.5", "dotenv": "^8.2.0", "envalid": "^6.0.2", "express": "^4.17.1", "extendable-error": "^0.1.7", "helmet": "^4.1.0", "nabbitmq": "^1.0.0", "pg": "^8.3.3", "pino": "^6.5.1", "pino-http": "^5.2.0", "reflect-metadata": "^0.1.13", "spt-rabbit-helpers": "^1.0.6", "tsyringe": "^4.3.0", "typeorm": "^0.2.25" }, "config": { "commitizen": { "path": "cz-conventional-changelog" } } } ``` tsconfig: ``` { "compilerOptions": { "target": "es2020", "module": "esnext", "allowJs": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "strictPropertyInitialization": false, "moduleResolution": "node", "baseUrl": "./src", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "typeRoots": ["node_modules/@types", "@types"] }, "include": ["src", "__tests__"], "exclude": ["node_modules"] } ``` main: ``` import 'reflect-metadata'; import express from 'express'; import { RabbitServer } from 'spt-rabbit-helpers'; import validateEnv from 'utils/validateEnvs'; import { RabbitMqConnectionFactory, ConsumerFactory, PublisherFactory, RabbitMqConnection, } from 'nabbitmq'; import { container, singleton } from 'tsyringe'; const factory = new RabbitMqConnectionFactory(); factory.setUri('amqp://localhost:5672'); const ConsumerConnection = await factory.newConnection(); const PublisherConnection = await factory.newConnection(); container.registerInstance('Consumer_Connection', ConsumerConnection); container.registerInstance('Publisher_Connection', PublisherConnection); ```
2020/09/13
[ "https://Stackoverflow.com/questions/63870080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13102905/" ]
To run ts-node (or plain node for that matter) you need to use `"module": "commonjs", "target": "ES2017"`, otherwise the `import`/`export` statements are illegally placed in an IIFE. So I would suggest using another file called *node.tsconfig.json* with the following contents: ```json { "extends": "./tsconfig.json", "compilerOptions": { "target": "ES2017" // For NodeJS 8 compat, see https://www.typescriptlang.org/tsconfig#target for more info } } ``` And then run ts-node with `--project ./node.tsconfig.json`
After a lot of searching, I found this solution works perfect: <https://github.com/TypeStrong/ts-node/issues/922#issuecomment-673155000> Just add a `"ts-node"` block to your `tsconfig.json` file as below: > > > ``` > { > "ts-node": { > "compilerOptions": { > "module": "commonjs" > } > }, > "compilerOptions": { > "module": "esnext" > } > } > > ``` > > And it has been documented in the ts-node official page "[Via tsconfig.json](https://github.com/TypeStrong/ts-node#via-tsconfigjson-recommended)" part. This saved hours of my life.
63,870,080
I was trying to use the top level in the project and saw that it was necessary to change the module from tscofnig to esnext or system, but for some reason my ts-node's error. And I already put the type: module I tried to use the flag: --experimental-modules but the error still does not know how to solve. package.json: ``` { "name": "micro-hr", "version": "1.0.0", "main": "index.js", "license": "MIT", "type": "module", "scripts": { "commit": "git-cz", "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored", "start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts", "start:debug": "node start --debug --watch", "start:prod": "node dist/index.ts", "test": "jest", "lint": "eslint --fix", "lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts", "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n" }, "devDependencies": { "@babel/cli": "^7.11.5", "@babel/core": "^7.11.5", "@babel/node": "^7.10.5", "@babel/preset-env": "^7.11.5", "@babel/preset-typescript": "^7.10.4", "@commitlint/cli": "^9.1.2", "@commitlint/config-conventional": "^9.1.2", "@types/bcryptjs": "^2.4.2", "@types/cookie-parser": "^1.4.2", "@types/cors": "^2.8.7", "@types/express": "^4.17.8", "@types/helmet": "^0.0.48", "@types/jest": "^26.0.13", "@types/node": "^14.6.4", "@types/pino": "^6.3.0", "@types/pino-http": "^5.0.5", "@types/supertest": "^2.0.10", "@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/parser": "^4.0.1", "babel-plugin-module-resolver": "^4.0.0", "commitizen": "^4.2.1", "cz-conventional-changelog": "^3.3.0", "eslint": "^7.8.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", "eslint-config-standard": "^14.1.1", "eslint-import-resolver-typescript": "^2.3.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", "husky": "^4.2.5", "jest": "^26.4.2", "pino-pretty": "^4.2.0", "prettier": "^2.1.1", "supertest": "^4.0.2", "ts-jest": "^26.3.0", "ts-node": "^9.0.0", "ts-node-dev": "^1.0.0-pre.62", "tsconfig-paths": "^3.9.0", "tscpaths": "^0.0.9", "typescript": "^4.0.2" }, "dependencies": { "amqplib": "^0.6.0", "assert": "^2.0.0", "bcryptjs": "^2.4.3", "class-transformer": "^0.3.1", "cors": "^2.8.5", "dotenv": "^8.2.0", "envalid": "^6.0.2", "express": "^4.17.1", "extendable-error": "^0.1.7", "helmet": "^4.1.0", "nabbitmq": "^1.0.0", "pg": "^8.3.3", "pino": "^6.5.1", "pino-http": "^5.2.0", "reflect-metadata": "^0.1.13", "spt-rabbit-helpers": "^1.0.6", "tsyringe": "^4.3.0", "typeorm": "^0.2.25" }, "config": { "commitizen": { "path": "cz-conventional-changelog" } } } ``` tsconfig: ``` { "compilerOptions": { "target": "es2020", "module": "esnext", "allowJs": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "strictPropertyInitialization": false, "moduleResolution": "node", "baseUrl": "./src", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "typeRoots": ["node_modules/@types", "@types"] }, "include": ["src", "__tests__"], "exclude": ["node_modules"] } ``` main: ``` import 'reflect-metadata'; import express from 'express'; import { RabbitServer } from 'spt-rabbit-helpers'; import validateEnv from 'utils/validateEnvs'; import { RabbitMqConnectionFactory, ConsumerFactory, PublisherFactory, RabbitMqConnection, } from 'nabbitmq'; import { container, singleton } from 'tsyringe'; const factory = new RabbitMqConnectionFactory(); factory.setUri('amqp://localhost:5672'); const ConsumerConnection = await factory.newConnection(); const PublisherConnection = await factory.newConnection(); container.registerInstance('Consumer_Connection', ConsumerConnection); container.registerInstance('Publisher_Connection', PublisherConnection); ```
2020/09/13
[ "https://Stackoverflow.com/questions/63870080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13102905/" ]
After a lot of searching, I found this solution works perfect: <https://github.com/TypeStrong/ts-node/issues/922#issuecomment-673155000> Just add a `"ts-node"` block to your `tsconfig.json` file as below: > > > ``` > { > "ts-node": { > "compilerOptions": { > "module": "commonjs" > } > }, > "compilerOptions": { > "module": "esnext" > } > } > > ``` > > And it has been documented in the ts-node official page "[Via tsconfig.json](https://github.com/TypeStrong/ts-node#via-tsconfigjson-recommended)" part. This saved hours of my life.
I had the same issue and I fixed it by changing the `module` in `tsconfig.json` to `commonjs` and removing the `module` key in `package.json`: ```js // tsconfig.json { "module": "CommonJS", } ```
63,870,080
I was trying to use the top level in the project and saw that it was necessary to change the module from tscofnig to esnext or system, but for some reason my ts-node's error. And I already put the type: module I tried to use the flag: --experimental-modules but the error still does not know how to solve. package.json: ``` { "name": "micro-hr", "version": "1.0.0", "main": "index.js", "license": "MIT", "type": "module", "scripts": { "commit": "git-cz", "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored", "start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts", "start:debug": "node start --debug --watch", "start:prod": "node dist/index.ts", "test": "jest", "lint": "eslint --fix", "lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts", "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n" }, "devDependencies": { "@babel/cli": "^7.11.5", "@babel/core": "^7.11.5", "@babel/node": "^7.10.5", "@babel/preset-env": "^7.11.5", "@babel/preset-typescript": "^7.10.4", "@commitlint/cli": "^9.1.2", "@commitlint/config-conventional": "^9.1.2", "@types/bcryptjs": "^2.4.2", "@types/cookie-parser": "^1.4.2", "@types/cors": "^2.8.7", "@types/express": "^4.17.8", "@types/helmet": "^0.0.48", "@types/jest": "^26.0.13", "@types/node": "^14.6.4", "@types/pino": "^6.3.0", "@types/pino-http": "^5.0.5", "@types/supertest": "^2.0.10", "@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/parser": "^4.0.1", "babel-plugin-module-resolver": "^4.0.0", "commitizen": "^4.2.1", "cz-conventional-changelog": "^3.3.0", "eslint": "^7.8.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", "eslint-config-standard": "^14.1.1", "eslint-import-resolver-typescript": "^2.3.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", "husky": "^4.2.5", "jest": "^26.4.2", "pino-pretty": "^4.2.0", "prettier": "^2.1.1", "supertest": "^4.0.2", "ts-jest": "^26.3.0", "ts-node": "^9.0.0", "ts-node-dev": "^1.0.0-pre.62", "tsconfig-paths": "^3.9.0", "tscpaths": "^0.0.9", "typescript": "^4.0.2" }, "dependencies": { "amqplib": "^0.6.0", "assert": "^2.0.0", "bcryptjs": "^2.4.3", "class-transformer": "^0.3.1", "cors": "^2.8.5", "dotenv": "^8.2.0", "envalid": "^6.0.2", "express": "^4.17.1", "extendable-error": "^0.1.7", "helmet": "^4.1.0", "nabbitmq": "^1.0.0", "pg": "^8.3.3", "pino": "^6.5.1", "pino-http": "^5.2.0", "reflect-metadata": "^0.1.13", "spt-rabbit-helpers": "^1.0.6", "tsyringe": "^4.3.0", "typeorm": "^0.2.25" }, "config": { "commitizen": { "path": "cz-conventional-changelog" } } } ``` tsconfig: ``` { "compilerOptions": { "target": "es2020", "module": "esnext", "allowJs": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "strictPropertyInitialization": false, "moduleResolution": "node", "baseUrl": "./src", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "typeRoots": ["node_modules/@types", "@types"] }, "include": ["src", "__tests__"], "exclude": ["node_modules"] } ``` main: ``` import 'reflect-metadata'; import express from 'express'; import { RabbitServer } from 'spt-rabbit-helpers'; import validateEnv from 'utils/validateEnvs'; import { RabbitMqConnectionFactory, ConsumerFactory, PublisherFactory, RabbitMqConnection, } from 'nabbitmq'; import { container, singleton } from 'tsyringe'; const factory = new RabbitMqConnectionFactory(); factory.setUri('amqp://localhost:5672'); const ConsumerConnection = await factory.newConnection(); const PublisherConnection = await factory.newConnection(); container.registerInstance('Consumer_Connection', ConsumerConnection); container.registerInstance('Publisher_Connection', PublisherConnection); ```
2020/09/13
[ "https://Stackoverflow.com/questions/63870080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13102905/" ]
After a lot of searching, I found this solution works perfect: <https://github.com/TypeStrong/ts-node/issues/922#issuecomment-673155000> Just add a `"ts-node"` block to your `tsconfig.json` file as below: > > > ``` > { > "ts-node": { > "compilerOptions": { > "module": "commonjs" > } > }, > "compilerOptions": { > "module": "esnext" > } > } > > ``` > > And it has been documented in the ts-node official page "[Via tsconfig.json](https://github.com/TypeStrong/ts-node#via-tsconfigjson-recommended)" part. This saved hours of my life.
If you are using `React`, "commonjs" can not be set for TypeScript. **tsconfig.json** ``` { "compilerOptions": { "module": "esnext" } } ``` **package.json** ``` { "type": "module", "scripts": { "tsnode": "node --loader ts-node/esm --no-warnings" }, "dependencies": { "ts-node": "^10.4.0" } } ``` **hello.ts** ``` import * as os from "os" console.log("os", os); ``` Two ways to execute the TypeScript file: * `node --loader ts-node/esm --no-warnings hello.ts` * `npm run tsnode hello.ts`
115,602
Context ======= I'm working on very complex enterprise solution. We have this table that shows list of let's call them contracts. Every contract (row) can contain one or more customers (and one or more products). Problem ======= I need to think of these use cases: 1. People want to copy & paste customer IDs. 2. People should be able to remove all the customers at once. 3. People should still have an overview what customers were selected. 4. People should be able to browse customers and pick those they want to. (Since we are in the able the solution needs to be compact) My proposal =========== [![My solution](https://i.stack.imgur.com/HLqCS.png)](https://i.stack.imgur.com/HLqCS.png) - Clicking on the "CD-0005" would trigger the browse window - **Missing** copy & paste functionality [![enter image description here](https://i.stack.imgur.com/vctwb.png)](https://i.stack.imgur.com/vctwb.png) - Looks super ugly - Hard to provide overview on all the items (having tooltip on input hover is somehow strange) **What do you think? How can this problem be solved?**
2018/02/06
[ "https://ux.stackexchange.com/questions/115602", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/108493/" ]
1. You can add a copy link in front of each customer ID on hover. [![enter image description here](https://i.stack.imgur.com/LMt7G.jpg)](https://i.stack.imgur.com/LMt7G.jpg) 2. Add filters on table headers 3. Highlight the selected rows or make customer ID a badge when selected 4. Making customer ID badge would make it easier to identify the ones needed and switch between states. I loved how "Clear Move" handle the tables. You can use it as inspiration. [![enter image description here](https://i.stack.imgur.com/zmTlD.jpg)](https://i.stack.imgur.com/zmTlD.jpg)
Why don't you add a context menu (invoked by right mouse click) containing "Copy" and "Copy all" items? To know which customer ID you are about to copy a hover (on mouse over above each ID) helps. The balloon closes on mouse out event. It can be programmatically challenging to add a context menu on a balloon but once you get over it, the ease of use compensates for your effort.
115,602
Context ======= I'm working on very complex enterprise solution. We have this table that shows list of let's call them contracts. Every contract (row) can contain one or more customers (and one or more products). Problem ======= I need to think of these use cases: 1. People want to copy & paste customer IDs. 2. People should be able to remove all the customers at once. 3. People should still have an overview what customers were selected. 4. People should be able to browse customers and pick those they want to. (Since we are in the able the solution needs to be compact) My proposal =========== [![My solution](https://i.stack.imgur.com/HLqCS.png)](https://i.stack.imgur.com/HLqCS.png) - Clicking on the "CD-0005" would trigger the browse window - **Missing** copy & paste functionality [![enter image description here](https://i.stack.imgur.com/vctwb.png)](https://i.stack.imgur.com/vctwb.png) - Looks super ugly - Hard to provide overview on all the items (having tooltip on input hover is somehow strange) **What do you think? How can this problem be solved?**
2018/02/06
[ "https://ux.stackexchange.com/questions/115602", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/108493/" ]
1. You can add a copy link in front of each customer ID on hover. [![enter image description here](https://i.stack.imgur.com/LMt7G.jpg)](https://i.stack.imgur.com/LMt7G.jpg) 2. Add filters on table headers 3. Highlight the selected rows or make customer ID a badge when selected 4. Making customer ID badge would make it easier to identify the ones needed and switch between states. I loved how "Clear Move" handle the tables. You can use it as inspiration. [![enter image description here](https://i.stack.imgur.com/zmTlD.jpg)](https://i.stack.imgur.com/zmTlD.jpg)
Usman Mani already proposed an elegant solution, however for anyone seeing this after... I had similar questions and stumbled upon a very useful article about building tables for reusability. <https://uxdesign.cc/designing-tables-for-reusability-490a3760533> TLDR: It's ok to not show all of the information in a row, do some usability testing and find the 2-3 most important data points a user needs in a table row and then hide the rest. Utilizing font awesome illustrate that there is more data if the user does require it.
115,602
Context ======= I'm working on very complex enterprise solution. We have this table that shows list of let's call them contracts. Every contract (row) can contain one or more customers (and one or more products). Problem ======= I need to think of these use cases: 1. People want to copy & paste customer IDs. 2. People should be able to remove all the customers at once. 3. People should still have an overview what customers were selected. 4. People should be able to browse customers and pick those they want to. (Since we are in the able the solution needs to be compact) My proposal =========== [![My solution](https://i.stack.imgur.com/HLqCS.png)](https://i.stack.imgur.com/HLqCS.png) - Clicking on the "CD-0005" would trigger the browse window - **Missing** copy & paste functionality [![enter image description here](https://i.stack.imgur.com/vctwb.png)](https://i.stack.imgur.com/vctwb.png) - Looks super ugly - Hard to provide overview on all the items (having tooltip on input hover is somehow strange) **What do you think? How can this problem be solved?**
2018/02/06
[ "https://ux.stackexchange.com/questions/115602", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/108493/" ]
1. You can add a copy link in front of each customer ID on hover. [![enter image description here](https://i.stack.imgur.com/LMt7G.jpg)](https://i.stack.imgur.com/LMt7G.jpg) 2. Add filters on table headers 3. Highlight the selected rows or make customer ID a badge when selected 4. Making customer ID badge would make it easier to identify the ones needed and switch between states. I loved how "Clear Move" handle the tables. You can use it as inspiration. [![enter image description here](https://i.stack.imgur.com/zmTlD.jpg)](https://i.stack.imgur.com/zmTlD.jpg)
An easier and cleaner way would be to provide an Edit icon for each Contract row and open the whole thing in a modal overlay, provided the form does not run too long.
6,887,091
I am a new user of git and can't figure out how to get around this. I have had some experience with SVN and am going by SVN behavior. Any time I pull files from remote repository, and the file I have modified are also modified remotely, it needs merging. I can understand merge conflicts for complex changes, but I am seeing merge conflicts for very small (e.g. one line change in different functions) changes. As far as I remember, SVN could merge most of it automatically and will put the file in conflicted state only if automatic merge failed. For git, it seems to be happening every time and forcing to open the git merge tool. Is there any way to automatically merge the files? Am I missing some setting that is basically putting the repository in conflicted set by default?
2011/07/31
[ "https://Stackoverflow.com/questions/6887091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871199/" ]
A common cause of this is differing line endings. Are you sharing a repo with someone else using a different OS? SVN does some munging of line endings. Git, on the other hand, stores files byte-for-byte exactly as they are by default. That means that when a Windows user saves a file with \r\n line endings and a Linux user saves the file with \n line feeds, every line appears changed, and if any other changes are in play, it causes conflicts everywhere. To change the way line endings are handled, use the configuration setting "core.autocrlf". In a repo where different OS's are in play, I recommend setting it to "input" for Linux users and "true" for Windows users: ``` git config [--global] core.autocrlf input ``` or ``` git config [--global] core.autocrlf true ``` Actually, I'd say just use these settings globally all the time. They'll save you some heartache. Read more about core.autocrlf on the [git-config man page](https://git-scm.com/docs/git-config), and note that if you're suffering from this problem and you turn autocrlf on with an existing repository, you may see some startling behavior, but it can be explained.
From the manual: > > <https://book.git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging> > > > git commit -a > > > At this point the two branches have diverged, with different changes > made in each. To merge the changes made in experimental into master, > run > > > git merge experimental > > > If the changes don't conflict, you're done. If there are conflicts, > markers will be left in the problematic files showing the conflict; > > > git diff > > > will show this. Once you've edited the files to resolve the conflicts, > > > git commit -a > > > will commit the result of the merge. Finally, > > > gitk > > > will show a nice graphical representation of the resulting history. > > > Q: What Git client are you using? The Git command line tool? Or something else? Q: Also, are the files in question both Linux, or both Windows? Or are they from different environments?
694,274
I am really confused with expressions under Lorentz transformation. I will try to showcase my confusion via an easy and very popular example: If we have two inertial systems $S$ and $S'$, and $S'$ is moving relative to S with velocity $v$. A point charge is in the origin of $S'$. Initially at $t=t'=0$ their origins are at the same point. In $S'$: We only have electric field: $\vec E'= \frac{1}{4\pi \epsilon\_0}\frac{\vec r'}{|\vec r'|^3}$ There is no magnetic field: $\vec B'=0$ We want to know the electric field and magnetic field at point $P=(0,b,0)$. This point is in $S$ system as $\vec P=(0,b,0)$. This point is in $S'$ system as $\vec P'=(x',b,0)$. Performing Lorentz transformation of the kind $x'=\gamma(x -vt)$. We know that $x=0$, therefore $x'=-v\gamma t$. Then $\vec P'=(-v\gamma t,b,0)$. I consider that these are the coordinates of point $\vec P'$ observed by someone in the system $S'$, but via the coordinates of the same point $\vec P$ observed by someone in the rest frame. But we can also express the coordinates of $\vec P'=(-vt',b,0)$. Here the coordinates are directly related to the frame at motion, and no Lorentz transformation takes place. Anyway, we perform Lorentz transformations etc and for the x component of the Electric field we have: $$E\_x=E\_x'=\frac{1}{4\pi \epsilon\_0} \frac{-vt'}{(b^2 + v^2t'^2)^{\frac 32 }}=\frac{1}{4\pi \epsilon\_0} \frac{-v\gamma t}{(b^2 + \gamma^2v^2t^2)^{\frac 32 }}$$ Both of the above expressions are related to $E\_x'$. When the observer is in the rest frame of the particle and no LT takes place, the expression for the electric field at $\vec P'$ is: $$E\_x'=\frac{1}{4\pi \epsilon\_0} \frac{-vt'}{(b^2 + v^2t'^2)^{\frac 32 }}$$ Now if we want to express the x-component of the electric field, but by utilizing the coordinates from the rest frame, we would get: $$E\_x'=\frac{1}{4\pi \epsilon\_0} \frac{-v\gamma t}{(b^2 + \gamma^2v^2t^2)^{\frac 32 }}$$ But if I want to know the expression of the x-component, described by an observer at the rest frame $S$, while taking into consideration the coordinates from the frame at motion $S'$, we need to perform the following LT: $x=\gamma(x'+vt)$ and because $x'=-vt$, I would get $x=0$, which is correct because in the rest frame the point where we want to find the electric field is $\vec P(0,b,0)$ which has a $0$ for the x component. As a result $E\_x=0$. But this is not possible since $E\_x=E\_x'$ for this case. So what exactly I am not understanding here?
2022/02/13
[ "https://physics.stackexchange.com/questions/694274", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/275029/" ]
The radius of the first maximum is approximately $$\frac{\lambda l}{d}\sim\frac{0.5\cdot 10^{-6}m\cdot0.3 m}{0.2\cdot 10^{-3}m}\sim 1mm.$$ As "The 'cloud' is about 8cm in radius", you are probably looking for the rings in wrong places. It is possible that even minimums of the "ring" diffraction picture look very bright (except for narrow areas).
Even though there is already a good answer that has been upvoted (and I will upvote right after this is posted) and accepted, this looked like a fun one to try, given that I have all the necessary components. So here is the setup I put together an hour ago: [![Setup photo 1](https://i.stack.imgur.com/yDuDd.jpg)](https://i.stack.imgur.com/yDuDd.jpg) The green (532 nm) laser, removed from its laser pointer housing and powered by an external adjustable DC power supply, is at left. The green beam is split at the non-polarizing beamsplitter cube. The beam that goes straight through strikes a 100 micron pinhole. The reflected beam from the beamsplitter cube is reflected from a front surface mirror and then strikes the adjustable slits (from a 1950s 3.4 m J-A spectrograph). Another view: [![Setup photo 2](https://i.stack.imgur.com/isMgi.jpg)](https://i.stack.imgur.com/isMgi.jpg) The resulting outputs of the 100 micron pinhole and the adjustable slits: [![Setup and outputs](https://i.stack.imgur.com/R5l1u.jpg)](https://i.stack.imgur.com/R5l1u.jpg) A closer view of the outputs: [![Outputs of 100 micron pinhole and slits](https://i.stack.imgur.com/yTwQQ.jpg)](https://i.stack.imgur.com/yTwQQ.jpg) Replacing the 100 micron pinhole with a Thorlabs 30 micron pinhole yields the following: [![Outputs of 30 micron pinhole and slits](https://i.stack.imgur.com/NvWcK.jpg)](https://i.stack.imgur.com/NvWcK.jpg) So the slits work fine, but the pinhole results are really poor. I assume this is due to the relatively bad beam quality of my inexpensive green laser pointer. Presumably spacial filtering the laser would help a great deal. I might try it later. Sorry about the stray light: I should add iris apertures, but this was just a quick setup.
6,666
My wife doesn't work anymore and she has a 401(k) of about $80,000 from an old job. I have been kicking around the idea of taking that money out or rolling into an IRA so that I can have better access to this money. Given the interest rates I want to purchase a new home and would like to leverage this money as a down payment if it makes sense. Thanks for the help.
2011/03/04
[ "https://money.stackexchange.com/questions/6666", "https://money.stackexchange.com", "https://money.stackexchange.com/users/-1/" ]
Unless that 401K has very low [expense ratios](http://www.investopedia.com/terms/e/expenseratio.asp) on its funds, you should roll it into an IRA and choose funds with low expense ratios. After rolling it over you should *not* take the 10% penalty and use it to purchase a home. Unless you use that home as an income property, it is unlikely to provide you more than a 1% inflation-adjusted rate of return given historical data. The S&P 500 is about 4% adjusted for inflation. And that money currently in your 401(k) is for your retirement - your future. Don't borrow against your future. Let compound interest do its work on that money. The value of a house is in the rent you aren't paying to live somewhere and there are a lot of costs to consider. That doesn't mean don't buy. It just means buy wisely. If you are currently maxing out your 401(k), you may consider cutting back to save for your down payment. Other than that I wouldn't touch retirement money unless it was a dire financial emergency.
It's not your money. What does your wife think of this? You know, the withdrawal is subject to full tax at your marginal rate as well as a 10% penalty. That's quite a price to pay, don't do it.
6,666
My wife doesn't work anymore and she has a 401(k) of about $80,000 from an old job. I have been kicking around the idea of taking that money out or rolling into an IRA so that I can have better access to this money. Given the interest rates I want to purchase a new home and would like to leverage this money as a down payment if it makes sense. Thanks for the help.
2011/03/04
[ "https://money.stackexchange.com/questions/6666", "https://money.stackexchange.com", "https://money.stackexchange.com/users/-1/" ]
Don't borrow from your future to live in the present.
It's not your money. What does your wife think of this? You know, the withdrawal is subject to full tax at your marginal rate as well as a 10% penalty. That's quite a price to pay, don't do it.
13,629,483
I have a list of list, such as ``` T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] ``` I would like to find the total sum of these numbers. I am new to python programming, when I try a simple `int(T[1])` conversion, I get error ``` TypeError: int() argument must be a string or a number, not 'list' ``` I appreciate any input.
2012/11/29
[ "https://Stackoverflow.com/questions/13629483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863596/" ]
easy: ``` sum(x[0] for x in T) ``` You're done :) --- Of course, you could use ``` import itertools sum(itertools.chain.from_iterable(T)) ``` too. This would work if your sublists had more than 1 element each.
``` In [31]: T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] In [32]: sum(t[0] for t in T) Out[32]: 0.8981600000000001 ```
13,629,483
I have a list of list, such as ``` T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] ``` I would like to find the total sum of these numbers. I am new to python programming, when I try a simple `int(T[1])` conversion, I get error ``` TypeError: int() argument must be a string or a number, not 'list' ``` I appreciate any input.
2012/11/29
[ "https://Stackoverflow.com/questions/13629483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863596/" ]
easy: ``` sum(x[0] for x in T) ``` You're done :) --- Of course, you could use ``` import itertools sum(itertools.chain.from_iterable(T)) ``` too. This would work if your sublists had more than 1 element each.
``` >>> T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] >>> sum(x[0] for x in T) 0.8981600000000001 ```
13,629,483
I have a list of list, such as ``` T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] ``` I would like to find the total sum of these numbers. I am new to python programming, when I try a simple `int(T[1])` conversion, I get error ``` TypeError: int() argument must be a string or a number, not 'list' ``` I appreciate any input.
2012/11/29
[ "https://Stackoverflow.com/questions/13629483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863596/" ]
easy: ``` sum(x[0] for x in T) ``` You're done :) --- Of course, you could use ``` import itertools sum(itertools.chain.from_iterable(T)) ``` too. This would work if your sublists had more than 1 element each.
You can use numpy sum module ``` import numpy as np result = int(np.sum(T, axis=0)) ``` or a inbuilt map function ``` result = int(sum(map(sum, T))) ```
13,629,483
I have a list of list, such as ``` T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] ``` I would like to find the total sum of these numbers. I am new to python programming, when I try a simple `int(T[1])` conversion, I get error ``` TypeError: int() argument must be a string or a number, not 'list' ``` I appreciate any input.
2012/11/29
[ "https://Stackoverflow.com/questions/13629483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863596/" ]
You can use [`map`](http://docs.python.org/2/library/functions.html#map) for this: ``` sum(map(sum, T)) ``` ``` >>> sum(map(sum, T)) 0.89816000000000007 ``` From the documentation for `map`: > > **map**(function, iterable, ...) > > > Apply function to every item of iterable and return a list of the results. > > > So you are using `map` to total up the inner lists, and then a call to `sum` to total those values for the final answer. This approach will work if your inner lists contain multiple items.
``` In [31]: T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] In [32]: sum(t[0] for t in T) Out[32]: 0.8981600000000001 ```
13,629,483
I have a list of list, such as ``` T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] ``` I would like to find the total sum of these numbers. I am new to python programming, when I try a simple `int(T[1])` conversion, I get error ``` TypeError: int() argument must be a string or a number, not 'list' ``` I appreciate any input.
2012/11/29
[ "https://Stackoverflow.com/questions/13629483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863596/" ]
You can use [`map`](http://docs.python.org/2/library/functions.html#map) for this: ``` sum(map(sum, T)) ``` ``` >>> sum(map(sum, T)) 0.89816000000000007 ``` From the documentation for `map`: > > **map**(function, iterable, ...) > > > Apply function to every item of iterable and return a list of the results. > > > So you are using `map` to total up the inner lists, and then a call to `sum` to total those values for the final answer. This approach will work if your inner lists contain multiple items.
``` >>> T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] >>> sum(x[0] for x in T) 0.8981600000000001 ```
13,629,483
I have a list of list, such as ``` T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] ``` I would like to find the total sum of these numbers. I am new to python programming, when I try a simple `int(T[1])` conversion, I get error ``` TypeError: int() argument must be a string or a number, not 'list' ``` I appreciate any input.
2012/11/29
[ "https://Stackoverflow.com/questions/13629483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863596/" ]
You can use [`map`](http://docs.python.org/2/library/functions.html#map) for this: ``` sum(map(sum, T)) ``` ``` >>> sum(map(sum, T)) 0.89816000000000007 ``` From the documentation for `map`: > > **map**(function, iterable, ...) > > > Apply function to every item of iterable and return a list of the results. > > > So you are using `map` to total up the inner lists, and then a call to `sum` to total those values for the final answer. This approach will work if your inner lists contain multiple items.
You can use numpy sum module ``` import numpy as np result = int(np.sum(T, axis=0)) ``` or a inbuilt map function ``` result = int(sum(map(sum, T))) ```
42,569
From random Internet sites, we can see many examples of the grammar structures: > > [verb] + 在了 > > > > > 手机**忘在了**出租车上。 > > 我**站在了**舞台上。 > > 因为人不在,快递员就**放在了**门口。 > > 小男孩被父亲故意**丢在了**超市。 > > 闺蜜和男友**睡在了**一起。 > > (Google the quotes surrounded by quotation marks to see the source(s).) > > > I think I get the gist from these examples. It looks like adding 在 modifies a verb, e.g., 忘 = "to forget" turns into 忘在 = "to forget at". The 了 is the [completion 了](https://resources.allsetlearning.com/chinese/grammar/Expressing_completion_with_%22le%22), added after the modified verb 忘在了 (so we don't write 忘了在 [or do we?]). 在了 doesn't seem to be used in the same way without a preceding verb (but we can say 不在了 or 没在了 to mean "not here", sometimes as a euphemism for being dead). However, there may be a better way to understand this. I'm wondering if there is a more rigorous treatment available. I didn't find a reference from Google, not at the Chinese Grammar Wiki. **Question**: How does one understand the [verb] + 在了 grammar structure?
2021/01/10
[ "https://chinese.stackexchange.com/questions/42569", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8099/" ]
在了 is very common, even colloquially, but it'd be better to see it as separate 在 and 了. The usage of 了 and its position in a sentence is complex. In the example sentence > > 手机忘在了出租车上, > > > 1. 忘 here can be understood as a [labile verb](https://en.wikipedia.org/wiki/Labile_verb) (perhaps?), meaning "be forgotten". 2. 在 is a **结果补语 (complement of result)**. Accroding to 刘月华(Liu Yuehua) et al.'s 《实用现代汉语语法》(*Practical Modern Chinese Grammar*, I'll refer to it as Gr from now on), the function of 在 is to "表示通过动作使人或事物处于某个处所,后边一定要有处所宾语" (convey the idea that something or someone is placed in some position via an action, and must be followed by an object of location). 3. 出租车上 is the **处所宾语 (object of location)** of 在. The object 出租车, or taxi, usually can't convey the idea of location on its own, but can do so when compounded with the adverb of position 上. 4. 了 is a **动态助词 (aspect particle)**. According to Gr, it's a bit complex; for a verb like 忘 in the sense of "to leave something at some place", 了 means the action has happened and has ended. I think your problem here can boil down to *where should the article 了 be in this sentence?* According to Gr, "如果谓语动词后有结果补语,“了”位于结果补语后:动词+结果补语+“了”+宾语" (**if there is a complement of result after the verb, then 了 is placed after the complement of result: verb + complement of result + 了 particle + object**). So, 手机(Subject)忘(Verb)在(Complement)了(Particle)出租车上(Object)。 This rule can explain the first four sentences you provided. I think the fifth one is the same, but I'm unsure for now. Also, please note that in every sentence you provided, 了 can be placed at the very end. This kind of 了 is called a 语气助词 (Modal particle), and the meanings of some sentences will change when you move 了 to the end, and some will not change very much. However, this is a much more complex grammar mischief of Chinese and I don't consider myself capable of talking about it. Hope this helps.
在... is prep phrase working as a compliment. E.g. 放[在门口]了. 了 is for completion. 放在了门口 is a variant of 放在门口了. I think it might be because we say 放在 so often that we take it as a verb as a whole. So both 放在哪里了 and 放在了哪里 are correct. So, 手机忘在了出租车上 = 手机忘在出租车上了. 小男孩被父亲故意丢在了超市 =小男孩被父亲故意丢在超市了. etc.
18,667,032
I found this answer here regarding graphic design: <https://graphicdesign.stackexchange.com/questions/265/font-face-loaded-on-windows-look-really-bad-which-fonts-are-you-using-that-rend> This is exactly what my fonts are doing, but I'm trying to find out if there's a way to prevent this using html or css or anything web-based. I'm using "platin" as my font. Do I just need to find a different font? Any other thoughts on the topic?
2013/09/06
[ "https://Stackoverflow.com/questions/18667032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2666084/" ]
An answer from [this similar question](https://stackoverflow.com/questions/11225654/xcode-how-to-connect-xib-to-viewcontroller-class/18003928#18003928): "Here's a more step-by-step way to associate your new UIViewController and .xib. Select File's Owner under Placeholders on the left pane of IB. In the Property Inspector(right pane of IB), select the third tab and edit "Class" under "Custom Class" to be the name of your new UIViewController subclass. Then ctrl-click or right-click on File's Owner in the left pane and draw a line to your top level View in the Objects portion of the left pane. Select the 'view' outlet and you're done. You should now be able to set up other outlets and actions. You're ready to instantiate your view controller in code and use initWithNibName and your nib name to load it."
If it's a UITableViewController, simply create a new XIB file via Xcode (File -> New -> iOS -> UserInterface -> View) and then add set the file's owner to your subclassed UITableViewController. You'll likely want to re-do how the user interface looks -- in terms of dropping objects like the table view and buttons or whatever else -- into the XIB's view. It'll certainly save a lot of time versus trying to debug programmatically creating and adding subviews and actions. And once that's in place, you can then make IBOutlets and IBActions to your heart's content.
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
Let's step through your code: 1. We setup an `int` with initial value of `0` and assign it to `sum`. 2. We setup a `for` loop, setting `int k = 1`, and we will loop while `k` is less than 10, and after each iteration, 2 will be added to `k`. So, the first iteration, `k = 1`. `sum` currently equals 0, so `sum += k` is actually 0 = 0 + 1 = 1. There's the 1 you are getting. For the second iteration, `k = 3`. `sum` currently equals 1, so `sum += k` is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up. Repeat this for the rest of the loop!
Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by `k+=2`. To translate, it means `k = k +2` Inside the loop `sum = sum + k`. It will then print the value that sum has plus a space. ``` k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ``` and keep repeating. Let me know if you still have trouble grasping this concept
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
The sections of the for loop are run at different times. 1. The first section is run once at the start to initialize the variables. 2. The second is run each time around the loop at the START of the loop to say whether to exit or not. 3. The final section is run each time around the loop at the END of the loop. All sections are optional and can just be left blank if you want. You can also depict a for loop as a while loop: ``` for (A;B;C) { D; } ``` is the same as: ``` A; while (B) { D; C; } ```
It goes like this: 1. Initialize (k = 1) 2. Check condition (k < 10) (stop if false) 3. Run the code in the loop (sum += k and print) 4. Increment (k += 2) 5. Repeat from step 2 Following this logic, you get that 1 is printed first.
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
It goes like this: 1. Initialize (k = 1) 2. Check condition (k < 10) (stop if false) 3. Run the code in the loop (sum += k and print) 4. Increment (k += 2) 5. Repeat from step 2 Following this logic, you get that 1 is printed first.
Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by `k+=2`. To translate, it means `k = k +2` Inside the loop `sum = sum + k`. It will then print the value that sum has plus a space. ``` k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ``` and keep repeating. Let me know if you still have trouble grasping this concept
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
Let's step through your code: 1. We setup an `int` with initial value of `0` and assign it to `sum`. 2. We setup a `for` loop, setting `int k = 1`, and we will loop while `k` is less than 10, and after each iteration, 2 will be added to `k`. So, the first iteration, `k = 1`. `sum` currently equals 0, so `sum += k` is actually 0 = 0 + 1 = 1. There's the 1 you are getting. For the second iteration, `k = 3`. `sum` currently equals 1, so `sum += k` is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up. Repeat this for the rest of the loop!
Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more. The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop' So this is how it starts, its starts with what you set 'k' for which is 1. k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has. So k = 1 + 2 = 3. And now we start the second loop. k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues. oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard... Good luck! has to
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
The last condition, `k += 2` occurs *after* the first iteration of the loop. So it's ```none k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ```
Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more. The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop' So this is how it starts, its starts with what you set 'k' for which is 1. k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has. So k = 1 + 2 = 3. And now we start the second loop. k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues. oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard... Good luck! has to
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
In the first iteration of the loop, `k=1`. The `k+=2` is only run at the beginning of the next iteration of the loop. The loop variable update condition (the last part of the for loop - i.e. the `k+=2` part) never runs on the first iteration but does run on every other one, at the start. Therefore what you have is: Iteration 1: ``` k=1 sum = 0 + 1; //so sum = 1 ``` Iteration 2: ``` k=1+2 // so k=3 sum = 1 + 3 // so sum = 4 ``` Iteration 3: ``` k=3+2 //k=5 sum = 4 + 5 //sum=9 ``` etc...
Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by `k+=2`. To translate, it means `k = k +2` Inside the loop `sum = sum + k`. It will then print the value that sum has plus a space. ``` k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ``` and keep repeating. Let me know if you still have trouble grasping this concept
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
The sections of the for loop are run at different times. 1. The first section is run once at the start to initialize the variables. 2. The second is run each time around the loop at the START of the loop to say whether to exit or not. 3. The final section is run each time around the loop at the END of the loop. All sections are optional and can just be left blank if you want. You can also depict a for loop as a while loop: ``` for (A;B;C) { D; } ``` is the same as: ``` A; while (B) { D; C; } ```
Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more. The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop' So this is how it starts, its starts with what you set 'k' for which is 1. k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has. So k = 1 + 2 = 3. And now we start the second loop. k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues. oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard... Good luck! has to
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
The last condition, `k += 2` occurs *after* the first iteration of the loop. So it's ```none k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ```
Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by `k+=2`. To translate, it means `k = k +2` Inside the loop `sum = sum + k`. It will then print the value that sum has plus a space. ``` k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ``` and keep repeating. Let me know if you still have trouble grasping this concept
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
The sections of the for loop are run at different times. 1. The first section is run once at the start to initialize the variables. 2. The second is run each time around the loop at the START of the loop to say whether to exit or not. 3. The final section is run each time around the loop at the END of the loop. All sections are optional and can just be left blank if you want. You can also depict a for loop as a while loop: ``` for (A;B;C) { D; } ``` is the same as: ``` A; while (B) { D; C; } ```
Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by `k+=2`. To translate, it means `k = k +2` Inside the loop `sum = sum + k`. It will then print the value that sum has plus a space. ``` k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ``` and keep repeating. Let me know if you still have trouble grasping this concept
21,211,502
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates. Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below. ``` public class Test { public static void main (String[] args) { int sum = 0; for (int k = 1; k < 10; k += 2) { sum += k; System.out.print(sum + " "); } } } ``` The output the program puts out is 1 4 9 16 25 Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3? It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about. My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around. Overall my question is, how is sum equal to 1 when k is actually equal to 3.
2014/01/19
[ "https://Stackoverflow.com/questions/21211502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966385/" ]
k is only incremented after the loop iteration. In general for any loop the values are updated after a loop iteration so k goes 1,3,5,7,9 and so the sum is correct.
Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by `k+=2`. To translate, it means `k = k +2` Inside the loop `sum = sum + k`. It will then print the value that sum has plus a space. ``` k = 1, sum = 1 k = 3, sum = 4 k = 5, sum = 9 k = 7, sum = 16 k = 9, sum = 25 ``` and keep repeating. Let me know if you still have trouble grasping this concept
26,337,469
So that is the question: how to revert to specific commit in history while saving current work to another branch? I've tried checking out to another branch and then `git reset --hard commit_hash` but the other branch was reverted too and i don't want this.
2014/10/13
[ "https://Stackoverflow.com/questions/26337469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491475/" ]
That seems to happen because you are using `mysqldump` 5.5 or prior with a MySQL 5.6 database. The `SET OPTION` syntax was removed (see discussion in [this bug report](http://bugs.mysql.com/bug.php?id=66765)), causing this tool to stop working. You will need to update your version of `mysqldump`. More info about it in [this other bug report](http://bugs.mysql.com/bug.php?id=67507).
You might need a space between `-p` and `DB_USER_PASSWORD`. ``` dumpcmd = "mysqldump -u " + DB_USER + " -p " + DB_USER_PASSWORD + " " + db + " > " + TODAYBACKUPPATH + "/" + db + ".sql" ```
26,337,469
So that is the question: how to revert to specific commit in history while saving current work to another branch? I've tried checking out to another branch and then `git reset --hard commit_hash` but the other branch was reverted too and i don't want this.
2014/10/13
[ "https://Stackoverflow.com/questions/26337469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491475/" ]
That seems to happen because you are using `mysqldump` 5.5 or prior with a MySQL 5.6 database. The `SET OPTION` syntax was removed (see discussion in [this bug report](http://bugs.mysql.com/bug.php?id=66765)), causing this tool to stop working. You will need to update your version of `mysqldump`. More info about it in [this other bug report](http://bugs.mysql.com/bug.php?id=67507).
Thanks to the answer from javidcf, I found the answer to my question. The solution is to use a command-line mysqldump version that supports MySQL 5.6.
52,773,492
I have the following data set: ``` column1 HL111 PG3939HL11 HL339PG RC--HL--PG ``` I am attempting to write a function that does the following: 1. Loop through each row of column1 2. Pull only the alphabet and put into an array 3. If the array has "HL" in it, remove it from the array UNLESS HL is the only word in the array. 4. Take the first word in the array and output results. So for the above example, my array (step2) would look like this: ``` [HL] [PG,HL] [HL,PG] [RC,HL,PG] ``` and my desired final output (step4) would look like this: ``` desired_column HL PG PG RC ``` I have the code for step 2, and it seems to work fine ``` df['array_column'] = (df.column1.str.extractall('([A-Z]+)') .unstack() .values.tolist()) ``` But I don't know how to get from here to my final output (step4).
2018/10/12
[ "https://Stackoverflow.com/questions/52773492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6365890/" ]
You may achieve what you need by replacing all non-letters first, then extracting pairs of letters and then applying some custom logic to extract the necessary value from the array: ``` >>> df['array_column'].str.replace('[^A-Z]+', '').str.findall('([A-Z]{2})').apply(lambda d: [''] if len(d) == 0 else d).apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0]) 0 HL 1 PG 2 PG 3 RC Name: array_column, dtype: object >>> ``` **Details** * `.replace('[^A-Z]+', '')` - remove all chars other the uppercase letters * `.str.findall('([A-Z]{2})')` - extract pairs of letters * `.apply(lambda d: [''] if len(d) == 0 else d)` will add an empty item if there is no regex match in the previous step * `.apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0])` - custom logic: if the list length is 1 and it is equal to `HL`, keep it, else remove all `HL` and get the first element
This is one approach using `apply` **Demo:** ``` import re import pandas as pd def checkValue(value): value = re.findall(r"[A-Z]{2}", value) if (len(value) > 1) and ("HL" in value): return [i for i in value if i != "HL"][0] else: return value[0] df = pd.DataFrame({"column1": ["HL111", "PG3939HL11", "HL339PG", "RC--HL--PG"]}) print(df.column1.apply(checkValue)) ``` **Output:** ``` 0 HL 1 PG 2 PG 3 RC Name: column1, dtype: object ```
52,773,492
I have the following data set: ``` column1 HL111 PG3939HL11 HL339PG RC--HL--PG ``` I am attempting to write a function that does the following: 1. Loop through each row of column1 2. Pull only the alphabet and put into an array 3. If the array has "HL" in it, remove it from the array UNLESS HL is the only word in the array. 4. Take the first word in the array and output results. So for the above example, my array (step2) would look like this: ``` [HL] [PG,HL] [HL,PG] [RC,HL,PG] ``` and my desired final output (step4) would look like this: ``` desired_column HL PG PG RC ``` I have the code for step 2, and it seems to work fine ``` df['array_column'] = (df.column1.str.extractall('([A-Z]+)') .unstack() .values.tolist()) ``` But I don't know how to get from here to my final output (step4).
2018/10/12
[ "https://Stackoverflow.com/questions/52773492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6365890/" ]
You may achieve what you need by replacing all non-letters first, then extracting pairs of letters and then applying some custom logic to extract the necessary value from the array: ``` >>> df['array_column'].str.replace('[^A-Z]+', '').str.findall('([A-Z]{2})').apply(lambda d: [''] if len(d) == 0 else d).apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0]) 0 HL 1 PG 2 PG 3 RC Name: array_column, dtype: object >>> ``` **Details** * `.replace('[^A-Z]+', '')` - remove all chars other the uppercase letters * `.str.findall('([A-Z]{2})')` - extract pairs of letters * `.apply(lambda d: [''] if len(d) == 0 else d)` will add an empty item if there is no regex match in the previous step * `.apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0])` - custom logic: if the list length is 1 and it is equal to `HL`, keep it, else remove all `HL` and get the first element
You can do something like this (or probably something more elegant), what you had already gets you to a fairly nice structure where you can use groupby to complete your solution ``` def extract_relevant_str(grp): ret_val = None if "HL" in grp[0].tolist() and len(grp) == 1: ret_val = "HL" elif len(grp) >= 1: ret_val = grp.loc[grp[0] != "HL", 0].iloc[0] return ret_val items = df.column1.str.extractall('([A-Z]+)') items.reset_index().groupby("level_0").apply(extract_relevant_str) ``` Output: ``` level_0 0 HL 1 PG 2 PG 3 RC dtype: object ```
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
**Here's how I finally managed to resolve this issue in 5 steps, I hope it helps:** 1. Click `"Toggle device toolbar"` to bring the toolbar up ![image of toggle device toolbar icon](https://i.stack.imgur.com/ggVMe.png) 2. Click the 3 dots on the right hand side of the device toolbar ![image of location of 3 dots](https://i.stack.imgur.com/7Bym1.png) 3. Click the option `"Add device type"`. 4. This will add a new dropdown to the device toolbar. From there you can select `"Desktop (touch)"` ![image of new device type dropdown](https://i.stack.imgur.com/1eCpn.png) 5. Problem solved.
under zoom menu in responsive window > auto adjust zoom must get disabled
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
I have had this issue a few times now. I'm unsure what causes it, but i've found that you can fix it by selecting `"Restore to defaults"` in the `Toggle device toolbar` menu. [![Screenshot here](https://i.stack.imgur.com/WSPye.png)](https://i.stack.imgur.com/WSPye.png)
As of now you can go to device toolbar then click **Responsive** here: [![enter image description here](https://i.stack.imgur.com/O7grU.png)](https://i.stack.imgur.com/O7grU.png) Then in the **Responsive** dropdown go to **Edit ...** and add the resolution you want. [![enter image description here](https://i.stack.imgur.com/vMwcA.png)](https://i.stack.imgur.com/vMwcA.png) Then you can select your custom one from the options and zoom and it will stay the same resolution!
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
To disable scaling and zooming you must add this inside the `<head>` tag: ```html <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> ``` The minimal `<meta>` tag (which doesn’t disable user-controlled scaling) is: ```html <meta name="viewport" content="initial-scale=1" /> ``` It’s not a Chrome problem.
Chrome is definitely doing something 'heuristically' and I'm pretty sure there are some bugs. When using the 'responsive mode' (so I can drag the width back and forth) below around 320px the whole page starts scaling down. This makes sense as a default since there are basically no devices below that width and most content looks awful if it's allowed to fend for itself at such small sizes. My original viewport settings were: ``` <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"> ``` The problem with that was there's nothing in the Chrome UI to constrain the minimum width to 320px (nobody needs to be designing for below that) and if you're dragging back and forth quickly then you'll inevitably end up with a width of say 169px. See the screenshot below to see how much of a mess I got in. The height of my menu bar is 50px so it's clear that it *is* being scaled down. Unfortunately the rendering engine just seems to get confused and my buttons end up overflowing and making a huge mess. Even if I resize to greater than 320px it still stays confused and I have to refresh the page. [![enter image description here](https://i.stack.imgur.com/BksBX.png)](https://i.stack.imgur.com/BksBX.png) The important part of the accepted answer is the `minimum-scale=1.0` which prevents this scaling at low screen widths. That's the key part to add to fix the issue and I can't see any reason to not have that.
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
I asked this question a long time ago, and today I noticed a change in Chrome. I am not sure when this was introduced, since I haven't used the responsive options as much, but on Version 73.0.3683.86 (Official Build) (64-bit) there's now an option called "Auto-adjust zoom", and it was checked (enabled) by default. I unchecked it, and now the zoom will no longer change when the screen is resized. You can access this option by clicking on "100%" next to the screen size, in the responsive screen. See image below: [![enter image description here](https://i.stack.imgur.com/NVDKt.png)](https://i.stack.imgur.com/NVDKt.png)
under zoom menu in responsive window > auto adjust zoom must get disabled
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
I've reported this bug to Chromium. Here's the link: <https://bugs.chromium.org/p/chromium/issues/detail?id=1129880#c2> I've found the reason why this happens as well as a "mitigation": set the height to empty string: ""
under zoom menu in responsive window > auto adjust zoom must get disabled
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
As of now you can go to device toolbar then click **Responsive** here: [![enter image description here](https://i.stack.imgur.com/O7grU.png)](https://i.stack.imgur.com/O7grU.png) Then in the **Responsive** dropdown go to **Edit ...** and add the resolution you want. [![enter image description here](https://i.stack.imgur.com/vMwcA.png)](https://i.stack.imgur.com/vMwcA.png) Then you can select your custom one from the options and zoom and it will stay the same resolution!
1. Click F12 2. In the right, top corner, near to chrome cross sign click on "Customize and control DevTools" kebab menu. 3. Click settings 4. Click Preferences 5. At the bottom, Click Restore defaults and reload 6. Make sure that you extensions will be removed.
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
**Here's how I finally managed to resolve this issue in 5 steps, I hope it helps:** 1. Click `"Toggle device toolbar"` to bring the toolbar up ![image of toggle device toolbar icon](https://i.stack.imgur.com/ggVMe.png) 2. Click the 3 dots on the right hand side of the device toolbar ![image of location of 3 dots](https://i.stack.imgur.com/7Bym1.png) 3. Click the option `"Add device type"`. 4. This will add a new dropdown to the device toolbar. From there you can select `"Desktop (touch)"` ![image of new device type dropdown](https://i.stack.imgur.com/1eCpn.png) 5. Problem solved.
Change Dock side to **Undock into separate window** as shown in the picture below: ![enter image description here](https://i.stack.imgur.com/YIIUg.png)
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
Chrome is definitely doing something 'heuristically' and I'm pretty sure there are some bugs. When using the 'responsive mode' (so I can drag the width back and forth) below around 320px the whole page starts scaling down. This makes sense as a default since there are basically no devices below that width and most content looks awful if it's allowed to fend for itself at such small sizes. My original viewport settings were: ``` <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"> ``` The problem with that was there's nothing in the Chrome UI to constrain the minimum width to 320px (nobody needs to be designing for below that) and if you're dragging back and forth quickly then you'll inevitably end up with a width of say 169px. See the screenshot below to see how much of a mess I got in. The height of my menu bar is 50px so it's clear that it *is* being scaled down. Unfortunately the rendering engine just seems to get confused and my buttons end up overflowing and making a huge mess. Even if I resize to greater than 320px it still stays confused and I have to refresh the page. [![enter image description here](https://i.stack.imgur.com/BksBX.png)](https://i.stack.imgur.com/BksBX.png) The important part of the accepted answer is the `minimum-scale=1.0` which prevents this scaling at low screen widths. That's the key part to add to fix the issue and I can't see any reason to not have that.
Here is what worked for me: 1. F12 (open developer tools) 2. Ctrl + Shift + M (toggle device toolbar) 3. Click the top right three dot menu 4. Click Add Device Type 5. On the top bar, A "Mobile" or "Desktop" dropdown list should appear 6. Chances are "Mobile" is selected, switch it to "Desktop" The auto-zoom should now go away, when you are in responsive mode and shrink the width of the viewport/device...
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
I've reported this bug to Chromium. Here's the link: <https://bugs.chromium.org/p/chromium/issues/detail?id=1129880#c2> I've found the reason why this happens as well as a "mitigation": set the height to empty string: ""
As of now you can go to device toolbar then click **Responsive** here: [![enter image description here](https://i.stack.imgur.com/O7grU.png)](https://i.stack.imgur.com/O7grU.png) Then in the **Responsive** dropdown go to **Edit ...** and add the resolution you want. [![enter image description here](https://i.stack.imgur.com/vMwcA.png)](https://i.stack.imgur.com/vMwcA.png) Then you can select your custom one from the options and zoom and it will stay the same resolution!
40,810,736
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region. I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting: ``` Error: Soundfile doesn't exist. Pleae check path Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help → Troubleshooting. ``` Firstly, is it possible to load 5 different sound files as conditions of `if` statements? Code here: ``` PImage img; // Declare variable "a" of type PImage import processing.sound.*; SoundFile file; void setup() { size(1475, 995); // The image file must be in the data folder of the current sketch // to load successfully img = loadImage("PaceTaker.jpg"); // Load the image into the program } void draw() { // Displays the image at its actual size at point (0,0) image(img, 0, 0); } void mousePressed() { if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) { // Load a soundfile from the /data folder of the sketch and play it back file = new SoundFile(this, "Heartbeatreg.mp3"); file.play(); stroke(0); } else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) { println("yikes2"); stroke(0); } else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) { println("yikes3"); stroke(0); } else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) { println("yikes4"); stroke(0); } else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) { println("yikes5"); stroke(0); } else { println("hello"); } } ```
2016/11/25
[ "https://Stackoverflow.com/questions/40810736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7186847/" ]
**Here's how I finally managed to resolve this issue in 5 steps, I hope it helps:** 1. Click `"Toggle device toolbar"` to bring the toolbar up ![image of toggle device toolbar icon](https://i.stack.imgur.com/ggVMe.png) 2. Click the 3 dots on the right hand side of the device toolbar ![image of location of 3 dots](https://i.stack.imgur.com/7Bym1.png) 3. Click the option `"Add device type"`. 4. This will add a new dropdown to the device toolbar. From there you can select `"Desktop (touch)"` ![image of new device type dropdown](https://i.stack.imgur.com/1eCpn.png) 5. Problem solved.
1. Click F12 2. In the right, top corner, near to chrome cross sign click on "Customize and control DevTools" kebab menu. 3. Click settings 4. Click Preferences 5. At the bottom, Click Restore defaults and reload 6. Make sure that you extensions will be removed.
10,875,055
Do I put it in each model, right before, `multisearchable :against => [ ... ]` or should this be in a separate file? Thanks.
2012/06/04
[ "https://Stackoverflow.com/questions/10875055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156125/" ]
I had similar questions about how to implement PgSearch.multisearch\_options. This is what worked for me. Hopefully it will help someone else out. I created the Initializer `config/initializers/pg_search.rb` ``` PgSearch.multisearch_options = { :using => { :tsearch => { :dictionary => "english" } } } ``` In my `application.rb` file I uncommented this line: `config.active_record.schema_format = :sql` Then created a migration called `rails g migration add_trigram_extension` adding the below to the migration file ``` def up execute "create extension pg_trgm" end def down execute "drop extension pg_trgm" end ``` Then run `bundle exec rake db:migrate` Restart the server Now full text search with Stemming is working. p.s. this worked using (PostgreSQL) 9.1.4
Okay found the answer, so I'll post it below. I created a file called `config/initializers/pg_search.rb` which looks like: ``` PgSearch.multisearch_options = { :using => { :tsearch => { :prefix => true }, :trigram => {}, :dmetaphone => {} }, :ignoring => :accents } ``` I don't fully understand why `:trigram => {}` works rather than just `:trigram`, but I guess that should be in another post.
71,616,876
I am trying to do this that strips "['" or "']" in the string. For Example, if we have ['Customer Name'] it should be "Customer Name" ``` select regexp_replace("['Customers NY']","\\['|\\']","") as customername; ``` > > I am getting this error-- > SQL compilation error: error line 1 at position 22 invalid identifier "['Customers NY']" > > >
2022/03/25
[ "https://Stackoverflow.com/questions/71616876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18408875/" ]
I managed to make it using *positions*. I assume this would give a better understanding on how to make these kind of shapes. ```css #cont { background: -webkit-linear-gradient(green -50%, #fff); width: 300px; height: 300px; border-radius: 100%; padding: 10px; position: relative; top: 0; left: 0; } #box { background: #fff; width: 320px; height: 320px; border-radius: 100%; position: absolute; top: 2%; left: 0.1%; } ``` ```html <div id="cont"> <div id="box"></div> <div id="box2"></div> </div> ```
You can use `:after` as below. ```css /*#cont{ background: -webkit-linear-gradient(green, #fff); width: 300px; height: 300px; border-radius: 1000px; padding: 10px; }*/ #box{ background: black; width: 300px; height: 300px; border-radius: 1000px; position: relative; } #box:after{ content: ''; display: block; width: 100%; height: 100%; background: white; border-radius: 1000px; display: block; top: 5px; position: absolute; } ``` ```html <div id="cont"> <div id="box"></div> </div> ```
19,786,196
First of all, sorry for bad english. Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code: ``` <body> <p>Parragraph one</p> <p>Parragraph two</p> <button onclick="CE()">change style</button> </body> for (var j=0;j<document.styleSheets[0].cssRules.length;j++) { if(document.styleSheets[0].cssRules[j].selectorText='p') document.styleSheets[0].cssRules[j].style.color="#FF0000"; } ``` And this is my CSS code: ``` p{ color: green; font-size: 20px; font-weight: bold; font-family: arial; } ``` I tried to change it with this too: `document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"`; (trying to change the background color, just to see if it works, but only works on Mozilla Firefox)
2013/11/05
[ "https://Stackoverflow.com/questions/19786196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382353/" ]
Try this ``` $(window).resize(function() { var bodyheight = $(document).height(); var divHeight = (bodyheight-10)/2; $('.grow').css("height", divHeight+"px");; }); ```
Try this ``` var width = (+$(window).width()); var divHeight = (width-10)/2; $(".grow").height(divHeight); ```
19,786,196
First of all, sorry for bad english. Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code: ``` <body> <p>Parragraph one</p> <p>Parragraph two</p> <button onclick="CE()">change style</button> </body> for (var j=0;j<document.styleSheets[0].cssRules.length;j++) { if(document.styleSheets[0].cssRules[j].selectorText='p') document.styleSheets[0].cssRules[j].style.color="#FF0000"; } ``` And this is my CSS code: ``` p{ color: green; font-size: 20px; font-weight: bold; font-family: arial; } ``` I tried to change it with this too: `document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"`; (trying to change the background color, just to see if it works, but only works on Mozilla Firefox)
2013/11/05
[ "https://Stackoverflow.com/questions/19786196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382353/" ]
here you go [http://jsfiddle.net/6KfHy/1/] ``` var baseWidth = 90; var stepWidth = 4; var baseHeight = 20; var growHeightPerStep = 1; function changeHeight() { var windowW = $(window).width(); var diffWidth = windowW - baseWidth; var diffHeight = parseInt(diffWidth / 4, 10); $('.grow').css('height', baseHeight + diffHeight + 'px'); } changeHeight(); $(window).resize(function() { changeHeight(); }); ```
Try this ``` var width = (+$(window).width()); var divHeight = (width-10)/2; $(".grow").height(divHeight); ```
19,786,196
First of all, sorry for bad english. Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code: ``` <body> <p>Parragraph one</p> <p>Parragraph two</p> <button onclick="CE()">change style</button> </body> for (var j=0;j<document.styleSheets[0].cssRules.length;j++) { if(document.styleSheets[0].cssRules[j].selectorText='p') document.styleSheets[0].cssRules[j].style.color="#FF0000"; } ``` And this is my CSS code: ``` p{ color: green; font-size: 20px; font-weight: bold; font-family: arial; } ``` I tried to change it with this too: `document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"`; (trying to change the background color, just to see if it works, but only works on Mozilla Firefox)
2013/11/05
[ "https://Stackoverflow.com/questions/19786196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382353/" ]
Try this ``` $(window).resize(function() { var bodyheight = $(document).height(); var divHeight = (bodyheight-10)/2; $('.grow').css("height", divHeight+"px");; }); ```
``` var $grow = $('.grow'), $window = $(window); $(window) .resize(function () { var windowWidth = $window.width(); if (windowWidth > 90) { $grow.height(~~ (windowWidth / 4)); } }) .resize(); ``` Trigger it the first time on dom ready. <http://jsfiddle.net/techunter/Xug5A/> remark careful with `.grow` margins and paddings :)
19,786,196
First of all, sorry for bad english. Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code: ``` <body> <p>Parragraph one</p> <p>Parragraph two</p> <button onclick="CE()">change style</button> </body> for (var j=0;j<document.styleSheets[0].cssRules.length;j++) { if(document.styleSheets[0].cssRules[j].selectorText='p') document.styleSheets[0].cssRules[j].style.color="#FF0000"; } ``` And this is my CSS code: ``` p{ color: green; font-size: 20px; font-weight: bold; font-family: arial; } ``` I tried to change it with this too: `document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"`; (trying to change the background color, just to see if it works, but only works on Mozilla Firefox)
2013/11/05
[ "https://Stackoverflow.com/questions/19786196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382353/" ]
here you go [http://jsfiddle.net/6KfHy/1/] ``` var baseWidth = 90; var stepWidth = 4; var baseHeight = 20; var growHeightPerStep = 1; function changeHeight() { var windowW = $(window).width(); var diffWidth = windowW - baseWidth; var diffHeight = parseInt(diffWidth / 4, 10); $('.grow').css('height', baseHeight + diffHeight + 'px'); } changeHeight(); $(window).resize(function() { changeHeight(); }); ```
Try this ``` $(window).resize(function() { var bodyheight = $(document).height(); var divHeight = (bodyheight-10)/2; $('.grow').css("height", divHeight+"px");; }); ```
19,786,196
First of all, sorry for bad english. Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code: ``` <body> <p>Parragraph one</p> <p>Parragraph two</p> <button onclick="CE()">change style</button> </body> for (var j=0;j<document.styleSheets[0].cssRules.length;j++) { if(document.styleSheets[0].cssRules[j].selectorText='p') document.styleSheets[0].cssRules[j].style.color="#FF0000"; } ``` And this is my CSS code: ``` p{ color: green; font-size: 20px; font-weight: bold; font-family: arial; } ``` I tried to change it with this too: `document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"`; (trying to change the background color, just to see if it works, but only works on Mozilla Firefox)
2013/11/05
[ "https://Stackoverflow.com/questions/19786196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382353/" ]
here you go [http://jsfiddle.net/6KfHy/1/] ``` var baseWidth = 90; var stepWidth = 4; var baseHeight = 20; var growHeightPerStep = 1; function changeHeight() { var windowW = $(window).width(); var diffWidth = windowW - baseWidth; var diffHeight = parseInt(diffWidth / 4, 10); $('.grow').css('height', baseHeight + diffHeight + 'px'); } changeHeight(); $(window).resize(function() { changeHeight(); }); ```
``` var $grow = $('.grow'), $window = $(window); $(window) .resize(function () { var windowWidth = $window.width(); if (windowWidth > 90) { $grow.height(~~ (windowWidth / 4)); } }) .resize(); ``` Trigger it the first time on dom ready. <http://jsfiddle.net/techunter/Xug5A/> remark careful with `.grow` margins and paddings :)
38,291
![enter image description here](https://i.stack.imgur.com/6EXpa.png) Why does the object not go inward, into the circle if the acceleration is inward? I think its because the velocity to outward? So they sort of cancel each other out? But if the speed is kept constant and the acceleration is inward, won't the object eventially move inward? Also, what keeps the direction of acceleration always point inward?
2012/09/25
[ "https://physics.stackexchange.com/questions/38291", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/12035/" ]
I suspect Luboš's answer may be a bit complex for you so I'll attempt a simpler explanation (if I'm wrong just ignore this answer). When you say "I think its because the velocity to outward" you're getting close. To show what's going on I've zoomed in on the diagram you posted in your question. ![Acceleration](https://i.stack.imgur.com/N6eQT.gif) Let's start at the moment where the velocity of the object is $u$. The thing you need to remember is that *velocity* is a vector so it has both magnitude and direction. Acceleration may be a change in the magnitude or a change in direction or both. In the case of circular motion it's the direction of the velocity that is changing not it's magnitude. To see this look at the vector $v$, which is the velocity of the particle after some short time. So the velocity has changed from $u$ to $v$. To get the size of the change we need to find what vector has to be added to $u$ to give $v$. At the top of the diagram I've put the two vectors $u$ and $v$ with their starting point together, so you can see that the vector needed to change $u$ to $v$ is the small vector $a$, and you can see it points downwards. If I move $a$ to the starting point of $u$ on the circle you can see that $a$ points towards the centre of the circle. The vector $a$ is of course the acceleration (well it's the acceleration times the short time interval between $u$ and $v$) and that's why the acceleration points towards the centre of the circle. If you didn't have any acceleration the object would move in a straight line so it would just move away at a tangent to the circle. The effect of the acceleration $a$ is to bend the trajectory of the object so it stays on the circle. Finally, you ask "what keeps the direction of acceleration always point inward". You've mixed up cause and effect. It isn't that there's some magical property of circular motion that causes the acceleration to be central. It's that if in some system the acceleration is always central the object will move in a circle (or strictly speaking in a conic section, but let's not complicate matters). For example suppose I tie a stone to a string and start whirling it round my head. The force causing the acceleration is provided by the string, and obviously the string always runs from the stone to the centre because my hand is at the centre. It's because the force caused by the string is always central that the stone moves in a circle.
No, a uniform circular motion has both constant speed and constant acceleration and it will continue indefinitely, never going inwards. If there were no inward acceleration, the object would move along the straight line in the direction of $\vec v$, and therefore away from the circle. To keep the object on the circle, there has to be a radial attractive force – the centripetal force – whose magnitude must be $F=ma=mv^2/r$. We may also describe the situation from the viewpoint of the frame rotating together with the object. In that frame, there is a centrifugal, outward force $mv^2/r$, which tries to "repel" the object from the origin. This centrifugal (fictitious) force must be compensated by a real, centripetal force if the object is supposed to stay at a fixed distance from the origin. Those statements may be easily derived from a particular coordinate parameterization of the motion. The coordinates are $$ x(t) = r\cdot \sin(\omega t), \quad y(t) = r\cdot \cos(\omega t)$$ The velocities are derivatives with respect to $t$ $$ v\_x(t) = r\omega \cdot \cos(\omega t), \quad v\_y(t) = -r\omega\cdot \sin(\omega t)$$ and the accelerations are derivatives of the velocities $$ a\_x(t) = -r\omega^2\cdot \sin(\omega t), \quad a\_y(t) = -r\omega^2\cdot \cos(\omega t)$$ and they are proportional to $(x,y)$ themselves, so the force is inward and radial. Note that $r\omega=v$ so $r\omega^2=v^2/r$.
38,291
![enter image description here](https://i.stack.imgur.com/6EXpa.png) Why does the object not go inward, into the circle if the acceleration is inward? I think its because the velocity to outward? So they sort of cancel each other out? But if the speed is kept constant and the acceleration is inward, won't the object eventially move inward? Also, what keeps the direction of acceleration always point inward?
2012/09/25
[ "https://physics.stackexchange.com/questions/38291", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/12035/" ]
No, a uniform circular motion has both constant speed and constant acceleration and it will continue indefinitely, never going inwards. If there were no inward acceleration, the object would move along the straight line in the direction of $\vec v$, and therefore away from the circle. To keep the object on the circle, there has to be a radial attractive force – the centripetal force – whose magnitude must be $F=ma=mv^2/r$. We may also describe the situation from the viewpoint of the frame rotating together with the object. In that frame, there is a centrifugal, outward force $mv^2/r$, which tries to "repel" the object from the origin. This centrifugal (fictitious) force must be compensated by a real, centripetal force if the object is supposed to stay at a fixed distance from the origin. Those statements may be easily derived from a particular coordinate parameterization of the motion. The coordinates are $$ x(t) = r\cdot \sin(\omega t), \quad y(t) = r\cdot \cos(\omega t)$$ The velocities are derivatives with respect to $t$ $$ v\_x(t) = r\omega \cdot \cos(\omega t), \quad v\_y(t) = -r\omega\cdot \sin(\omega t)$$ and the accelerations are derivatives of the velocities $$ a\_x(t) = -r\omega^2\cdot \sin(\omega t), \quad a\_y(t) = -r\omega^2\cdot \cos(\omega t)$$ and they are proportional to $(x,y)$ themselves, so the force is inward and radial. Note that $r\omega=v$ so $r\omega^2=v^2/r$.
> > Why does the object not go inward, into the circle if the acceleration is inward? I think its because the velocity to outward? So they sort of cancel each other out? > > > No, the velocity on the object is not outwards, which you can see if you recall that the velocity of an object is $\vec {v} = \frac d {dt} \vec r$. Over a time $dt$, the change in the position vector $d\vec r$ points in the same direction as the tangent to the trajectory of the moving object. Dividing this by the scalar $dt$ gives the velocity vector with the direction still along the tangent. > > But if the speed is kept constant and the acceleration is inward, won't the object eventially move inward? > > > Over a time $dt$ the displacement from the velocity is $Vdt$, that from the acceleration is $\frac 1 2 a {dt}^2$. The displacement is therefore dominated by the velocity because ${dt}^2$ becomes far smaller than ${dt}$ as $dt\rightarrow 0$ > > Also, what keeps the direction of acceleration always point inward? > > > The force causing the acceleration.
38,291
![enter image description here](https://i.stack.imgur.com/6EXpa.png) Why does the object not go inward, into the circle if the acceleration is inward? I think its because the velocity to outward? So they sort of cancel each other out? But if the speed is kept constant and the acceleration is inward, won't the object eventially move inward? Also, what keeps the direction of acceleration always point inward?
2012/09/25
[ "https://physics.stackexchange.com/questions/38291", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/12035/" ]
I suspect Luboš's answer may be a bit complex for you so I'll attempt a simpler explanation (if I'm wrong just ignore this answer). When you say "I think its because the velocity to outward" you're getting close. To show what's going on I've zoomed in on the diagram you posted in your question. ![Acceleration](https://i.stack.imgur.com/N6eQT.gif) Let's start at the moment where the velocity of the object is $u$. The thing you need to remember is that *velocity* is a vector so it has both magnitude and direction. Acceleration may be a change in the magnitude or a change in direction or both. In the case of circular motion it's the direction of the velocity that is changing not it's magnitude. To see this look at the vector $v$, which is the velocity of the particle after some short time. So the velocity has changed from $u$ to $v$. To get the size of the change we need to find what vector has to be added to $u$ to give $v$. At the top of the diagram I've put the two vectors $u$ and $v$ with their starting point together, so you can see that the vector needed to change $u$ to $v$ is the small vector $a$, and you can see it points downwards. If I move $a$ to the starting point of $u$ on the circle you can see that $a$ points towards the centre of the circle. The vector $a$ is of course the acceleration (well it's the acceleration times the short time interval between $u$ and $v$) and that's why the acceleration points towards the centre of the circle. If you didn't have any acceleration the object would move in a straight line so it would just move away at a tangent to the circle. The effect of the acceleration $a$ is to bend the trajectory of the object so it stays on the circle. Finally, you ask "what keeps the direction of acceleration always point inward". You've mixed up cause and effect. It isn't that there's some magical property of circular motion that causes the acceleration to be central. It's that if in some system the acceleration is always central the object will move in a circle (or strictly speaking in a conic section, but let's not complicate matters). For example suppose I tie a stone to a string and start whirling it round my head. The force causing the acceleration is provided by the string, and obviously the string always runs from the stone to the centre because my hand is at the centre. It's because the force caused by the string is always central that the stone moves in a circle.
> > Why does the object not go inward, into the circle if the acceleration is inward? I think its because the velocity to outward? So they sort of cancel each other out? > > > No, the velocity on the object is not outwards, which you can see if you recall that the velocity of an object is $\vec {v} = \frac d {dt} \vec r$. Over a time $dt$, the change in the position vector $d\vec r$ points in the same direction as the tangent to the trajectory of the moving object. Dividing this by the scalar $dt$ gives the velocity vector with the direction still along the tangent. > > But if the speed is kept constant and the acceleration is inward, won't the object eventially move inward? > > > Over a time $dt$ the displacement from the velocity is $Vdt$, that from the acceleration is $\frac 1 2 a {dt}^2$. The displacement is therefore dominated by the velocity because ${dt}^2$ becomes far smaller than ${dt}$ as $dt\rightarrow 0$ > > Also, what keeps the direction of acceleration always point inward? > > > The force causing the acceleration.
10,943
I'm doing a total kitchen renovation with solid hardwood flooring. Do I go hardwood all the way under the cabinets to the wall or stop just past the toe kick and finish the rest with ply of the same thickness?
2011/12/27
[ "https://diy.stackexchange.com/questions/10943", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/4711/" ]
You can do either, but in my opinion it's better to use plywood as the base because: * it's a lot cheaper than hardwood flooring. * if you need to replace the hardwood flooring at some point in the future, it will be a lot easier to remove just the hardwoods: if you run planks under the cabinets, you'll have to cut them off where they go under the toe kick which will be a lot trickier with the cabinets in place.
I ran mine all the way to the wall. Turned out to be a good thing because I made a cabinet change which pushed everything down six inches.
10,943
I'm doing a total kitchen renovation with solid hardwood flooring. Do I go hardwood all the way under the cabinets to the wall or stop just past the toe kick and finish the rest with ply of the same thickness?
2011/12/27
[ "https://diy.stackexchange.com/questions/10943", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/4711/" ]
In your situation, using real 3/4" hardwood flooring should be a lifetime floor. I cannot see any reason to remove it as any other type of flooring in the future could be installed right over it. Since it is much more likely to have some type of cabinet upgrade rather than actually needing to remove the hardwood, I would install the hardwood wall to wall and install cabinets over it. The actual extra amount of hardwood used under the cabinet area is minimal, and will make installation easier and faster than working around the cabinet footprint.
I ran mine all the way to the wall. Turned out to be a good thing because I made a cabinet change which pushed everything down six inches.
29,145,564
I have created two classes, StepsCell and WeightCell ``` import UIKit class StepsCell { let name = "Steps" let count = 2000 } import UIKit class WeightCell { let name = "Weight" let kiloWeight = 90 } ``` In my VC I attempt to create an array, cellArray, to hold the objects. ``` import UIKit class TableViewController: UIViewController { var stepsCell = StepsCell() var weightCell = WeightCell() override func viewDidLoad() { super.viewDidLoad() var cellArray = [stepsCell, weightCell] println(StepsCell().name) println(stepsCell.name) println(cellArray[0].name) } ``` but when I index into the array : ``` println(cellArray[0].name) ``` I get nil.. Why? How can I create an array that "holds" these classes and that I can index into to get the various variables (and functions to be added later). I thought this would be a super simple thing but I can't find any answers for this. Any ideas?
2015/03/19
[ "https://Stackoverflow.com/questions/29145564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4051036/" ]
The problem is that you create an array with mixed types. Because of this, the compiler doesn't know the type of the object returned by `cellArray[0]`. It infers that this object must be of type `AnyObject`. Apparently this has a property named `name`, which returns nil. The solution is to either cast it `println((cellArray[0] as StepsCell).name)`, or use a common protocol or superclass: ``` protocol Nameable { var name: String { get } } class StepsCell: Nameable { let name = "Steps" let count = 2000 } class WeightCell: Nameable { let name = "Weight" let kiloWeight = 90 } var stepsCell = StepsCell() var weightCell = WeightCell() var cellArray: [Nameable] = [stepsCell, weightCell] println(StepsCell().name) println(stepsCell.name) println(cellArray[0].name) ```
As @Rengers said in his answer you may use the approach, To drill down to your code you can solve it like this, ``` class StepsCell { let name = "Steps" let cellCount = 2000 } class WeightCell { let name = "Weight" let weightCount = 90 } var stepcell = StepsCell() // creating the object var weightcell = WeightCell() // Your array where you store both the object var myArray = [stepcell,weightcell]; // creating a temp object for StepsCell let tempStepCell = myArray[0] as StepsCell println(tempStepCell.name) ``` Your array is holding the instance of the classes which you created so you may use a temp variable to extract those values OR to make it more simpler you may also do something like this ``` ((myArray[0]) as StepsCell ).name ``` Since you have two classes and at run time we just love to keep things dynamic you can add a conditional operator which would identify the type of object you want to work with ``` if let objectIdentification = myArray[0] as? StepsCell { println("Do operations with steps cell object here") }else{ println("Do operation with weight cell object here") } ```
21,517,685
I'm making an application to scan multiple page pdf files. I have a `PDFView` and a `PDFThumbnailView` that are linked. The first time a scan is completed, I create a new `PDFDocument` and set it to `PDFView`. Then whenever another scan is completed I add a `PDFPage` to `[pdfView document]`. Now the problem is whenever a page is added, neither the `PDFView` or `PDFThumbnailView` update to show the new document with the extra page. That is until I zoom in or out, then they both update to show the document with the new page. The temporary solution I have now (zoom in and then autoscale) is certainly not the best one. Take for example when you have already zoomed in on the document, and you scan a new page, the view will then autoscale. I tried `[pdfView setNeedsDisplay:YES]` before but that doesn't seem to work. This is the method where the scan arrives as `NSData`: ``` - (void)scannerDevice:(ICScannerDevice *)scanner didScanToURL:(NSURL *)url data:(NSData *)data { //Hide the progress bar [progressIndicator stopAnimation:nil]; //Create a pdf page from the data NSImage *image = [[NSImage alloc] initWithData:data]; PDFPage *page = [[PDFPage alloc] initWithImage:image]; //If the pdf view has a document if ([pdfView document]) { //Set the page number and add it to the document [page setValue:[NSString stringWithFormat:@"%d", [[pdfView document] pageCount] + 1] forKey:@"label"]; [[pdfView document] insertPage:page atIndex:[[pdfView document] pageCount]]; } else { //Create a new document and add the page [page setValue:@"1" forKey:@"label"]; PDFDocument *document = [[PDFDocument alloc] init]; [document insertPage:page atIndex:0]; [pdfView setDocument:document]; } //Force a redraw for the pdf view so the pages are shown properly [pdfView zoomIn:self]; [pdfView setAutoScales:YES]; } ``` Does anyone know of a way where I can add a `PDFPage` and have the `PDFView` update without messing with the zoom state of the `PDFView`?
2014/02/02
[ "https://Stackoverflow.com/questions/21517685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1640293/" ]
You need to manually call: ``` - (void)layoutDocumentView ``` I imagine the reason that this is not called manually is to allow coalescing of multiple changes into one update. This is documented: > > The PDFView actually contains several subviews, such as the document > view (where the PDF is actually drawn) and a “matte view” (which may > appear as a gray area around the PDF content, depending on the > scaling). Changes to the PDF content may require changes to these > inner views, so you must call this method explicitly if you use PDF > Kit utility classes to add or remove a page, rotate a page, or perform > other operations affecting visible layout. > > > This method is called automatically from PDFView methods that affect > the visible layout (such as setDocument:, setDisplayBox: or zoomIn:). > > >
The best solution I got so far to refresh manually the PDFView with annotation was to move the PDFView to another page and come back to the page you need to refresh because: `- (void)layoutDocumentView` didn't work for me in my case. Then: ``` [self.pdfView goToLastPage:nil]; [self.pdfView goToPage:destinationPage]; ```
46,435,623
Hi the custom policy gets called with the client id of the B2C app <https://login.microsoftonline.com/TENANT/oauth2/v2.0/authorize?p=B2C_1A_POLICY&client_id=THE-CLIENT-ID-I-WANT> How can I access this in the policy, i thought this would be hard coded to the client\_id claim but I dont think it is Its only returned as default as the aud claim but again I dont see that in the custom policy Thanks
2017/09/26
[ "https://Stackoverflow.com/questions/46435623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1197563/" ]
Ok its a bit of a work around but I tried with a standard UserJourneyContextProvider technical profile and this didnt work so to get the client id as a claim I did the following Create an orchestration step ``` <OrchestrationStep Order="2" Type="ClaimsExchange"> <ClaimsExchanges> <ClaimsExchange Id="ClientIdFromOIDC-JC" TechnicalProfileReferenceId="Get-ClientID-FromOIDC"/> </ClaimsExchanges> </OrchestrationStep> ``` Then create a RESTFUL technical profile which will call a Function App passing the OIDC with the {OIDC:ClientID} ``` <TechnicalProfile Id="Get-ClientID-FromOIDC"> <DisplayName>Get-ClientID-FromOIDC</DisplayName> <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> <Metadata> <Item Key="AuthenticationType">None</Item> <Item Key="ServiceUrl">--FUNCTION APP URL--</Item> <Item Key="SendClaimsIn">QueryString</Item> </Metadata> <InputClaims> <InputClaim ClaimTypeReferenceId="client_id" PartnerClaimType="client_id" DefaultValue="{OIDC:ClientId}" /> </InputClaims> <OutputClaims> <OutputClaim ClaimTypeReferenceId="client_id" /> </OutputClaims> </TechnicalProfile> ``` And then finally create a function app which accepts the client id from the querystring and returns it with the correct format for B2C to identify using System.Net; using System.Net.Http.Formatting; ``` public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // parse query parameter string client_id = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "client_id", true) == 0) .Value; return req.CreateResponse<ResponseContent>( HttpStatusCode.OK, new ResponseContent { version = "1.0.0", status = (int) HttpStatusCode.OK, client_id = client_id }, new JsonMediaTypeFormatter(), "application/json"); } class ResponseContent { public string version; public int status; public string client_id; } ``` You will now get the B2C application client\_id as a claim in the claim bag so you can do what you want with it now
**You need to add the following into the metadata tag of technical profile:** `<Item Key="IncludeClaimResolvingInClaimsHandling">true</Item>` For more on this. See here: [OAUTH-KV Claims Resolver in AAD B2C does not work](https://stackoverflow.com/questions/53008134/oauth-kv-claims-resolver-in-aad-b2c-does-not-work) **Then use:** `<OutputClaim ClaimTypeReferenceId="ClientId" DefaultValue="{OIDC:ClientId}" AlwaysUseDefaultValue="true"/>` See here: <https://learn.microsoft.com/en-us/azure/active-directory-b2c/claim-resolver-overview>
71,096,453
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats. I've tried to use the `append` method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my `output` as the result? This is my code: ``` def func(L): n = [] lists = [i.split(',') for i in L] for xlist in lists: xlist[1:] = [float(item) for item in xlist[1:]] n.append(xlist) print(n) if __name__ == '__main__': func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38']) OUTPUT: [['PersonX', 10.0, 92.0, 70.0]] [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]] [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]] EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]] ``` Thanks in advance for any help.
2022/02/12
[ "https://Stackoverflow.com/questions/71096453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can combine your two approaches: ``` df %>% split(~test_nr) %>% map_dfr(~ .x %>% add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))) ```
You could achieve your target with this Base R one-liner: ``` merge( df, aggregate( df, by = list( df$test_nr ), FUN = mean ), all = TRUE )[ , 1:4 ] ``` `aggregate` provides you with the lines you need, and `merge` inserts them into the right places of your dataframe. You don't need the last column of the combined dataframe, so use only the first four columns. The code produces some warnings for the `region` column which can be disregarded. In the region column, the function (`MEAN`) is not displayed. Making it a little more generic: ``` f <- "mean" df1 <- merge( df, aggregate( df, by = list( df$test_id, df$test_nr ), FUN = f ), all = TRUE )[ , 1:4 ] df1$region[ is.na( df1$region ) ] <- toupper( f ) ``` Here, you aggregate also by `test_id`, you can change the function you are using in one place, and you have it printed in the `region` column: ``` > df1 test_id test_nr region test_value 1 1 1 A 3.00 2 1 1 B 1.00 3 1 1 C 1.00 4 1 1 D 2.00 5 1 1 MEAN 1.75 6 1 2 A 4.00 7 1 2 B 2.00 8 1 2 C 4.00 9 1 2 D 1.00 10 1 2 MEAN 2.75 ```
71,096,453
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats. I've tried to use the `append` method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my `output` as the result? This is my code: ``` def func(L): n = [] lists = [i.split(',') for i in L] for xlist in lists: xlist[1:] = [float(item) for item in xlist[1:]] n.append(xlist) print(n) if __name__ == '__main__': func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38']) OUTPUT: [['PersonX', 10.0, 92.0, 70.0]] [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]] [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]] EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]] ``` Thanks in advance for any help.
2022/02/12
[ "https://Stackoverflow.com/questions/71096453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I actually recently made a little helper function for exactly this. The idea is to use `group_modify()` to take the group data, and `bind_rows()` the summary statistics calculated with `summarise()`. This is what it looks like in code: ```r add_summary_rows <- function(.data, ...) { group_modify(.data, function(x, y) bind_rows(x, summarise(x, ...))) } ``` And here’s how that would work with your data: ```r library(dplyr, warn.conflicts = FALSE) df <- data.frame( test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1, 1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B", "C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1) ) df %>% group_by(test_id, test_nr) %>% add_summary_rows( region = "MEAN", test_value = mean(test_value) ) #> # A tibble: 10 x 4 #> # Groups: test_id, test_nr [2] #> test_id test_nr region test_value #> <dbl> <dbl> <chr> <dbl> #> 1 1 1 A 3 #> 2 1 1 B 1 #> 3 1 1 C 1 #> 4 1 1 D 2 #> 5 1 1 MEAN 1.75 #> 6 1 2 A 4 #> 7 1 2 B 2 #> 8 1 2 C 4 #> 9 1 2 D 1 #> 10 1 2 MEAN 2.75 ```
You can combine your two approaches: ``` df %>% split(~test_nr) %>% map_dfr(~ .x %>% add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))) ```
71,096,453
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats. I've tried to use the `append` method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my `output` as the result? This is my code: ``` def func(L): n = [] lists = [i.split(',') for i in L] for xlist in lists: xlist[1:] = [float(item) for item in xlist[1:]] n.append(xlist) print(n) if __name__ == '__main__': func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38']) OUTPUT: [['PersonX', 10.0, 92.0, 70.0]] [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]] [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]] EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]] ``` Thanks in advance for any help.
2022/02/12
[ "https://Stackoverflow.com/questions/71096453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I actually recently made a little helper function for exactly this. The idea is to use `group_modify()` to take the group data, and `bind_rows()` the summary statistics calculated with `summarise()`. This is what it looks like in code: ```r add_summary_rows <- function(.data, ...) { group_modify(.data, function(x, y) bind_rows(x, summarise(x, ...))) } ``` And here’s how that would work with your data: ```r library(dplyr, warn.conflicts = FALSE) df <- data.frame( test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1, 1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B", "C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1) ) df %>% group_by(test_id, test_nr) %>% add_summary_rows( region = "MEAN", test_value = mean(test_value) ) #> # A tibble: 10 x 4 #> # Groups: test_id, test_nr [2] #> test_id test_nr region test_value #> <dbl> <dbl> <chr> <dbl> #> 1 1 1 A 3 #> 2 1 1 B 1 #> 3 1 1 C 1 #> 4 1 1 D 2 #> 5 1 1 MEAN 1.75 #> 6 1 2 A 4 #> 7 1 2 B 2 #> 8 1 2 C 4 #> 9 1 2 D 1 #> 10 1 2 MEAN 2.75 ```
You could achieve your target with this Base R one-liner: ``` merge( df, aggregate( df, by = list( df$test_nr ), FUN = mean ), all = TRUE )[ , 1:4 ] ``` `aggregate` provides you with the lines you need, and `merge` inserts them into the right places of your dataframe. You don't need the last column of the combined dataframe, so use only the first four columns. The code produces some warnings for the `region` column which can be disregarded. In the region column, the function (`MEAN`) is not displayed. Making it a little more generic: ``` f <- "mean" df1 <- merge( df, aggregate( df, by = list( df$test_id, df$test_nr ), FUN = f ), all = TRUE )[ , 1:4 ] df1$region[ is.na( df1$region ) ] <- toupper( f ) ``` Here, you aggregate also by `test_id`, you can change the function you are using in one place, and you have it printed in the `region` column: ``` > df1 test_id test_nr region test_value 1 1 1 A 3.00 2 1 1 B 1.00 3 1 1 C 1.00 4 1 1 D 2.00 5 1 1 MEAN 1.75 6 1 2 A 4.00 7 1 2 B 2.00 8 1 2 C 4.00 9 1 2 D 1.00 10 1 2 MEAN 2.75 ```
59,439,204
I've seen some usage of `self.destroy()` within classes but I couldn't get it working with what I wanted it to do. I have the class `resultsPage` that shows results obtained on another page. I have made the `displayResults(pageNo)` function to show these when `resultsPage` is visible. The problem arises with the back and next buttons which are made to go between pages of results. All widgets are created on top of each other but I want to remove them all then create the new ones. I added `self.destroy()` to try and fix this but it didn't work. I'm not sure if it's to do with the placement of where I'm defining my functions but I have had a play around with where they're defined and it hasn't changed the error message. This is a simplified example of my code: ``` class resultsPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) def onShowFrame(self, event): def displayResults(pageNo): self.destroy() #Create widgets related to pageNo #Create back and next buttons e.g. back = tk.Button(self, text="<=", command=lambda: displayResults(pageNo - 1)) displayResults(1) ``` The error I get is: `_tkinter.TclError: bad window path name ".!frame.!previewresultspage"` If it helps, I can post my full code but I thought I'd generalise it so it's more helpful to others.
2019/12/21
[ "https://Stackoverflow.com/questions/59439204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11204185/" ]
The problem comes from the line: ``` tempArray = finalValues[-1] ``` You don't create a copy of the previous list, but only a new name to refer to it. After that, all changes you make to `tempArray` are actually changes to this list, and when you finally do: ``` finalValues.append(tempArray) ``` you just add another reference to this same list in `finalValues`. In the end, `finalValues` contains 4 references to the same list, which you can access with `finalValues[0]`, `finalValues[1]`... What you need is to create a new list by copying the previous one. One way to do it is to use a slice: ``` tempArray = finalValues[-1][:] ``` You can find other ways to close or copy a list in [this question](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) And so, the complete code gives the expected output: ``` Last array of final: [1, 2, 3, 4] Temp Array: [1, 2, 3, 4] Final Values: [[1, 2, 3, 4], [2, 3, 4, 1]] Last array of final: [2, 3, 4, 1] Temp Array: [2, 3, 4, 1] Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2]] Last array of final: [3, 4, 1, 2] Temp Array: [3, 4, 1, 2] Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] ```
Thierry has provided a very comprehensive explanation of why your code doesn't work as you expect. As such it is the best answer to your question.I have added my answer just as an example of you you can code this in a less complex way . create the 2d list with the first index as list of numbers. for each iteration take the last index of temp and slice from index 1 to the end then add on index 0. then return the list ```py def numbers(list_of_numbers): temp = [list_of_numbers] for _ in range(1, len(list_of_numbers)): temp.append(temp[-1][1:] + temp[-1][0:1]) return temp print(numbers([1,2,3,4])) ``` **OUTPUT** ``` [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] ```
59,439,204
I've seen some usage of `self.destroy()` within classes but I couldn't get it working with what I wanted it to do. I have the class `resultsPage` that shows results obtained on another page. I have made the `displayResults(pageNo)` function to show these when `resultsPage` is visible. The problem arises with the back and next buttons which are made to go between pages of results. All widgets are created on top of each other but I want to remove them all then create the new ones. I added `self.destroy()` to try and fix this but it didn't work. I'm not sure if it's to do with the placement of where I'm defining my functions but I have had a play around with where they're defined and it hasn't changed the error message. This is a simplified example of my code: ``` class resultsPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) def onShowFrame(self, event): def displayResults(pageNo): self.destroy() #Create widgets related to pageNo #Create back and next buttons e.g. back = tk.Button(self, text="<=", command=lambda: displayResults(pageNo - 1)) displayResults(1) ``` The error I get is: `_tkinter.TclError: bad window path name ".!frame.!previewresultspage"` If it helps, I can post my full code but I thought I'd generalise it so it's more helpful to others.
2019/12/21
[ "https://Stackoverflow.com/questions/59439204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11204185/" ]
The problem comes from the line: ``` tempArray = finalValues[-1] ``` You don't create a copy of the previous list, but only a new name to refer to it. After that, all changes you make to `tempArray` are actually changes to this list, and when you finally do: ``` finalValues.append(tempArray) ``` you just add another reference to this same list in `finalValues`. In the end, `finalValues` contains 4 references to the same list, which you can access with `finalValues[0]`, `finalValues[1]`... What you need is to create a new list by copying the previous one. One way to do it is to use a slice: ``` tempArray = finalValues[-1][:] ``` You can find other ways to close or copy a list in [this question](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) And so, the complete code gives the expected output: ``` Last array of final: [1, 2, 3, 4] Temp Array: [1, 2, 3, 4] Final Values: [[1, 2, 3, 4], [2, 3, 4, 1]] Last array of final: [2, 3, 4, 1] Temp Array: [2, 3, 4, 1] Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2]] Last array of final: [3, 4, 1, 2] Temp Array: [3, 4, 1, 2] Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] ```
The problems is in `shallow` assignment of arrays. You should make `deep` copy, to really clone arrays, to make them independent. I did it in your own code. There are a few changes of your code: 1. `import copy` that it have been added to first row. 2. Three usages of `copy.deepcopy` function instead of `=`(simple assignment). ```py import copy def numbers(list_of_numbers): finalValues = copy.deepcopy([list_of_numbers]) #print(list_of_numbers) for i in range(1,len(list_of_numbers)): print("Last array of final: ", finalValues[-1]) tempArray = copy.deepcopy(finalValues[-1]) print("Temp Array: ",tempArray) temp = tempArray[0] for j in range(0,len(list_of_numbers)-1): tempArray[j] = tempArray[j+1] tempArray[-1] = temp finalValues.append(copy.deepcopy(tempArray)) print("Final Values: ",finalValues) return finalValues numbers([1,2,3,4]) ``` > > Program Output > > > ``` [[4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3]] ``` > > Program Output > > > ``` [[1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]] ```
59,439,204
I've seen some usage of `self.destroy()` within classes but I couldn't get it working with what I wanted it to do. I have the class `resultsPage` that shows results obtained on another page. I have made the `displayResults(pageNo)` function to show these when `resultsPage` is visible. The problem arises with the back and next buttons which are made to go between pages of results. All widgets are created on top of each other but I want to remove them all then create the new ones. I added `self.destroy()` to try and fix this but it didn't work. I'm not sure if it's to do with the placement of where I'm defining my functions but I have had a play around with where they're defined and it hasn't changed the error message. This is a simplified example of my code: ``` class resultsPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) def onShowFrame(self, event): def displayResults(pageNo): self.destroy() #Create widgets related to pageNo #Create back and next buttons e.g. back = tk.Button(self, text="<=", command=lambda: displayResults(pageNo - 1)) displayResults(1) ``` The error I get is: `_tkinter.TclError: bad window path name ".!frame.!previewresultspage"` If it helps, I can post my full code but I thought I'd generalise it so it's more helpful to others.
2019/12/21
[ "https://Stackoverflow.com/questions/59439204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11204185/" ]
Thierry has provided a very comprehensive explanation of why your code doesn't work as you expect. As such it is the best answer to your question.I have added my answer just as an example of you you can code this in a less complex way . create the 2d list with the first index as list of numbers. for each iteration take the last index of temp and slice from index 1 to the end then add on index 0. then return the list ```py def numbers(list_of_numbers): temp = [list_of_numbers] for _ in range(1, len(list_of_numbers)): temp.append(temp[-1][1:] + temp[-1][0:1]) return temp print(numbers([1,2,3,4])) ``` **OUTPUT** ``` [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] ```
The problems is in `shallow` assignment of arrays. You should make `deep` copy, to really clone arrays, to make them independent. I did it in your own code. There are a few changes of your code: 1. `import copy` that it have been added to first row. 2. Three usages of `copy.deepcopy` function instead of `=`(simple assignment). ```py import copy def numbers(list_of_numbers): finalValues = copy.deepcopy([list_of_numbers]) #print(list_of_numbers) for i in range(1,len(list_of_numbers)): print("Last array of final: ", finalValues[-1]) tempArray = copy.deepcopy(finalValues[-1]) print("Temp Array: ",tempArray) temp = tempArray[0] for j in range(0,len(list_of_numbers)-1): tempArray[j] = tempArray[j+1] tempArray[-1] = temp finalValues.append(copy.deepcopy(tempArray)) print("Final Values: ",finalValues) return finalValues numbers([1,2,3,4]) ``` > > Program Output > > > ``` [[4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3]] ``` > > Program Output > > > ``` [[1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]] ```
20,572,423
I have a PNG file which is a one-pixel-wide, 283-pixel-tall gradient image, which I need to stretch across the background of an ImageView, stretching only horizontally. I attempted to set the asset as a background to an ImageView like this: ``` <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/gradient_tile" android:layout_gravity="bottom|center" android:scaleType="matrix"/> ``` but that just creates a one-pixel line in the middle of the parent view. Is there a way to do this, or do I need to request a wider image, and use a 9-patch? Thanks in advance. UPDATE: I ended up having to set minimum height properties in the XML as follows: ``` <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="119dp" android:background="@drawable/gradient_tile_drawable" android:id="@+id/tiledGradientBackground" android:layout_gravity="bottom|center" android:scaleType="matrix"/> ``` ...and then set minimumWidth to the width of the parent view in code. Not sure why this solved it, but it did... ``` int width = holder.container.getResolvedWidth(); holder.tiledGradientBackground.setMinimumWidth(width); ```
2013/12/13
[ "https://Stackoverflow.com/questions/20572423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239318/" ]
Because you're doing nothing with that function in the parameter. You can do this: ``` function mySecondFunction(func) { alert("Second Function"); func(); } ```
You are passing anonymous function `function () { alert("Third Function"); }` as a parameter to `mySecondFunction()`, but you're not calling this anonymous function anywhere inside `mySecondFunction()`. This would work: ``` function mySecondFunction(callback) { alert("Second Function"); callback(); } ```
3,963,664
**Problem:** Let $g\_t(x)=\frac{1}{\sqrt{2\pi}} e^{ \frac{- (x-t)^2}{2}}$ be the Gaussian function centered at $t\in \mathbb R$. Let $I$ be a subset of $\mathbb R$. Consider the "convolution operator" \begin{align} \mathcal A: L^1(I) & \longrightarrow L^2(I)\\ f & \longmapsto \left(x\longmapsto \int\_{I} g\_t(x)f(t) dt \right). \end{align} How can I prove (or disprove) that the operator is well-defined and injective? --- **My attempts:** Here are some of my attempts to prove the well-defined property. * I have tried to use Cauchy inequality but with no success: \begin{align} \int\_{I} \left( \int\_{I} g\_t(x)f(t)dt\right)^2 dx \leq \int\_{I} \int\_{I} g\_t^2(x)dx dt \int\_{I}f^2(t)dt. \end{align} as the right-hand-side may be infinite as $f$ does not belong to $L^2(I)$. * I have tried to use the boundedness of Gaussian function but nothing better. We have \begin{align} \int\_{I} \left( \int\_{I} g\_t(x)f(t)dt\right)^2 dx \leq M \left( \int\_{I} f(t)dt \right)^2 \int\_I dx. \end{align} and the right-hand-side may be infinite as $I$ is unbounded.
2020/12/27
[ "https://math.stackexchange.com/questions/3963664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/818617/" ]
I'm going to unclutter the situation and leave out some constants. If it works in the simplified case, you can throw constants at it later. Suppose $f\in L^1(\mathbb R)$ and $g(t) = e^{-t^2}.$ For $x\in \mathbb R,$ define $$(g\*f)(x) = \int\_{\mathbb R}g(x-t)f(t)\,dt.$$ That is certainly well defined for any $x,$ since $g\in L^\infty.$ To show $g\*f\in L^2,$ note $$|g\*f(x)|^2 \le (\int\_{\mathbb R}g(x-t)|f(t)|\,dt)^2$$ $$ = \|f\|\_1^2(\int\_{\mathbb R}(g(x-t)(|f(t)|/\|f\|\_1)\,dt)^2.$$ Use Jensen to see the last expression is bounded above by $$\|f\|\_1^2\int\_{\mathbb R}(g(x-t))^2(|f(t)|/\|f\|\_1)\,dt.$$ Thus, using Fubini, we have $$\int |g\*f(x)|^2\,dx \le \|f\|\_1^2 \int g(x)^2\,dx.$$ This proves $\|g\*f\|\_2 \le \|f\|\_1\|g\|\_2.$ Thus $f\to g\*f$ is a bounded linear operator from $L^1$ to $L^2.$ For injectivity, I'll use some Fourier analysis. Let $F$ denote the Fourier transform. Then $F$ is an isometry on $L^2,$ and is injective on $L^1.$ Thus $g\*f$ is the zero function iff $F(g\*f)$ is the zero function. Now $$F(g\*f)(x) =F(g)(x)\cdot F(f)(x).$$ And as is well known, $F(g)>0$ everywhere. (In fact for the Gaussian $g,$ $F(g)$ is essentially $g,$ meaning $F(g)(x)= ag(bx)$ for some nonzero constants $a,b.$) Thus $F(g\*f)=0$ iff $F(f)=0.$ And the later happens iff $f=0.$ It follow that $f\to g\*f$ is injective.
\begin{align\*} \left|\int\_I \left(\int\_I e^{-(x-t)^2}f(t)dt\right)^2dx\right| &= \left|\int\_I \int\_I \int\_I e^{-(x-t)^2}f(t)e^{-(x-s)^2}f(s)dsdtdx\right| \\ &= \left|\int\_I \int\_I f(t)f(s)\left(\int\_I e^{-(x-t)^2}e^{-(x-s)^2}dx\right)dsdt\right| \\ &\le \int\_I\int\_I |f(t)|\hspace{1mm}|f(s)| \left(\int\_\mathbb{R} e^{-(x-t)^2}e^{-(x-s)^2}dx\right)dsdt \\ &\le C\int\_I \int\_I |f(t)|\hspace{1mm} |f(s)|dsdt \\ &= C\left(\int\_I |f(t)|dt\right)^2 \end{align\*}
32,107,344
Can some one explain what is the difference between these two code blocks? Why would we ever need the first type when second one is more concise. First ``` var Utility; (function (Utility) { var Func = (function () { function Func(param1, param2) { var self = this; this.Owner = param2; } return Func; })(); Utility.Func = Func; })(Utility || (Utility = {})); ``` Second: ``` var Utility; (function (Utility) { Utility.Func = function (param1, param2) { var self = this; this.Owner = param2; } })(Utility || (Utility = {})); ``` context: First version was code generated by typescript compiler and I am trying to understand why did it generate the first instead of a simpler second.
2015/08/19
[ "https://Stackoverflow.com/questions/32107344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322933/" ]
The only difference between the code blocks is that the first has a function scope around the code that creates the `Func` function. The only reason to do that would be to create a scope where you can declare variables that would not be available in the outer scope: ``` var Utility; (function (Utility) { var Func = (function () { var x; // a variable in the inner scope function Func(param1, param2) { var self = this; this.Owner = param2; } return Func; })(); // the variable x is not reachable from code here Utility.Func = Func; })(Utility || (Utility = {})); ```
from what I see they are the same, in both cases you are defining the function and making it as a member of Utility, the calling it. Add to it, no scope differences, no context differences, no difference really. I think it's a matter of preference nothing more. But, I can see one potential difference, in case the very inside one was a `async` function call, there might be a difference , since `Utility.Func` will end up having `undefined` as a value, which is a very big problem with the first one, but I doubt the person writing it will not notice.
68,454,237
I'm trying to retrieve some data from a dummy function declared in an Oracle DB. The function was created like this in SQL Developer: ```sql create or replace NONEDITIONABLE FUNCTION hello RETURN varchar2 is BEGIN return 'Voici les caractères accentués : àéôï etc...' || chr(10) || 'ça marche ?'; END; ``` My Java application is executed in NetBeans at the moment and goes like this: ```java try(Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:OraDoc", "sys as sysdba", "MyPasswd123")) { CallableStatement cs = connection.prepareCall("{? = call hello}"); cs.registerOutParameter(1, Types.NVARCHAR); cs.execute(); byte[] bytes = cs.getBytes(1); logger.info(Hex.encodeHexString(bytes)); logger.info(new String(bytes, StandardCharsets.UTF_8)); logger.info(new String(bytes, StandardCharsets.UTF_16)); logger.info(new String(bytes, StandardCharsets.ISO_8859_1)); logger.info(new String(bytes, StandardCharsets.US_ASCII)); } catch(SQLException e) { logger.error(e.getMessage(), e); return; } ``` The output looks like this: ```none 2021-07-20 13:24:36 INFO Main:119 - 0056006f0069006300690020006c00650073002000630061007200610063007400e800720065007300200061006300630065006e0074007500e900730020003a002000e000e900f400ef0020006500740063002e002e002e000a00e700610020006d006100720063006800650020003f 2021-07-20 13:24:36 INFO Main:121 - Voici les caract?res accentu?s : ???? etc... ?a marche ? 2021-07-20 13:24:36 INFO Main:122 - Voici les caract?res accentu?s : ???? etc... ?a marche ? 2021-07-20 13:24:36 INFO Main:123 - Voici les caract?res accentu?s : ???? etc... ?a marche ? 2021-07-20 13:24:36 INFO Main:124 - Voici les caract?res accentu?s : ???? etc... ?a ma ``` Using the same connection, I ran two different queries to try to understand this issue: ```sql SELECT * FROM v$nls_parameters WHERE parameter LIKE '%CHARACTERSET'; SELECT * FROM nls_session_parameters; ``` which yield the following (truncated): ```none 2021-07-20 13:24:36 INFO Main:51 - PARAMETER -> NLS_CHARACTERSET 2021-07-20 13:24:36 INFO Main:51 - VALUE -> AL32UTF8 2021-07-20 13:24:36 INFO Main:51 - CON_ID -> 0 2021-07-20 13:24:36 INFO Main:51 - PARAMETER -> NLS_NCHAR_CHARACTERSET 2021-07-20 13:24:36 INFO Main:51 - VALUE -> AL16UTF16 2021-07-20 13:24:36 INFO Main:51 - CON_ID -> 0 2021-07-20 13:24:36 INFO Main:55 - ============================================================== 2021-07-20 13:24:36 INFO Main:63 - PARAMETER -> NLS_LANGUAGE 2021-07-20 13:24:36 INFO Main:63 - VALUE -> AMERICAN 2021-07-20 13:24:36 INFO Main:63 - PARAMETER -> NLS_TERRITORY 2021-07-20 13:24:36 INFO Main:63 - VALUE -> AMERICA ``` I've tried different things like: * adding "?useUnicode=true&characterEncoding=utf-8" at the end of the connection string like I do when I connect to a MySQL database * changing the NLS\_LANG to NLS\_LANG=AMERICAN\_AMERICA.UTF8 per [How to setup the NLS\_LANG Properly for UNIX](https://www.oracle.com/database/technologies/faq-nls-lang.html) * using NVARCHAR instead of VARCHAR when registering the outParameter * adding the parameter -Doracle.jdbc.defaultNChar=true But it's not improving. For reference, this is my only two dependencies in that project (related to Oracle): ```xml <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc11</artifactId> <version>21.1.0.0</version> </dependency> <dependency> <groupId>com.oracle.ojdbc</groupId> <artifactId>orai18n</artifactId> <version>19.3.0.0</version> </dependency> ``` * I've removed the NLS\_LANG environment variable (thanks @Wernfried Domscheit) * I've switched back to VARCHAR instead of NVARCHAR when registering the out parameter a * I am using getString() (I was using getBytes() to try to see whether I was receiving ? characters or if it was a display issue. * I've tried to create the string with UTF\_16BE charset Still, the result stays the same: ```java try(Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:OraDoc?useUnicode=true&characterEncoding=utf-8", "sys as sysdba", "MyPasswd123")) { CallableStatement cs = connection.prepareCall("{? = call hello}"); cs.registerOutParameter(1, Types.VARCHAR); cs.execute(); logger.info(cs.getString(1)); } catch(SQLException e) { logger.error(e.getMessage(), e); return; } ``` ```none 2021-07-20 17:00:20 INFO Main:43 - Voici les caract?res accentu?s : ???? etc... ``` What am I missing?
2021/07/20
[ "https://Stackoverflow.com/questions/68454237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/894876/" ]
Well, I also raised a defect to spring-data-redis repository on GitHub for the same but the defect got closed by one of the maintainers of this repository without even posting any proper solution. He just gave a reference to an existing issue that was even closed without posting any solution. Here is the link to that issue. <https://github.com/spring-projects/spring-data-redis/issues/2130> Hence, while doing some research, I came across a solution that I am sharing here which worked in my case. The solution is not to use the default CRUD repository methods implemented by Spring Boot, instead, write your own repository class having methods with your criteria to store and fetch the data from the Redis cache. That's it, now you should be able to store/fetch the data using the repository methods across your project. I am posting an example below for reference. **Custom Repository Interface** ``` package com.test.cache.repository; import java.io.IOException; import java.util.Map; import com.test.cache.entity.OTPValidationLogCache; public interface OTPValidationLogCacheRepository { void save(OTPValidationLogCache customer); OTPValidationLogCache find(Long id); Map<?,?> findAll() throws IOException; void update(OTPValidationLogCache customer); void delete(Long id); } ``` **Custom Repository Interface Implementation** ``` package com.test.cache.repository; import java.io.IOException; import java.time.Duration; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.Cursor; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ScanOptions; import org.springframework.data.redis.core.ScanOptions.ScanOptionsBuilder; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.test.cache.entity.OTPValidationLogCache; import com.test.configuration.AppConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; @Repository public class OTPValidationLogCacheRepositoryImpl implements OTPValidationLogCacheRepository { private String key; private RedisTemplate redisTemplate; private HashOperations hashOperations; private ObjectMapper objMapper; @Autowired public OTPValidationLogCacheRepositoryImpl(RedisTemplate redisTemplate, ObjectMapper objmapper) { this.redisTemplate = redisTemplate; this.objMapper = objmapper; } @PostConstruct private void init() { hashOperations = redisTemplate.opsForHash(); } @Override public void save(OTPValidationLogCache otpvalCache) { hashOperations.put(key.concat(otpvalCache.getId().toString()), otpvalCache.getId(), otpvalCache); setExpiryTime(key.concat(String.valueOf(otpvalCache.getId())), AppConfig.getUserBanDurationInSeconds()); } @Override public OTPValidationLogCache find(Long id) { return (OTPValidationLogCache) hashOperations.get(key.concat(String.valueOf(id)), id); } @Override public Map findAll() throws IOException { Map<Integer, OTPValidationLogCache> values = Maps.newHashMap(); Cursor c = hashOperations.scan(OTPValidationLogCache.class, new ScanOptionsBuilder().match(key.concat("*")).build()); AtomicInteger count = new AtomicInteger(1); c.forEachRemaining(element -> { values.put(count.getAndIncrement(), objMapper.convertValue(element, OTPValidationLogCache.class)); } ); c.close(); return values; } @Override public void update(OTPValidationLogCache customer) { hashOperations.put(key, customer.getId(), customer); } @Override public void delete(Long id) { hashOperations.delete(key, id); } private void setExpiryTime(String key, Long timeout) { redisTemplate.expire(key, Duration.ofSeconds(timeout)); } public synchronized void setKey(String key) { this.key = key; } } ``` Hope this helps others who may encounter this issue in the future. Also, there is one more alternative available for this issue, that is switching to a different library provider such as Redisson, however, I have not tried it yet, so if you want, you may try and check.
You need to have the same package for your entities , I resolved the problem by extracting a lib and putting my entities there You would find an explication here : <https://github.com/spring-projects/spring-data-redis/issues/2114>
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
Fast answear ============ [Mean Shift LSH](https://github.com/beckgael/Mean-Shift-LSH) which is an upgrade in **$O(n)$** of the famous Mean Shift algorithm in $O(n^2)$ well know for its image segmentation ability Some explanations ================= If you desire a true **unsupervised** approach to segment images, use **clustering algorithms**. The fact is that there is a lot of algorithms with different **time complexity** and **specificity**. Take the most famous one, the $K$-Means, it is in $O(n)$ so pretty fast but you have to specify how many cluster you want which is not what you intend by exploring an unknown image without any information about how many shapes are presents in it. Moreover even if you suppose that you know how many shape are present, we may suppose that there shapes are random which is another point where the $K$-Means fail because it is design to find elliptic clusters and **NOT** random shape ones. At the opposite we have the Mean Shift that is able to find **automatically** the number of cluster -- which is useful when you don't know what you're looking for -- with **random shapes**. Of course you replace the $K$ parameter of $K$-Means by others Mean Shift parameters which can be tricky to fine tuned but it doesn't exist a tool that allow you to do magic if you're not exercising to do magic. An advice to image segmentation clustering ========================================== Transform your color space from RGB to LUV which is better for euclidean distance. $K$-Means vs Mean Shift LSH time complexity =========================================== * Mean Shift : $O(\alpha.n)$ * K-Means : $O(\beta.n)$ * $\alpha \gt \beta$ Mean Shift LSH is slower but it fits better with your needs. It stay still linear and is also **scalable** with the mentioned implementation. PS : My profile picture is an application of the Mean Shift LSH on myself if it can help to figure out how it works.
Actually, your task is supervised. [`Segnet`](https://arxiv.org/abs/1511.00561) can be good architecture for your purpose which one of its implementations can be accessed [here](https://github.com/alexgkendall/caffe-segnet). *SegNet learns to predict pixel-wise class labels from supervised learning. Therefore we require a dataset of input images with corresponding ground truth labels. Label images must be single channel, with each pixel labelled with its class [...](http://mi.eng.cam.ac.uk/projects/segnet/tutorial.html)*. Also, take a look at [**Fully Convolutional Networks**](https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf) which are well suited for your task. --- Based on the edits in the question, I add extra information. There are numerous methods that can be applied for this task. Basically the easiest one is to use a *background* label and classify those classes that you don't know as background by employing the mentioned architectures. By doing so you will have labels which can have overlap for background class which is a probable downside of this approach but its advantage is that in cases where your trained labels are frequently used in the inputs, you can have a relatively light version of architecture which recognizes the unknown classes.
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
Actually, your task is supervised. [`Segnet`](https://arxiv.org/abs/1511.00561) can be good architecture for your purpose which one of its implementations can be accessed [here](https://github.com/alexgkendall/caffe-segnet). *SegNet learns to predict pixel-wise class labels from supervised learning. Therefore we require a dataset of input images with corresponding ground truth labels. Label images must be single channel, with each pixel labelled with its class [...](http://mi.eng.cam.ac.uk/projects/segnet/tutorial.html)*. Also, take a look at [**Fully Convolutional Networks**](https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf) which are well suited for your task. --- Based on the edits in the question, I add extra information. There are numerous methods that can be applied for this task. Basically the easiest one is to use a *background* label and classify those classes that you don't know as background by employing the mentioned architectures. By doing so you will have labels which can have overlap for background class which is a probable downside of this approach but its advantage is that in cases where your trained labels are frequently used in the inputs, you can have a relatively light version of architecture which recognizes the unknown classes.
This might be something that you are looking for. Since you ask for image segmentation and not `semantic / instance` segmentation, I presume you don't require the labelling for each segment in the image. The method is called `scene-cut` which segments an image into class-agnostic regions in an unsupervised fashion. This works very well in case of indoor cluttered environment. Paper link: [arxiv](https://arxiv.org/abs/1709.07158) Code: [code](https://github.com/trungtpham/SceneCut)
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
Fast answear ============ [Mean Shift LSH](https://github.com/beckgael/Mean-Shift-LSH) which is an upgrade in **$O(n)$** of the famous Mean Shift algorithm in $O(n^2)$ well know for its image segmentation ability Some explanations ================= If you desire a true **unsupervised** approach to segment images, use **clustering algorithms**. The fact is that there is a lot of algorithms with different **time complexity** and **specificity**. Take the most famous one, the $K$-Means, it is in $O(n)$ so pretty fast but you have to specify how many cluster you want which is not what you intend by exploring an unknown image without any information about how many shapes are presents in it. Moreover even if you suppose that you know how many shape are present, we may suppose that there shapes are random which is another point where the $K$-Means fail because it is design to find elliptic clusters and **NOT** random shape ones. At the opposite we have the Mean Shift that is able to find **automatically** the number of cluster -- which is useful when you don't know what you're looking for -- with **random shapes**. Of course you replace the $K$ parameter of $K$-Means by others Mean Shift parameters which can be tricky to fine tuned but it doesn't exist a tool that allow you to do magic if you're not exercising to do magic. An advice to image segmentation clustering ========================================== Transform your color space from RGB to LUV which is better for euclidean distance. $K$-Means vs Mean Shift LSH time complexity =========================================== * Mean Shift : $O(\alpha.n)$ * K-Means : $O(\beta.n)$ * $\alpha \gt \beta$ Mean Shift LSH is slower but it fits better with your needs. It stay still linear and is also **scalable** with the mentioned implementation. PS : My profile picture is an application of the Mean Shift LSH on myself if it can help to figure out how it works.
The state-of-the-art (SOTA) for image segmentation would be Facebook's [Mask-RCNN](https://arxiv.org/abs/1703.06870). While it is usually trained on dataset such like [COCO](http://cocodataset.org/#home) or [Pascal](http://host.robots.ox.ac.uk/pascal/VOC/) which feature real-life objects, you can re-trained it on a dataset of your choice, real or not. Facebook provides an implementation ([Detectron](https://github.com/facebookresearch/Detectron)) under the Apache2 license. Give it a try!
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
The state-of-the-art (SOTA) for image segmentation would be Facebook's [Mask-RCNN](https://arxiv.org/abs/1703.06870). While it is usually trained on dataset such like [COCO](http://cocodataset.org/#home) or [Pascal](http://host.robots.ox.ac.uk/pascal/VOC/) which feature real-life objects, you can re-trained it on a dataset of your choice, real or not. Facebook provides an implementation ([Detectron](https://github.com/facebookresearch/Detectron)) under the Apache2 license. Give it a try!
This might be something that you are looking for. Since you ask for image segmentation and not `semantic / instance` segmentation, I presume you don't require the labelling for each segment in the image. The method is called `scene-cut` which segments an image into class-agnostic regions in an unsupervised fashion. This works very well in case of indoor cluttered environment. Paper link: [arxiv](https://arxiv.org/abs/1709.07158) Code: [code](https://github.com/trungtpham/SceneCut)
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
Fast answear ============ [Mean Shift LSH](https://github.com/beckgael/Mean-Shift-LSH) which is an upgrade in **$O(n)$** of the famous Mean Shift algorithm in $O(n^2)$ well know for its image segmentation ability Some explanations ================= If you desire a true **unsupervised** approach to segment images, use **clustering algorithms**. The fact is that there is a lot of algorithms with different **time complexity** and **specificity**. Take the most famous one, the $K$-Means, it is in $O(n)$ so pretty fast but you have to specify how many cluster you want which is not what you intend by exploring an unknown image without any information about how many shapes are presents in it. Moreover even if you suppose that you know how many shape are present, we may suppose that there shapes are random which is another point where the $K$-Means fail because it is design to find elliptic clusters and **NOT** random shape ones. At the opposite we have the Mean Shift that is able to find **automatically** the number of cluster -- which is useful when you don't know what you're looking for -- with **random shapes**. Of course you replace the $K$ parameter of $K$-Means by others Mean Shift parameters which can be tricky to fine tuned but it doesn't exist a tool that allow you to do magic if you're not exercising to do magic. An advice to image segmentation clustering ========================================== Transform your color space from RGB to LUV which is better for euclidean distance. $K$-Means vs Mean Shift LSH time complexity =========================================== * Mean Shift : $O(\alpha.n)$ * K-Means : $O(\beta.n)$ * $\alpha \gt \beta$ Mean Shift LSH is slower but it fits better with your needs. It stay still linear and is also **scalable** with the mentioned implementation. PS : My profile picture is an application of the Mean Shift LSH on myself if it can help to figure out how it works.
You may need to take a look at this work submitted and accepted for CVPR 2018 : **[Learning to Segment Every Thing](https://arxiv.org/abs/1711.10370)** In this work, they try to segment everything, even objects not known to the network. Mask R-CNN has been used, combined with a transfer learning sub-network, they get very good results in segmenting almost everything.
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
You may need to take a look at this work submitted and accepted for CVPR 2018 : **[Learning to Segment Every Thing](https://arxiv.org/abs/1711.10370)** In this work, they try to segment everything, even objects not known to the network. Mask R-CNN has been used, combined with a transfer learning sub-network, they get very good results in segmenting almost everything.
This might be something that you are looking for. Since you ask for image segmentation and not `semantic / instance` segmentation, I presume you don't require the labelling for each segment in the image. The method is called `scene-cut` which segments an image into class-agnostic regions in an unsupervised fashion. This works very well in case of indoor cluttered environment. Paper link: [arxiv](https://arxiv.org/abs/1709.07158) Code: [code](https://github.com/trungtpham/SceneCut)
30,697
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online? Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
2018/04/23
[ "https://datascience.stackexchange.com/questions/30697", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/50956/" ]
Fast answear ============ [Mean Shift LSH](https://github.com/beckgael/Mean-Shift-LSH) which is an upgrade in **$O(n)$** of the famous Mean Shift algorithm in $O(n^2)$ well know for its image segmentation ability Some explanations ================= If you desire a true **unsupervised** approach to segment images, use **clustering algorithms**. The fact is that there is a lot of algorithms with different **time complexity** and **specificity**. Take the most famous one, the $K$-Means, it is in $O(n)$ so pretty fast but you have to specify how many cluster you want which is not what you intend by exploring an unknown image without any information about how many shapes are presents in it. Moreover even if you suppose that you know how many shape are present, we may suppose that there shapes are random which is another point where the $K$-Means fail because it is design to find elliptic clusters and **NOT** random shape ones. At the opposite we have the Mean Shift that is able to find **automatically** the number of cluster -- which is useful when you don't know what you're looking for -- with **random shapes**. Of course you replace the $K$ parameter of $K$-Means by others Mean Shift parameters which can be tricky to fine tuned but it doesn't exist a tool that allow you to do magic if you're not exercising to do magic. An advice to image segmentation clustering ========================================== Transform your color space from RGB to LUV which is better for euclidean distance. $K$-Means vs Mean Shift LSH time complexity =========================================== * Mean Shift : $O(\alpha.n)$ * K-Means : $O(\beta.n)$ * $\alpha \gt \beta$ Mean Shift LSH is slower but it fits better with your needs. It stay still linear and is also **scalable** with the mentioned implementation. PS : My profile picture is an application of the Mean Shift LSH on myself if it can help to figure out how it works.
This might be something that you are looking for. Since you ask for image segmentation and not `semantic / instance` segmentation, I presume you don't require the labelling for each segment in the image. The method is called `scene-cut` which segments an image into class-agnostic regions in an unsupervised fashion. This works very well in case of indoor cluttered environment. Paper link: [arxiv](https://arxiv.org/abs/1709.07158) Code: [code](https://github.com/trungtpham/SceneCut)
7,570,496
I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this: ``` <html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> ``` I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.
2011/09/27
[ "https://Stackoverflow.com/questions/7570496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821562/" ]
Try the following ``` var doc=document.getElementById("frame").contentDocument; // Earlier versions of IE or IE8+ where !DOCTYPE is not specified var doc=document.getElementById("frame").contentWindow.document; ``` Note: AndyE pointed out that `contentWindow` is supported by all major browsers so this may be the best way to go. * <http://help.dottoro.com/ljctglqj.php> Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy * <http://javascript.info/tutorial/same-origin-security-policy>
This is the code I use: ``` var ifrm = document.getElementById('myFrame'); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); ``` > > **contentWindow vs. contentDocument** > > > * IE (Win) and Mozilla (1.7) will return the window object inside the > iframe with oIFrame.contentWindow. > * Safari (1.2.4) doesn't understand that property, but does have > oIframe.contentDocument, which points to the document object inside > the iframe. > * To make it even more complicated, Opera 7 uses > oIframe.contentDocument, but it points to the window object of the > iframe. Because Safari has no way to directly access the window object > of an iframe element via standard DOM (or does it?), our fully > modern-cross-browser-compatible code will only be able to access the > document within the iframe. > > >
7,570,496
I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this: ``` <html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> ``` I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.
2011/09/27
[ "https://Stackoverflow.com/questions/7570496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821562/" ]
Try the following ``` var doc=document.getElementById("frame").contentDocument; // Earlier versions of IE or IE8+ where !DOCTYPE is not specified var doc=document.getElementById("frame").contentWindow.document; ``` Note: AndyE pointed out that `contentWindow` is supported by all major browsers so this may be the best way to go. * <http://help.dottoro.com/ljctglqj.php> Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy * <http://javascript.info/tutorial/same-origin-security-policy>
For even more robustness: ``` function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc && iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc && iframe_object.document) { doc = iframe_object.document; } if (doc && doc.defaultView) { return doc.defaultView; } if (doc && doc.parentWindow) { return doc.parentWindow; } return undefined; } ``` and ``` ... var el = document.getElementById('targetFrame'); var frame_win = getIframeWindow(el); if (frame_win) { frame_win.targetFunction(); ... } ... ```
7,570,496
I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this: ``` <html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> ``` I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.
2011/09/27
[ "https://Stackoverflow.com/questions/7570496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821562/" ]
Try the following ``` var doc=document.getElementById("frame").contentDocument; // Earlier versions of IE or IE8+ where !DOCTYPE is not specified var doc=document.getElementById("frame").contentWindow.document; ``` Note: AndyE pointed out that `contentWindow` is supported by all major browsers so this may be the best way to go. * <http://help.dottoro.com/ljctglqj.php> Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy * <http://javascript.info/tutorial/same-origin-security-policy>
In my case, it was due to Same Origin policies. To explain it further, [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentDocument) states the following: > > If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null. > > >
7,570,496
I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this: ``` <html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> ``` I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.
2011/09/27
[ "https://Stackoverflow.com/questions/7570496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821562/" ]
This is the code I use: ``` var ifrm = document.getElementById('myFrame'); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); ``` > > **contentWindow vs. contentDocument** > > > * IE (Win) and Mozilla (1.7) will return the window object inside the > iframe with oIFrame.contentWindow. > * Safari (1.2.4) doesn't understand that property, but does have > oIframe.contentDocument, which points to the document object inside > the iframe. > * To make it even more complicated, Opera 7 uses > oIframe.contentDocument, but it points to the window object of the > iframe. Because Safari has no way to directly access the window object > of an iframe element via standard DOM (or does it?), our fully > modern-cross-browser-compatible code will only be able to access the > document within the iframe. > > >
In my case, it was due to Same Origin policies. To explain it further, [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentDocument) states the following: > > If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null. > > >
7,570,496
I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this: ``` <html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> ``` I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.
2011/09/27
[ "https://Stackoverflow.com/questions/7570496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821562/" ]
For even more robustness: ``` function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc && iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc && iframe_object.document) { doc = iframe_object.document; } if (doc && doc.defaultView) { return doc.defaultView; } if (doc && doc.parentWindow) { return doc.parentWindow; } return undefined; } ``` and ``` ... var el = document.getElementById('targetFrame'); var frame_win = getIframeWindow(el); if (frame_win) { frame_win.targetFunction(); ... } ... ```
In my case, it was due to Same Origin policies. To explain it further, [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentDocument) states the following: > > If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null. > > >
52,784,794
I'm working through TestDome.com and ran into this question. > > Implement the removeProperty function which takes an object and > property name, and does the following: > > > If the object obj has a property prop, the function removes the > property from the object and returns true; in all other cases it > returns false. > > > My solution was this: ``` function removeProperty(obj, prop) { if (obj[prop]) { delete obj[prop]; return true; } else { return false; } } ``` The test says that this doesn't work and their solution is: ``` function removeProperty(obj, prop) { if (prop in obj) { delete obj[prop]; return true; } else { return false; } } ``` For the life of me I can't figure out why my solution is wrong. Edit: further examples. ``` const a = { b: 'c'}; if(a['b']) {console.log(true);} //true if('b' in a) {console.log(true);} //true ```
2018/10/12
[ "https://Stackoverflow.com/questions/52784794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3792201/" ]
The difference is the following: ```js obj = { prop: 1 }; // retrieves the property from the object console.log(obj['prop']); // 1 // checks if prop is in obj object console.log('prop' in obj); // true ``` In the case of an if statement, both will evaluate to true. However, if the value retrieved from `obj['prop']` is coerced to `false` the `if` block would not run. For example: ```js obj = { prop: 0 }; // 0 convert to false so if (obj['prop']) { console.log('executed 1'); } // prop is a property of obj so // 'prop' in obj will evaluate to true if ('prop' in obj) { console.log('executed 2'); } ```
let's say you have an object ``` const a = {apple: 0} ``` In this case, `a['apple']` would be falsy, where as `"apple" in a` would be truthy. Therefore, if you want to delete some key, just delete the key directly. I believe you do not even need to check for it before deleting it.
13,676,616
I made a implementation of the KMP algorithm's fail table. ``` kmp s = b where a = listArray (0,length s-1) s b = 0:list 0 (tail s) list _ [] = [] list n (x:xs) | x==a!n = (n+1):list (n+1) xs | n > 0 = list (b!!(n-1)) (x:xs) | otherwise = 0:list 0 xs ``` `b` is a list, and `b!!(n-1)` in the last line is slow, therefore I wish to speed it up and did the following. ``` kmp s = b where a = listArray (0,length s-1) s t = listArray (0,length s-1) b b = 0:list 0 (tail s) list _ [] = [] list n (x:xs) | x==a!n = (n+1):list (n+1) xs | n > 0 = list (t!(n-1)) (x:xs) | otherwise = 0:list 0 xs ``` Note the only difference is to replace `b!!` by `t!` and declares `t` to be the array generated from `b`. For the same input, the original code have the correct output, but the new one just outputs `<<loop>>`. How can one fix this problem?
2012/12/03
[ "https://Stackoverflow.com/questions/13676616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303863/" ]
Your problem is that the list `b` needs the array `t` to determine its structure (length). But the array `t` needs the length of the list before it exists: ``` listArray :: Ix i => (i,i) -> [e] -> Array i e listArray (l,u) es = runST (ST $ \s1# -> case safeRangeSize (l,u) of { n@(I# n#) -> case newArray# n# arrEleBottom s1# of { (# s2#, marr# #) -> let fillFromList i# xs s3# | i# ==# n# = s3# | otherwise = case xs of [] -> s3# y:ys -> case writeArray# marr# i# y s3# of { s4# -> fillFromList (i# +# 1#) ys s4# } in case fillFromList 0# es s2# of { s3# -> done l u n marr# s3# }}}) ``` As you can see, first a raw array of appropriate size is allocated, then it is filled with `arrEleBottom` (which is an `error` call with message undefined array element), then the list is traversed and the list elements are written to the array (the list elements can refer to array values without problem). Then, finally, the array is frozen. Before the array is frozen, it cannot be accessed from outside the filling code (it's basically an `ST s` computation). The simplest way to fix it is IMO to use a mutable array in an `ST s` monad, ``` kmp s = elems b where l = length s - 1 a = listArray (0, l) s b = runSTArray $ do t <- newArray_ (0,l) writeArray t 0 0 let fill _ _ [] = return t fill i n (x:xs) | x == a!n = do writeArray t i (n+1) fill (i+1) (n+1) xs | n > 0 = do k <- readArray t (n-1) fill i k (x:xs) | otherwise = do writeArray t i 0 fill (i+1) 0 xs fill 1 0 (tail s) ``` is a very direct (and a bit inefficient) translation of the code.
This doesn't directly answer your question, but gives a simpler fix than the proposed version using `STArray`s. The imperative version of the algorithm translates directly into a version that doesn't use repeated list indexing or state, just lazy array construction: ``` import Data.Array.IArray kmp :: String -> Array Int Int kmp s = b where a :: Array Int Char a = listArray (0,l-1) s b = listArray (1,l) (0:map (\q -> f (b!(q-1)) q) [2..l]) f k q | k > 0 && (a ! k) /= (a ! (q-1)) = f (b ! k) q | a ! k == a ! (q-1) = k + 1 | otherwise = k l = length s ``` However, I haven't benchmarked this.
35,214,094
I tried setting the following: set ftp:initial-prot "" set ftp:ssl-force true set ftp:ssl-protect-data true set ftp:ssl-auth TLS and am on RHEL4 trying to lftp to a 2010 Windows server but I am getting Fatal error: gnutls\_handshake: A TLS packet with unexpected length was received. Can you please let me know what is that am missing now?
2016/02/05
[ "https://Stackoverflow.com/questions/35214094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249798/" ]
Let does not create local "variables", it gives names to values, and does not let you change them after giving them the name. So introducing a let is more like defining a local constant. First I'll just add another item into the `loop` expression to store the value so far. Each time through the loop we will update this to incorporate the new information. This pattern is very common. I also needed to add a new argument to the function to hold the initial state (reduce as a concept needs this) ``` user> (defn new-reduce [function initial-value coll] (loop [i 0 answer-so-far initial-value] (if (< i (count coll)) (recur (inc i) (function answer-so-far (get coll i))) answer-so-far))) user> (new-reduce + 0 [1 2 3]) 6 ``` This moves the "global variable" into a name that is local to the loop expression can be updated once per loop at the time you jump back up to the top. Once it reaches the end of the loop it will return the answer thus far as the return value of the function rather than recurring again. Building your own reduce function is a great way to build understanding on how to use reduce effectively. There is a function that introduces true local variables, though it is very nearly never used in Clojure code. It's only really used in the runtime bootstap code. If you are really curious read up on binding very carefully.
Here's a simple, functional solution that replicates the behavior of the standard `reduce`: ``` (defn reduce ([f [head & tail :as coll]] (if (empty? coll) (f) (reduce f head tail))) ([f init [head & tail :as coll]] (cond (reduced? init) @init (empty? coll) init :else (recur f (f init head) tail)))) ``` There is no `loop` here, because the function itself serves as the recursion point. I personally find it easier to think about this recursively, but since we're using tail recursion with `recur`, you can think about it imperatively/iteratively as well: 1. If `init` is a signal to return early then return its value, otherwise go to step 2 2. If `coll` is empty then return `init`, otherwise go to step 3 3. Set `init` to the result of calling `f` with `init` and the first item of `coll` as arguments 4. Set `coll` to a sequence of all items in `coll` except the first one 5. Go to step 1 Actually, under the hood (with tail-call optimization and such), that's essentially what's really going on. I'd encourage you to compare these two expressions of the same solution to get a better idea of how to go about solving these sorts of problems in Clojure.
52,023,130
What i'm trying to do is to read big file 5.6GB have approximately 600Million lines and the second is 16MB have 2M lines. I want to check the duplicate lines in these two files. ``` $wordlist = array_unique(array_filter(file('small.txt', FILE_IGNORE_NEW_LINES))); $duplicate = array(); if($file = fopen('big.txt', 'r')){ while(!feof($file)){ $lines = rtrim(fgets($file)); if(in_array($lines, $wordlist)){ echo $lines." : exists.\n"; } } fclose($file); } ``` But this take forever to finish ( its been running from 6 hours and didn't finish yet :/ ). My question is. Is there a better way to search in huge files fast?
2018/08/26
[ "https://Stackoverflow.com/questions/52023130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8966922/" ]
You won't need to call `array_filter()` or `array_unique()` if you are going to call `array_flip()` -- it will eliminate the duplicates for you because you can't have duplicate keys in the same level of an array. Furthermore: 1. `array_unique()` is stated to be slower than `array_flip()` (and there are times when it is slower than two `array_flip()`s) 2. `array_filter()` has a bad reputation for killing falsey/empty/null/zero-ish data, so I will caution you not to use its default behavior. 3. `array_flip()` sets up the very speedy `isset()` check. `isset()` will likely outperform `array_key_exists()` because `isset()` doesn't check for `null` values. 4. I am adding the `FILE_SKIP_EMPTY_LINES` flag to `file()` call so that your lookup array is potentially smaller. 5. Calling `rtrim()` of every line of your big file, may be causing some drag too. Do you know if you have consistently identical newline characters on both files? It would spare you six hundred millions calls of `rtrim()` if you can safely remove the `FILE_IGNORE_NEW_LINES` flag from the `file()` call. Alternatively, if you *know* the newlines (e.g. `\n`? or `\r\n`?) that trail the big.txt lines, you can append specific newline(s) to the `$lookup` keys -- this means preparing the smaller file's data versus every line of the big file. Untested Code: ``` $lookup = array_flip(file('small.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); if($file = fopen('big.txt', 'r')){ while(!feof($file)){ $line = rtrim(fgets($file)); if (isset($lookup[$line])) { echo "$lines : exists.\n"; } } fclose($file); } ```
i think ``` $wordlist=array_flip(array_unique(array_filter(file('small.txt', FILE_IGNORE_NEW_LINES)))); ``` which you actually use in your code,slows it.It may be better to build the wordslist once and foverer yourself: ``` if($file1 = fopen('big.txt', 'r')){ if($file = fopen('small.txt', 'r')){ while(!feof($file)){ $line=trim(fgets($file)); if(!isset($wordlist[$line])&&!ctype_space($line)&&!empty($line)){ $wordlist[$line]=0; } } fclose($file); } while(!feof($file1)){ $line1 = trim(fgets($file1)); if(isset($wordlist[$line1])) $wordlist[$line1]++; } fclose($file1); } ``` At this step the variable $wordlist contain the list of all lines in your small.txt file and the number of occurences of each line in your big.txt file . You could use the array like that or filter it to remove null lines.You could also sort the array with uasort to know more about which lines occurs the most and which one occurs less and and you can even go further in your analyze...
71,621,056
I have an app that I need to clean up some resources before it shuts down. I've got it handling the event using: `AppDomain.CurrentDomain.ProcessExit += OnProcessExit;` ``` private static async void OnProcessExit(object? sender, EventArgs e) { Console.WriteLine("We"); Thread.Sleep(1000); Console.WriteLine("Are"); Thread.Sleep(1000); Console.WriteLine("Closing"); } ``` But the event never gets fired? At least I don't see it, it instantly closes. I've tried this in an external and internal console and neither seem to catch it. Using Linux Ubuntu 20.10
2022/03/25
[ "https://Stackoverflow.com/questions/71621056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18571693/" ]
While you might see it as overkill in the beginning, I can recommend wrapping your console app in .NET Generic Host. This enables you to easily handle resource initialisation and cleanup, it also encapsulates logging and DI and nested services if available. The console app becomes easy to startup in an integration test, install as a Windows service (e.g. via Topshelf) or just keep running as a console app. <https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host> To get started you can run in command prompt ``` dotnet new worker ``` Then in Worker.cs you can override the StopAsync ``` public override async Task StopAsync(CancellationToken cancellationToken) { await Task.Delay(1000); _logger.LogInformation("Ended!"); } ``` Running with `dotnet run` you will see logging each second, and when you Ctrl+C you will see "Ended!" after 1 second - here you do any resource cleanup needed.
Normally you should use [`AppDomain.ProcessExit`](https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.processexit?view=net-6.0) rather than `AppDomain.CurrentDomain.ProcessExit`. Is there a specific reason why you're using the second form? How is your console app closing? Is it a normal exit after finishing its work, or failing due to an unmanaged exception, or dying due to a rude shutdown (eg `Ctrl-C`, `Environment.FailFast`, etc)? In the first two cases `AppDomain.ProcessExit` should be invoked normally. But if that isn't happening for some reason, you can use `Try..Finally` to do resource cleanup. In the third case, it's very likely that `AppDomain.ProcessExit` won't be invoked. And there's not a lot you can do about that. Are you using a Debug or Release build? Because shutdown behaviour can be different depending on the build type. In addition, apps hosted within Docker might have [unusual shutdown behaviour](https://github.com/dotnet/runtime/issues/36089).