id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
26,126,853
Verifying PEP8 in iPython notebook code
<p>Is there an easy way to check that iPython notebook code, while it's being written, is compliant with PEP8?</p>
37,423,434
7
0
null
2014-09-30 17:41:27.587 UTC
24
2021-12-13 14:03:28.29 UTC
2014-10-06 18:53:39.163 UTC
null
1,079,075
null
1,079,075
null
1
53
python|ipython|ipython-notebook|pep8
27,887
<p>In case this helps anyone, I'm using:</p> <p><code>conttest "jupyter nbconvert notebook.ipynb --stdout --to script | flake8 - --ignore=W391"</code></p> <ul> <li><code>conttest</code> reruns when saving changes to the notebook</li> <li><code>flake8 -</code> tells flake8 to take input from stdin</li> <li><code>--ignore=W391</code> - this is because the output of <code>jupyter nbconvert</code> seems to always have a "blank line at end of file", so I don't want flake8 to complain about that.</li> </ul> <p>I'm having a problem with markdown cells (whose line lengths may legitimately be quite long, though): <a href="https://stackoverflow.com/questions/37423380/ignore-markdown-cells-in-jupyter-nbconvert-with-to-script">ignore markdown cells in `jupyter nbconvert` with `--to script`</a>.</p>
3,038,203
Is there any point in using a volatile long?
<p>I occasionally use a <code>volatile</code> instance variable in cases where I have two threads reading from / writing to it and don't want the overhead (or potential deadlock risk) of taking out a lock; for example a timer thread periodically updating an int ID that is exposed as a getter on some class:</p> <pre><code>public class MyClass { private volatile int id; public MyClass() { ScheduledExecutorService execService = Executors.newScheduledThreadPool(1); execService.scheduleAtFixedRate(new Runnable() { public void run() { ++id; } }, 0L, 30L, TimeUnit.SECONDS); } public int getId() { return id; } } </code></pre> <p>My question: Given that the JLS only guarantees that 32-bit reads will be atomic is there any point in <strong>ever</strong> using a volatile long? (i.e. 64-bit).</p> <p><strong>Caveat</strong>: Please do not reply saying that using <code>volatile</code> over <code>synchronized</code> is a case of pre-optimisation; I am well aware of how / when to use <code>synchronized</code> but there are cases where <code>volatile</code> is preferable. For example, when defining a Spring bean for use in a single-threaded application I tend to favour <code>volatile</code> instance variables, as there is no guarantee that the Spring context will initialise each bean's properties in the main thread.</p>
3,038,233
3
3
null
2010-06-14 14:49:32.08 UTC
19
2015-12-23 17:15:11.117 UTC
2010-11-23 08:15:21.003 UTC
null
276,052
null
127,479
null
1
58
java|multithreading|concurrency|volatile
17,318
<p>Not sure if I understand your question correctly, but the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4" rel="noreferrer">JLS 8.3.1.4. volatile Fields</a> states:</p> <blockquote> <p>A field may be declared volatile, in which case the Java memory model ensures that all threads see a consistent value for the variable (<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4" rel="noreferrer">§17.4</a>).</p> </blockquote> <p>and, perhaps more importantly, <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7" rel="noreferrer">JLS 17.7 Non-atomic Treatment of double and long</a> :</p> <blockquote> <p><strong>17.7 Non-atomic Treatment of double and long</strong><br/> [...]<br/> For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64 bit value from one write, and the second 32 bits from another write. <strong>Writes and reads of volatile long and double values are always atomic.</strong> Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.</p> </blockquote> <p>That is, the "entire" variable is protected by the volatile modifier, not just the two parts. This tempts me to claim that it's <strong>even more important</strong> to use volatile for <code>long</code>s than it is for <code>int</code>s since <em>not even a read</em> is atomic for non-volatile longs/doubles.</p>
2,503,010
Extracting columns from text file using PowerShell
<p>I have to extract columns from a text file explained in this post:</p> <p><a href="https://stackoverflow.com/questions/2499746/extracting-columns-from-text-file-using-perl-similar-to-unix-cut">Extracting columns from text file using Perl one-liner: similar to Unix cut</a></p> <p>but I have to do this also in a Windows Server 2008 which does not have Perl installed. How could I do this using PowerShell? Any ideas or resources? I'm PowerShell noob...</p>
2,503,038
4
0
null
2010-03-23 19:34:36.49 UTC
3
2017-09-22 15:13:43.333 UTC
2017-05-23 10:30:17.893 UTC
null
-1
null
255,564
null
1
13
powershell|windows-server-2008
58,738
<p>Try this:</p> <pre><code>Get-Content test.txt | Foreach {($_ -split '\s+',4)[0..2]} </code></pre> <p>And if you want the data in those columns printed on the same line:</p> <pre><code>Get-Content test.txt | Foreach {"$(($_ -split '\s+',4)[0..2])"} </code></pre> <p>Note that this requires PowerShell 2.0 for the <code>-split</code> operator. Also, the <code>,4</code> tells the the split operator the maximum number of split strings you want but keep in mind the last string will always contain all extras concat'd.</p> <p>For fixed width columns, here's one approach for column width equal to 7 ($w=7):</p> <pre><code>$res = Get-Content test.txt | Foreach { $i=0;$w=7;$c=0; ` while($i+$w -lt $_.length -and $c++ -lt 2) { $_.Substring($i,$w);$i=$i+$w-1}} </code></pre> <p>$res will contain each column for all rows. To set the max columns change <code>$c++ -lt 2</code> from 2 to something else. There is probably a more elegant solution but don't have time right now to ponder it. :-)</p>
2,888,422
axis2 maven example
<p>I try to use axis2 (1.5.1) version to generate java codes from wsdl files, but I can't figure out what is the correct pom.xml</p> <pre><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-wsdl2code-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.5.1&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;wsdl2code&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;wsdlFile&gt;src/main/resources/wsdl/stockquote.wsdl&lt;/wsdlFile&gt; &lt;databindingName&gt;xmlbeans&lt;/databindingName&gt; &lt;packageName&gt;a.bc&lt;/packageName&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2&lt;/artifactId&gt; &lt;version&gt;1.5.1&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>when I type mvn compile, it complains the </p> <pre><code>Retrieving document at 'src/main/resources/wsdl/stockquote.wsdl'. java.lang.ClassNotFoundException: org.apache.xml.serializer.TreeWalker </code></pre> <p>And if i try to find the TreeWalker, it is a mess to find a suitable jar files.</p> <p>can u someone give me a hints ? or give me correct pom.xml</p> <p>[update] the xalan-2.7.0.jar needs be depedent as well, and the jar file is broken ( due to nexus problem), thx pascal</p>
2,889,488
4
1
null
2010-05-22 14:22:41.373 UTC
6
2015-07-30 02:29:22.38 UTC
2010-05-26 06:56:28.12 UTC
null
308,174
null
308,174
null
1
20
maven-2|wsdl|axis2|xmlserializer|wsdl2code
53,767
<p>It's maybe not optimal but the following pom.xml seems to allow the generated code to be compiled:</p> <pre><code>&lt;project&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.stackoverflow&lt;/groupId&gt; &lt;artifactId&gt;Q2888422&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; ... &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2&lt;/artifactId&gt; &lt;version&gt;1.5.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.ws.commons.axiom&lt;/groupId&gt; &lt;artifactId&gt;axiom-api&lt;/artifactId&gt; &lt;version&gt;1.2.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.ws.commons.axiom&lt;/groupId&gt; &lt;artifactId&gt;axiom-impl&lt;/artifactId&gt; &lt;version&gt;1.2.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;axis&lt;/groupId&gt; &lt;artifactId&gt;axis-wsdl4j&lt;/artifactId&gt; &lt;version&gt;1.5.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.xmlbeans&lt;/groupId&gt; &lt;artifactId&gt;xmlbeans&lt;/artifactId&gt; &lt;version&gt;2.3.0&lt;/version&gt; &lt;/dependency&gt; ... &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-wsdl2code-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.5.1&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;wsdl2code&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;wsdlFile&gt;src/main/resources/wsdl/stockquote.wsdl&lt;/wsdlFile&gt; &lt;databindingName&gt;xmlbeans&lt;/databindingName&gt; &lt;packageName&gt;a.bc&lt;/packageName&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>This pom.xml is the result or try and error plus some googling, I couldn't find a single official or unofficial resource with a working setup. Seriously, why the hell is it so hard to setup an Axis2 project? One more reason I don't like Axis.</p>
2,687,012
Split string into sentences
<p>I have written this piece of code that splits a string and stores it in a string array:-</p> <pre><code>String[] sSentence = sResult.split("[a-z]\\.\\s+"); </code></pre> <p>However, I've added the [a-z] because I wanted to deal with some of the abbreviation problem. But then my result shows up as so:-</p> <blockquote> <p>Furthermore when Everett tried to instruct them in basic mathematics they proved unresponsiv</p> </blockquote> <p>I see that I lose the pattern specified in the split function. It's okay for me to lose the period, but losing the last letter of the word disturbs its meaning.</p> <p>Could someone help me with this, and in addition, could someone help me with dealing with abbreviations? For example, because I split the string based on periods, I do not want to lose the abbreviations.</p>
2,687,929
4
0
null
2010-04-21 22:29:34.107 UTC
17
2021-01-22 15:07:07.643 UTC
2016-01-22 18:48:44.563 UTC
null
1,393,766
null
282,544
null
1
27
java|regex|split|abbreviation
35,965
<p>Parsing sentences is far from being a trivial task, even for latin languages like English. A naive approach like the one you outline in your question will fail often enough that it will prove useless in practice.</p> <p>A better approach is to use a <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/BreakIterator.html#KIND_SENTENCE" rel="noreferrer">BreakIterator</a> configured with the right Locale.</p> <pre><code>BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US); String source = "This is a test. This is a T.L.A. test. Now with a Dr. in it."; iterator.setText(source); int start = iterator.first(); for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) { System.out.println(source.substring(start,end)); } </code></pre> <p>Yields the following result:</p> <ol> <li>This is a test.</li> <li>This is a T.L.A. test.</li> <li>Now with a Dr. in it.</li> </ol>
2,443,885
graph library for scala
<p>Is there a good library (or wrapper to Java library) for graphs, and/or graph algorithms in scala?</p> <p><a href="http://code.google.com/p/scala-graphs/" rel="noreferrer">This one</a> seems to be quite dead. <a href="http://en.literateprograms.org/Dijkstra&#39;s_algorithm_(Scala)" rel="noreferrer">This</a> is an example for the Dijkstra algorithm in scala, but I'm looking for a library a-la <a href="http://jgrapht.sourceforge.net/" rel="noreferrer">JGraphT</a>.</p>
2,445,951
4
2
null
2010-03-14 21:40:34.873 UTC
10
2014-10-11 18:33:34.47 UTC
null
null
null
null
55,094
null
1
33
scala|graph
14,370
<p>We have developed a small graph library for the apparat project. You can take a look at it <a href="http://code.google.com/p/apparat/source/browse/#hg%2Fapparat-core%2Fsrc%2Fmain%2Fscala%2Fapparat%2Fgraph" rel="noreferrer">here</a>. It is not purely functional and not a zipper graph but does a good job for us. You get also mutable and immutable graphs.</p> <p>Here is a simple example for graph creation:</p> <pre><code>implicit val factory = DefaultEdge[String](_, _) val G = Graph( "Entry" -&gt; "A", "A" -&gt; "B", "B" -&gt; "C", "B" -&gt; "D", "D" -&gt; "F", "F" -&gt; "E", "E" -&gt; "F", "E" -&gt; "C", "C" -&gt; "A", "C" -&gt; "Exit") G.dotExport to Console.out </code></pre> <p>Finding SCCs and subcomponents</p> <pre><code>G.sccs foreach println G.sccs map { _.entry } foreach println G.sccs filter { _.canSearch } map { _.subcomponents } foreach { _ foreach println } </code></pre> <p>Traversal</p> <pre><code>for(x &lt;- G.topsort) println(x) for(x &lt;- G.dft(y)) println(x) </code></pre> <p>The current drawback is that the library is supporting only invariant types and not feature complete for a whole graph library.</p>
2,419,650
C/C++ macro/template blackmagic to generate unique name
<p>Macros are fine. Templates are fine. Pretty much whatever it works is fine.</p> <p>The example is OpenGL; but the technique is C++ specific and relies on no knowledge of OpenGL.</p> <p>Precise problem:</p> <p>I want an expression E; where I do not have to specify a unique name; such that a constructor is called where E is defined, and a destructor is called where the block E is in ends.</p> <p>For example, consider:</p> <pre><code>class GlTranslate { GLTranslate(float x, float y, float z); { glPushMatrix(); glTranslatef(x, y, z); } ~GlTranslate() { glPopMatrix(); } }; </code></pre> <p>Manual solution:</p> <pre><code>{ GlTranslate foo(1.0, 0.0, 0.0); // I had to give it a name ..... } // auto popmatrix </code></pre> <p>Now, I have this not only for glTranslate, but lots of other PushAttrib/PopAttrib calls too. I would prefer not to have to come up with a unique name for each var. Is there some trick involving macros templates ... or something else that will automatically create a variable who's constructor is called at point of definition; and destructor called at end of block?</p> <p>Thanks!</p>
2,419,720
4
8
null
2010-03-10 18:53:08.383 UTC
30
2019-06-09 07:57:34.417 UTC
2015-09-19 16:29:31.557 UTC
null
1,023,390
null
247,265
null
1
44
c++|c-preprocessor|raii
18,499
<p>If your compiler supports <code>__COUNTER__</code> (it probably does), you could try:</p> <pre><code>// boiler-plate #define CONCATENATE_DETAIL(x, y) x##y #define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y) #define MAKE_UNIQUE(x) CONCATENATE(x, __COUNTER__) // per-transform type #define GL_TRANSLATE_DETAIL(n, x, y, z) GlTranslate n(x, y, z) #define GL_TRANSLATE(x, y, z) GL_TRANSLATE_DETAIL(MAKE_UNIQUE(_trans_), x, y, z) </code></pre> <p>For</p> <pre><code>{ GL_TRANSLATE(1.0, 0.0, 0.0); // becomes something like: GlTranslate _trans_1(1.0, 0.0, 0.0); } // auto popmatrix </code></pre>
2,970,361
How to read the full stacktrace in Java where it says e.g. "... 23 more"
<p>I want to read the full stack trace of an exception that I capture.</p> <p>For example:</p> <pre><code>org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.ibm.db2.jcc.DB2Driver' at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1136) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880) at com.azurian.lce.usuarios.ConnectionManager.getConnection(ConnectionManager.java:65) at com.azurian.lce.usuarios.db2.UsuarioDAOImpl.autenticar(UsuarioDAOImpl.java:101) at com.azurian.lce.usuarios.UsuarioServiceImpl.autenticar(UsuarioServiceImpl.java:31) at com.azurian.lce.web.admin.actions.LoginAction.execute(LoginAction.java:49) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: COM.ibm.db2.jcc.DB2Driver at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1130) ... 23 more </code></pre> <p>I want to read the "... 23 more" to see where the exception comes from.</p>
2,970,366
4
3
null
2010-06-03 22:53:16.863 UTC
6
2021-01-10 14:21:41.17 UTC
2021-01-10 14:21:41.17 UTC
null
157,882
null
332,897
null
1
68
java|stack-trace
80,564
<p>The answer is simple, those lines are already in the stacktrace :)</p> <pre><code> at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880) at com.azurian.lce.usuarios.ConnectionManager.getConnection(ConnectionManager.java:65) at com.azurian.lce.usuarios.db2.UsuarioDAOImpl.autenticar(UsuarioDAOImpl.java:101) at com.azurian.lce.usuarios.UsuarioServiceImpl.autenticar(UsuarioServiceImpl.java:31) at com.azurian.lce.web.admin.actions.LoginAction.execute(LoginAction.java:49) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source) </code></pre> <p>Basically, the following is happening in <code>BasicDataSource#createDataSource()</code>:</p> <pre><code>try { Class.forName(driverClassName); // Line 1130 } catch (ClassNotFoundException e) { throw new SQLNestedException(e, "Cannot load JDBC driver class '" + driverClassName + "'"); // Line 1136 } </code></pre>
2,634,073
How do I animate View.setVisibility(GONE)
<p>I want to make an <code>Animation</code> for when a <code>View</code> gets it's visibility set to <code>GONE</code>. Instead of just dissapearing, the <code>View</code> should 'collapse'. I tried this with a <code>ScaleAnimation</code> but then the <code>View</code> is collapse, but the layout will only resize it's space after (or before) the <code>Animation</code> stops (or starts).</p> <p>How can I make the <code>Animation</code> so that, while animating, the lower <code>View</code>s will stay directly below the content, instead of having a blank space?</p>
3,952,933
4
4
null
2010-04-14 00:10:59.607 UTC
59
2014-08-13 18:16:42.14 UTC
2010-04-14 21:49:56.777 UTC
null
120,309
null
120,309
null
1
84
android|animation
65,471
<p>There doesn't seem to be an easy way to do this through the API, because the animation just changes the rendering matrix of the view, not the actual size. But we can set a negative margin to fool LinearLayout into thinking that the view is getting smaller. </p> <p>So I'd recommend creating your own Animation class, based on ScaleAnimation, and overriding the "applyTransformation" method to set new margins and update the layout. Like this...</p> <pre><code>public class Q2634073 extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.q2634073); findViewById(R.id.item1).setOnClickListener(this); } @Override public void onClick(View view) { view.startAnimation(new MyScaler(1.0f, 1.0f, 1.0f, 0.0f, 500, view, true)); } public class MyScaler extends ScaleAnimation { private View mView; private LayoutParams mLayoutParams; private int mMarginBottomFromY, mMarginBottomToY; private boolean mVanishAfter = false; public MyScaler(float fromX, float toX, float fromY, float toY, int duration, View view, boolean vanishAfter) { super(fromX, toX, fromY, toY); setDuration(duration); mView = view; mVanishAfter = vanishAfter; mLayoutParams = (LayoutParams) view.getLayoutParams(); int height = mView.getHeight(); mMarginBottomFromY = (int) (height * fromY) + mLayoutParams.bottomMargin - height; mMarginBottomToY = (int) (0 - ((height * toY) + mLayoutParams.bottomMargin)) - height; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if (interpolatedTime &lt; 1.0f) { int newMarginBottom = mMarginBottomFromY + (int) ((mMarginBottomToY - mMarginBottomFromY) * interpolatedTime); mLayoutParams.setMargins(mLayoutParams.leftMargin, mLayoutParams.topMargin, mLayoutParams.rightMargin, newMarginBottom); mView.getParent().requestLayout(); } else if (mVanishAfter) { mView.setVisibility(View.GONE); } } } } </code></pre> <p>The usual caveat applies: because we are overriding a protected method (applyTransformation), this is not guaranteed to work in future versions of Android.</p>
52,882,119
Create React App not installing, showing an error and aborting installation
<p>I Reinstalled Node.js and Yarn. Now I am getting this error.</p> <p>My environment information is:</p> <blockquote> <p>Node: v8.12.0</p> <p>NPM: 6.4.1</p> <p>Yarn: 1.10.1</p> <p>OS: Windows 10</p> </blockquote> <pre><code>PS C:\Users\mdbel\Desktop\Project\redux&gt; npx create-react-app learnredux Creating a new React app in C:\Users\mdbel\Desktop\Project\redux\learnredux. Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts... yarn add v1.10.1 [1/4] Resolving packages... [2/4] Fetching packages... error An unexpected error occurred: &quot;https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.1.tgz: Request failed \&quot;404 Not Found\&quot;&quot;. info If you think this is a bug, please open a bug report with the information provided in &quot;C:\\Users\\mdbel\\Desktop\\Project\\redux\\learnredux\\yarn-error.log&quot;. info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command. Aborting installation. yarnpkg add --exact react react-dom react-scripts --cwd C:\Users\mdbel\Desktop\Project\redux\learnredux has failed. Deleting generated file... package.json Deleting generated file... yarn.lock Done. </code></pre>
59,962,639
18
1
null
2018-10-18 20:33:05.02 UTC
5
2022-02-21 20:10:49.153 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,114,949
null
1
14
node.js|reactjs|npm|create-react-app|yarnpkg
38,198
<p>removing <code>.npmrc</code> from <code>C:\Users\you\.npmrc</code> can also solve the problem.</p>
2,731,719
How can "this" of the outer class be accessed from an inner class?
<p>Is it possible to get a reference to <code>this</code> from within a Java inner class?</p> <p>i.e.</p> <pre><code>class Outer { void aMethod() { NewClass newClass = new NewClass() { void bMethod() { // How to I get access to "this" (pointing to outer) from here? } }; } } </code></pre>
2,731,729
5
0
null
2010-04-28 17:22:45.853 UTC
21
2018-10-22 18:39:46.08 UTC
2015-06-25 18:36:05.533 UTC
null
18,103
null
317,778
null
1
74
java|inner-classes
24,774
<p>You can access the instance of the outer class like this:</p> <pre><code>Outer.this </code></pre>
2,726,993
How to specify preference of library path?
<p>I'm compiling a c++ program using <code>g++</code> and <code>ld</code>. I have a <code>.so</code> library I want to be used during linking. However, a library of the same name exists in <code>/usr/local/lib</code>, and <code>ld</code> is choosing that library over the one I'm directly specifying. How can I fix this?</p> <p>For the examples below, my library file is <code>/my/dir/libfoo.so.0</code>. Things I've tried that don't work:</p> <ul> <li>my g++ command is <code>g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp</code></li> <li>adding <code>/my/dir</code> to the beginning or end of my <code>$PATH</code> en` variable</li> <li>adding <code>/my/dir/libfoo.so.0</code> as an argument to g++</li> </ul>
2,727,033
5
1
null
2010-04-28 05:17:06.657 UTC
57
2018-10-15 06:30:06.17 UTC
2017-01-03 06:29:39.94 UTC
null
3,980,929
null
218,386
null
1
112
c++|linker|g++
268,638
<p><strong>Add the path to where your new library is to <code>LD_LIBRARY_PATH</code> (it has slightly different name on Mac ...)</strong></p> <p>Your solution should work with using the <code>-L/my/dir -lfoo</code> options, at runtime use LD_LIBRARY_PATH to point to the location of your library.</p> <p><a href="https://www.hpc.dtu.dk/?page_id=1180" rel="noreferrer">Careful with using LD_LIBRARY_PATH</a> - in short (from link):<br/></p> <blockquote> <p>..implications..:<br/> <strong>Security</strong>: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable!<br/> <strong>Performance</strong>: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system!<br/> <strong>Inconsistency</strong>: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug.</p> </blockquote> <p>OR</p> <p>Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option):</p> <pre><code>-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH) </code></pre> <p>This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.</p> <p>If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:</p> <pre><code>LD_LIBRARY_PATH=/some/custom/dir ./fooo </code></pre> <p>You can check what libraries linker knows about using (example):</p> <pre><code>/sbin/ldconfig -p | grep libpthread libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) =&gt; /lib/libpthread.so.0 </code></pre> <p>And you can check which library your application is using:</p> <pre><code>ldd foo linux-gate.so.1 =&gt; (0xffffe000) libpthread.so.0 =&gt; /lib/libpthread.so.0 (0xb7f9e000) libxml2.so.2 =&gt; /usr/lib/libxml2.so.2 (0xb7e6e000) librt.so.1 =&gt; /lib/librt.so.1 (0xb7e65000) libm.so.6 =&gt; /lib/libm.so.6 (0xb7d5b000) libc.so.6 =&gt; /lib/libc.so.6 (0xb7c2e000) /lib/ld-linux.so.2 (0xb7fc7000) libdl.so.2 =&gt; /lib/libdl.so.2 (0xb7c2a000) libz.so.1 =&gt; /lib/libz.so.1 (0xb7c18000) </code></pre>
2,431,040
java outOfMemoryError with stringbuilder
<p>I'm getting a java outOfMemoryError when I call this method - i'm using it in a loop to parse many large files in sequence. my guess is that <code>result.toString()</code> is not getting garbage collected properly during the loop. if so, how should i fix it?</p> <pre><code>private String matchHelper(String buffer, String regex, String method){ Pattern abbrev_p = Pattern.compile(regex);//norms U.S.A., B.S., PH.D, PH.D. Matcher abbrev_matcher = abbrev_p.matcher(buffer); StringBuffer result = new StringBuffer(); while (abbrev_matcher.find()){ abbrev_matcher.appendReplacement(result, abbrevHelper(abbrev_matcher)); } abbrev_matcher.appendTail(result); String tempResult = result.toString(); //ERROR OCCURS HERE return tempResult; } </code></pre>
2,431,094
6
3
null
2010-03-12 07:06:59.723 UTC
6
2021-11-01 12:29:15.23 UTC
2021-11-01 12:29:15.23 UTC
null
5,459,839
null
276,712
null
1
8
java|string|out-of-memory|heap-memory|stringbuilder
38,227
<p>Written this way, you'll need roughly <strong>6</strong> bytes of memory for every character in the file. </p> <p>Each character is two bytes. You have the raw input, the substituted output (in the buffer), and you are asking for a third copy when you run out of memory.</p> <p>If the file is encoded in something like ASCII or ISO-8859-1 (a single-byte character encoding), that means it will be six times larger in memory than on disk.</p> <p>You could allocate more memory to the process, but a better solution might be to process the input "streamwise"&mdash;read, scan, and write the data without loading it all into memory at once.</p>
2,420,135
Hide HTML element by id
<p>Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript:</p> <pre><code> &lt;div class="nav" style="float: right;"&gt; &lt;ul&gt; &lt;li style="margin-right: 0px;" &gt; &lt;a id="nav-ask" href="/questions/ask"&gt;Ask Question&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I can't hide the <code>nav</code> class because other page elements use it.</p> <p>Can I hide the link element via the <code>nav-ask</code> id?</p>
2,420,166
6
2
null
2010-03-10 20:01:44.513 UTC
6
2015-02-01 16:27:52.057 UTC
2015-02-01 16:27:52.057 UTC
null
3,204,551
null
2,915
null
1
31
javascript|html|css
151,313
<pre><code>&lt;style type="text/css"&gt; #nav-ask{ display:none; } &lt;/style&gt; </code></pre>
2,681,243
How should I declare default values for instance variables in Python?
<p>Should I give my class members default values like this:</p> <pre><code>class Foo: num = 1 </code></pre> <p>or like this?</p> <pre><code>class Foo: def __init__(self): self.num = 1 </code></pre> <p>In <a href="https://stackoverflow.com/questions/2424451/about-python-class-and-instance-variables">this question</a> I discovered that in both cases,</p> <pre><code>bar = Foo() bar.num += 1 </code></pre> <p>is a well-defined operation.</p> <p>I understand that the first method will give me a class variable while the second one will not. However, if I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?</p> <p>One thing I've noticed is that in the Django tutorial, <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3" rel="noreferrer">they use the second method to declare Models.</a> Personally I think the second method is more elegant, but I'd like to know what the 'standard' way is.</p>
2,681,507
6
0
null
2010-04-21 08:11:40.563 UTC
38
2020-07-06 14:24:06.217 UTC
2017-05-23 11:46:55.12 UTC
null
-1
null
149,330
null
1
116
python|class|oop
167,086
<p>Extending bp's answer, I wanted to show you what he meant by immutable types.</p> <p>First, this is okay:</p> <pre><code>&gt;&gt;&gt; class TestB(): ... def __init__(self, attr=1): ... self.attr = attr ... &gt;&gt;&gt; a = TestB() &gt;&gt;&gt; b = TestB() &gt;&gt;&gt; a.attr = 2 &gt;&gt;&gt; a.attr 2 &gt;&gt;&gt; b.attr 1 </code></pre> <p>However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:</p> <pre><code>&gt;&gt;&gt; class Test(): ... def __init__(self, attr=[]): ... self.attr = attr ... &gt;&gt;&gt; a = Test() &gt;&gt;&gt; b = Test() &gt;&gt;&gt; a.attr.append(1) &gt;&gt;&gt; a.attr [1] &gt;&gt;&gt; b.attr [1] &gt;&gt;&gt; </code></pre> <p>Note that both <code>a</code> and <code>b</code> have a shared attribute. This is often unwanted.</p> <p>This is the Pythonic way of defining default values for instance variables, when the type is mutable:</p> <pre><code>&gt;&gt;&gt; class TestC(): ... def __init__(self, attr=None): ... if attr is None: ... attr = [] ... self.attr = attr ... &gt;&gt;&gt; a = TestC() &gt;&gt;&gt; b = TestC() &gt;&gt;&gt; a.attr.append(1) &gt;&gt;&gt; a.attr [1] &gt;&gt;&gt; b.attr [] </code></pre> <p>The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.</p>
2,435,695
Converting a md5 hash byte array to a string
<p>How can I convert the hashed result, which is a byte array, to a string?</p> <pre><code>byte[] bytePassword = Encoding.UTF8.GetBytes(password); using (MD5 md5 = MD5.Create()) { byte[] byteHashedPassword = md5.ComputeHash(bytePassword); } </code></pre> <p>I need to convert <code>byteHashedPassword</code> to a string. </p>
2,435,734
7
1
null
2010-03-12 20:35:43.557 UTC
11
2019-05-28 20:47:36.087 UTC
2019-05-28 20:47:36.087 UTC
null
2,224,584
null
39,677
null
1
88
c#|hash|cryptography|md5|cryptographic-hash-function
89,908
<pre><code> public static string ToHex(this byte[] bytes, bool upperCase) { StringBuilder result = new StringBuilder(bytes.Length*2); for (int i = 0; i &lt; bytes.Length; i++) result.Append(bytes[i].ToString(upperCase ? "X2" : "x2")); return result.ToString(); } </code></pre> <p>You can then call it as an extension method:</p> <pre><code>string hexString = byteArray.ToHex(false); </code></pre>
3,038,302
Why do ZeroMemory, etc. exist when there are memset, etc. already?
<p>Why does <code>ZeroMemory()</code>, and similar calls exist in the Windows API when there are memset and related calls in the C standard library already? Which ones should I call? I can guess the answer is "depends". On what?</p>
3,038,539
8
0
null
2010-06-14 15:04:56.073 UTC
3
2022-09-11 09:31:22.067 UTC
2018-10-01 21:42:47.497 UTC
null
3,204,551
null
113,748
null
1
32
c++|c|windows|winapi|memset
28,339
<p>In C and C++, <code>ZeroMemory()</code> and <code>memset()</code> are the exact same thing.</p> <pre><code>/* In winnt.h */ #define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length)) /* In winbase.h */ #define ZeroMemory RtlZeroMemory </code></pre> <p>Why use <code>ZeroMemory()</code> then? <a href="https://devblogs.microsoft.com/oldnewthing/20050628-07/?p=35183" rel="nofollow noreferrer">To make it obvious.</a> But I prefer <code>memset()</code> in C or C++ programs.</p>
2,579,734
Get the type name
<p>How i can get full right name of generic type?</p> <p>For example: This code </p> <pre><code>typeof(List&lt;string&gt;).Name </code></pre> <p>return </p> <blockquote> <p>List`1</p> </blockquote> <p>instead of </p> <pre><code>List&lt;string&gt; </code></pre> <h2>How to get a right name?</h2> <pre><code>typeof(List&lt;string&gt;).ToString() </code></pre> <p>returns System.Collections.Generic.List`1[System.String] but i want to get initial name:</p> <pre><code>List&lt;string&gt; </code></pre> <p>Is it real?</p>
2,579,755
10
1
null
2010-04-05 17:09:53.513 UTC
4
2019-09-07 13:20:26.777 UTC
2010-04-05 17:16:35.093 UTC
null
290,082
null
290,082
null
1
42
c#|generics
39,788
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.type.fullname.aspx" rel="noreferrer">FullName property</a>.</p> <pre><code>typeof(List&lt;string&gt;).FullName </code></pre> <p>That will give you the namespace + class + type parameters.</p> <p>What you are asking for is a C# specific syntax. As far as .NET is concerned, this is proper:</p> <pre><code>System.Collections.Generic.List`1[System.String] </code></pre> <p>So to get what you want, you'd have to write a function to build it the way you want it. Perhaps like so:</p> <pre><code>static string GetCSharpRepresentation( Type t, bool trimArgCount ) { if( t.IsGenericType ) { var genericArgs = t.GetGenericArguments().ToList(); return GetCSharpRepresentation( t, trimArgCount, genericArgs ); } return t.Name; } static string GetCSharpRepresentation( Type t, bool trimArgCount, List&lt;Type&gt; availableArguments ) { if( t.IsGenericType ) { string value = t.Name; if( trimArgCount &amp;&amp; value.IndexOf("`") &gt; -1 ) { value = value.Substring( 0, value.IndexOf( "`" ) ); } if( t.DeclaringType != null ) { // This is a nested type, build the nesting type first value = GetCSharpRepresentation( t.DeclaringType, trimArgCount, availableArguments ) + "+" + value; } // Build the type arguments (if any) string argString = ""; var thisTypeArgs = t.GetGenericArguments(); for( int i = 0; i &lt; thisTypeArgs.Length &amp;&amp; availableArguments.Count &gt; 0; i++ ) { if( i != 0 ) argString += ", "; argString += GetCSharpRepresentation( availableArguments[0], trimArgCount ); availableArguments.RemoveAt( 0 ); } // If there are type arguments, add them with &lt; &gt; if( argString.Length &gt; 0 ) { value += "&lt;" + argString + "&gt;"; } return value; } return t.Name; } </code></pre> <p>For these types (with true as 2nd param):</p> <pre><code>typeof( List&lt;string&gt; ) ) typeof( List&lt;Dictionary&lt;int, string&gt;&gt; ) </code></pre> <p>It returns:</p> <pre><code>List&lt;String&gt; List&lt;Dictionary&lt;Int32, String&gt;&gt; </code></pre> <p>In general though, I'd bet you probably don't <em>need</em> to have the C# representation of your code and perhaps if you do, some format better than the C# syntax would be more appropriate.</p>
33,743,493
Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?
<p>I have installed the Visual Studio 2015 and created Win32 project with some code. I compiled it successfully, but I can't launch exe file, because I don't have some ucrtbased.dll...So how can I solve it? </p> <p><a href="https://i.stack.imgur.com/g6vTC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g6vTC.png" alt="enter image description here"></a></p> <p>Edit: The English equivalent message is: "The program can't start because ucrtbased.dll is missing from your computer. Try reinstalling the program to fix this problem. "</p>
41,970,093
6
2
null
2015-11-16 19:55:03.54 UTC
19
2021-07-15 13:48:19.467 UTC
2017-01-04 09:43:31.237 UTC
null
28,411
null
5,175,197
null
1
47
visual-studio|visual-studio-2015|exe
131,714
<p>This problem is from VS 2015 silently failing to copy <code>ucrtbased.dll</code> (debug) and <code>ucrtbase.dll</code> (release) into the appropriate system folders during the installation of Visual Studio. (Or you did not select &quot;Common Tools for Visual C++ 2015&quot; during installation.) This is why reinstalling may help. However, reinstalling is an extreme measure... this can be fixed without a complete reinstall.</p> <p>First, if you don't really care about the underlying problem and just want to get this <em>one</em> project working quickly, then here is a fast solution: just copy <code>ucrtbased.dll</code> from <code>C:\Program Files (x86)\Windows Kits\10\bin\x86\ucrt\ucrtbased.dll</code> (for 32bit debug) into your application's \debug directory alongside the executable. Then it WILL be found and the error will go away. But, this will only work for this <em>one</em> project.</p> <p>A more permanent solution is to get <code>ucrtbased.dll</code> and <code>ucrtbase.dll</code> into the correct system folders. Now we could start copying these files into \Windows\System32 and \SysWOW64, and it <em>might</em> fix the problem. However, this isn't the best solution. There was a reason this failed in the first place, and forcing the use of specific .dll's this way could cause major problems.</p> <p>The best solution is to open up the control panel --&gt; Programs and Features --&gt; Microsoft Visual Studio 2015 --&gt; Modify. Then uncheck &quot;Visual C++ --&gt; Common Tools for Visual C++ 2015&quot;. Click Next, then and click Update, and after a few minutes, Common Tools should be uninstalled. Then repeat, but this time install the Common Tools. Make sure anti-virus is disabled, no other tasks are open, etc. and it should work. This is the best way to ensure that these files are copied exactly where they should be.</p> <hr /> <p><strong>Error Codes</strong>: Note that if the installer returns a cryptic error number such as -2147023293, you can convert this to hex using any of the free online decimal-to-hex converters. For this error it is 0xFFFFFFFF80070643 which, dropping the FF's and googling for &quot;0x80070643&quot;, means `0x80070643 - Installation cache or ISO is corrupted'.</p> <hr /> <p><strong>Why is <code>ucrtbased.dll</code> even needed?</strong>: Any DLL named &quot;<em>crt</em>&quot; is a &quot;C-Run-Time&quot; module or library. <a href="https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-library-features?view=msvc-160" rel="nofollow noreferrer">Microsoft explains them best</a>. There are many variants of CRT today. They contain essential helper-code used by all Microsoft compiled executables, to &quot;shim&quot; or help your executable operate on the ever-growing number of OS versions and hardware. If the MSVC compiler is used, the relevant CRT DLL is linked automatically at compile-time. (If the DLL cannot be found at compile-time, then a linking error is generated.)</p> <p>One way to <strong>not</strong> require the DLL, is to &quot;statically-link&quot; it to your project. This means that you essentially take the contents of <code>ucrtbased.dll</code>, and <em>include it</em> in your executable. Your file size will grow by approximately the size of <code>ucrtbased.dll</code>.</p> <p>Incidentally, if you've ever run a MSVC program (usually from another individual, one of your old compiled programs from a previous OS version, or yours from a different machine) and it does not start, giving an error message of needing &quot;Microsoft Visual C++ 20xx Redistributable&quot; or &quot;run-time&quot; - then it means it can't find the needed <code>*crt*.dll</code> file. Installing that particular redistributable package (if known) will install the DLL, and allow the program to run... or at least get past that error and alert you of another missing DLL.</p> <p>If you find yourself in this &quot;DLL Hell&quot; predicament, google &quot;dependency walker&quot; for an advanced tool to show which DLLs are still missing. This usually doesn't happen with professional software, simply because their (large, bundled) installers check for any missing dependent libraries (including CRT) and installs them first.</p>
30,893,225
IE Input type Date not appearing as Date Picker
<p>I am using the input type DATE in my HTML and everything works fine in Chrome and Firefox, but IE does not show the date picker.</p> <p>When I use the JQuery Datepicker I get two date picker dialogs in Chrome and Firefox.</p> <p>How can I fix the functionality where I can have the date input type and only have one popup for my form?</p>
30,893,387
1
0
null
2015-06-17 13:34:47.367 UTC
2
2019-04-15 00:46:21.513 UTC
2017-02-09 14:28:16.43 UTC
null
487,670
null
487,670
null
1
6
internet-explorer|date|datepicker
38,899
<p>You need to use a <a href="https://en.wikipedia.org/wiki/Polyfill_(programming)" rel="nofollow noreferrer">polyfill</a> so that the input type DATE has a consistent behaviour in all browsers. You can use this <a href="http://afarkas.github.io/webshim/demos/index.html" rel="nofollow noreferrer">webshim</a> as a polyfill.</p> <p>Input type DATE is an HTML5 feature which is not supported by all browsers. In case you want to use the HTML5 feature not supported by your browser (which usually will be IE) then use two things:</p> <ul> <li>Feature Detection</li> <li>Polyfills</li> </ul> <p>Feature Detection is the ability to determine if the HTML5 feature is supported or not by our browser. A good library for that is <a href="http://modernizr.com/" rel="nofollow noreferrer">Modernizr</a>. What you can do with modernizr is to detect if any feature that you need is not supported and if not then you can conditionally load some javascript libraries that will implement that feature. Those libraries are called <a href="https://en.wikipedia.org/wiki/Polyfill_(programming)" rel="nofollow noreferrer">Polyfills</a>.</p> <p>So for example if you want to use the tag in IE 10 you could use the jqueryui.com controls to provide a date picker.</p> <pre><code>Modernizr.load({ test: Modernizr.inputtypes.date, nope: "js/jquery-ui.custom.js", callback: function() { $("input[type=date]").datepicker(); } }); </code></pre> <p>Modernizr tests if the feature is supported, optionally you can use the nope to indicate if there is a library that you want to load ONLY if the feature is not supported, and callback is the code that will be called after the test and after loading the library.</p>
23,226,888
Horizontal list items - fit to 100% with even spacing
<p>I have a simple list and i am trying to get the list items to be evenly spaced horizontally, but still fill 100% of the width of the container regardless of the width of the container.</p> <p>I do not want each list item to be of equal width, but instead the spacing between each list item to be even:</p> <p>jsfiddle: <a href="http://jsfiddle.net/b6muX/1/">http://jsfiddle.net/b6muX/1/</a></p> <p>Also the number of list items might be dynamic and not the same as the number in my example.</p> <p>Can this be done without js?</p> <p>Here is my markup and css:</p> <pre><code>&lt;ul&gt; &lt;li&gt;This is menu item 1&lt;/li&gt; &lt;li&gt;Number 2&lt;/li&gt; &lt;li&gt;Item Number 3&lt;/li&gt; &lt;li&gt;Menu 4&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>and the following css:</p> <pre><code>ul { width: 100%; background: #cacaca; margin: 0; padding: 0; } li { list-style-type: none; display: inline-block; padding-right: 10%; width: auto; margin-right: 0.5%; background: #fafafa; padding-left: 0; margin-left: 0; } li:last-child { margin-right: 0; padding-right: 0; } </code></pre>
23,226,961
1
0
null
2014-04-22 17:56:23.633 UTC
20
2016-10-17 15:26:44.143 UTC
null
null
null
null
1,189,880
null
1
39
html|css|responsive-design
83,338
<p>The new CSS flexbox specification would be the solution to your problem :) </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul { display: flex; align-items: stretch; /* Default */ justify-content: space-between; width: 100%; background: #cacaca; margin: 0; padding: 0; } li { display: block; flex: 0 1 auto; /* Default */ list-style-type: none; background: #fafafa; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;This is menu item 1&lt;/li&gt; &lt;li&gt;Number 2&lt;/li&gt; &lt;li&gt;Item Number 3&lt;/li&gt; &lt;li&gt;Menu 4&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>See also: <a href="http://jsfiddle.net/teddyrised/b6muX/3/" rel="noreferrer">http://jsfiddle.net/teddyrised/b6muX/3/</a></p> <p>If you would allow me to indulge myself in a bit of explanation:</p> <ol> <li><code>display: flex</code> on the parent tells the parent to adopt the CSS flexbox model</li> <li><code>align-items: stretch</code> tells the parent that its children should stretch to the full height of the row. This is the default value of the property.</li> <li><code>justify-content: space-between</code> is the <strong>magic</strong> here &mdash; it instructs the parent to distribute remaining space left after laying out the children between them.</li> </ol> <p>On the children:</p> <ol> <li><code>flex: 0 1 auto</code> on the children tells them that: <ul> <li><code>flex-grow: 0</code>: Do no grow, otherwise they will fill up the parent</li> <li><code>flex-shrink: 1</code>: Shrink when necessary, to prevent overflowing (you can turn this off by setting to 0.</li> <li><code>flex-basis: auto</code>: Widths of children element are calculated automatically based on their content. If you want fixed, equal width children element, simply set it to <code>100%</code>.</li> </ul></li> </ol> <p>You can adjust the padding to the <code>&lt;li&gt;</code> element as of when you see please.</p> <hr> <h2>Old CSS method: <code>text-align: justify</code></h2> <p>The old method, while working perfectly, is a little more cumbersome as it requires you to reset the font-size in the unordered list element to eliminate spacing between child elements. It also requires you to render an pseudo-element to ensure that the content overflows the first row for text justification to kick in (remember that the default behavior of justified text is that a row that is not 100% will not be justified).</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul { font-size: 0; /* Eliminate spacing between inline block elements */ text-align: justify; width: 100%; background: #cacaca; list-style: none; margin: 0; padding: 0; } ul:after { content: 'abc'; display: inline-block; width: 100%; height: 0; } li { display: inline-block; background: #fafafa; font-size: 1rem; /* Reuse root element's font size */ } p { font-size: 1rem; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;This is menu item 1&lt;/li&gt; &lt;li&gt;Number 2&lt;/li&gt; &lt;li&gt;Item Number 3&lt;/li&gt; &lt;li&gt;Menu 4&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>See also: <a href="http://jsfiddle.net/teddyrised/b6muX/5/" rel="noreferrer">http://jsfiddle.net/teddyrised/b6muX/5/</a></p>
32,190,881
How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?
<p>This is running on Windows Server 2008 and used to work several months ago. I am just now using this server again for some dev work with VS.</p> <p>This is live web server used to serve up a few test sites as well.</p> <p>This came up when running Visual Studio, then launching my projects for debugging.</p> <p>Trying to launch any site through <code>localhost:xxxx</code> when IISExpress has been launched (using actual port #'s in the config to access different sites):</p> <pre><code>This webpage is not available ERR_CONNECTION_REFUSED </code></pre> <p>I have been at this for a few days already, as I have read others have had similar issues, tried <a href="https://stackoverflow.com/questions/15584862/iis-express-not-working-in-visual-studio-2012">most things</a> I have read including changing the <code>managedruntimeversion</code> from "v4.0" to "v4.0.30319" for .net 4.5 (I have never had to do this before) and disabling the logging module (all suggestions found <a href="https://stackoverflow.com/questions/15584862/iis-express-not-working-in-visual-studio-2012">here</a>).</p> <p>There are only two entries in my <code>hosts</code> file that point to internal server IP addresses. No <code>localhost</code> related IP's or references.</p> <p>I have gone as far as re-installing IIS Express, and Visual Studio 2013. I also created a brand new <code>WebApplication</code> site to try to resolve this (simple and no other complicated bindings).</p> <p>When I spin up Fiddler, I see the following on the page:</p> <pre><code>[Fiddler] The socket connection to localhost failed. ErrorCode: 10061. No connection could be made because the target machine actively refused it 127.0.0.1:23162 </code></pre> <p><a href="https://i.stack.imgur.com/5JEJu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5JEJu.png" alt="Fiddler capture"></a></p> <p>I have removed all proxy settings from IE's LAN connection section, where before I was getting a <em>red-x</em> popup in VS indicating something like <em>IISExpress could not launch</em>.</p> <p>This is not a matter of SSL vs non SSL.</p> <p>I had TFS Server installed - uninstalled that in case there were some odd bindings that were interfering.</p> <p>I tried deleting the IISExpress config/settings folder several times.</p> <p>Current <em>applicationhost.config</em> contains:</p> <pre><code>&lt;site name="WebApplication1" id="4"&gt; &lt;application path="/" applicationPool="Clr4IntegratedAppPool"&gt; &lt;virtualDirectory path="/" physicalPath="C:\TFS-WorkRepository\Sandbox\WebApplication1\WebApplication1" /&gt; &lt;/application&gt; &lt;bindings&gt; &lt;binding protocol="http" bindingInformation="*:23162:localhost" /&gt; &lt;/bindings&gt; &lt;/site&gt; &lt;siteDefaults&gt; &lt;logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" /&gt; &lt;traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" /&gt; &lt;/siteDefaults&gt; &lt;applicationDefaults applicationPool="Clr4IntegratedAppPool" /&gt; </code></pre> <p>I wish there was a tag for <code>really-stuck</code>.</p> <p>Please suggest away, as I don't want to go as far as spinning up a new server.</p> <p><strong>-- UPDATE --</strong></p> <p>In the URL bar, when I enter the computer name or IP address :xxxx I get the <code>ERR_CONNECTION_TIMED_OUT</code> rather than <code>ERR_CONNECTION_REFUSED</code>.</p>
35,418,904
23
1
null
2015-08-24 20:09:09.573 UTC
17
2022-04-28 11:55:21.107 UTC
2017-07-11 09:35:21.4 UTC
null
1,842,261
null
172,359
null
1
112
visual-studio|localhost|iis-express
502,275
<p>Try changing the port number in your project?</p> <p>Project Properties → Web → Servers → Project Url:</p> <p><a href="https://i.stack.imgur.com/cg3uW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cg3uW.png" alt="enter image description here"></a></p> <p>Don't forget to click <code>Create Virtual Directory</code>, or reply "Yes" to the prompt for creating virtual directory after you change your port number! (Thanks <a href="https://stackoverflow.com/questions/32190881/how-to-solve-err-connection-refused-when-trying-to-connect-to-localhost-running#comment78845581_35418904">Connor</a>)</p> <p>Note: I'm a little reluctant to post this as an answer, as I have no idea what the issue is or what caused it, but I had a similar issue, and changing the port number did the trick for me. I'm only posting this per the suggestion in the comments that this worked for someone else as well.</p> <p>In my case, it seemed like something was conflicting with the specific port number I was using, so I changed to a different one, and my site popped right back up! I'm not sure what that means for the old port number, or if I'll ever be able to use it again. Maybe someone more knowledgeable than myself can chime in on this.</p>
35,618,998
How to implement Bottom Sheets using new design support library 23.2
<p>Google release the new update to support library 23.2 in that they added bottom sheet feature. Can any one tell how to implement that bottom sheet using that library.</p>
35,620,244
4
1
null
2016-02-25 05:21:19.483 UTC
15
2017-03-17 09:57:08.513 UTC
null
null
null
null
2,586,055
null
1
32
android|android-support-library|android-support-design
38,938
<p><a href="https://i.stack.imgur.com/Mi8y6.png"><img src="https://i.stack.imgur.com/Mi8y6.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/FYdNb.png"><img src="https://i.stack.imgur.com/FYdNb.png" alt="enter image description here"></a></p> <p>use layout like below</p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"&gt; &lt;android.support.design.widget.AppBarLayout&gt; &lt;android.support.design.widget.CollapsingToolbarLayout&gt; &lt;ImageView/&gt; &lt;android.support.v7.widget.Toolbar/&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"&gt; &lt;LinearLayout&gt; //..... &lt;/LinearLayout&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;FrameLayout android:id="@+id/bottom_sheet" android:layout_width="match_parent" android:layout_height="wrap_content" app:behavior_hideable="true" app:layout_behavior="android.support.design.widget.BottomSheetBehavior"&gt; //your bottom sheet layout &lt;/LinearLayout&gt; &lt;/FrameLayout&gt; &lt;android.support.design.widget.FloatingActionButton/&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <hr> <p>in Activity</p> <pre><code>CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content); // The View with the BottomSheetBehavior View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet); final BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet); behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { // React to state change Log.e("onStateChanged", "onStateChanged:" + newState); if (newState == BottomSheetBehavior.STATE_EXPANDED) { fab.setVisibility(View.GONE); } else { fab.setVisibility(View.VISIBLE); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { // React to dragging events Log.e("onSlide", "onSlide"); } }); behavior.setPeekHeight(100); </code></pre>
36,816,788
How do I call an Angular 2 pipe with multiple arguments?
<p>I know I can call a pipe like this:</p> <pre><code>{{ myData | date:'fullDate' }} </code></pre> <p>Here the date pipe takes only one argument. What is the syntax to call a pipe with more parameters, from component's template HTML and directly in code?</p>
36,816,789
6
0
null
2016-04-23 21:41:45.09 UTC
43
2022-04-04 14:05:59.063 UTC
2016-12-21 19:44:13.767 UTC
null
5,862,315
null
5,862,315
null
1
308
javascript|angular|angular2-pipe
277,684
<p>In your component's template you can use multiple arguments by separating them with colons:</p> <pre><code>{{ myData | myPipe: 'arg1':'arg2':'arg3'... }} </code></pre> <p>From your code it will look like this:</p> <pre><code>new MyPipe().transform(myData, arg1, arg2, arg3) </code></pre> <p>And in your transform function inside your pipe you can use the arguments like this:</p> <pre><code>export class MyPipe implements PipeTransform { // specify every argument individually transform(value: any, arg1: any, arg2: any, arg3: any): any { } // or use a rest parameter transform(value: any, ...args: any[]): any { } } </code></pre> <p><strong>Beta 16 and before (2016-04-26)</strong></p> <p>Pipes take an array that contains all arguments, so you need to call them like this:</p> <pre><code>new MyPipe().transform(myData, [arg1, arg2, arg3...]) </code></pre> <p>And your transform function will look like this:</p> <pre><code>export class MyPipe implements PipeTransform { transform(value:any, args:any[]):any { var arg1 = args[0]; var arg2 = args[1]; ... } } </code></pre>
46,725,357
Firestore - batch.add is not a function
<p>The <a href="https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes" rel="noreferrer">documentation</a> for Firestore batch writes lists only <code>set()</code>, <code>update()</code> and <code>delete()</code> as permitted operations.</p> <p>Is there no way to add an <code>add()</code> operation to the batch? I need a document to be created with an auto-generated id.</p>
46,739,496
9
0
null
2017-10-13 08:08:20.93 UTC
10
2022-03-11 11:35:15.367 UTC
null
null
null
null
2,131,598
null
1
80
google-cloud-firestore
24,249
<p>You can do this in two steps:</p> <pre><code>// Create a ref with auto-generated ID var newCityRef = db.collection('cities').doc(); // ... // Add it in the batch batch.set(newCityRef, { name: 'New York City' }); </code></pre> <p>The <code>.doc()</code> method does not write anything to the network or disk, it just makes a reference with an auto-generated ID you can use later.</p>
8,813,265
Why doesn't ignorecase flag (re.I) work in re.sub()
<p>From pydoc:</p> <blockquote> <p>re.sub = sub(pattern, repl, string, count=0, flags=0)<br> Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.</p> </blockquote> <p>example code:</p> <pre><code>import re print re.sub('class', 'function', 'Class object', re.I) </code></pre> <p>No replacement is made unless I change pattern to 'Class'. </p> <p>Documentation doesn't mention anything about this limitation, so I assume I may be doing something wrong. </p> <p>What's the case here?</p>
8,813,281
5
0
null
2012-01-11 02:04:45.513 UTC
8
2019-11-26 12:34:43.007 UTC
null
null
null
null
992,005
null
1
60
python|regex
35,096
<p>Seems to me that you should be doing:</p> <pre><code>import re print(re.sub('class', 'function', 'Class object', flags=re.I)) </code></pre> <p>Without this, the <code>re.I</code> argument is passed to the <code>count</code> argument.</p>
38,862,101
How do I share Protocol Buffer .proto files between multiple repositories
<p>We are considering using <a href="https://developers.google.com/protocol-buffers/" rel="noreferrer">Protocol Buffers</a> for communicating between a python &amp; a node.js service that each live in their own repos. </p> <p>Since the <code>.proto</code> files must be accessible to both repos, how should we share the <code>.proto</code> files? </p> <p>We are currently considering:</p> <ol> <li>Creating a repo for all our <code>.proto</code> files, and making it a git subtree of all our services</li> <li>Creating a repo for all our <code>.proto</code> files, publishing both a private python module and private node module on push, and requiring the modules from the respective services</li> <li>Creating a repo for all our <code>.proto</code> files, and specifying the repository as the destination of a <code>pip</code> / <code>npm</code> package</li> </ol> <p>What is the standard way to share <code>.proto</code> files between repositories?</p>
38,866,138
2
0
null
2016-08-09 23:41:03.533 UTC
6
2016-08-10 19:30:06.503 UTC
2016-08-10 00:04:36.057 UTC
null
475,505
null
475,505
null
1
33
python|node.js|git|protocol-buffers
8,788
<p>This depends on your development process.</p> <p>A git subtree / submodule seems like a sensible solution for most purposes. If you had more downstream projects, publishing a ready-made module would make sense, as then the protobuf generator wouldn't be needed for every project.</p>
27,568,265
Neo4j super node issue - fanning out pattern
<p>I'm new to the Graph Database scene, looking into Neo4j and learning Cypher, we're trying to model a graph database, it's a fairly simple one, we got <em>users</em>, and we got <em>movies</em>, <em>users</em> can <strong>VIEW</strong> <em>movies</em>, <strong>RATE</strong> <em>movies</em>, create <em>playlists</em> and <em>playlists</em> can <strong>HAVE</strong> <em>movies</em>.</p> <p>The question is regarding the Super Node performance issue. And I will quote something from a very good book I am currently reading - <em>Learning Neo4j by Rik Van Bruggen</em>, so here it is:</p> <blockquote> <p>A very interesting problem then occurs in datasets where some parts of the graph are all connected to the same node. This node, also referred to as a dense node or a supernode, becomes a real problem for graph traversals because the graph database management system will have to evaluate all of the connected relationships to that node in order to determine what the next step will be in the graph traversal. </p> </blockquote> <p>The solution to this problem proposed in the book is to have a Meta node with 100 connections to it, and the 101th connection to be linked to a new Meta node that is linked to the previous Meta Node.</p> <h2><img src="https://i.stack.imgur.com/DMQGs.png" alt="DENSE_LIKES fanning out"></h2> <p>I have seen a blog post from the official Neo4j Blog saying that they will fix this problem in the upcoming future (the blog post is from January 2013) - <a href="http://neo4j.com/blog/2013-whats-coming-next-in-neo4j/" rel="noreferrer">http://neo4j.com/blog/2013-whats-coming-next-in-neo4j/</a></p> <p>More exactly they say:</p> <blockquote> <p>Another project we have planned around “bigger data” is to add some specific optimizations to handle traversals across densely-connected nodes, having very large numbers (millions) of relationships. (This problem is sometimes referred to as the “supernodes” problem.)</p> </blockquote> <p>What are your opinions on this issue? Should we go with the Meta node fanning-out pattern or go with the basic relationship that every tutorial seem to be using? Any other suggestions?</p>
27,569,672
3
0
null
2014-12-19 14:41:16.287 UTC
14
2020-10-19 13:09:19.857 UTC
2014-12-19 14:48:29.08 UTC
null
991,683
null
991,683
null
1
26
performance|neo4j|cypher|graph-databases|node-neo4j
4,457
<p><strong>UPDATE - October 2020</strong>. <a href="https://medium.com/neo4j/graph-modeling-all-about-super-nodes-d6ad7e11015b" rel="nofollow noreferrer">This article is the best source on this topic</a>, covering all aspects of super nodes</p> <p>(my original answer below)</p> <p>It's a good question. This isn't really an answer, but why shouldn't we be able to discuss this here? Technically I think I'm supposed to flag your question as &quot;primarily opinion based&quot; since you're explicitly soliciting opinions, but I think it's worth the discussion.</p> <p>The boring but honest answer is that it always depends on your query patterns. Without knowing what kinds of queries you're going to issue against this data structure, there's really no way to know the &quot;best&quot; approach.</p> <p>Supernodes are problems in other areas as well. Graph databases sometimes are very difficult to scale in some ways, because the data in them is hard to partition. If this were a relational database, we could partition vertically or horizontally. In a graph DB when you have supernodes, everything is &quot;close&quot; to everything else. (An Alaskan farmer likes Lady Gaga, so does a New York banker). Moreso than just graph traversal speed, supernodes are a big problem for all sorts of scalability.</p> <p>Rik's suggestion boils down to encouraging you to create &quot;sub-clusters&quot; or &quot;partitions&quot; of the super-node. For certain query patterns, this might be a good idea, and I'm not knocking the idea, but I think hidden in here is the notion of a clustering strategy. How many meta nodes do you assign? How many max links per meta-node? How did you go about assigning this user to this meta node (and not some other)? Depending on your queries, those questions are going to be very hard to answer, hard to implement correctly, or both.</p> <p>A different (but conceptually very similar) approach is to clone Lady Gaga about a thousand times, and duplicate her data and keep it in sync between nodes, then assert a bunch of &quot;same as&quot; relationships between the clones. This isn't that different than the &quot;meta&quot; approach, but it has the advantage that it copies Lady Gaga's data to the clone, and the &quot;Meta&quot; node isn't just a dumb placeholder for navigation. Most of the same problems apply though.</p> <p>Here's a different suggestion though: you have a large-scale many-to-many mapping problem here. It's possible that if this is a really huge problem for you, you'd be better off breaking this out into a single relational table with two columns <code>(from_id, to_id)</code>, each referencing a neo4j node ID. You then might have a hybrid system that's mostly graph (but with some exceptions). Lots of tradeoffs here; of course you couldn't traverse that rel in cypher at all, but it would scale and partition much better, and querying for a particular rel would probably be much faster.</p> <p>One general observation here: whether we're talking about relational, graph, documents, K/V databases, or whatever -- when the databases get really big, and the performance requirements get really intense, it's almost inevitable that people end up with some kind of a hybrid solution with more than one kind of DBMS. This is because of the inescapable reality that all databases are good at some things, and not good at others. So if you need a system that's good at most everything, you're going to have to use more than one kind of database. :)</p> <p>There is probably quite a bit neo4j can do to optimize in these cases, but it would seem to me that the system would need some kinds of hints on access patterns in order to do a really good job at that. Of the 2,000,000 relations present, how to the endpoints best cluster? Are older relationships more important than newer, or vice versa?</p>
34,803,565
How to send a value from one component to another?
<p>I make a componenet in which I have one input field and button.On click of button I am diplaying the second component.I want to send data from one component to another component ?</p> <p>how I will send data from one component to another ..I need to send input value (what ever user type in input field ) I need to show on next component or next page .On button click .how to send data ? here is my plunker <a href="http://plnkr.co/edit/IINX8Zq8J2LUTIyf4DYD?p=preview" rel="noreferrer">http://plnkr.co/edit/IINX8Zq8J2LUTIyf4DYD?p=preview</a></p> <pre><code>import {Component,View} from 'angular2/core'; import {Router} from 'angular2/router'; @Component({ templateUrl: 'home/home.html' }) export class AppComponent { toDoModel; constructor(private _router:Router) { } onclck(inputValue){ alert(inputValue) this._router.navigate(['Second']); } } </code></pre>
34,807,178
3
0
null
2016-01-15 02:44:44.15 UTC
10
2019-01-14 12:24:45.487 UTC
2016-03-06 16:41:44.983 UTC
null
217,408
null
3,701,974
null
1
10
angular|angular2-routing|angular2-template|angular2-directives
57,964
<p>Oh!! may be I' m too late to answer the question! But never mind.This might help you or other to share data between components using Router,Shared-Service and Shared-object used withing shared-service. I hope this will surely help.</p> <p><a href="http://plnkr.co/edit/RRE6rGGVkHrgTIwzdXxc?p=preview">Answer</a></p> <p><strong>Boot.ts</strong></p> <pre><code>import {Component,bind} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router'; import {SharedService} from 'src/sharedService'; import {ComponentFirst} from 'src/cone'; import {ComponentTwo} from 'src/ctwo'; @Component({ selector: 'my-app', directives: [ROUTER_DIRECTIVES], template: ` &lt;h1&gt; Home &lt;/h1&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; `, }) @RouteConfig([ {path:'/component-first', name: 'ComponentFirst', component: ComponentFirst} {path:'/component-two', name: 'ComponentTwo', component: ComponentTwo} ]) export class AppComponent implements OnInit { constructor(router:Router) { this.router=router; } ngOnInit() { console.log('ngOnInit'); this.router.navigate(['/ComponentFirst']); } } bootstrap(AppComponent, [SharedService, ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname) ]); </code></pre> <p><strong>FirstComponent</strong></p> <pre><code>import {Component,View,bind} from 'angular2/core'; import {SharedService} from 'src/sharedService'; import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router'; @Component({ //selector: 'f', template: ` &lt;div&gt;&lt;input #myVal type="text" &gt; &lt;button (click)="send(myVal.value)"&gt;Send&lt;/button&gt; `, }) export class ComponentFirst { constructor(service:SharedService,router:Router){ this.service=service; this.router=router; } send(str){ console.log(str); this.service.saveData(str); console.log('str'); this.router.navigate(['/ComponentTwo']); } } </code></pre> <p><strong>SecondComponent</strong></p> <pre><code>import {Component,View,bind} from 'angular2/core'; import {SharedService} from 'src/sharedService'; import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router'; @Component({ //selector: 'f', template: ` &lt;h1&gt;{{myName}}&lt;/h1&gt; &lt;button (click)="back()"&gt;Back&lt;button&gt; `, }) export class ComponentTwo { constructor(router:Router,service:SharedService) { this.router=router; this.service=service; console.log('cone called'); this.myName=service.getData(); } back() { console.log('Back called'); this.router.navigate(['/ComponentFirst']); } } </code></pre> <p><strong>SharedService and shared Object</strong></p> <pre><code>import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core' // Name Service export interface myData { name:string; } @Injectable() export class SharedService { sharingData: myData={name:"nyks"}; saveData(str){ console.log('save data function called' + str + this.sharingData.name); this.sharingData.name=str; } getData:string() { console.log('get data function called'); return this.sharingData.name; } } </code></pre>
35,013,383
ItemDecoration based on viewtype in recyclerview
<p>I have multiple <em>view types</em> in my <code>RecyclerView</code> and I want to add an <code>ItemDecoration</code> based on the views type. Is there a way to do this?</p> <p>This will add a decoration to every element:</p> <pre><code>recyclerView.addItemDecoration(decoration); </code></pre> <p>I saw this <a href="https://github.com/magiepooh/RecyclerItemDecoration" rel="noreferrer">library</a> but it supports only <code>LinearLayoutManager</code> vertical or horizontal, but I am using <code>GrildLayoutManager</code> and I use drawables for dividers.</p>
35,013,727
4
0
null
2016-01-26 11:59:43.873 UTC
9
2020-09-21 23:01:00.087 UTC
2016-01-26 18:22:45 UTC
null
1,837,367
null
3,531,883
null
1
21
java|android|android-recyclerview
18,459
<p>Yes, you can.</p> <p>If you draw the decoration yourself, you can distinguish between different view types in <code>getItemOffsets</code> and <code>onDraw</code> by accessing the same method on the adapter like this:</p> <pre><code>// get the position int position = parent.getChildAdapterPosition(view); // get the view type int viewType = parent.getAdapter().getItemViewType(position); </code></pre> <p>Using this, you can draw your decoration only for your selected views. By accessing <code>getLeft()</code> and <code>getRight()</code> that code supports <code>GridLayout</code> as well as <code>LinearLayout</code>, to support <em>horizontal</em> alignment, the drawing just has to be done on the right side using the same approach.</p> <p>In the end, you would create a decoration like the following:</p> <pre><code>public class DividerDecoration extends RecyclerView.ItemDecoration { private final Paint mPaint; private int mHeightDp; public DividerDecoration(Context context) { this(context, Color.argb((int) (255 * 0.2), 0, 0, 0), 1f); } public DividerDecoration(Context context, int color, float heightDp) { mPaint = new Paint(); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(color); mHeightDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, heightDp, context.getResources().getDisplayMetrics()); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); int viewType = parent.getAdapter().getItemViewType(position); if (viewType == MY_VIEW_TYPE) { outRect.set(0, 0, 0, mHeightDp); } else { outRect.setEmpty(); } } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { for (int i = 0; i &lt; parent.getChildCount(); i++) { View view = parent.getChildAt(i); int position = parent.getChildAdapterPosition(view); int viewType = parent.getAdapter().getItemViewType(position); if (viewType == MY_VIEW_TYPE) { c.drawRect(view.getLeft(), view.getBottom(), view.getRight(), view.getBottom() + mHeightDp, mPaint); } } } } </code></pre> <p>There is a similar <a href="https://github.com/bleeding182/recyclerviewItemDecorations/blob/master/app/src/main/java/com/github/bleeding182/recyclerviewdecorations/DividerDecoration.java" rel="noreferrer">sample on GitHub</a> with a demo project, which will not draw before or after header views or at the very end.</p>
28,989,605
Add Metadata, headers (Expires, CacheControl) to a file uploaded to Amazon S3 using the Laravel 5.0 Storage facade
<p>I am trying to find out how to add in Metadata or headers (Expires, CacheControl etc.) to a file uploaded using the Laravel 5.0 Storage facade. I have use the page here as reference.</p> <p><a href="http://laravel.com/docs/5.0/filesystem" rel="noreferrer">http://laravel.com/docs/5.0/filesystem</a></p> <p>The following code works correctly:</p> <pre><code>Storage::disk('s3')-&gt;put('/test.txt', 'test'); </code></pre> <p>After digging I also found that there is a 'visibility' parameter which sets the ACL to 'public-read' so the following also works correctly.</p> <pre><code>Storage::disk('s3')-&gt;put('/test.txt', 'test', 'public'); </code></pre> <p>But I would like to be able to set some other values to the header of the file. I have tried the following:</p> <pre><code>Storage::disk('s3')-&gt;put('/index4.txt', 'test', 'public', array('Expires'=&gt;'Expires, Fri, 30 Oct 1998 14:19:41 GMT')); </code></pre> <p>Which doesn't work, I have also tried:</p> <pre><code>Storage::disk('s3')-&gt;put('/index4.txt', 'test', array('ACL'=&gt;'public-read')); </code></pre> <p>But that creates an error where the 'visibility' parameter can not be converted from a string to an array. I have checked the source of AwsS3Adapter and it seems there is code for options but I can not seem to see how to pass them correctly. I think it takes the following:</p> <pre><code>protected static $metaOptions = [ 'CacheControl', 'Expires', 'StorageClass', 'ServerSideEncryption', 'Metadata', 'ACL', 'ContentType', 'ContentDisposition', 'ContentLanguage', 'ContentEncoding', ]; </code></pre> <p>Any help on how to accomplish this would be appreciated.</p>
30,355,563
10
0
null
2015-03-11 14:41:32.187 UTC
11
2022-08-18 11:44:36.303 UTC
2015-03-13 18:00:44.37 UTC
null
1,178,974
null
3,333,232
null
1
29
php|amazon-s3|laravel-5|flysystem
16,642
<p>First, you need to call <code>getDriver</code> so you can send over an array of options. And then you need to send the options as an array.</p> <p>So for your example:</p> <pre><code>Storage::disk('s3')-&gt;getDriver()-&gt;put('/index4.txt', 'test', [ 'visibility' =&gt; 'public', 'Expires' =&gt; 'Expires, Fri, 30 Oct 1998 14:19:41 GMT']); </code></pre> <p>Be aware that if you're setting <code>Cache-Control</code> it has to be passed as <code>CacheControl</code>. This may well be true for other keys with non-alphanumierc characters.</p>
29,192,579
Fixed UISearchBar using UISearchController - Not using header view of UITableView
<p>Is it possible to put UISearchBar of UISearchController somewhere other than header view of UITableView?</p> <p>In the <a href="https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html" rel="noreferrer">apple's sample code for UISearchController</a>, following is used.</p> <pre><code>[self.searchController.searchBar sizeToFit]; self.tableView.tableHeaderView = self.searchController.searchBar; </code></pre> <p>Is it possible to position searchBar somewhere else? Say we want to implement a fixed UISearchBar like the one used in contacts app. I've tried this but the searchBar doesn't appear at all.</p>
29,193,911
3
0
null
2015-03-22 08:58:03.767 UTC
8
2018-09-22 10:04:33.083 UTC
2016-05-12 15:49:09.37 UTC
null
750,510
null
2,541,555
null
1
14
ios|uisearchbar|uisearchcontroller
9,495
<p>You can place the UISearchBar of UISearchController in the navigation bar so that it remains fixed</p> <pre><code>self.searchController.hidesNavigationBarDuringPresentation = NO; self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal; // Include the search bar within the navigation bar. self.navigationItem.titleView = self.searchController.searchBar; self.definesPresentationContext = YES; </code></pre>
27,129,169
Android Studio - running a build collapses all the folders in the Project browser?
<p>I've been developing on Eclipse for years and have just started a new project on Android Studio.</p> <p>I'm noticing that every time I run a build, Android Studio <strong>collapses ALL the folders</strong> in the Project Files browser, such that they need to be re-expanded to get back to where I want them.</p> <p>This is what I'm left with:</p> <blockquote> <p>-&gt; app</p> <p>-&gt; MyApplicationName</p> </blockquote> <p>For me, this is incredibly annoying and unnecessarily disruptive to the development process. Yet, I don't see a solution online, so I'm suspecting I'm missing something obvious...</p> <p>Is there a way to prevent Studio from auto-collapsing the Project Files browser?</p>
27,149,717
2
0
null
2014-11-25 14:22:20.64 UTC
4
2014-11-26 12:50:42.997 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,418,562
null
1
34
android|android-studio
4,131
<p>I think you want to use the "Project" view, and not the "Project Files" view. I had this problem when I first switched from Eclipse to Android Studio and found it was because I'd set the file browser (top left) to look at Project files and not Project. The normal Project view does much the same thing and doesn't collapse when running tests.</p>
3,063,652
What's the status of multicore programming in Haskell?
<p>What's the status of multicore programming in Haskell? What projects, tools, and libraries are available now? What experience reports have there been?</p>
3,063,668
1
0
2010-06-17 18:26:18.407 UTC
2010-06-17 16:39:24.857 UTC
109
2015-06-13 18:40:24.857 UTC
null
null
null
null
83,805
null
1
163
haskell|concurrency|functional-programming|multicore|parallel-processing
13,369
<p>In the 2009-2012 period, the following things have happened:</p> <p>2012:</p> <ul> <li>From 2012, the parallel Haskell status updates began appearing in the <a href="http://www.well-typed.com/blog/65" rel="noreferrer">Parallel Haskell Digest</a>.</li> </ul> <p>2011:</p> <ul> <li><a href="http://community.haskell.org/~simonmar/par-tutorial.pdf" rel="noreferrer">Parallel and Concurrent Programming in Haskell</a>, a tutorial. version 1.1 released by Simon Marlow</li> <li><a href="http://www.economist.com/node/18750706?story_id=18750706" rel="noreferrer">Haskell and parallelism</a>, mentioned in an article in the Economist magazine, Jun 2nd 2011.</li> <li><a href="http://conal.net/blog/posts/parallel-tree-scanning-by-composition/" rel="noreferrer">Parallel tree scans via composition</a>, an article by Conal Elliott</li> <li><a href="http://www.haskell.org/haskellwiki/Numeric_Haskell:_A_Repa_Tutorial" rel="noreferrer">Numeric Haskell</a>, a tutorial on parallel array programming with Repa, released</li> <li>Works has begun on extending GHC eventlog and Threadscope to support multi-process or distributed Haskell systems</li> <li><a href="http://www.well-typed.com/blog/53" rel="noreferrer">Parallel Haskell Digest: Edition 2</a>.</li> <li><a href="http://hackage.haskell.org/package/monad-par" rel="noreferrer">The par-monad package</a> and <a href="http://community.haskell.org/~simonmar/papers/monad-par.pdf" rel="noreferrer">a monad for deterministic parallelism</a>, Simon Marlow -- more control over pure parallelism than strategies/par/pseq.</li> <li><a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/parallel/remote.pdf" rel="noreferrer">Cloud Haskell</a>: Erlang-style message passing between distributed Haskell nodes.</li> <li><a href="http://skillsmatter.com/podcast/scala/talk-by-haskell-expert-simon-peyton-jones/js-1434" rel="noreferrer">Parallel Haskell: Embracing Diversity</a>, a talk by SPJ.</li> <li><a href="http://disciple-devel.blogspot.com/2011/03/real-time-edge-detection-in-haskell.html" rel="noreferrer">Real time edge detection in parallel Haskell</a></li> <li><a href="http://www.well-typed.com/blog/52" rel="noreferrer">Parallel Haskell Digest: news on parallel Haskell</a></li> <li><a href="http://conal.net/blog/posts/composable-parallel-scanning/" rel="noreferrer">Composable parallel scanning</a></li> <li><a href="http://hackage.haskell.org/package/haskell-mpi-1.0.0" rel="noreferrer">Haskell-MPI</a> is released</li> </ul> <p>2010:</p> <ul> <li><a href="http://ghcmutterings.wordpress.com/2010/08/20/parallel-programming-in-haskell-with-explicit-futures/" rel="noreferrer">Parallel futures</a> for Haskell, in GHC.</li> <li>The <a href="http://corp.galois.com/blog/2010/6/14/orc-in-haskell-now-on-hackage.html" rel="noreferrer">Orc language</a>, for concurrent job scheduling and scripting, was released.</li> <li>A <a href="http://www.serpentine.com/bos/files/ghc-event-manager.pdf" rel="noreferrer">new scalable thread event manager</a> was merged into GHC.</li> <li>An <a href="http://www.haskell.org/~simonmar/papers/strategies.pdf" rel="noreferrer">improved approach to parallel sparks</a> and strategies was developed.</li> <li>The <a href="http://www.eecs.harvard.edu/~mainland/publications/mainland10nikola.pdf" rel="noreferrer">Nikola EDSL</a> for embedding GPU programs in Haskell was developed.</li> <li>The <a href="http://www.cse.unsw.edu.au/~chak/papers/TC10.html" rel="noreferrer">LLVM backend for GHC</a> was merged in, with good performance improvements.</li> <li><a href="http://article.gmane.org/gmane.comp.lang.haskell.general/17678" rel="noreferrer">ghc 6.12.x series: with parallel performance improvements</a></li> <li>Microsoft announces <a href="http://blog.well-typed.com/2010/04/parallel-haskell-2-year-project-to-push-real-world-use/" rel="noreferrer">2 years of funding to support commercial users of Parallel Haskell</a></li> <li><a href="http://www.icfpconference.org/icfp2010/accepted_papers.html" rel="noreferrer">Google published their experience report on the use of Haskell</a> (<a href="http://k1024.org/~iusty/papers/icfp10-haskell-reagent.pdf" rel="noreferrer">PDF</a>)</li> <li>Intel announced <a href="http://software.intel.com/en-us/blogs/2010/05/27/announcing-intel-concurrent-collections-for-haskell-01/" rel="noreferrer">the Concurrent Collections for Haskell library</a>, including <a href="http://software.intel.com/en-us/blogs/2010/06/07/parallel-performance-in-intel-concurrent-collections-for-haskell-an-in-depth-example/" rel="noreferrer">scalability numbers</a> -- scaling results <a href="http://software.intel.com/en-us/blogs/2010/06/24/haskell-cnc-new-paper-available-tests-on-32-and-48-cores/" rel="noreferrer">for 32 and 48 cores</a></li> <li>Sun/Oracle <a href="http://hackage.haskell.org/trac/ghc/wiki/OpenSPARC" rel="noreferrer">bought us a machine</a> and funded work on <a href="http://ghcsparc.blogspot.com/" rel="noreferrer">improving parallel performance</a>.</li> <li>Recent updates <a href="http://www.youtube.com/watch?v=NWSZ4c9yqW8" rel="noreferrer">to the status of Data Parallelism in Haskell</a></li> <li>MSR released <a href="http://research.microsoft.com/en-us/projects/threadscope/" rel="noreferrer">ThreadScope</a>, a graphical profiler for parallel Haskell programs</li> <li>The GHC runtime <a href="http://ghcmutterings.wordpress.com/2009/03/03/new-paper-runtime-support-for-multicore-haskell/" rel="noreferrer">got extensively tuned for sparks and futures</a></li> <li>There was a good <a href="http://ghcmutterings.wordpress.com/2010/01/25/yielding-more-improvements-in-parallel-performance/" rel="noreferrer">discussion on additional ways to improve parallel performance</a></li> <li>A collection of <a href="http://donsbot.wordpress.com/2009/09/03/parallel-programming-in-haskell-a-reading-list/" rel="noreferrer">reading material on parallelism in Haskell</a> to help you get started</li> <li>The <a href="http://gregorycollins.net/posts/2010/03/12/attoparsec-iteratee#comment-39671374" rel="noreferrer">Snap guys are getting 45k req/sec on their 4 way box</a>, by using all the cores.</li> <li>Even the <a href="http://orbitz-erlang.blogspot.com/2009/09/impressed-with-haskells-concurrency.html" rel="noreferrer">Erlang guys are taking notice</a>.</li> <li>Meanwhile, <a href="http://www.serpentine.com/blog/2009/12/17/making-ghcs-io-manager-more-scalable/" rel="noreferrer">there is work to make the IO manager more scalable</a> -- now with <a href="http://www.serpentine.com/bos/files/ghc-event-manager.pdf" rel="noreferrer">a paper on the design</a> :: PDF.</li> <li>We're out <a href="http://www.slideshare.net/bos31337/bayfp-concurrent-and-multicore-haskell" rel="noreferrer">there teaching people too</a> .. <a href="http://donsbot.wordpress.com/2010/06/01/open-source-bridge-talk-multicore-haskell-now/" rel="noreferrer">all</a> .. <a href="http://vimeo.com/channels/haskell#6680185" rel="noreferrer">over</a> .. <a href="http://ulf.wiger.net/weblog/2008/02/29/satnam-singh-declarative-programming-techniques-for-many-core-architectures/" rel="noreferrer">the</a> ... <a href="http://blip.tv/file/324976" rel="noreferrer">place</a>.</li> <li>Starling Software <a href="http://www.starling-software.com/misc/icfp-2009-cjs.pdf" rel="noreferrer">wrote about their real time, multicore financial trading system in Haskell</a>.</li> <li>Ericsson published a <a href="http://hackage.haskell.org/package/feldspar-language" rel="noreferrer">parallel language for DSP</a> based on, and written in Haskell</li> <li>Galois published an implementation of <a href="http://hackage.haskell.org/package/orc" rel="noreferrer">Orc</a>, a concurrent workflow language, in Haskell.</li> <li>And a <a href="http://repa.ouroborus.net/" rel="noreferrer">new library</a> for <a href="http://hackage.haskell.org/package/repa" rel="noreferrer">fast regular, parallel arrays appeared</a></li> <li>And <a href="http://shootout.alioth.debian.org/u64q/which-programming-languages-are-fastest.php#table" rel="noreferrer">Haskell continues to do well on the quad-core shootout</a>.</li> <li><a href="http://www.haskell.org/pipermail/haskell-cafe/2010-May/078005.html" rel="noreferrer">Snap</a>, a multicore-enabled scalable web server with great performance numbers</li> <li><a href="http://jlouisramblings.blogspot.com/2009/12/concurrency-bittorrent-clients-and.html" rel="noreferrer">haskell-torrent</a> - benchmarking a mulitcore-enabled bittorrent client in Haskell</li> <li><a href="http://scyourway.supercomputing.org/conference/view/spost112_1" rel="noreferrer">Haskell code was published</a> at Supercomputing 09 -- our first appearance at SC!</li> </ul>
32,417,776
You do not have permission to use the bulk load statement error
<p>I am trying to insert an image into a VARBINARY(MAX) column. I get this error: </p> <blockquote> <p>You do not have permission to use the bulk load statement.</p> </blockquote> <p>Here is my code:</p> <pre><code>INSERT INTO Stickers (Name, Category, Gender, ImageData) SELECT 'Red Dress', 'Dress', 'F', BulkColumn FROM OPENROWSET(Bulk '\\Mac\Home\Documents\MMImages\reddress.png', SINGLE_BLOB) AS BLOB </code></pre> <p>I realise there are a lot of answers on this topic but none of them have worked for me. <a href="https://stackoverflow.com/a/13002720/3935156">This answer</a> would be the easiest one for me to follow, however when using the object explorer and going into security > logins > right clicking my user does not reveal a "properties" menu item to go into.</p> <p>I am using Sql Server Management Studio. Maybe I am not using the SQL Server version that I think I am, because none of the programmatic ways to set the permissions for my user worked. I think I am using SQL Server 2012. I probably have a few versions of SQL server on my computer. Clicking Help > About, it does show the logo "Microsoft SQL Server 2012" above the version information for various components (It does not show the version information for SQL Server here).</p> <p><strong>EDIT: Perhaps could someone please state the exact code I would use above my insert statement, given that the database is called MirrorMirror, the table is called Stickers, my user is called Amber, and my server is called gonskh1ou0.database.windows.net.</strong></p>
32,418,341
3
0
null
2015-09-05 21:19:14.31 UTC
3
2021-01-20 07:05:30.73 UTC
2017-05-23 11:52:04.293 UTC
null
-1
null
3,935,156
null
1
24
sql-server|ssms
99,596
<p>To make sure you have the right permissions to use BULK commands follow the below</p> <ul> <li>Expand <strong>Security</strong></li> <li>Expand <strong>Logins</strong></li> <li>Right click on your username and choose <em>properties</em> (A dialog window appears)</li> <li>Choose <strong>Server Roles</strong></li> <li>Select <em>bulkadmin</em> to be able to use bulk commands or <em>sysadmin</em> to be able to use any commands to your database.</li> </ul> <p>Now, in regards to the query your are using it's not quite right.</p> <p>For creating the table</p> <pre><code>CREATE TABLE [dbo].[Stickers] ( [name] varchar(10) , [category] varchar(10) , [gender] varchar(1) , [imageData] varchar(max) ) </code></pre> <p>For inserting the large value data</p> <pre><code>INSERT INTO [dbo].[Stickers] ([name], [category], [gender], [imageData]) SELECT 'Red dress' , 'Dress' , 'F' , photo.* FROM OPENROWSET(BULK 'C:\Users\username\Desktop\misc-flower-png-55d7744aca416.png', SINGLE_BLOB) [photo] </code></pre> <p>A couple of notes:</p> <ul> <li>You need to set a correlation name for the bulk rowset after the FROM clause ([photo])</li> <li>Use the right column prefix that has been used for the correlation of the bulk rowset (photo.*)</li> <li>The column for the bulk insert needs to be set as <strong>varchar(max)</strong></li> </ul> <p>MSDN article for this: <a href="https://msdn.microsoft.com/en-us/library/a1904w6t(VS.80).aspx" rel="noreferrer">here</a></p>
6,051,145
Using the repository pattern to support multiple providers
<p>Well, not sure if that's exactly the right title, but basically I have been having a lot of problems using repositories in MVC applications in such a way that you can substitute one set of repositories, implementing a different data storage technology, for another.</p> <p>For example, suppose I want to use Entity Framework for my application. However, I also want to have a set of test data implemented in hard-coded Lists. I would like to have a set of interfaces (IUserRepository, IProductRepository, etc. -- let's not talk about a more generic IRepository&lt;T&gt; for now) that both approaches can instantiate. Then, using (say) a Dependency Injection tool such as Ninject or Castle Windsor, I can switch back and forth between the entity framework provider (accessing the actual database) and the test provider (accessing the lists).</p> <p>In a nutshell, here's the problem:</p> <p>-- If you are going to use Entity Framework, you want your repositories returning IQueryable&lt;SomeType&gt;. </p> <p>-- If you are going to use hard-coded lists, you do NOT want your repositories returning IQueryable, because it adds hugely to the overhead, and plus, Linq to Entities is significantly different from Linq to Objects, causing many headaches in the code that is common to both providers.</p> <p>In other words, I have found that the best approach isolates all the EF-dependent code within the repositories, so that the repositories themselves return IEnumerable or IList or some such -- then both EF and some other technology can use the same repositories. Thus, all the IQueryable's would be contained WITHIN the EF repositories. That way, you can use Linq to Entities with the EF repositories, and Linq to Objects with the Test repositories.</p> <p>Yet this approach puts an enormous amount of the business logic into the repositories, and results in much duplicated code -- the logic has to be duplicated in each of the repositories, even if the implementations are somewhat different.</p> <p>The whole idea of the repositories as this layer that is very thin and just connects to the database is then lost -- the repositories are "repositories" of business logic as well as of data store connectivity. You can't just have Find, Save, Update, etc.</p> <p>I've been unable to resolve this discrepancy between needing to isolate provider-dependent code, and having business logic in a centralized location.</p> <p>Any ideas? If anyone could point me to an example of an implementation that addresses this concern, I would be most appreciative. (I've read a lot, but can't find anything that specifically talks about these issues.)</p> <p>UPDATE:</p> <p>I guess I'm starting to feel that it's probably not possible to have repositories that can be swapped out for different providers -- that if you are going to use Entity Framework, for example, you just have to devote your whole application to Entity Framework. Unit tests? I'm struggling with that. My practice to this point has been to set up a separate repository with hard-coded data and use that for unit testing, as well as to test the application itself before the database is set up. I think I will have to look to a different solution, perhaps some mocking tool.</p> <p>But then that raises the question of why use repositories, and especially why use repository interfaces. I'm working on this. I think determining the best practice is going to take a bit of research.</p>
6,051,328
1
2
null
2011-05-18 21:17:35.693 UTC
12
2014-02-02 10:46:18.483 UTC
2014-02-02 10:46:18.483 UTC
null
727,208
null
244,346
null
1
14
asp.net-mvc|entity-framework|design-patterns|repository-pattern
3,914
<p>What I can say? Welcome to the club ...</p> <p>What you found is problem reached by many developers who followed "repository boom" with EFv4. Yes it is the problem and the problem is really complex. I discussed this several times:</p> <ul> <li><a href="https://stackoverflow.com/questions/5609508/asp-net-mvc3-and-entity-framework-code-first-architecture/5610685#5610685">ASP.NET MVC 3 and Entity Framework code first architecture</a></li> <li><a href="https://stackoverflow.com/questions/5488313/organizationally-where-should-i-put-common-queries-when-using-entity-framework-c/5488947#5488947">Organizationally, where should I put common queries when using Entity framework</a></li> </ul> <p>Separate topic is why to use repositories:</p> <ul> <li><a href="https://stackoverflow.com/questions/5625746/generic-repository-with-ef-4-1-what-is-the-point/5626884#5626884">Generic repository, what is the point</a></li> </ul> <p>Basically your proposed way is a solution but do you really want it? In my opinion the result is not repository but the Data Access Object (DAO) exposing plenty of access methods. Repository definition by <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="nofollow noreferrer">Martin Fowler</a> is:</p> <blockquote> <p>A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.</p> </blockquote> <p>I believe exposing <code>IQueryable</code> fulfils this 100 times better then creating a public interface similar to repositories from Stored procedures era - one access method per stored procedure (fixed query). </p> <p>The problem can be summarized by the rule of <a href="http://en.wikipedia.org/wiki/Leaky_abstraction" rel="nofollow noreferrer">leaky abstraction</a>. <code>IQueryable</code> is an abstraction of the database query but the features provided by <code>IQueryable</code> are dependent on the provider. Different provider = different feature set. </p> <p>What is a conclusion? Do you want such architecture because of testing? In such case start using integration tests as proposed in first two linked answers because in my opinion it is the lest painful way. If you go with your proposed approach you should still use integration tests to verify your repositories hiding all EF related logic and queries.</p>
5,607,774
ack regex: Matching two words in order in the same line
<p>I would like to find lines in files that include two words, <code>word_1</code> and <code>word_2</code> in order, such as in <code>Line A</code> below, but not as in <code>Line B</code> or <code>Line C</code>:</p> <pre><code>Line A: ... word_1 .... word_2 .... Line B: ... word_1 .... Line C: ... word_2 .... </code></pre> <p>I have tried</p> <pre><code>$ack '*word_1*word_2' $ack '(word_1)+*(word_2)+' </code></pre> <p>and the same commands with <code>^</code> appended at the beginning of the regex (in an attempt to follow the Perl regex syntax).</p> <p>None of these commands return the files or the lines I am interested in.</p> <p>What am I doing wrong?</p> <p>Thanks!</p>
5,607,981
1
0
null
2011-04-09 20:42:18.313 UTC
6
2011-04-09 21:18:50.01 UTC
2011-04-09 20:59:00.66 UTC
null
283,296
null
283,296
null
1
33
regex|ack
46,127
<p>You want to find <code>word_1</code>, followed by anything, any number of times, followed by <code>word_2</code>. That should be </p> <pre><code>word_1.*word_2 </code></pre> <p>You seem to be using <code>*</code> as it is often used in command line searches, but in regexes is it a quantifier for the preceding character, meaning match it at least 0 times. For example, the regex <code>a*</code> would match 0 or more <code>a</code>s, whereas the regex <code>a+</code> would match at least one <code>a</code>.</p> <p>The regex metacharacter meaning "match anything" is <code>.</code>, so <code>.*</code> means "match anything, any number of times. See <a href="http://perldoc.perl.org/perlrequick.html#Matching-repetitions">perlrequick</a> for a brief introduction on the topic.</p>
25,071,985
Thymeleaf th:text - Put a text without removing HTML structures
<p>I'm new in thymeleaf and I try to create a template. My problem is this code:</p> <pre><code>&lt;h1 th:text=&quot;${header.title}&quot; &gt; title &lt;small th:text=&quot;${header.subtitle}&quot; &gt;Subtitle&lt;/small&gt; &lt;/h1&gt; </code></pre> <p>I would like to get this output:</p> <pre><code>&lt;h1&gt; TITLE &lt;small&gt; SUBTITLE&lt;/small&gt; &lt;/h1&gt; </code></pre> <p>But this is the real output:</p> <pre><code>&lt;h1&gt; TITLE &lt;/h1&gt; </code></pre> <p>How can I do it, so it does not remove what is inside of &quot;small&quot;?</p>
29,317,466
4
0
null
2014-08-01 02:29:25.163 UTC
14
2022-08-31 00:54:25.81 UTC
2022-08-31 00:54:25.81 UTC
null
12,370,687
null
1,086,120
null
1
70
templates|spring-mvc|thymeleaf
125,463
<p>I faced the same problem. <strong>The answer is <code>th:inline='text'</code></strong></p> <p>This should solve your issue</p> <pre><code>&lt;h1 th:inline="text" &gt; [[${header.title}]] &lt;small th:text="${header.subtitle}"&gt;Subtitle&lt;/small&gt; &lt;/h1&gt; </code></pre> <hr/> <p>or you can also use <code>th:remove="tag"</code></p> <pre><code>&lt;h1&gt; &lt;span th:text="${header.title}" th:remove="tag"&gt;title&lt;/span&gt; &lt;small th:text="${header.subtitle}" &gt;Subtitle&lt;/small&gt; &lt;/h1&gt; </code></pre>
25,092,666
text-decoration: none not working on ul
<p>I've seen a lot of questions relating to this subject but none of them answered my question. I am making a sidebar for a site and I'm trying to make the links in boxes that are the same width as the sidebar, have just a little padding, maybe 10-15px and a tiny bit of space between each. Maybe 3px. But I can't seem to get text-decoration: none; to work no matter what I've tried.</p> <p>This is the most successful code I've gotten so far:</p> <p>HTML</p> <pre><code>&lt;div id= "sidebar"&gt; &lt;h3&gt;Navigation Links&lt;/h3&gt; &lt;div id= "sidelinks"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href= "#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href= "#"&gt;Biography&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>#sidebar { background: #464646; width: 250px; height: 1000px; margin-left: 50px; border-radius: 15px; } h3 { font-family: 'Coda', cursive; color: white; background: #6B6B6B; font-size: 24px; text-align: center; padding: 15px 0 8px 0; border-top-left-radius: 15px; border-top-right-radius: 15px; } #sidelinks { font-family: 'Armata', sans-serif; font-size: 25px; text-decoration: none; color: white; background-color: #4D4D4D; padding: 10px; position: relative; } </code></pre>
25,092,767
2
0
null
2014-08-02 07:13:56.123 UTC
1
2014-08-02 07:29:52.793 UTC
2014-08-02 07:22:45.523 UTC
null
1,326,536
null
3,901,556
null
1
5
html|css|text-decorations
54,077
<p>Removing the <code>text-decoration</code> and setting the colour is easy</p> <pre><code>#sidelinks a { color:black; text-decoration:none; } </code></pre> <p>So is removing the dots</p> <pre><code>#sidelinks ul { list-style:none; padding:0; margin:0; } </code></pre> <p>If you look at the CSS you posted none of it was actually targeting <code>&lt;a&gt;</code> or <code>&lt;ul&gt;</code> so not sure why you were expecting other style than the default ones.</p> <p>The fiddle doesn't have everything but it should send you in the right direction: <a href="http://jsfiddle.net/eNUpJ/" rel="noreferrer">http://jsfiddle.net/eNUpJ/</a></p>
351,954
Accessing iPhone WiFi Information via SDK
<p>Is there a way using the iPhone SDK to get WiFi information? Things like Signal Strength, WiFi Channel and SSID are the main things I'm looking for.</p> <p>Only interested in Wifi info, not cellular.</p>
412,548
3
4
null
2008-12-09 06:29:30.883 UTC
9
2017-04-27 09:22:31.497 UTC
2009-01-13 23:43:20.213 UTC
MrValdez
1,599
KiwiBastard
1,075
null
1
25
iphone|cocoa-touch|wifi
48,215
<p>Based on <a href="http://openradar.appspot.com/radar?id=306" rel="nofollow noreferrer">this</a> bug report and <a href="https://stackoverflow.com/questions/339089/can-the-iphone-sdk-obtain-the-wi-fi-ssid-currently-connected-to">this</a> SO question, I'm guessing there's no supported way to do this atm.</p> <p>EDIT: Chris mentioned WiFinder, which prompted me to do a little more digging. According to the WiFinder author's <a href="http://larsbergstrom.wordpress.com/2008/11/03/on-the-lack-of-wifinder-updates/" rel="nofollow noreferrer">blog</a> he used methods from the private Apple80211.framework. (The framework mentioned in the above linked SO question.) Apparently Apple will no longer allow these private API calls in apps, which is preventing him from updating WiFinder.</p> <p>But, if you want to use them anyway, some kind folks have posted a list of discovered Apple80211 functions to <a href="http://code.google.com/p/iphone-wireless/wiki/Apple80211Functions" rel="nofollow noreferrer">google code</a>.</p> <p>It looks like <a href="http://code.google.com/p/iphone-wireless/wiki/Apple80211GetInfoCopy" rel="nofollow noreferrer"><code>Apple80211GetInfoCopy</code></a> might do the trick.</p>
1,206,884
PHP GD: How to get imagedata as binary string?
<p>I'm using a solution for assembling image files to a zip and streaming it to browser/Flex application. (ZipStream by Paul Duncan, <a href="http://pablotron.org/software/zipstream-php/" rel="noreferrer">http://pablotron.org/software/zipstream-php/</a>).</p> <p>Just loading the image files and compressing them works fine. Here's the core for compressing a file:</p> <pre><code>// Reading the file and converting to string data $stringdata = file_get_contents($imagefile); // Compressing the string data $zdata = gzdeflate($stringdata ); </code></pre> <p>My problem is that I want to process the image using GD before compressing it. Therefore I need a solution for converting the image data (imagecreatefrompng) to string data format:</p> <pre><code>// Reading the file as GD image data $imagedata = imagecreatefrompng($imagefile); // Do some GD processing: Adding watermarks etc. No problem here... // HOW TO DO THIS??? // convert the $imagedata to $stringdata - PROBLEM! // Compressing the string data $zdata = gzdeflate($stringdata );</code></pre> <p>Any clues?</p>
1,206,909
3
0
null
2009-07-30 14:17:23.803 UTC
7
2019-12-30 02:36:37.667 UTC
null
null
null
null
146,400
null
1
33
php|zip|gd
24,258
<p>One way is to tell GD to output the image, then use PHP buffering to capture it to a string:</p> <pre><code>$imagedata = imagecreatefrompng($imagefile); ob_start(); imagepng($imagedata); $stringdata = ob_get_contents(); // read from buffer ob_end_clean(); // delete buffer $zdata = gzdeflate($stringdata); </code></pre>
6,358,066
How to implement a dynamic list with a JSF 2.0 Composite Component?
<p>I asked <a href="https://stackoverflow.com/questions/6355543/pass-argument-to-a-composite-component-action-attribute">this</a> question and although the answer directly satisfied my needs I am left with a feeling that there has to a simpler solution for this specific problem.</p> <p>I would like to have a composite component that accepts a list of items (The type of the items agreed upon so the members can be used freely within the composite component)</p> <p>The CC (composite component) display the list of items and allows for addition and subtraction of items.</p> <p>I would like to do this in the most simple and efficient manner.</p> <p>To illustrate the problem, an example:</p> <p><img src="https://i.stack.imgur.com/0rOdy.png" alt="enter image description here"></p> <p>The definition should be rather simple (unless of course, its not :-) ):</p> <pre><code>&lt;special:dynamicFieldList value="#{bean.fieldList} /&gt; </code></pre> <p>The most abstract form of a <code>Field</code> object would be:</p> <pre><code>public class Field{ String uuid; String value; } </code></pre> <p>I guess that's it. How would you implement this in a simple manner?</p> <p>Thanks!</p>
6,358,272
1
0
null
2011-06-15 13:02:51.09 UTC
11
2015-07-16 15:28:45.4 UTC
2017-05-23 11:45:34.29 UTC
null
-1
null
128,076
null
1
16
jsf|jsf-2|facelets|dynamic-forms|composite-component
15,701
<p>I'd use a <code>&lt;h:dataTable&gt;</code> in a composite component with a backing <code>UIComponent</code> which you can bind by <code>componentType</code> attribute of the <code>&lt;composite:interface&gt;</code>. In the backing <code>UIComponent</code> you can then maintain the <code>DataModel</code> and define the actions.</p> <p><code>dynamicFieldList.xhtml</code></p> <pre class="lang-xml prettyprint-override"><code>&lt;ui:composition xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:cc="http://java.sun.com/jsf/composite" &gt; &lt;cc:interface componentType="dynamicFieldList"&gt; &lt;cc:attribute name="value" type="java.util.List" required="true" /&gt; &lt;/cc:interface&gt; &lt;cc:implementation&gt; &lt;h:dataTable id="table" binding="#{cc.table}" value="#{cc.attrs.value}" var="field"&gt; &lt;h:column&gt;&lt;h:outputLabel value="#{field.label}" /&gt;&lt;/h:column&gt; &lt;h:column&gt;&lt;h:inputText value="#{field.value}" /&gt;&lt;/h:column&gt; &lt;h:column&gt;&lt;h:commandButton value="remove" action="#{cc.remove}" /&gt;&lt;/h:column&gt; &lt;/h:dataTable&gt; &lt;h:commandButton value="add" action="#{cc.add}" /&gt; &lt;/cc:implementation&gt; &lt;/ui:composition&gt; </code></pre> <p><em>(the <code>&lt;h:inputText&gt;</code> can if necessary be your composite field component)</em></p> <p><code>com.example.DynamicFieldList</code></p> <pre><code>@FacesComponent(value="dynamicFieldList") // To be specified in componentType attribute. @SuppressWarnings({"rawtypes", "unchecked"}) // We don't care about the actual model item type anyway. public class DynamicFieldList extends UINamingContainer { private UIData table; public void add() { ((List) getAttributes().get("value")).add(new Field("somelabel")); } public void remove() { ((List) getAttributes().get("value")).remove(table.getRowData()); } public UIData getTable() { return table; } public void setTable(UIData table) { this.table = table; } } </code></pre> <p>Use it as follows:</p> <pre><code>&lt;h:form&gt; &lt;my:dynamicFieldList value="#{bean.fields}" /&gt; &lt;/h:form&gt; </code></pre> <p>with just this</p> <pre><code>@ManagedBean @ViewScoped public class Bean implements Serializable { private List&lt;Field&gt; fields; public Bean() { fields = new ArrayList&lt;&gt;(); } public List&lt;Field&gt; getFields() { return fields; } } </code></pre> <p>and</p> <pre><code>public class Field implements Serializable { private String label; private String value; public Field() { // } public Field(String label) { this.label = label; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } </code></pre>
6,584,898
How to set list of values as parameter into hibernate query?
<p>For example, I have this query </p> <pre><code> select cat from Cat cat where cat.id in :ids </code></pre> <p>and I want to set ids to list (1,2,3,4,5,6,17,19).</p> <p>This code doesn't work </p> <pre><code>session.createQuery("select cat from Cat cat where cat.id in :ids") .setParameter("ids", new Long[]{1,2,3,4,5}) </code></pre> <p>As the result I would like to have SQL query like <code>id in (1,2,3,4)</code></p>
6,584,995
1
0
null
2011-07-05 15:09:02.023 UTC
6
2017-11-17 08:43:54.17 UTC
2017-11-17 08:43:54.17 UTC
null
100,297
null
426,377
null
1
32
sql|hibernate|jpa
47,641
<p>Use <a href="https://docs.jboss.org/hibernate/orm/5.1/javadocs/org/hibernate/Query.html#setParameterList-java.lang.String-java.lang.Object:A-"><code>setParameterList()</code></a>. You'll also have to put parenthesis around the list param.</p> <pre><code>session.createQuery("select cat from Cat cat where cat.id in (:ids)").setParameterList("ids", new Long[]{1,2,3,4,5}) </code></pre>
20,479,794
How do I properly git stash/pop in pre-commit hooks to get a clean working tree for tests?
<p>I'm trying to do a pre-commit hook with a bare run of unit tests and I want to make sure my working directory is clean. Compiling takes a long time so I want to take advantage of reusing compiled binaries whenever possible. My script follows examples I've seen online:</p> <pre><code># Stash changes git stash -q --keep-index # Run tests ... # Restore changes git stash pop -q </code></pre> <p>This causes problems though. Here's the repro:</p> <ol> <li>Add <code>// Step 1</code> to <code>a.java</code></li> <li><code>git add .</code></li> <li>Add <code>// Step 2</code> to <code>a.java</code></li> <li><code>git commit</code> <ol> <li><code>git stash -q --keep-index</code> # Stash changes</li> <li>Run tests</li> <li><code>git stash pop -q</code> # Restore changes</li> </ol></li> </ol> <p>At this point I hit the problem. The <code>git stash pop -q</code> apparently has a conflict and in <code>a.java</code> I have</p> <pre><code>// Step 1 &lt;&lt;&lt;&lt;&lt;&lt;&lt; Updated upstream ======= // Step 2 &gt;&gt;&gt;&gt;&gt;&gt;&gt; Stashed changes </code></pre> <p>Is there a way to get this to pop cleanly?</p>
20,480,591
4
0
null
2013-12-09 20:13:09.017 UTC
13
2021-12-10 20:12:21.693 UTC
null
null
null
null
156,767
null
1
28
git|githooks|git-stash
10,379
<p>There is—but let's get there in a slightly roundabout fashion. (Also, see warning below: there's a bug in the stash code which I thought was very rare, but apparently more people are running into. New warning, added in Dec 2021: <code>git stash</code> has been rewritten in C and has a whole new crop of bugs. I used to suggest mildly that <code>git stash</code> be avoided; now I urge <em>everyone</em> to <strong>avoid it if at all possible</strong>.)</p> <p><code>git stash push</code> (the default action for <code>git stash</code>; note that this was spelled <code>git stash save</code> in 2015, when I wrote the first version of this answer) makes a commit that has at least two parents (see <a href="https://stackoverflow.com/a/20412685/1256452">this answer</a> to a more basic question about stashes). The <code>stash</code> commit is the work-tree state, and the second parent commit <code>stash^2</code> is the index-state at the time of the stash.</p> <p>After the stash is made (and assuming no <code>-p</code> option), the script—<code>git stash</code> is a shell script—uses <code>git reset --hard</code> to clean out the changes.</p> <p>When you use <code>--keep-index</code>, the script does not change the saved stash in any way. Instead, after the <code>git reset --hard</code> operation, the script uses an extra <code>git read-tree --reset -u</code> to wipe out the work-directory changes, replacing them with the &quot;index&quot; part of the stash.</p> <p>In other words, it's almost like doing:</p> <pre><code>git reset --hard stash^2 </code></pre> <p>except that <code>git reset</code> would also move the branch—not at all what you want, hence the <code>read-tree</code> method instead.</p> <p>This is where your code comes back in. You now <code># Run tests</code> on the contents of the index commit.</p> <p>Assuming all goes well, I presume you want to get the index back into the state it had when you did the <code>git stash</code>, and get the work-tree back into its state as well.</p> <p>With <code>git stash apply</code> or <code>git stash pop</code>, the way to do that is to use <code>--index</code> (not <code>--keep-index</code>, that's just for stash-creation time, to tell the stash script &quot;whack on the work directory&quot;).</p> <p>Just using <code>--index</code> will still fail though, because <code>--keep-index</code> re-applied the index changes to the work directory. So you must first get rid of all of those changes ... and to do that, you simply need to (re)run <code>git reset --hard</code>, just like the stash script itself did earlier. (Probably you also want <code>-q</code>.)</p> <p>So, this gives as the last <code># Restore changes</code> step:</p> <pre><code># Restore changes git reset --hard -q git stash pop --index -q </code></pre> <p>(I'd separate them out as:</p> <pre><code>git stash apply --index -q &amp;&amp; git stash drop -q </code></pre> <p>myself, just for clarity, but the <code>pop</code> will do the same thing).</p> <hr /> <p>As noted in a comment below, the final <code>git stash pop --index -q</code> complains a bit (or, worse, restores an <em>old</em> stash) if the initial <code>git stash push</code> step finds no changes to save. You should therefore protect the &quot;restore&quot; step with a test to see if the &quot;save&quot; step actually stashed anything.</p> <p>The initial <code>git stash --keep-index -q</code> simply exits quietly (with status 0) when it does nothing, so we need to handle two cases: no stash exists either before or after the save; and, some stash existed before the save, and the save did nothing so the old existing stash is still the top of the stash stack.</p> <p>I think the simplest method is to use <code>git rev-parse</code> to find out what <code>refs/stash</code> names, if anything. So we should have the script read something more like this:</p> <pre><code>#! /bin/sh # script to run tests on what is to be committed # First, stash index and work dir, keeping only the # to-be-committed changes in the working directory. old_stash=$(git rev-parse -q --verify refs/stash) git stash push -q --keep-index new_stash=$(git rev-parse -q --verify refs/stash) # If there were no changes (e.g., `--amend` or `--allow-empty`) # then nothing was stashed, and we should skip everything, # including the tests themselves. (Presumably the tests passed # on the previous commit, so there is no need to re-run them.) if [ &quot;$old_stash&quot; = &quot;$new_stash&quot; ]; then echo &quot;pre-commit script: no changes to test&quot; sleep 1 # XXX hack, editor may erase message exit 0 fi # Run tests status=... # Restore changes git reset --hard -q &amp;&amp; git stash apply --index -q &amp;&amp; git stash drop -q # Exit with status from test-run: nonzero prevents commit exit $status </code></pre> <hr /> <h2>warning: small bug in git stash</h2> <p>(Note: I believe this bug was fixed in the conversion to C. Instead, there are numerous <em>other</em> bugs now. They will no doubt eventually be fixed, but depending on which version of Git you are using, <code>git stash</code> may have various bugs of varying seriousness.)</p> <p>There's a minor bug in the way <code>git stash</code> writes its <a href="https://stackoverflow.com/q/20586009/1256452">&quot;stash bag&quot;</a>. The index-state stash is correct, but suppose you do something like this:</p> <pre><code>cp foo.txt /tmp/save # save original version sed -i '' -e '1s/^/inserted/' foo.txt # insert a change git add foo.txt # record it in the index cp /tmp/save foo.txt # then undo the change </code></pre> <p>When you run <code>git stash push</code> after this, the index-commit (<code>refs/stash^2</code>) has the inserted text in <code>foo.txt</code>. The work-tree commit (<code>refs/stash</code>) <em>should</em> have the version of <code>foo.txt</code> without the extra inserted stuff. If you look at it, though, you'll see it has the wrong (index-modified) version.</p> <p>The script above uses <code>--keep-index</code> to get the working tree set up as the index was, which is all perfectly fine and does the right thing for running the tests. After running the tests, it uses <code>git reset --hard</code> to go back to the <code>HEAD</code> commit state (which is still perfectly fine) ... and then it uses <code>git stash apply --index</code> to restore the index (which works) and the work directory.</p> <p>This is where it goes wrong. The index is (correctly) restored from the stash index commit, but the work-directory is restored from the stash work-directory commit. This work-directory commit has the version of <code>foo.txt</code> that's in the index. In other words, that last step—<code>cp /tmp/save foo.txt</code>—that undid the change, has been un-un-done!</p> <p>(The bug in the <code>stash</code> script occurs because the script compares the work-tree state against the <code>HEAD</code> commit in order to compute the set of files to record in the special temporary index before making the special work-dir commit part of the stash-bag. Since <code>foo.txt</code> is unchanged with respect to <code>HEAD</code>, it fails to <code>git add</code> it to the special temporary index. The special work-tree commit is then made with the index-commit's version of <code>foo.txt</code>. The fix is very simple but no one has put it into official git [yet?].</p> <p>Not that I want to encourage people to modify their versions of git, but <a href="http://git.661346.n2.nabble.com/git-stash-doesn-t-always-save-work-dir-as-is-bug-tp7595679.html" rel="nofollow noreferrer">here's the fix</a>.)</p>
564,935
No implicit conversion between 'lambda expression' and 'lambda expression'?
<blockquote> <p>Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'</p> </blockquote> <p>Say whaat? Could someone please explain this compile error to me? This is the code that produces it:</p> <pre><code> protected override Func&lt;System.IO.Stream&gt; GetStream() { return someBool ? () =&gt; EmbeddedResourceExtractor.GetFile("SomeFile1.ext") : () =&gt; EmbeddedResourceExtractor.GetFile("SomeFile2.ext"); } </code></pre> <p>This does not:</p> <pre><code> protected override Func&lt;System.IO.Stream&gt; GetStream() { return () =&gt; EmbeddedResourceExtractor.GetFile("SomeFile1.ext"); } </code></pre> <p>And neither do this:</p> <pre><code> protected override Func&lt;System.IO.Stream&gt; GetStream() { if(someBool) return () =&gt; EmbeddedResourceExtractor.GetFile("SomeFile1.ext"); return () =&gt; EmbeddedResourceExtractor.GetFile("SomeFile2.ext"); } </code></pre>
564,973
1
1
null
2009-02-19 11:50:13.273 UTC
4
2020-06-26 14:53:36.463 UTC
2020-06-26 14:53:36.463 UTC
null
4,671,754
Svish
39,321
null
1
45
c#|lambda
9,261
<p>The type of the conditional expression has to be inferred as a whole - and lambda expressions always have to be converted to a specific delegate or expression tree type.</p> <p>In your latter two examples, the compiler knows what it's trying to convert the lambda expression to. In the first example, it tries to work out the type of the whole conditional expression first.</p> <p>A cast in one of the branches would be enough though:</p> <pre><code>protected override Func&lt;Stream&gt; GetStream() { return someBool ? (Func&lt;Stream&gt;) (() =&gt; EmbeddedResourceExtractor.GetFile("SomeFile1.ext")) : () =&gt; EmbeddedResourceExtractor.GetFile("SomeFile2.ext"); } </code></pre> <p>Sergio's fix (now deleted, but included below) will work <em>if</em> you were happy to evaluate <code>someBool</code> at the time the function is called:</p> <pre><code>protected override Func&lt;Stream&gt; GetStream() { return () =&gt; someBool ? EmbeddedResourceExtractor.GetFile("SomeFile1.ext") : EmbeddedResourceExtractor.GetFile("SomeFile2.ext"); } </code></pre> <p>Depending on timing, there are all kinds of different ways of fixing the example you've actually given, e.g.</p> <pre><code>protected override Func&lt;Stream&gt; GetStream() { string name = someBool ? "SomeFile1.ext" : "SomeFile2.ext"; return () =&gt; EmbeddedResourceExtractor.GetFile(name); } </code></pre> <p>I'm guessing your real code is more complicated though.</p> <p>It's a shame in some ways that C#'s type inference can't be more powerful - but it's already pretty complicated.</p>
2,699,584
How to split (chunk) a Ruby array into parts of X elements?
<p>I have an array</p> <pre><code>foo = %w(1 2 3 4 5 6 7 8 9 10) </code></pre> <p>How can I split or "chunk" this into smaller arrays?</p> <pre><code>class Array def chunk(size) # return array of arrays end end foo.chunk(3) # =&gt; [[1,2,3],[4,5,6],[7,8,9],[10]] </code></pre>
2,699,615
2
0
null
2010-04-23 15:00:30.623 UTC
33
2015-06-27 14:19:10.203 UTC
2011-08-18 06:30:58.23 UTC
null
184,600
null
184,600
null
1
200
ruby|arrays
139,107
<p>Take a look at <a href="http://apidock.com/ruby/Enumerable/each_slice" rel="noreferrer">Enumerable#each_slice</a>:</p> <pre><code>foo.each_slice(3).to_a #=&gt; [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]] </code></pre>
32,843,213
Operator does not exist: json = json
<p>when I try to select some record from a table</p> <pre><code> SELECT * FROM movie_test WHERE tags = ('["dramatic","women", "political"]'::json) </code></pre> <p>The sql code cast a error</p> <pre><code>LINE 1: SELECT * FROM movie_test WHERE tags = ('["dramatic","women",... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. ********** 错误 ********** ERROR: operator does not exist: json = json SQL 状态: 42883 指导建议:No operator matches the given name and argument type(s). You might need to add explicit type casts. 字符:37 </code></pre> <p>Did I miss something or where I can learn something about this error.</p>
32,843,380
1
0
null
2015-09-29 11:49:06.307 UTC
10
2021-08-28 14:18:38.673 UTC
2017-06-09 11:11:38.2 UTC
null
1,995,738
null
4,482,493
null
1
40
sql|json|postgresql|postgresql-9.4|jsonb
61,464
<p>In short - use JSONB instead of JSON or cast JSON to JSONB.</p> <p>You cannot compare json values. You can compare text values instead:</p> <pre><code>SELECT * FROM movie_test WHERE tags::text = '[&quot;dramatic&quot;,&quot;women&quot;,&quot;political&quot;]' </code></pre> <p>Note however that values of type JSON are stored as text in a format in which they are given. Thus the result of comparison depends on whether you consistently apply the same format:</p> <pre><code>SELECT '[&quot;dramatic&quot; ,&quot;women&quot;, &quot;political&quot;]'::json::text = '[&quot;dramatic&quot;,&quot;women&quot;,&quot;political&quot;]'::json::text -- yields false! </code></pre> <p>In Postgres 9.4+ you can solve this problem using type JSONB, which is stored in a decomposed binary format. Values of this type can be compared:</p> <pre><code>SELECT '[&quot;dramatic&quot; ,&quot;women&quot;, &quot;political&quot;]'::jsonb = '[&quot;dramatic&quot;,&quot;women&quot;,&quot;political&quot;]'::jsonb -- yields true </code></pre> <p>so this query is much more reliable:</p> <pre><code>SELECT * FROM movie_test WHERE tags::jsonb = '[&quot;dramatic&quot;,&quot;women&quot;,&quot;political&quot;]'::jsonb </code></pre> <p>Read more about <a href="https://www.postgresql.org/docs/current/datatype-json.html" rel="noreferrer">JSON Types</a>.</p>
33,207,164
Spark Window Functions - rangeBetween dates
<p>I have a Spark SQL <code>DataFrame</code> with date column, and what I'm trying to get is all the rows preceding current row in a given date range. So for example I want to have all the rows from 7 days back preceding given row. I figured out, I need to use a <code>Window Function</code> like:</p> <pre class="lang-py prettyprint-override"><code>Window \ .partitionBy('id') \ .orderBy('start') </code></pre> <p>I want to have a <code>rangeBetween</code> 7 days, but there is nothing in the Spark docs I could find on this. Does Spark even provide such option? For now I'm just getting all the preceding rows with:</p> <pre class="lang-py prettyprint-override"><code>.rowsBetween(-sys.maxsize, 0) </code></pre> <p>but would like to achieve something like:</p> <pre class="lang-py prettyprint-override"><code>.rangeBetween(&quot;7 days&quot;, 0) </code></pre>
33,226,511
3
0
null
2015-10-19 05:24:07.907 UTC
26
2022-08-09 03:33:36.337 UTC
2022-07-04 09:56:38.06 UTC
null
2,753,501
null
4,248,237
null
1
51
apache-spark|date|pyspark|apache-spark-sql|window-functions
69,702
<p><strong>Spark >= 2.3</strong></p> <p>Since Spark 2.3 it is possible to use interval objects using SQL API, but the <code>DataFrame</code> API support is <a href="https://issues.apache.org/jira/browse/SPARK-25841" rel="noreferrer">still work in progress</a>.</p> <pre class="lang-py prettyprint-override"><code>df.createOrReplaceTempView("df") spark.sql( """SELECT *, mean(some_value) OVER ( PARTITION BY id ORDER BY CAST(start AS timestamp) RANGE BETWEEN INTERVAL 7 DAYS PRECEDING AND CURRENT ROW ) AS mean FROM df""").show() ## +---+----------+----------+------------------+ ## | id| start|some_value| mean| ## +---+----------+----------+------------------+ ## | 1|2015-01-01| 20.0| 20.0| ## | 1|2015-01-06| 10.0| 15.0| ## | 1|2015-01-07| 25.0|18.333333333333332| ## | 1|2015-01-12| 30.0|21.666666666666668| ## | 2|2015-01-01| 5.0| 5.0| ## | 2|2015-01-03| 30.0| 17.5| ## | 2|2015-02-01| 20.0| 20.0| ## +---+----------+----------+------------------+ </code></pre> <p><strong>Spark &lt; 2.3</strong></p> <p>As far as I know it is not possible directly neither in Spark nor Hive. Both require <code>ORDER BY</code> clause used with <code>RANGE</code> to be numeric. The closest thing I found is conversion to timestamp and operating on seconds. Assuming <code>start</code> column contains <code>date</code> type:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.sql import Row row = Row("id", "start", "some_value") df = sc.parallelize([ row(1, "2015-01-01", 20.0), row(1, "2015-01-06", 10.0), row(1, "2015-01-07", 25.0), row(1, "2015-01-12", 30.0), row(2, "2015-01-01", 5.0), row(2, "2015-01-03", 30.0), row(2, "2015-02-01", 20.0) ]).toDF().withColumn("start", col("start").cast("date")) </code></pre> <p>A small helper and window definition:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.sql.window import Window from pyspark.sql.functions import mean, col # Hive timestamp is interpreted as UNIX timestamp in seconds* days = lambda i: i * 86400 </code></pre> <p>Finally query:</p> <pre class="lang-py prettyprint-override"><code>w = (Window() .partitionBy(col("id")) .orderBy(col("start").cast("timestamp").cast("long")) .rangeBetween(-days(7), 0)) df.select(col("*"), mean("some_value").over(w).alias("mean")).show() ## +---+----------+----------+------------------+ ## | id| start|some_value| mean| ## +---+----------+----------+------------------+ ## | 1|2015-01-01| 20.0| 20.0| ## | 1|2015-01-06| 10.0| 15.0| ## | 1|2015-01-07| 25.0|18.333333333333332| ## | 1|2015-01-12| 30.0|21.666666666666668| ## | 2|2015-01-01| 5.0| 5.0| ## | 2|2015-01-03| 30.0| 17.5| ## | 2|2015-02-01| 20.0| 20.0| ## +---+----------+----------+------------------+ </code></pre> <p>Far from pretty but works.</p> <hr> <p>* <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types#LanguageManualTypes-timestamp" rel="noreferrer">Hive Language Manual, Types</a></p>
33,123,093
Insert CSS into loaded HTML in UIWebView / WKWebView
<p>I am successfully able to get HTML content and display into my UIWebView. </p> <p>But want to customize the content by adding an external CSS file. I can only change the size of text and font. I tried every possible solution to make changes but it does not work - it shows no changes. </p> <p>Below is my code</p> <pre><code>HTMLNode* body = [parser body]; HTMLNode* mainContentNode = [body findChildWithAttribute:@"id" matchingName:@"main_content" allowPartial:NO]; NSString *pageContent = [NSString stringWithFormat:@"%@%@", cssString, contentHtml]; [webView loadHTMLString:pageContent baseURL:[NSURL URLWithString:@"http://www.example.org"]]; -(void)webViewDidFinishLoad:(UIWebView *)webView1{ int fontSize = 50; NSString *font = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", fontSize]; NSString *fontString = [[NSString alloc] initWithFormat:@"document.getElementById('body').style.fontFamily=\"helvetica\""]; [webView1 stringByEvaluatingJavaScriptFromString:fontString]; [webView1 stringByEvaluatingJavaScriptFromString:font]; } </code></pre> <p>Please help me get the css stylesheet in my view.</p>
33,126,467
6
0
null
2015-10-14 10:37:03.217 UTC
16
2020-07-09 12:18:38.207 UTC
2017-04-20 01:04:12.947 UTC
null
47,281
null
5,444,667
null
1
43
ios|objective-c|uiwebview|wkwebview
49,506
<p>You can do it like this:</p> <pre><code>- (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *cssString = @"body { font-family: Helvetica; font-size: 50px }"; // 1 NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2 NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3 [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString]; // 4 } </code></pre> <p>What this code does:</p> <p>// 1 : Define a string that contains all the CSS declarations</p> <p>// 2 : Define a javascript string that creates a new <code>&lt;style&gt;</code> HTML DOM element and inserts the CSS declarations into it. Actually the inserting is done in the next step, right now there is only the <code>%@</code> placeholder. I did this to prevent the line from becoming too long, but step 2 and 3 could be done together.</p> <p>// 3 : Combine the 2 strings</p> <p>// 4 : Execute the javascript in the UIWebView</p> <p>For this to work, your HTML has to have a <code>&lt;head&gt;&lt;/head&gt;</code> element. </p> <p><strong>EDIT:</strong></p> <p>You can also load the css string from a local css file (named "styles.css" in this case). Just replace step //1 with the following:</p> <pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"styles" ofType:@"css"]; NSString *cssString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; </code></pre> <p>As another option you can just inject a <code>&lt;link&gt;</code> element to the <code>&lt;head&gt;</code> that loads the CSS file:</p> <pre><code>- (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *path = [[NSBundle mainBundle] pathForResource:@"styles" ofType:@"css"]; NSString *javascriptString = @"var link = document.createElement('link'); link.href = '%@'; link.rel = 'stylesheet'; document.head.appendChild(link)"; NSString *javascriptWithPathString = [NSString stringWithFormat:javascriptString, path]; [webView stringByEvaluatingJavaScriptFromString:javascriptWithPathString]; } </code></pre> <p>This solution works best for large CSS files. Unfortunately it does not work with remote HTML files. You can only use this when you want to insert CSS into HTML that you have downloaded to your app.</p> <p><strong>UPDATE: WKWebView / Swift 3.x</strong></p> <p>When you are working with a <code>WKWebView</code> injecting a <code>&lt;link&gt;</code> element does not work because of <code>WKWebView</code>'s security settings.</p> <p>You can still inject the css as a string. Either create the CSS string in your code <code>//1</code> or put it in a local file <code>//2</code>. Just be aware that with WKWebView you have to do the injection in <code>WKNavigationDelegate</code>'s <code>webView(_:didFinish:)</code> method:</p> <pre><code>func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { insertCSSString(into: webView) // 1 // OR insertContentsOfCSSFile(into: webView) // 2 } func insertCSSString(into webView: WKWebView) { let cssString = "body { font-size: 50px; color: #f00 }" let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);" webView.evaluateJavaScript(jsString, completionHandler: nil) } func insertContentsOfCSSFile(into webView: WKWebView) { guard let path = Bundle.main.path(forResource: "styles", ofType: "css") else { return } let cssString = try! String(contentsOfFile: path).trimmingCharacters(in: .whitespacesAndNewlines) let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);" webView.evaluateJavaScript(jsString, completionHandler: nil) } </code></pre>
23,353,009
Vim spellcheck not always working in .tex file. Check region in Vim
<p>I use Vim to write my <code>.tex</code> files, but I am having trouble with the spell checker in Vim. Sometimes it does not check the words, and I think that it might be for the following reason.</p> <p>Since Vim is clearly not supposed to check all of the words in the <code>.tex</code> document, for example, not the preamble, it only check spelling in certain regions (in the syntax sense). As I have gathered from <a href="http://vim.1045645.n5.nabble.com/Spellchecker-doesn-t-work-in-all-latex-files-td5718129.html">here</a>, one of these regions is <code>texSectionZone</code>. These regions can become quite large, indeed a section often is, so Vim is having trouble realising that it actually is in a <code>texSectionZone</code> region (or in ay other), and therefore does not check the spelling. This can happen if I make a search in the document, or any kind of jump that skips multiple lines (or rather pages).</p> <p>The way that I concluded this might be the reason is the following: I know that the command</p> <pre><code>:echo synIDattr(synID(line("."),col("."),1),"name") </code></pre> <p>prints the name of the region/regions you are in (I found it <a href="http://vim.wikia.com/wiki/Identify_the_syntax_highlighting_group_used_at_the_cursor">here</a>), so when the spell checker did not work I tried this, and it told me that it was not in any region at all. The places it did work, I was in a region where it ought to check the spelling.</p> <p>So far my only solution is to find the nearest section above the point I want the speller to check, and then manually move the cursor back down to the given point.</p> <p>Ideally I would very much like a solution that ensures that this does not happen, but I would also settle for a way to manually make vim 'update' which region it is in, without me having to move the cursor a lot. In the latter case I am thinking of a solution which could be made to a shortcut.</p> <p>PS I was in doubt about what to call the question. If you come up with a title which explain the problem better, fell free to change it.</p>
23,357,364
3
0
null
2014-04-28 23:37:30.497 UTC
13
2022-01-28 14:04:01.083 UTC
null
null
null
null
1,529,157
null
1
38
vim|latex|spell-checking|region
9,264
<p><code>syntax/tex.vim</code> already uses quite elaborate <em>sync patterns</em> to ensure that the syntax highlighting is accurate, but for long and complex documents, this may still fail.</p> <p>Best you can do is trying to increase both values of</p> <pre><code>syn sync maxlines=200 syn sync minlines=50 </code></pre> <p>(e.g. to 2000 and 500). Put this in <code>~/.vim/after/syntax/tex.vim</code> to override the defaults.</p> <pre><code>syntax sync fromstart </code></pre> <p>might give the best results, but may be too slow. You'll find a description of syntax syncing at <code>:help :syn-sync</code>.</p>
30,918,732
How to determine which textfield is active swift
<p>I cant figure out which <code>UITextField</code> is currently active so i can clear its text if they hit cancel on a <code>UIBarButtonItem</code>. Here is my code. There is a view with a <code>UIPickerView</code>,<code>UIToolBar</code> and two bar button items. The cancel item has an action that will clear its text only i cant figure out how to get the correct <code>UITextField</code>.</p> <p>I've tried these both:</p> <pre><code>@IBAction func cancelText(sender: AnyObject) { if self.truckYear.editing == true{ println("truckYear") clearText(self.truckYear) } else if self.truckMake.editing == true{ clearText(self.truckMake) } } @IBAction func doneText(sender: AnyObject) { pickerView.hidden = true } func clearText(textField:UITextField){ println("in clear text") textField.text = nil } </code></pre> <p>And:</p> <pre><code>@IBAction func cancelText(sender: AnyObject) { if self.truckYear.isFirstResponder(){ println("truckYear") clearText(self.truckYear) } else if self.truckMake.isFirstResponder(){ clearText(self.truckMake) } } @IBAction func doneText(sender: AnyObject) { pickerView.hidden = true } func clearText(textField:UITextField){ println("in clear text") textField.text = nil } </code></pre>
30,918,882
7
0
null
2015-06-18 14:49:41.127 UTC
4
2018-11-24 20:29:58.113 UTC
2015-06-18 15:25:03.457 UTC
null
1,226,963
null
4,926,460
null
1
35
ios|swift
44,874
<p>You can declare a <code>UITextField</code> property in your class, and assign the current text field to it in <code>textFieldDidBeginEditing</code>. Then you can just call this text field whenever you need to.</p> <pre><code>class ViewController : UIViewController, UITextFieldDelegate { var activeTextField = UITextField() // Assign the newly active text field to your activeTextField variable func textFieldDidBeginEditing(textField: UITextField) { self.activeTextField = textField } // Call activeTextField whenever you need to func anotherMethod() { // self.activeTextField.text is an optional, we safely unwrap it here if let activeTextFieldText = self.activeTextField.text { print("Active text field's text: \(activeTextFieldText)") return; } print("Active text field is empty") } } </code></pre>
47,114,672
What is difference between Barrier and Guideline in Constraint Layout?
<p><strong>Recently trying to implement <code>Constraint Layout</code> but I found <code>Barrier</code> and <code>Guideline</code> works same.</strong> Both works like divider. Is there any difference between them?</p>
47,241,263
2
0
null
2017-11-04 19:21:44.32 UTC
46
2021-10-01 07:26:32.347 UTC
null
null
null
null
2,976,830
null
1
180
android|android-constraintlayout
72,736
<h2>When to use barriers</h2> <p>Assume you have two <code>TextView</code> widgets with dynamic heights and you want to place a <code>Button</code> just below the tallest <code>TextView</code>:</p> <p><a href="https://i.stack.imgur.com/Vy0g6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vy0g6.png" alt="Task view" /></a></p> <p>The <em><strong>ONLY</strong></em> way to implement that directly in the layout is to use a horizontal <code>Barrier</code>. That <code>Barrier</code> allows you to specify a constraint based on the height of those two <code>TextView</code>s. Then you constrain the top of your <code>Button</code> to the bottom of the horizontal <code>Barrier</code>.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;TextView android:id=&quot;@+id/left_text_view&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;8dp&quot; android:layout_marginEnd=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:text=&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot; android:textSize=&quot;16sp&quot; android:background=&quot;#AAA&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/right_text_view&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;TextView android:id=&quot;@+id/right_text_view&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:layout_marginEnd=&quot;8dp&quot; android:text=&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890&quot; android:textSize=&quot;16sp&quot; android:background=&quot;#DDD&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toEndOf=&quot;@+id/left_text_view&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;androidx.constraintlayout.widget.Barrier android:id=&quot;@+id/barrier&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; app:barrierDirection=&quot;bottom&quot; app:constraint_referenced_ids=&quot;left_text_view,right_text_view&quot; /&gt; &lt;Button android:id=&quot;@+id/button&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginEnd=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:text=&quot;Button&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;@+id/barrier&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> <hr /> <h2>When to use guidelines</h2> <p>Assume you want to restrict the above-mentioned <code>TextView</code> heights to 30% of screen height, no matter the content they have.</p> <p><a href="https://i.stack.imgur.com/ilHH2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ilHH2.png" alt="Test view" /></a></p> <p>To implement that you should add horizontal <code>Guideline</code> with percentage position and constrain the <code>TextView</code> bottom to that <code>Guideline</code>.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;TextView android:id=&quot;@+id/left_text_view&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:layout_marginEnd=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:layout_marginTop=&quot;8dp&quot; android:background=&quot;#AAA&quot; android:text=&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot; android:textSize=&quot;16sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/guideline&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/right_text_view&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;TextView android:id=&quot;@+id/right_text_view&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; android:layout_marginEnd=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:layout_marginTop=&quot;8dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:background=&quot;#DDD&quot; android:text=&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890&quot; android:textSize=&quot;16sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/guideline&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toEndOf=&quot;@+id/left_text_view&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;Button android:id=&quot;@+id/button&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginEnd=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:text=&quot;Button&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;@+id/guideline&quot; /&gt; &lt;androidx.constraintlayout.widget.Guideline android:id=&quot;@+id/guideline&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot; app:layout_constraintGuide_percent=&quot;0.3&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> <hr /> <h2>Conclusion</h2> <p>The only difference between <code>Barrier</code> and <code>Guideline</code> is that <code>Barrier</code>'s position is flexible and always based on the size of multiple UI elements contained within it and <code>Guideline</code>'s position is always fixed.</p>
1,518,279
JSON IPHONE: How to send a JSON request and pull the data from a server?
<p>I know barely nothing about JSON and I need to send a request to a server and read the data coming from it, using the iPhone only.</p> <p>I have tried to use the <a href="https://github.com/stig/json-framework" rel="nofollow noreferrer">jason-framework</a> to do that, but after readin the documentations I was not able to figure out how to construct the object and send it on the request. So I decided to adapted another code I saw here on SO.</p> <p>The Object I need is this:</p> <p>{ "code" : xxx }</p> <p>Here I have a problem. This xxx is a NSData, so I suspect that I have to convert this data to a string, then use this string to build an object and send this on the request.</p> <p>the server response is also a JSON object, in the form</p> <p>{ "answer" : "yyy" } where yyy is a number between 10000 and 99999</p> <p>this is the code I have so far.</p> <pre><code>- (NSString *)checkData:(NSData) theData { NSString *jsonObjectString = [self encode:(uint8_t *)theData length:theData.length]; NSString *completeString = [NSString stringWithFormat:@"http://www.server.com/check?myData=%@", jsonObjectString]; NSURL *urlForValidation = [NSURL URLWithString:completeString]; NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation]; [validationRequest setHTTPMethod:@"POST"]; NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil]; [validationRequest release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding]; NSInteger response = [responseString integerValue]; NSLog(@"%@", responseString); [responseString release]; return responseString; } - (NSString *)encode:(const uint8_t *)input length:(NSInteger)length { static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; uint8_t *output = (uint8_t *)data.mutableBytes; for (NSInteger i = 0; i &lt; length; i += 3) { NSInteger value = 0; for (NSInteger j = i; j &lt; (i + 3); j++) { value &lt;&lt;= 8; if (j &lt; length) { value |= (0xFF &amp; input[j]); } } NSInteger index = (i / 3) * 4; output[index + 0] = table[(value &gt;&gt; 18) &amp; 0x3F]; output[index + 1] = table[(value &gt;&gt; 12) &amp; 0x3F]; output[index + 2] = (i + 1) &lt; length ? table[(value &gt;&gt; 6) &amp; 0x3F] : '='; output[index + 3] = (i + 2) &lt; length ? table[(value &gt;&gt; 0) &amp; 0x3F] : '='; } ret urn [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; } </code></pre> <p>all this code gives me is errors. Or BAD URL or java exception.</p> <p>What is wrong with this code?</p> <p>If you guys prefer to give another solution using the json-framework please tell me how to encode the object using that pair ("code", "my NSData here converted to string")...</p> <p>thanks for any help.</p>
1,518,569
1
0
null
2009-10-05 04:37:58.44 UTC
10
2012-09-02 16:35:59.527 UTC
2012-09-02 16:35:59.527 UTC
null
264,419
null
316,469
null
1
5
iphone|objective-c|json|iphone-sdk-3.0
14,569
<p>JSON framework supports converting Arrays, Dictionaries, Strings, Numbers, and Booleans. So what you want to do is convert your data to one of these formats. Since your data is NSData easiest way is to convert it with:</p> <pre><code>NSString* stringData = [[NSString alloc] initWithData:yourData encoding:NSUTF8StringEncoding]; </code></pre> <p>Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (check <a href="http://www.cocoadev.com/index.pl?BaseSixtyFour" rel="noreferrer">http://www.cocoadev.com/index.pl?BaseSixtyFour</a> if you don't have a converter handy). You could even go straight from NSData to a Base64-encoded string.</p> <p>Now create a dictionary with one item with key <code>code</code> and value <code>stringData</code> (from last step):</p> <pre><code>NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData forKey:@"code"]; </code></pre> <p>This can be easily converted to JSON. Just import JSON.h in your code header, then use:</p> <pre><code>NSString* jsonString = [jsonDictionary JSONRepresentation]; </code></pre> <p>Dump it out and you'll see your JSON string -- something like: { <code>"code" : "{yourstringdata}"; }</code>. Easiest way to send this over to your server is to use the <a href="http://allseeing-i.com/ASIHTTPRequest/" rel="noreferrer">ASIHTTPRequest</a> library with a POST method.</p> <p>Once you get the result back from the server the JSON framework can parse it back into a dictionary and then you can get out the data you need:</p> <pre><code>NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue]; NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"]; int answer = [answerNum intValue]; </code></pre>
30,115,242
Generating a Simple QR-Code with just HTML
<p>I came across this <code>APIserver</code> to generate the QRCode but I was wondering is it possible to just use HTML to generate the QRcode for example this is what I was thinking</p> <pre class="lang-html prettyprint-override"><code>&lt;input id=&quot;text&quot; type=&quot;text&quot; value=&quot;Please Enter Your NRIC or Work Permit&quot; style=&quot;Width:20%&quot;/&gt; &lt;img src=&quot;https://api.qrserver.com/v1/create-qr-code/?data=HelloWorld&amp;amp;size=100x100&quot; alt=&quot;&quot; title=&quot;HELLO&quot; /&gt; </code></pre> <p>In the &quot;title&quot; I believe it is where you will write your text and the QR code would generate, I was wondering how can I create a text box for me to key in the value directly on a website.</p>
30,115,477
1
0
null
2015-05-08 03:24:50.303 UTC
1
2021-08-23 04:15:46.883 UTC
2020-07-15 09:29:58.407 UTC
null
9,154,188
null
4,848,728
null
1
10
qr-code
83,846
<p>Were you thinking of something like this? <a href="https://jsfiddle.net/v7d6d1ps/" rel="noreferrer">https://jsfiddle.net/v7d6d1ps/</a></p> <p>Your HTML can be similar to what you have but with added onblur event. Only HTML cannot do this, so I have added jQuery/JavaScript combination.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Testing QR code&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function generateBarCode() { var nric = $('#text').val(); var url = 'https://api.qrserver.com/v1/create-qr-code/?data=' + nric + '&amp;amp;size=50x50'; $('#barcode').attr('src', url); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input id="text" type="text" value="NRIC or Work Permit" style="Width:20%" onblur='generateBarCode();' /&gt; &lt;img id='barcode' src="https://api.qrserver.com/v1/create-qr-code/?data=HelloWorld&amp;amp;size=100x100" alt="" title="HELLO" width="50" height="50" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Copy and paste this into an HTML file on your desktop. Type in the text box 12345 and hit tab. Notice that the QR code will update.</p>
37,039,943
Spark Scala: How to transform a column in a DF
<p>I have a dataframe in Spark with many columns and a udf that I defined. I want the same dataframe back, except with one column transformed. Furthermore, my udf takes in a string and returns a timestamp. Is there an easy way to do this? I tried</p> <pre><code>val test = myDF.select("my_column").rdd.map(r =&gt; getTimestamp(r)) </code></pre> <p>but this returns an RDD and just with the transformed column. </p>
37,039,990
1
0
null
2016-05-04 23:44:46.117 UTC
13
2022-09-13 14:24:14.973 UTC
2016-05-05 00:32:37.663 UTC
null
3,864,822
null
3,689,314
null
1
29
scala|apache-spark
42,800
<p>If you really need to use your function, I can suggest two options:</p> <ol> <li><p>Using map / toDF:</p> <pre><code>import org.apache.spark.sql.Row import sqlContext.implicits._ def getTimestamp: (String =&gt; java.sql.Timestamp) = // your function here val test = myDF.select(&quot;my_column&quot;).rdd.map { case Row(string_val: String) =&gt; (string_val, getTimestamp(string_val)) }.toDF(&quot;my_column&quot;, &quot;new_column&quot;) </code></pre> </li> <li><p>Using UDFs (<code>UserDefinedFunction</code>):</p> <pre><code>import org.apache.spark.sql.functions._ def getTimestamp: (String =&gt; java.sql.Timestamp) = // your function here val newCol = udf(getTimestamp).apply(col(&quot;my_column&quot;)) // creates the new column val test = myDF.withColumn(&quot;new_column&quot;, newCol) // adds the new column to original DF </code></pre> </li> </ol> <hr /> <p><strong>Alternatively</strong>,</p> <p>If you just want to transform a <code>StringType</code> column into a <code>TimestampType</code> column you can use the <code>unix_timestamp</code> <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$" rel="nofollow noreferrer">column function</a> available since Spark SQL 1.5:</p> <pre><code>val test = myDF .withColumn(&quot;new_column&quot;, unix_timestamp(col(&quot;my_column&quot;), &quot;yyyy-MM-dd HH:mm&quot;) .cast(&quot;timestamp&quot;)) </code></pre> <p>Note: For spark 1.5.x, it is necessary to multiply the result of <code>unix_timestamp</code> by <code>1000</code> before casting to timestamp (issue <a href="https://issues.apache.org/jira/browse/SPARK-11724" rel="nofollow noreferrer">SPARK-11724</a>). The resulting code would be:</p> <pre><code>val test = myDF .withColumn(&quot;new_column&quot;, (unix_timestamp(col(&quot;my_column&quot;), &quot;yyyy-MM-dd HH:mm&quot;) *1000L) .cast(&quot;timestamp&quot;)) </code></pre> <p><em>Edit: Added udf option</em></p>
20,674,720
Backup/Restore from different database causing Restore failed exclusive access could not be obtained
<p>I have a database A. I have taken a backup of database A called A.bak. I created a new database B. Now, I right click and Restore B from A.bak. In the Restore Dialog, I checked overwrite existing database and change the LogicalFileName from <code>C:\Program Files\Microsoft SQL Server\MSSQL11.SQLSERVER2012\MSSQL\DATA\A.mdf</code> to <code>C:\Program Files\Microsoft SQL Server\MSSQL11.SQLSERVER2012\MSSQL\DATA\B.mdf</code> and did the same with ldf file. But I am getting </p> <p><code>Exclusive access could not be obtained because the database is in use</code>.</p> <p>Also tried,</p> <pre><code>ALTER DATABASE [B] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; </code></pre> <p>Also sp_who2, there was no existing connection of [B]</p>
22,363,859
3
0
null
2013-12-19 06:23:05.673 UTC
3
2015-09-13 11:58:36.583 UTC
2013-12-19 07:18:34.823 UTC
null
960,567
null
960,567
null
1
26
sql|sql-server|sql-server-2012
40,230
<p>A cause for the attempt to get exclusive access comes from the options page of the restore dialog in SQL Server 2012 Management Studio. It will turn on tail-log and leave in restoring state options for the SOURCE database. So, it will try to gain exclusive access to the source database (in this case A) in order to perform this action. If you turn off the tail log option, you will find that the operation works much more smoothly.</p>
27,251,644
How to get 1 hour ago from a date in iOS swift?
<p>I have been researching, but I couldnt find exact solution for my problem. I have been trying to get 1 hour ago from a date. How can I achieve this in swift?</p>
27,251,855
14
0
null
2014-12-02 14:19:23.127 UTC
18
2021-02-24 17:11:51.917 UTC
2018-04-06 04:42:16.703 UTC
null
7,576,100
null
4,300,689
null
1
52
ios|iphone|swift|date
42,983
<p>For correct calculations involving NSDate that take into account all edge cases of different calendars (e.g. switching between day saving time) you should use NSCalendar class:</p> <p><strong>Swift 3+</strong></p> <pre><code>let earlyDate = Calendar.current.date( byAdding: .hour, value: -1, to: Date()) </code></pre> <p><strong>Older</strong></p> <pre><code>// Get the date that was 1hr before now let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit( .Hour, value: -1, toDate: NSDate(), options: []) </code></pre>
30,355,185
How to read an integer input from the user in Rust 1.0?
<p>Existing answers I've found are all based on <code>from_str</code> (such as <a href="https://stackoverflow.com/q/25632070/155423">Reading in user input from console once efficiently</a>), but apparently <code>from_str(x)</code> has changed into <code>x.parse()</code> in Rust 1.0. As a newbie, it's not obvious how the original solution should be adapted taking this change into account. </p> <p>As of Rust 1.0, what is the easiest way to get an integer input from the user? </p>
30,355,925
8
0
null
2015-05-20 16:17:27.2 UTC
6
2021-11-27 18:52:31.87 UTC
2017-09-27 16:26:04.093 UTC
null
155,423
null
8,127
null
1
30
input|integer|rust|user-input
38,169
<p>Here is a version with all optional type annotations and error handling which may be useful for beginners like me:</p> <pre><code>use std::io; fn main() { let mut input_text = String::new(); io::stdin() .read_line(&amp;mut input_text) .expect("failed to read from stdin"); let trimmed = input_text.trim(); match trimmed.parse::&lt;u32&gt;() { Ok(i) =&gt; println!("your integer input: {}", i), Err(..) =&gt; println!("this was not an integer: {}", trimmed), }; } </code></pre>
30,535,309
Where should I define JS function to call in EJS template
<p>I am working on a template where I am trying to render template using express and ejs. As to the standard structure of node app, I have app.js file which which contains functions like following:</p> <pre><code>app.locals.getFlag = function(country) { var flag_img_name = ""; if (country.toLowerCase() == "us") { flag_img_name = "flag_us16x13.gif"; } else if (country.toLowerCase() == "ca"){ flag_img_name = "flag_ca16x13.gif"; } return flag_img_name; } </code></pre> <p>I have some_template.ejs file which calls this function like follows:</p> <pre><code>&lt;img src="http://some_url_path/&lt;%=getFlag(data_point[0].country_name) %&gt;" width="16" height="14" alt="country" &gt; </code></pre> <p>and it works just fine. However, I have around 15-20 functions like this and I don't want to define all of them in app.js. Is there any other place where I can define these functions and call them in the template same way as I am doing now? If yes, what would be the way to define them so that they are accessible like they are right now.</p> <p>I am new to node, express and ejs and not sure of different techniques. If someone could shed a light over it, it would be great. Thank you in advance.</p>
30,539,675
7
0
null
2015-05-29 17:07:35.217 UTC
10
2020-01-31 07:06:16.21 UTC
null
null
null
null
3,482,656
null
1
30
node.js|express|ejs
56,352
<p>Just posting this answer here for someone who would might end up on this question while resolving same issue.</p> <p>All you have to do is create new file (say <code>functions.ejs</code>) and include it in the .ejs file where you want to call that function. So, I have function like this in file named <code>functions.ejs</code>:</p> <pre><code>&lt;% getPriceChgArrow = function(value) { arrow_img_name = ""; if (value &lt; 0) { arrow_img_name = "arrow_down12x13.gif"; } else { arrow_img_name = "arrow_up12x13.gif"; } return arrow_img_name; } %&gt; </code></pre> <p>Then include <code>functions.ejs</code> into the file you want to call function from. Say, I want to call this function in <code>quote.ejs</code> file. So, I would include it as follows:</p> <pre><code>&lt;% include *file_path*/functions %&gt; </code></pre> <p>Just use this function at appropriate location in your ejs file from where you want to call it. For example:</p> <pre><code>&lt;img src = "http:/some_url/&lt;% getPriceChgArrow(data_point[0].value) %&gt;" /&gt; </code></pre> <p>and you are all set. Hope this helps someone.</p>
30,590,243
Using Laravel Socialite to login to facebook
<p>I am new to Laravel however and I am following the tutorial on <a href="http://www.codeanchor.net/blog/complete-laravel-socialite-tutorial/" rel="noreferrer">http://www.codeanchor.net/blog/complete-laravel-socialite-tutorial/</a>, to login a user through Facebook into my application. However, almost everywhere I find a tutorial using either Github or Twitter for the Socialite Plugin provided in Laravel.</p> <p>My problem is that on following everything in the tutorial, as I click on the "Login to Facebook" button, it throws an "Invalid Argument Exception" with No Socialite driver was specified.".</p> <p>Another stack overflow question seemed to narrow things down: <a href="https://stackoverflow.com/questions/29673898/laravel-socialite-invalidargumentexception-in-socialitemanager-php-line-138-n">https://stackoverflow.com/questions/29673898/laravel-socialite-invalidargumentexception-in-socialitemanager-php-line-138-n</a></p> <p>Stating that the problem is in the config/services.php</p> <p>Now, i have the app_id and app_secret. However, the redirect link seems to be confusing as I can't find it on Facebook either. I am aware that this is where my app should go to Facebook for login, however, unsure of what it should be.</p> <p>Does anyone have any idea on this.</p>
30,590,747
3
0
null
2015-06-02 07:45:00.03 UTC
15
2018-07-26 11:44:03.397 UTC
2017-05-23 12:34:41.687 UTC
null
-1
null
325,533
null
1
16
php|facebook|facebook-graph-api|laravel|laravel-socialite
38,460
<p>In your composer.json add- <code>"laravel/socialite": "~2.0",</code></p> <pre><code>"require": { "laravel/framework": "5.0.*", "laravel/socialite": "~2.0", </code></pre> <p>the run <code>composer update</code></p> <p>In <strong>config/services.php</strong> add:</p> <pre><code>//Socialite 'facebook' =&gt; [ 'client_id' =&gt; '1234567890444', 'client_secret' =&gt; '1aa2af333336fffvvvffffvff', 'redirect' =&gt; 'http://laravel.dev/login/callback/facebook', ], </code></pre> <p>You need to create two routes, mine are like these:</p> <pre><code>//Social Login Route::get('/login/{provider?}',[ 'uses' =&gt; 'AuthController@getSocialAuth', 'as' =&gt; 'auth.getSocialAuth' ]); Route::get('/login/callback/{provider?}',[ 'uses' =&gt; 'AuthController@getSocialAuthCallback', 'as' =&gt; 'auth.getSocialAuthCallback' ]); </code></pre> <p>You also need to create controller for the routes above like so:</p> <pre><code>&lt;?php namespace App\Http\Controllers; use Laravel\Socialite\Contracts\Factory as Socialite; class AuthController extends Controller { public function __construct(Socialite $socialite){ $this-&gt;socialite = $socialite; } public function getSocialAuth($provider=null) { if(!config("services.$provider")) abort('404'); //just to handle providers that doesn't exist return $this-&gt;socialite-&gt;with($provider)-&gt;redirect(); } public function getSocialAuthCallback($provider=null) { if($user = $this-&gt;socialite-&gt;with($provider)-&gt;user()){ dd($user); }else{ return 'something went wrong'; } } } </code></pre> <p>and finally add Site URL to your Facebook App like so:</p> <p><img src="https://i.stack.imgur.com/APwCK.png" alt="enter image description here"></p>
26,561,604
Create Named Pipe C++ Windows
<p>I am trying to create a simple comunication between 2 processes in C++ ( Windows ) like FIFO in linux. This is my server:</p> <pre><code>int main() { HANDLE pipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); ConnectNamedPipe(pipe, NULL); while(TRUE){ string data; DWORD numRead =1 ; ReadFile(pipe, &amp;data, 1024, &amp;numRead, NULL); cout &lt;&lt; data &lt;&lt; endl; } CloseHandle(pipe); return 0; } </code></pre> <p>And this is my client:</p> <pre><code>int main() { HANDLE pipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); ConnectNamedPipe(pipe, NULL); string message = "TEST"; DWORD numWritten; WriteFile(pipe, message.c_str(), message.length(), &amp;numWritten, NULL); return 0; } </code></pre> <p>The code does't work , how can i fixed it to like FIFO ? </p>
26,561,999
1
0
null
2014-10-25 10:53:48.883 UTC
32
2020-02-28 09:42:37.507 UTC
2020-02-28 09:42:37.507 UTC
null
995,714
null
3,052,078
null
1
27
windows|c++11|ipc|named-pipes|fifo
90,985
<p>You cannot create a named pipe by calling <code>CreateFile(..)</code>.</p> <p>Have a look at the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365799%28v=vs.85%29.aspx" rel="noreferrer">pipe examples of the MSDN</a>. Since these examples are quite complex I've quickly written a <strong>VERY</strong> simple named pipe server and client.</p> <pre><code>int main(void) { HANDLE hPipe; char buffer[1024]; DWORD dwRead; hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists... 1, 1024 * 16, 1024 * 16, NMPWAIT_USE_DEFAULT_WAIT, NULL); while (hPipe != INVALID_HANDLE_VALUE) { if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe { while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &amp;dwRead, NULL) != FALSE) { /* add terminating zero */ buffer[dwRead] = '\0'; /* do something with data in buffer */ printf("%s", buffer); } } DisconnectNamedPipe(hPipe); } return 0; } </code></pre> <p>And here is the client code:</p> <pre><code>int main(void) { HANDLE hPipe; DWORD dwWritten; hPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe != INVALID_HANDLE_VALUE) { WriteFile(hPipe, "Hello Pipe\n", 12, // = length of string + terminating '\0' !!! &amp;dwWritten, NULL); CloseHandle(hPipe); } return (0); } </code></pre> <p>You should replace the name of the pipe <code>TEXT("\\\\.\\pipe\\Pipe")</code> by a #define which is located in a commonly used header file.</p>
27,652,686
Python: What does for x in A[1:] mean?
<p>I was trying to understand Kadane's algorithm from Wikipedia, when I found this:</p> <pre><code>def max_subarray(A): max_ending_here = max_so_far = A[0] for x in A[1:]: max_ending_here = max(x, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far </code></pre> <p>I'm not familiar with Python. I tried to google what this syntax does but I couldn't find the right answer because I didn't know what's it called. But, I figured <code>A[1:]</code> is the equivalent of omitting <code>A[0]</code>, so I thought <code>for x in A[1:]:</code> is equivalent to <code>for(int i = 1; i &lt; A.length; i++)</code> in Java</p> <p>But, after changing <code>for x in A[1:]:</code> to <code>for x in range(1,len(A))</code>, I got the wrong result</p> <p>Sorry if this is a stupid question, but I don't know where else to find the answer. Can somebody tell me what this syntax does and what is it called? Also, could you give me the equivalent of <code>for x in A[1:]:</code> in Java?</p>
27,652,711
6
0
null
2014-12-26 03:58:06.073 UTC
13
2021-11-25 09:47:32.747 UTC
null
null
null
null
4,383,783
null
1
17
python
89,547
<p>This is <a href="https://docs.python.org/2/tutorial/introduction.html#lists" rel="noreferrer">array slice</a> syntax. See this SO question: <a href="https://stackoverflow.com/questions/509211/explain-pythons-slice-notation">Explain Python&#39;s slice notation</a> .</p> <p>For a list <code>my_list</code> of objects e.g. <code>[1, 2, "foo", "bar"]</code>, <code>my_list[1:]</code> is equivalent to a shallow copied list of all elements starting from the 0-indexed <code>1</code>: <code>[2, "foo", "bar"]</code>. So your <code>for</code> statement iterates over these objects:</p> <pre><code>for-iteration 0: x == 2 for-iteration 1: x == "foo" for-iteration 2: x == "bar" </code></pre> <p><code>range(..)</code> returns a list/generator of indices (integers), so your for statement would iterate over integers <code>[1, 2, ..., len(my_list)]</code></p> <pre><code>for-iteration 0: x == 1 for-iteration 1: x == 2 for-iteration 2: x == 3 </code></pre> <p>So in this latter version you could use <code>x</code> as an index into the list: <code>iter_obj = my_list[x]</code>.</p> <p>Alternatively, a slightly more pythonic version if you still need the iteration index (e.g. for the "count" of the current object), you could use <code>enumerate</code>:</p> <pre><code>for (i, x) in enumerate(my_list[1:]): # i is the 0-based index into the truncated list [0, 1, 2] # x is the current object from the truncated list [2, "foo", "bar"] </code></pre> <p>This version is a bit more future proof if you decide to change the type of <code>my_list</code> to something else, in that it does not rely on implementation detail of 0-based indexing, and is therefore more likely to work with other iterable types that support slice syntax.</p>
27,689,425
How to make maven build of child module with parent module?
<p>I have multiple modules in my project and they are dependent on each other either directly or transitively. When I maven build «Project A» some where «Project D» gets build automatically.</p> <pre><code>Project A &gt; Project B &gt; Project C &gt; Project D where &gt; means Project B depends on Project A </code></pre> <p>«Project D» pom snipeet is:</p> <pre class="lang-xml prettyprint-override"><code>&lt;project xmlns="..."&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.myProduct&lt;/groupId&gt; &lt;artifactId&gt;build-MyProjectD&lt;/artifactId&gt; &lt;name&gt;MyProjectD&lt;/name&gt; ........ &lt;/project&gt; </code></pre> <p>As building «Project A» automatically build «Project B», as per my understanding to make this happen somewhere <code>build-MyProjectD</code> should be added as dependency in one of these projects <code>Project A &gt; Project B &gt; Project C</code> but I did not find any reference of string <code>build-MyProjectD</code> under poms of these projects.</p> <p>Any idea how is there any other way to make build of child module (in this case «Project D») without having child <code>artifactId</code> presence in upstream project?</p>
27,689,569
2
1
null
2014-12-29 13:00:37.14 UTC
3
2016-03-04 10:12:42.04 UTC
2016-03-04 10:12:42.04 UTC
null
490,018
null
3,907,459
null
1
13
java|maven|pom.xml
50,981
<p>You need to create an aggregator project. See <a href="http://maven.apache.org/pom.html#Aggregation" rel="noreferrer">the link for more information on the aggregation concept</a>.</p> <p>Basically, you create a parent project containing several "modules". When building the parent, the modules automatically gets built as well.</p> <p>If you declare dependencies between the modules, Maven will automatically build the different modules in a correct order so that if «Project A» depends on «Project B», «Project B» is built first and then «Project A» is built so that its artifact is available for the building of the second artifact.</p> <p>See also <a href="http://maven.apache.org/guides/getting-started/index.html#How_do_I_build_more_than_one_project_at_once" rel="noreferrer">this question from the Maven's FAQ</a>.</p>
44,383,601
AWS elastic-search. FORBIDDEN/8/index write (api). Unable to write to index
<p>I am trying dump a list of docs to an AWS elastic-search instance. It was running fine. Then, all of sudden it started throwing this error:</p> <pre><code>{ _index: '&lt;my index name&gt;', _type: 'type', _id: 'record id', status: 403, error: { type: 'cluster_block_exception', reason: 'blocked by: [FORBIDDEN/8/index write (api)];' } } </code></pre> <p>I checked in forums. Most of them says that it is a JVM memory issue. If it is going more than 92%, AWS will stop any writes to the cluster/index. However, when I checked the JVM memory, it shows less than 92%. I am missing something here?</p>
47,745,128
5
0
null
2017-06-06 07:15:27.247 UTC
8
2022-09-23 08:34:42.12 UTC
2021-09-29 20:08:23.943 UTC
null
321,731
null
5,453,496
null
1
48
amazon-web-services|elasticsearch
37,335
<p>This error is the Amazon ES service actively blocking writes to protect the cluster from reaching red or yellow status. It does this using <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.0/index-modules.html#dynamic-index-settings" rel="noreferrer"><code>index.blocks.write</code></a>.</p> <p>The two reasons being:</p> <p><strong><a href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/aes-handling-errors.html#aes-handling-errors-block-disks" rel="noreferrer">Low Memory</a></strong></p> <blockquote> <p>When the JVMMemoryPressure metric exceeds 92% for 30 minutes, Amazon ES triggers a protection mechanism and blocks all write operations to prevent the cluster from reaching red status. When the protection is on, write operations fail with a ClusterBlockException error, new indexes can't be created, and the IndexCreateBlockException error is thrown.</p> <p>When the JVMMemoryPressure metric returns to 88% or lower for five minutes, the protection is disabled, and write operations to the cluster are unblocked.</p> </blockquote> <p><strong><a href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/aes-handling-errors.html#aes-handling-errors-watermark" rel="noreferrer">Low Disk Space</a></strong></p> <blockquote> <p>Elasticsearch has a default &quot;low watermark&quot; of 85%, meaning that once disk usage exceeds 85%, Elasticsearch no longer allocates shards to that node. Elasticsearch also has a default &quot;high watermark&quot; of 90%, at which point it attempts to relocate shards to other nodes.</p> </blockquote>
34,440,604
Whether to use invokeAll or submit - java Executor service
<p>I have a scenario where I have to execute 5 thread asynchronously for the same callable. As far as I understand, there are two options:</p> <p>1) using submit(Callable)</p> <pre><code>ExecutorService executorService = Executors.newFixedThreadPool(5); List&lt;Future&lt;String&gt;&gt; futures = new ArrayList&lt;&gt;(); for(Callable callableItem: myCallableList){ futures.add(executorService.submit(callableItem)); } </code></pre> <p>2) using invokeAll(Collections of Callable)</p> <pre><code>ExecutorService executorService = Executors.newFixedThreadPool(5); List&lt;Future&lt;String&gt;&gt; futures = executorService.invokeAll(myCallableList)); </code></pre> <ol> <li>What should be the preferred way?</li> <li>Is there any disadvantage or performance impact in any of them compared to the other one?</li> </ol>
34,798,567
3
0
null
2015-12-23 17:10:45.403 UTC
10
2019-12-31 09:40:51.467 UTC
2015-12-23 17:40:58.167 UTC
null
810,176
null
810,176
null
1
25
java|concurrency|executorservice|java.util.concurrent
25,043
<p><strong>Option 1</strong> : You are submitting the tasks to <code>ExecutorService</code> and you are not waiting for the completion of all tasks, which have been submitted to <code>ExecutorService</code></p> <p><strong>Option 2</strong> : You are waiting for completion of all tasks, which have been submitted to <code>ExecutorService</code>.</p> <blockquote> <p>What should be the preferred way?</p> </blockquote> <p>Depending on application requirement, either of them is preferred.</p> <ol> <li>If you don't want to wait after task submit() to <code>ExecutorService</code>, prefer <code>Option 1</code>.</li> <li>If you need to wait for completion of all tasks, which have been submitted to <code>ExecutorService</code>, prefer <code>Option 2</code>. </li> </ol> <blockquote> <p>Is there any disadvantage or performance impact in any of them compared to the other one?</p> </blockquote> <p>If your application demands Option 2, you have to wait for completion of all tasks submitted to <code>ExecutorService</code> unlike in Option 1. Performance is not criteria for comparison as both are designed for two different purposes. </p> <p>And one more important thing: Whatever option you prefer, <code>FutureTask</code> swallows Exceptions during task execution. You have to be careful. Have a look at this SE question: <a href="https://stackoverflow.com/questions/2554549/handling-exceptions-for-threadpoolexecutor/34640459#34640459">Handling Exceptions for ThreadPoolExecutor</a></p> <p>With Java 8, you have one more option: <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorCompletionService.html" rel="noreferrer">ExecutorCompletionService</a></p> <blockquote> <p>A <strong><em>CompletionService</em></strong> that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.</p> </blockquote> <p>Have a look at related SE question: <a href="https://stackoverflow.com/questions/11872520/executorcompletionservice-why-do-need-one-if-we-have-invokeall">ExecutorCompletionService? Why do need one if we have invokeAll?</a></p>
34,800,331
r modify and rebuild package
<p>I'm trying to use the SemiMarkov package and I want to change one small line of code in there. I've done some digging via:</p> <pre><code>getAnywhere("semiMarkov") </code></pre> <p>&amp; I've identified that I want to change this line:</p> <pre><code>hessian &lt;- diag(ginv(hessian(V, solution))) </code></pre> <p>to try something like:</p> <pre><code>hessian &lt;- diag(ginv(pracma::hessian(V, solution))) </code></pre> <p>How do I go about this? Do I need to rebuild the package from scratch, and if so do I need rTools etc for this, or is there a simple-ish workaround (I'm a relevant R novice)? I've done some searching online and can't find anything obvious. Any ideas/pointers gratefully appreciated.</p>
34,800,599
2
0
null
2016-01-14 21:44:34.473 UTC
13
2016-01-15 21:28:50.917 UTC
2016-01-14 21:57:15.297 UTC
null
5,730,082
null
5,730,082
null
1
24
r|package|rebuild
26,608
<h1>Linux environment</h1> <p>Starting with downloading the package source from CRAN. </p> <ul> <li>This is the landing page: <a href="https://cran.r-project.org/web/packages/SemiMarkov/index.html" rel="noreferrer">https://cran.r-project.org/web/packages/SemiMarkov/index.html</a> </li> <li>This is the package source: <a href="https://cran.r-project.org/src/contrib/SemiMarkov_1.4.2.tar.gz" rel="noreferrer">https://cran.r-project.org/src/contrib/SemiMarkov_1.4.2.tar.gz</a></li> </ul> <p>Download and extract the source: </p> <pre><code>wget https://cran.r-project.org/src/contrib/SemiMarkov_1.4.2.tar.gz tar -xvzf SemiMarkov_1.4.2.tar.gz </code></pre> <p>This should result in a directory named <code>SemiMarkov</code>. Open up the source (<code>cd SemiMarkov</code>), and modify as necessary. </p> <p>Next, build the changes: </p> <pre><code>cd .. R CMD build SemiMarkov/ </code></pre> <p>This will result in a new archive file named <code>SemiMarkov_1.4.2.tar.gz</code>. </p> <p>Lastly, install your modified archive:</p> <pre><code>R CMD INSTALL SemiMarkov_1.4.2.tar.gz </code></pre> <h1>Windows environment</h1> <p>I'm less familiar with the Windows platform. *nix tooling is available in Cygwin, but it's painful. Instead, as Josh O'Brien points out, you should follow the <a href="https://cran.r-project.org/doc/manuals/r-release/R-admin.html#The-Windows-toolset" rel="noreferrer">Windows-specific instructions</a> in the R Installation and Administration manual.</p>
26,389,952
Powershell export-csv with no headers?
<p>So I'm trying to export a list of resources without the headers. Basically I need to omit line 1, "Name".</p> <p>Here is my current code:</p> <pre><code>Get-Mailbox -RecipientTypeDetails RoomMailbox,EquipmentMailbox | Select-Object Name | Export-Csv -Path "$(get-date -f MM-dd-yyyy)_Resources.csv" -NoTypeInformation </code></pre> <p>I've looked at several examples and things to try, but haven't quite gotten anything to work that still only lists the resource names.</p> <p>Any suggestions? Thanks in advance!</p>
26,390,115
2
0
null
2014-10-15 18:51:56.913 UTC
2
2021-04-16 18:27:16.347 UTC
2014-10-15 18:57:00.25 UTC
null
3,861,838
null
3,861,838
null
1
21
powershell|export|office365
81,104
<p>It sounds like you basically want just text a file list of the names:</p> <pre><code>Get-Mailbox -RecipientTypeDetails RoomMailbox,EquipmentMailbox | Select-Object -ExpandProperty Name | Set-Content -Path "$(get-date -f MM-dd-yyyy)_Resources.txt" </code></pre> <p>Edit: if you really want an export-csv without a header row:</p> <pre><code>(Get-Mailbox -RecipientTypeDetails RoomMailbox,EquipmentMailbox | Select-Object Name | ConvertTo-Csv -NoTypeInformation) | Select-Object -Skip 1 | Set-Content -Path "$(get-date -f MM-dd-yyyy)_Resources.csv" </code></pre>
24,659,005
Radar chart with multiple scales on multiple axes
<p>I want to plot a radar chart with multiple scales on multiple axes using <code>matplotlib</code>. <a href="http://matplotlib.org/examples/api/radar_chart.html" rel="noreferrer">The official API example</a> gives only one scale on one axis. (Scales are 0.2,0.4,0.6,0.8 in this example)</p> <p>I want different scales on all axes. (There are 9 axes in the given example.)</p> <p>I found an example of what I am looking for <a href="http://www.scottlogic.com/blog/archive/2011/09/few.png" rel="noreferrer">here</a>. There are 5 axes on this example and 5 scales on all axes just like I want.</p>
24,669,479
1
0
null
2014-07-09 16:24:06.413 UTC
9
2022-03-23 12:44:23.92 UTC
null
null
null
null
547,820
null
1
14
python|matplotlib|plot
21,946
<p>I think you can plot this with multiple axes, the lines are in the first axe, and other axes only shows ticklabels.</p> <pre><code>import numpy as np import pylab as pl class Radar(object): def __init__(self, fig, titles, labels, rect=None): if rect is None: rect = [0.05, 0.05, 0.95, 0.95] self.n = len(titles) self.angles = np.arange(90, 90+360, 360.0/self.n) self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i) for i in range(self.n)] self.ax = self.axes[0] self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14) for ax in self.axes[1:]: ax.patch.set_visible(False) ax.grid("off") ax.xaxis.set_visible(False) for ax, angle, label in zip(self.axes, self.angles, labels): ax.set_rgrids(range(1, 6), angle=angle, labels=label) ax.spines["polar"].set_visible(False) ax.set_ylim(0, 5) def plot(self, values, *args, **kw): angle = np.deg2rad(np.r_[self.angles, self.angles[0]]) values = np.r_[values, values[0]] self.ax.plot(angle, values, *args, **kw) fig = pl.figure(figsize=(6, 6)) titles = list("ABCDE") labels = [ list("abcde"), list("12345"), list("uvwxy"), ["one", "two", "three", "four", "five"], list("jklmn") ] radar = Radar(fig, titles, labels) radar.plot([1, 3, 2, 5, 4], "-", lw=2, color="b", alpha=0.4, label="first") radar.plot([2.3, 2, 3, 3, 2],"-", lw=2, color="r", alpha=0.4, label="second") radar.plot([3, 4, 3, 4, 2], "-", lw=2, color="g", alpha=0.4, label="third") radar.ax.legend() </code></pre> <p><img src="https://i.stack.imgur.com/2ATlI.png" alt="enter image description here"></p>
6,048,661
How to place a character below a function in Latex?
<p>Is it possible to place a character or a formula below an other part of a larger formula in Latex?</p> <pre><code>foo f(x) = ... x </code></pre> <p>In case that this example is not clear. I'd like to make one of my custom functions - just defined as <code>\text{foo}</code> in a math environment - look like one of the built-in functions like sum, min or max which accept parameters that are placed above or below the function symbol.</p> <p>Simply using <code>\text{foo}_x</code> does not work.</p>
6,049,281
3
1
null
2011-05-18 17:28:10.883 UTC
3
2015-08-30 21:58:15.437 UTC
2013-12-07 21:30:03.593 UTC
null
759,866
null
114,490
null
1
18
math|latex
82,750
<p>The function you're looking for is <code>\underset</code> provided by the <code>amsmath</code> package. Here's an example:</p> <pre><code>\documentclass{article} \usepackage{amsmath} \begin{document} $\underset{below}{above}$ \end{document} </code></pre> <p>Output:</p> <p><img src="https://i.stack.imgur.com/dS9J7.png" alt="enter image description here"></p>
5,865,069
Why is this Java code in curly braces ({}) outside of a method?
<p>I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests: </p> <pre><code>class Foo { int x = 1; public static void main(String [] args) { int x = 2; Foo f = new Foo(); f.whatever(); } { x += x; } // &lt;-- what's up with this? void whatever() { ++x; System.out.println(x); } } </code></pre> <p>My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?</p>
5,865,116
3
5
null
2011-05-03 04:38:39.68 UTC
11
2021-12-27 17:24:52.42 UTC
2014-11-25 12:19:21.577 UTC
user166390
1,681,681
null
126,077
null
1
31
java|syntax|braces
22,064
<p>Borrowed from <a href="http://download.oracle.com/javase/tutorial/java/javaOO/initial.html" rel="noreferrer">here</a> -</p> <blockquote> <p>Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:</p> <pre><code>{ // whatever code is needed for initialization goes here } </code></pre> <p>The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.</p> </blockquote> <p>You may also wanna look at the discussions <a href="https://stackoverflow.com/questions/2007666/in-what-order-do-static-initializer-blocks-in-java-run">here</a>.</p>
5,606,915
iOS download and save HTML file
<p>I am trying to download a webpage (html) then display the local html that has been download in a UIWebView. </p> <p>This is what I have tried -</p> <pre><code>NSString *stringURL = @"url to file"; NSURL *url = [NSURL URLWithString:stringURL]; NSData *urlData = [NSData dataWithContentsOfURL:url]; if ( urlData ) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"index.html"]; [urlData writeToFile:filePath atomically:YES]; } //Load the request in the UIWebView. [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]]; // Do any additional setup after loading the view from its nib. </code></pre> <p>But this gives a 'SIGABRT' error.</p> <p>Not too sure what I have done wrong?</p> <p>Any help would be appreciated. Thanks!</p>
5,607,132
4
1
null
2011-04-09 18:17:08.6 UTC
10
2016-10-31 13:30:53.473 UTC
null
null
null
null
443,859
null
1
17
iphone|xcode|ios|ios4|uiwebview
36,323
<p>The path passed to the UIWebView is incorrect, like Freerunnering mentioned, try this instead:</p> <pre><code>// Determile cache file path NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"]; // Download and write to file NSURL *url = [NSURL URLWithString:@"http://www.google.nl"]; NSData *urlData = [NSData dataWithContentsOfURL:url]; [urlData writeToFile:filePath atomically:YES]; // Load file in UIWebView [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]]; </code></pre> <p>Note: Correct error-handling needs to be added.</p>
1,945,722
Selecting between two dates within a DateTime field - SQL Server
<p>How to select records between a date to another date given a DateTime field in a table.</p>
1,945,744
2
2
null
2009-12-22 11:10:30.72 UTC
6
2020-09-08 22:42:22.843 UTC
2015-12-17 15:08:47.69 UTC
null
2,451,726
null
207,556
null
1
18
sql|sql-server-2005|datetime
138,031
<pre><code>SELECT * FROM tbl WHERE myDate BETWEEN #date one# AND #date two#; </code></pre>
1,449,370
latex error: environment proof undefined
<p>hi i am using latex... wanted to use the following:</p> <pre><code> \begin{proof} ... \end{proof} </code></pre> <p>it gives me the following error: !Latex error: Environment proof undefined. can you help me to solve this problem? thanks</p>
1,449,403
2
0
null
2009-09-19 19:56:01.67 UTC
1
2018-03-09 01:14:55.083 UTC
null
null
null
rikitak
null
null
1
22
latex|texmaker
57,118
<p>The <code>proof</code> environment is part of AMS-LaΤεχ, not plain LaΤεχ, so you need to:</p> <pre><code>\usepackage{amsthm} </code></pre> <p>See this <a href="http://www.stat.umn.edu/~charlie/amslatex.html" rel="noreferrer">AMS-LaTeX page</a> for details. If you don't already have the packages installed, grab them at <a href="http://www.ams.org/tex/amslatex.html" rel="noreferrer">http://www.ams.org/tex/amslatex.html</a></p>
32,301,206
How to fold table columns into rows on mobile devices?
<p>I'm developing a website featuring a restaurant's menu. Each item is available in different sizes, each at a different price. This is displayed on medium and large devices using a table, with a column for each price:</p> <p><a href="https://i.stack.imgur.com/rXATK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rXATK.png" alt="Menu in columns"></a></p> <p>On mobile devices, the screen is too narrow to properly display up to 4 different sizes per product.</p> <p>So I would like to fold columns into rows, having each row starting with the column name:</p> <p><a href="https://i.stack.imgur.com/g2I4a.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g2I4a.png" alt="enter image description here"></a></p> <p>Is there anything like this possible using a responsive design? I'm trying to avoid maintaining two different HTML versions of the content, one visible only on mobile, and one visible only on larger screens.</p> <p>I'm using Foundation 5, so I'm ideally looking for a solution using this grid system, but I'm open to any solution really.</p>
32,314,671
2
1
null
2015-08-30 21:13:48.153 UTC
10
2020-07-10 19:00:43.767 UTC
null
null
null
null
759,866
null
1
12
responsive-design|zurb-foundation|zurb-foundation-5
26,455
<p>The solution involves making table cells <code>display: block</code> on mobile devices, and adding a <code>data-*</code> attribute to each cell, matching the column name.</p> <p>This data attribute is injected in the cell's <code>::before</code> pseudo-element with <code>content: attr()</code>.</p> <p>Example:</p> <pre class="lang-html prettyprint-override"><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Pasta&lt;/th&gt; &lt;th&gt;Small&lt;/th&gt; &lt;th&gt;Regular&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Spaghetti Bolognese&lt;/td&gt; &lt;td data-th="Small"&gt;£5.00&lt;/td&gt; &lt;td data-th="Regular"&gt;£7.00&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Lasagna&lt;/td&gt; &lt;td data-th="Small"&gt;£5.00&lt;/td&gt; &lt;td data-th="Regular"&gt;£7.00&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>@media only screen and (max-width: 40em) { thead th:not(:first-child) { display: none; } td, th { display: block; } td[data-th]:before { content: attr(data-th); } } </code></pre> <p>You'll need to add some extra <code>float</code> to make it pretty.</p> <p>Working example: <a href="http://codepen.io/anon/pen/medrZo" rel="noreferrer">http://codepen.io/anon/pen/medrZo</a></p>
5,978,108
Open Vim from within a Bash shell script
<p>I want to write a Bash shell script that does the following:</p> <ol> <li>Opens a file using Vim;</li> <li>Writes something into the file;</li> <li>Saves the file and exits.</li> </ol> <pre><code>echo 'About to open a file' vim file.txt # I need to use vim application to open a file # Now write something into file.txt ... # Then close the file. ... echo 'Done' </code></pre> <p>Is that possible? I found something called Vimscript, but not sure how to use it. Or something like a here document can be used for this?</p> <p><strong>Update:</strong> I need to verify that Vim is working fine over our file system. So I need to write script that invokes Vim, executes some command, and closes it. My requirements do not fit into doing stuffs like <code>echo 'something' &gt; file.txt</code>. I got to open the file using Vim.</p>
5,978,288
5
5
null
2011-05-12 12:38:31.23 UTC
9
2020-08-05 23:03:44.657 UTC
2020-08-05 23:02:37.53 UTC
null
254,635
null
246,365
null
1
16
linux|bash|vim
30,702
<p>Vim has several options:</p> <ul> <li><code>-c</code> => pass ex commands. Example: <code>vim myfile.txt -c 'wq'</code> to force the last line of a file to be newline terminated (unless <code>binary</code> is set in some way by a script)</li> <li><code>-s</code> => play a scriptout that was recorded with <code>-W</code>. For example, if your file contains <code>ZZ</code>, then <code>vim myfile.txt -s the_file_containing_ZZ</code> will do the same as previously.</li> </ul> <p>Also note that, invoked as <code>ex</code>, vim will start in ex mode ; you can try <code>ex my_file.txt &lt;&lt;&lt; wq</code></p>
5,724,455
Can I make a user-specific gitignore file?
<p>I want to change the gitignore, but not everyone on the team wants these changes. How can a user have their own specific git ignore file?</p>
5,724,499
5
1
null
2011-04-20 00:56:35.92 UTC
25
2019-03-09 01:47:51.21 UTC
null
null
null
null
702,928
null
1
157
git|version-control|gitignore
35,175
<p>For user-specific and repo-specific file ignoring you should populate the following file: <pre>$GIT_DIR/info/exclude</pre></p> <p>Usually $GIT_DIR stands for: <pre>your_repo_path/.git/</pre></p>
5,874,558
How to pass arguments to the __code__ of a function?
<p>The following works:</p> <pre><code>def spam(): print "spam" exec(spam.__code__) </code></pre> <blockquote> <p>spam</p> </blockquote> <p>But what if <code>spam</code> takes arguments?</p> <pre><code>def spam(eggs): print "spam and", eggs exec(spam.__code__) </code></pre> <blockquote> <p>TypeError: spam() takes exactly 1 argument (0 given)</p> </blockquote> <p>Given, that I don't have access to the function itself but only to a code object, how can I pass arguments to the code object when executing it? Is it possible with eval?</p> <p>Edit: Since most readers tend not to believe in the usefulness of this, see the following use case:</p> <p>I want to save small Python functions to a file so that they can be called e.g. from another computer. (Needless to say here that this usecase restricts the possible functions severely.) Pickling the function object itself can't work because this only saves the name and the module where the function is defined. Instead, I could pickle the <code>__code__</code> of the function. When I unpickle it again, of course the reference to the function vanished, which is why I can't call the function. I simply don't have it at runtime.</p> <p>Another usecase:</p> <p>I work on several functions in one file that calculate some data and store it on the hard drive. The calculations consume a lot of time so I don't want to execute the functions every time, but only when the implementation of the function changed.</p> <p>I have a version of this running for a whole module instead of a function. It works by looking at the modification time of the file where the module is implemented in. But this is not an option if I have many functions that I don't want to separate in single files.</p>
5,874,844
6
12
null
2011-05-03 19:24:41.313 UTC
10
2021-09-12 13:01:38.57 UTC
2021-09-12 13:01:38.57 UTC
null
355,230
null
562,583
null
1
32
python|function|parameter-passing|exec|eval
13,268
<p>Can you change the function to <em>not</em> take any arguments? The variables is then looked up from the locals/globals where you can supply into <code>exec</code>:</p> <pre><code>&gt;&gt;&gt; def spam(): ... print "spam and", eggs ... &gt;&gt;&gt; exec(spam.__code__, {'eggs':'pasta'}) spam and pasta </code></pre> <p>(Why not just send the whole function as a string? Pickle <code>"def spam(eggs): print 'spam and', eggs"</code>, and <code>exec</code> the string (after verification) on the other side.)</p>
5,770,973
Django: how to change the choices of AdminTimeWidget
<p>The <code>AdminTimeWidget</code> rendered in admin for a <code>DateTimeField</code> displays an icon of a clock and when you click you have the choice between: "Now Midnight 6:00 Noon".</p> <p>How can I change these choices to "16h 17h 18h"?</p>
5,987,580
7
0
null
2011-04-24 14:08:15.113 UTC
9
2021-12-18 06:04:54.78 UTC
2011-05-18 02:35:51.993 UTC
null
260,365
null
395,239
null
1
11
django|django-admin|django-forms
4,490
<p>Chris has a great answer. As an alternative you could do this using just javascript. Place the following javascript on the pages where you want the different time options. </p> <pre><code>DateTimeShortcuts.overrideTimeOptions = function () { // Find the first time element timeElement = django.jQuery("ul.timelist li").eq(0).clone(); originalHref = timeElement.find('a').attr('href'); // remove all existing time elements django.jQuery("ul.timelist li").remove(); // add new time elements representing those you want var i=0; for (i=0;i&lt;=23;i++) { // use a regular expression to update the link newHref = originalHref.replace(/Date\([^\)]*\)/g, "Date(1970,1,1," + i + ",0,0,0)"); // update the text for the element timeElement.find('a').attr('href', newHref).text(i+"h"); // Add the new element into the document django.jQuery("ul.timelist").append(timeElement.clone()); } } addEvent(window, 'load', DateTimeShortcuts.overrideTimeOptions); </code></pre>
6,265,995
Flipboard’s layout algorithm
<p>I hope many of you would have heard about <a href="http://flipboard.com/" rel="nofollow noreferrer">Flipboard</a>. One of the most amazing things about this iPad app is the way it lays out the content which changes dynamically based on orientation of iPad &amp; based on the streaming content.</p> <p><img src="https://i.stack.imgur.com/LKDCf.jpg" alt="enter image description here"></p> <p>So given a set of articles what algorithms would one use to have the best layout. The definition of best could be - most efficient layout (as in circuit design) or the most aesthetically looking layout. </p> <p>Anybody know of any such algorithms? or the basic approach to such problems? Does this fall under "computational geometry" ?</p>
6,406,135
7
0
null
2011-06-07 13:34:59.813 UTC
33
2012-12-17 16:59:22.567 UTC
2012-08-30 20:02:54.403 UTC
null
50,776
null
147,019
null
1
21
algorithm|ipad|layout|flipboard
9,406
<p>Based on the screenshots and theories in <a href="http://corgitoergosum.net/2011/03/06/replicating-flipboard-part-iii-how-flipboard-lays-out-content/" rel="nofollow noreferrer">the blog post linked to by Jason Moore</a> in <a href="https://stackoverflow.com/questions/6265995/flipboards-layout-algorithm/6393263#6393263">his answer</a>, I would say that there are ten-or-so predefined block sizes into which content is placed. What size box a piece of content is placed in is based on various different parameters — something that many people retweet or like may be considered higher priority and therefore get a larger box, and items with pictures, videos or lots of text may also be prioritized. These boxes (preferably with well thought-out sizes) are then packed optimally on the pages (though this is not a simple problem, and even Flipbook seems to fail as evidenced by the strange whitespace in the <a href="http://www.corgitoergosum.net/wp/wp-content/uploads/2011/03/flipboard_facebook_layout2.png" rel="nofollow noreferrer">second render of the Facebook stream</a> from the previously linked blog post).</p> <p>From the looks of the <a href="http://www.corgitoergosum.net/wp/wp-content/uploads/2011/03/flipboard_facebook_layout.png" rel="nofollow noreferrer">rendered Facebook feed</a>, Flipbook has (at least) the following predefined box sizes (width and height given as percentage of full width/height):</p> <pre><code>Designation | Width | Height | Example --------------------------------------------------------------- full page | 100% | 100% | #12 2/3 page | 100% | 67% | #1 1/3 note | 50% | 33% | #3, #11 1/9 quote | 50% | 11% | #2, #8, #10, #15, #17, #18, #22 1/2 note | 50% | 50% | #16, #19 2/3 note | 50% | 67% | ? </code></pre> <p>Some of these have fairly obvious grouping patterns (1/9 quotes are always stacked three at a time to form a block the same size of a 1/3 note, for example), while others can be more freely packed. Similar analysis of the <a href="http://www.corgitoergosum.net/wp/wp-content/uploads/2011/03/flipboard_twitter_layout.png" rel="nofollow noreferrer">rendered Twitter feed</a> show some additional boxes.</p> <h3>Summary</h3> <p>So, in summary the algorithm appears to be fairly simple. Start with a couple of predefined (sensibly selected) box sizes. When new feeds are rendered, do the following:</p> <ol> <li>Assign each item a box whose size depends on certain properties such as popularity, wether it contains images, etc.</li> <li>Pack the boxes optimally (this is in essence the <a href="http://en.wikipedia.org/wiki/Bin_packing_problem" rel="nofollow noreferrer">bin packing problem</a>, an NP-hard problem for which there appears to be no efficient algorithms; a greedy approximation algorithm would do fine)</li> </ol> <p>Emphasis here should be put on step 1, as well as on crafting the predefined boxes.</p> <p><strong>To clarify:</strong> The predefined box sizes I talk about here are defined for the <em>portrait</em> orientation. For landscape, a different set of box sizes would be used as evidenced by <a href="https://i.stack.imgur.com/LKDCf.jpg" rel="nofollow noreferrer">the picture in the question</a>.</p>
55,807,079
I found invalid data while decoding error updating NuGet packages
<p>I have been trying to update NuGet packages in Visual Studio 2019 from both package manager consoles and the manage NuGet packages from the context options, but in both cases I get &quot;Found invalid data while decoding.&quot; error.</p> <p>I have to revert to Visual Studio 2017 to update. Is there a way to deal with this or do I have to contend with this switching for now?</p> <p>The error outputs are as below for both scenarios:</p> <p><a href="https://i.stack.imgur.com/8zOEz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8zOEz.png" alt="Enter image description here" /></a></p>
59,122,631
2
4
null
2019-04-23 08:25:06.16 UTC
4
2021-11-20 13:00:30.587 UTC
2020-07-27 20:11:47.587 UTC
null
63,550
null
767,781
null
1
28
visual-studio-2019
11,880
<p>Visual Studio 2019</p> <ol> <li>Go to menu <em>Tools</em> → <em>NuGet Package Manager</em> → <em>Package Manager Console</em>.</li> <li>Type <code>dotnet nuget locals all --clear</code>.</li> <li>Clean the solution.</li> <li>Delete the <code>bin</code> and <code>obj</code> folders from the project folder.</li> </ol> <p>It is 100% working.</p>
17,941,054
Android - Dynamically Updating a custom ListView after items in an ArrayList are added
<p>I have an activity that displays an initially populated custom ListView taken from an ArrayList, the user can then add to this list which I have no problem storing. I'm having problems displaying the added items. So far, the codes I see online use ArrayAdapter and they're only using the simple listView and not a custom one.</p> <p>Here are the related files: </p> <p>list_row_layout.xml</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;TextView android:id="@+id/variant" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="variant" /&gt; &lt;TextView android:id="@+id/quantity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="quantity" /&gt; &lt;TextView android:id="@+id/unit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginRight="221dp" android:layout_toLeftOf="@+id/quantity" android:text="unit" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Here is the part in my activity_order_form.xml that has the listView element.</p> <pre><code>&lt;RelativeLayout android:id="@+id/relativeLayout3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_below="@+id/relativeLayout2" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/textViewVariantB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="94dp" android:text="Variant" android:textAppearance="?android:attr/textAppearanceLarge" /&gt; &lt;TextView android:id="@+id/textViewUnit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="123dp" android:text="Unit" android:textAppearance="?android:attr/textAppearanceLarge" /&gt; &lt;ListView android:id="@+id/listViewProductOrder" android:layout_width="match_parent" android:layout_height="350dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/textViewVariantB" &gt; &lt;/ListView&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Here is the class where the ArrayList are stored.</p> <pre><code>public class CurrentOrderClass { private String productName; //ArrayLists private ArrayList&lt;String&gt; variantArray = new ArrayList&lt;String&gt;(); private ArrayList&lt;String&gt; unitArray = new ArrayList&lt;String&gt;(); private ArrayList&lt;Integer&gt; quantityArray = new ArrayList&lt;Integer&gt;(); //TODO ArrayList functions public ArrayList&lt;String&gt; getUnitArray() { return unitArray; } public void setUnitArray(ArrayList&lt;String&gt; unitArray) { this.unitArray = unitArray; } public void addToUnitArray(String unit){ this.unitArray.add(unit); } public ArrayList&lt;Integer&gt; getQuantityArray() { return quantityArray; } public void setQuantityArray(ArrayList&lt;Integer&gt; quantityArray) { this.quantityArray = quantityArray; } public void addToQuantityArray(int quantity){ this.quantityArray.add(quantity); } public ArrayList&lt;String&gt; getVariantArray() { return variantArray; } public void setVariantArray(ArrayList&lt;String&gt; variantArray) { this.variantArray = variantArray; } public void addToVariantArray(String variantArray){ this.variantArray.add(variantArray); } } </code></pre> <p>Here is the CustomListAdapter.java file</p> <pre><code>public class CustomListAdapter extends BaseAdapter { private ArrayList&lt;CurrentOrderClass&gt; listData; private LayoutInflater layoutInflater; public CustomListAdapter(Context context, ArrayList&lt;CurrentOrderClass&gt; listData) { this.listData = listData; layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_row_layout, null); holder = new ViewHolder(); holder.variantView = (TextView) convertView.findViewById(R.id.variant); holder.unitView = (TextView) convertView.findViewById(R.id.unit); holder.quantityView = (TextView) convertView.findViewById(R.id.quantity); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString()); holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString()); holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow())); return convertView; } static class ViewHolder { TextView variantView; TextView unitView; TextView quantityView; } } </code></pre> <p>This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView, as well as the part where user input is taken.</p> <pre><code>public class OrderForm extends Activity { public TextView tv; private int variantPosition; CustomListAdapter customListAdapter; CurrentOrderClass currentOrder = new CurrentOrderClass(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_form); tv = (TextView)findViewById(R.id.textViewProduct); //set variants here popolateItem(); //set current order listview here ArrayList image_details = getListData(); final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder); customListAdapter = new CustomListAdapter(this, image_details); lv1.setAdapter(customListAdapter); } private ArrayList getListData() { ArrayList results = new ArrayList(); for(int i = 0; i &lt; 10; i++){ currentOrder.getQuantityArray().add(i); currentOrder.getUnitArray().add("Sample text here." + i); currentOrder.getVariantArray().add("Another sample text here" + i); results.add(currentOrder); } return results; } //....snip snip excess code..... //This is the part wherein I add new items to the ArrayList in the class //After this, I'm not sure how to proceed currentOrder.setProductName(product.getName()); currentOrder.addToQuantityArray(newQuantity); currentOrder.addToUnitArray(product.getUnit()[position]); currentOrder.addToVariantArray(product.getVariant()[variantPosition]); Log.d("Angelo", currentOrder.getProductName() + " " + currentOrder.getQuantityArray() + " " + currentOrder.getUnitArray() + " " + currentOrder.getVariantArray()); } </code></pre> <p>I also tried to place <code>customListAdapter.notifyDataSetChanged();</code> after the Log entry but nothing happened. Any ideas anyone? Thanks. </p> <p><strong>EDIT AFTER ANSWERS AND MODIFICATIONS.</strong> </p> <p>Just follow FD's answer below and add the function he specified there and the 2 function calls after that. Now, you want to modify your <code>getListData()</code> function like this:</p> <pre><code>private ArrayList getListData() { ArrayList results = new ArrayList(); int loopUntil; /* Two scenarios * First ---&gt; the user started the activity for the first time, which means that the pre-populated list is what we want * if this is the case, look at the else part of the boolean statement, it only loops until 10 * and in addition, populates those elements * Second ---&gt; the user has set something already and we want to populate until that element. * */ if(currentOrder.getQuantityArray().size() &gt; 10){ loopUntil = currentOrder.getQuantityArray().size(); for(int i = 0; i &lt; loopUntil; i++){ currentOrder.getQuantityArray(); currentOrder.getUnitArray(); currentOrder.getVariantArray(); results.add(currentOrder); } } else{ loopUntil = 10; for(int i = 0; i &lt; loopUntil; i++){ currentOrder.getQuantityArray().add(i); currentOrder.getUnitArray().add("Sample text here." + i); currentOrder.getVariantArray().add("Another sample text here" + i); results.add(currentOrder); } } return results; } </code></pre> <p>The first condition executes when there is an item beyond the pre-populated one, since the else statement loops only until the pre-populated item (item number 9, index 0). This loop ensures that everything you add to the ArrayList gets added to the ListView. </p> <p>The second condition executes when the activity is opened for the first time and there's supposed to be nothing in that list yet except the ones that you populated yourself.</p>
17,941,189
1
3
null
2013-07-30 07:41:31.937 UTC
4
2013-07-30 09:46:46.033 UTC
2013-07-30 09:46:46.033 UTC
null
1,374,416
null
1,374,416
null
1
2
android|listview|arraylist
38,096
<p>Your adapter does not get the new data, because you are initializing it with its own set of data.</p> <p>One possibility would be to instantiate a new adapter and assign it to the ListView.</p> <p>Add a field for your ListView in your activity:</p> <pre><code>public TextView tv; private int variantPosition; CustomListAdapter customListAdapter; CurrentOrderClass currentOrder = new CurrentOrderClass(); ListView myListView; //Listview here </code></pre> <p>In onCreate, set myListView to point to your ListView:</p> <pre><code>final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder) myListView = lv1; </code></pre> <p>Finally, when you change your data, create a new Adapter for the new data:</p> <pre><code>myListView.setAdapter(new CustomListAdapter(this, getListData()); </code></pre> <p>Alternatively, modify your Custom adapter to contain a setListData method:</p> <pre><code>public class CustomListAdapter extends BaseAdapter { private ArrayList&lt;CurrentOrderClass&gt; listData; private LayoutInflater layoutInflater; public CustomListAdapter(Context context, ArrayList&lt;CurrentOrderClass&gt; listData) { this.listData = listData; layoutInflater = LayoutInflater.from(context); } public void setListData(ArrayList&lt;CurrentOrderClass&gt; data){ listData = data; } @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_row_layout, null); holder = new ViewHolder(); holder.variantView = (TextView) convertView.findViewById(R.id.variant); holder.unitView = (TextView) convertView.findViewById(R.id.unit); holder.quantityView = (TextView) convertView.findViewById(R.id.quantity); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString()); holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString()); holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow())); return convertView; } static class ViewHolder { TextView variantView; TextView unitView; TextView quantityView; } } </code></pre> <p>Then, after modifying your data, just call:</p> <pre><code>customListAdapter.setListData(getListData()); customListAdapter.notifyDataSetChanged(); </code></pre>
5,536,532
In-App Billing Security and Design questions
<p>I have a few questions connected to Android In-App Billing:</p> <ol> <li><p>Is it possible to make a purchase from non-Market app? I understand that it would be a vulnerability, but I have no opportunity to find out if it's possible or not.</p></li> <li><p>How can I get purchase state for a particular product? As far as I understand it can be done using <code>RESTORE_TRANSACTIONS</code> request, but it's not recommended to use very often. That's not a theoretical problem. My application allows users to buy content using in-app billing. Content can be downloaded from a server, and server must allow content downloading only if it was purchased. But it can't check if content was purchased or not without using signed response from Android Market.</p></li> <li><p>How can I get price and description of an item from Android Market? Seems that I know the answer and it's "there's no way it can be done", but maybe I'm wrong. It would be very useful to have a possibility of retrieving item's price.</p></li> </ol> <p>It's very interesting to me how you solved/are going to solve these problems in your apps. Answer to any of these questions will be appreciated.</p>
5,652,627
1
0
null
2011-04-04 09:10:59.89 UTC
10
2011-04-22 05:27:26.727 UTC
2011-04-22 05:27:26.727 UTC
null
170,842
null
170,842
null
1
24
android|security|in-app-purchase|google-play
3,195
<p>In order:</p> <p>1- Nope. The in-app billing process is part of Market. If the app comes from elsewhere, there's no way for Market to verify the origin/authenticity of the application.</p> <p>2- It's your responsibility to store the purchase state for a particular product. From the <a href="http://developer.android.com/guide/market/billing/billing_integrate.html#billing-implement" rel="noreferrer">doc</a>:</p> <blockquote> <p>You must set up a database or some other mechanism for storing users' purchase information.</p> </blockquote> <p>RESTORE_TRANSACTIONS should be reserved for reinstalls or first-time installs on a device.</p> <p>3- Unfortunately, at this time you're right. File a feature request! </p> <p>In the meantime, one option is to set up a website with appengine, store listings of all your content &amp; pricing there, and then manually sync prices listed on your appengine server with the updated prices in Market. Then have your Android app pull the data from the AppEngine server. This is much better than hardcoding price values into the app itself, since you don't need to have everyone update the app immediately to see accurate pricing whenever you change something. The only caveat of this method is that if the user is in a different country, in-app billing will display an approximated price in their native currency, and there's no way for you to determine exactly what price will be displayed to them.</p> <p>Related, One of the Android Developer Advocates is giving a talk on LVL/IAP at IO, called "Evading Pirates and Stopping Vampires using License Verification Library, In-App Billing, and App Engine." - It would definitely be worth your while to watch when they release the session videos on the website.</p>
4,940,259
lambdas require capturing 'this' to call static member function?
<p>For the following code:</p> <pre><code>struct B { void g() { []() { B::f(); }(); } static void f(); }; </code></pre> <p>g++ 4.6 gives the error:</p> <blockquote> <p>test.cpp: In lambda function:<br> test.cpp:44:21: error: 'this' was not captured for this lambda function</p> </blockquote> <p>(Interestingly, g++ 4.5 compiles the code fine).</p> <p>Is this a bug in g++ 4.6, or is it really necessary to capture the 'this' parameter to be able to call a static member function? I don't see why it should be, I even qualified the call with <code>B::</code>.</p>
4,941,046
1
3
null
2011-02-09 00:43:52.407 UTC
10
2014-08-04 12:43:13.5 UTC
2014-08-04 12:43:13.5 UTC
null
2,642,204
null
141,719
null
1
65
c++|lambda|c++11
38,272
<p>I agree, it should compile just fine. For the fix (if you didn't know already), just add the reference capture and it will compile fine on gcc 4.6</p> <pre><code>struct B { void g() { [&amp;]() { B::f(); }(); } static void f() { std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl; }; }; </code></pre>
24,851,824
How long does it take for GitHub page to show changes after changing index.html
<p>I am just wondering how long does it take for GitHub page to show the new items that I have added to the repository.</p> <p>I changed <code>index.html</code> but after 10 minutes it still showed up the previous page...</p>
24,871,850
4
2
null
2014-07-20 15:10:02.523 UTC
19
2022-08-11 17:47:28.797 UTC
2019-02-27 14:30:15.553 UTC
null
680,068
null
3,394,937
null
1
124
github|updates|github-pages
95,805
<p>The first time you generate your site it will take about 10 minutes for it to show up. Subsequent builds take only seconds from the time you push the changes to your GitHub repository.</p> <p>However, depending on <a href="https://help.github.com/articles/setting-up-a-custom-domain-with-github-pages">how your have your domain configured</a>, there may be extra time for the CDN cache to break.</p> <p>Note: using a subdomain, such as <code>yourproject.github.io</code> is the <a href="https://help.github.com/articles/about-custom-domains-for-github-pages-sites">recommended domain setup</a>, but does mean page builds take longer to show up since it has the benefit of using the GitHub CDN.</p>
49,236,325
Babel Preset does not provide support on IE11 for Object.assign - "Object doesn't support property or method 'assign'"
<p>I am using <strong>babel-preset-env version - 1.6.1</strong> for my react app, i am getting a error on IE :- <em>Object doesn't support property or method 'assign'</em> <a href="https://i.stack.imgur.com/TmBJo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TmBJo.png" alt="enter image description here"></a></p> <p>this is my <strong>.babelrc</strong> :-</p> <pre><code>{ "presets": [ "react", [ "env", { "targets": { "browsers": [ "last 1 versions", "ie &gt;= 11" ] }, "debug": true, "modules": "commonjs" } ] ], "env": { "test": { "presets": [ [ "babel-preset-env", "react" ] ], "plugins": [ "transform-object-rest-spread", "transform-class-properties", "transform-runtime", "babel-plugin-dynamic-import-node", "array-includes", "url-search-params-polyfill", "transform-object-assign" ] } }, "plugins": [ "transform-object-rest-spread", "transform-class-properties", "syntax-dynamic-import", "transform-runtime", "array-includes", "url-search-params-polyfill", "transform-object-assign" ] </code></pre> <p>}</p> <p>i tried these polyfills :-</p> <p><a href="https://babeljs.io/docs/plugins/transform-object-assign/" rel="noreferrer">https://babeljs.io/docs/plugins/transform-object-assign/</a> <a href="https://www.npmjs.com/package/babel-plugin-object-assign" rel="noreferrer">https://www.npmjs.com/package/babel-plugin-object-assign</a></p> <p>but it didn't work </p> <p>i am using syntax:- </p> <pre><code>let a = Object.assign({},obj); </code></pre> <p>everywhere in my project</p> <p>i need a polyfill that would work for my project.</p>
49,236,446
2
1
null
2018-03-12 13:21:41.543 UTC
8
2019-07-01 07:04:13.233 UTC
null
null
null
null
5,006,144
null
1
30
reactjs|internet-explorer|webpack|babeljs|babel-preset-env
34,547
<p>You need <a href="https://babeljs.io/docs/usage/polyfill/" rel="noreferrer">Babel Polyfill</a>.</p> <p>Either import it in your entry JS file, or use Webpack.</p> <pre><code>import "babel-polyfill"; </code></pre> <p>or in <code>webpack.config.js</code></p> <pre><code>module.exports = { entry: ["babel-polyfill", "./app/main"] } </code></pre> <p><strong>NOTE : <code>babel-polyfill</code> Should be imported on very top else It will not work</strong></p>
44,677,960
How to use Material Design Icons In Angular 4?
<p>I want to use the icons from <a href="https://materialdesignicons.com/" rel="noreferrer">https://materialdesignicons.com/</a> in my angular 4 project. The instructions on the website are only covering how to include it in <code>Angular 1.x</code> (<a href="https://materialdesignicons.com/getting-started" rel="noreferrer">https://materialdesignicons.com/getting-started</a>)</p> <p>How can I include the Material design icons so I can use them like <code>&lt;md-icon svgIcon="source"&gt;&lt;/md-icon&gt;</code> using <code>Angular Material</code> and <code>ng serve</code>? </p> <p><strong>NOTE: I already Included the <code>google material icons</code> which are different!</strong></p>
44,692,684
9
1
null
2017-06-21 13:46:05.123 UTC
14
2020-11-01 18:21:21.513 UTC
null
null
null
null
5,111,904
null
1
50
angular|angular-material2
81,566
<p>Instructions on how to include Material Design Icons into your Angular Material app can now be found on the <a href="https://dev.materialdesignicons.com/getting-started/angular#angular-material" rel="noreferrer">Material Design Icons - Angular</a> documentation page.</p> <p>TL;DR: You can now leverage the <a href="https://npmjs.com/package/@mdi/angular-material" rel="noreferrer"><code>@mdi/angular-material</code></a> NPM package which includes the MDI icons distributed as a single SVG file (<code>mdi.svg</code>):</p> <pre class="lang-sh prettyprint-override"><code>npm install @mdi/angular-material </code></pre> <p>This SVG file can then be included into your app by including it in your project's <code>assets</code> configuration property in <code>angular.json</code>:</p> <pre class="lang-json prettyprint-override"><code>{ // ... &quot;architect&quot;: { &quot;build&quot;: { &quot;options&quot;: { &quot;assets&quot;: [ { &quot;glob&quot;: &quot;**/*&quot;, &quot;input&quot;: &quot;./assets/&quot;, &quot;output&quot;: &quot;./assets/&quot; }, { &quot;glob&quot;: &quot;favicon.ico&quot;, &quot;input&quot;: &quot;./&quot;, &quot;output&quot;: &quot;./&quot; }, { &quot;glob&quot;: &quot;mdi.svg&quot;, &quot;input&quot;: &quot;./node_modules/@mdi/angular-material&quot;, &quot;output&quot;: &quot;./assets&quot; } ] } } } // ... } </code></pre> <p>Your app's main module will also need the necessary imports (<code>HttpClientModule</code> from <code>@angular/common/http</code> used to load the icons and <code>MatIconModule</code> from <code>@angular/material/icon</code>) to be declared, as well as adding the icon set to the registry:</p> <pre class="lang-js prettyprint-override"><code>import { HttpClientModule } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { MatIconModule, MatIconRegistry } from '@angular/material/icon'; import { DomSanitizer } from '@angular/platform-browser'; @NgModule({ imports: [ // ... HttpClientModule, MatIconModule ] }) export class AppModule { constructor(iconRegistry: MatIconRegistry, domSanitizer: DomSanitizer) { iconRegistry.addSvgIconSet( domSanitizer.bypassSecurityResourceHtml('./assets/mdi.svg') ); } } </code></pre> <p>A <a href="https://stackblitz.com/edit/mdi-material-example" rel="noreferrer">StackBlitz demo</a> is also now available.</p> <p>The steps for older versions of Angular are as mentioned below:</p> <hr /> <p>Simply follow these steps:</p> <ol> <li><p>Download <code>mdi.svg</code> from <a href="https://materialdesignicons.com/getting-started" rel="noreferrer">here</a> under the <strong>Angular Material</strong> section and place it in your <code>assets</code> folder, which should be located at (from your project's root) <code>/src/assets</code>:</p> <p><a href="https://materialdesignicons.com/getting-started" rel="noreferrer" title="Visit MaterialDesignIcons"><img src="https://i.stack.imgur.com/ZRqCE.jpg" alt="Documentation" /></a> <a href="https://i.stack.imgur.com/F7VXv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/F7VXv.jpg" alt="assets folder" /></a></p> </li> <li><p>In your app's module (aka <code>app.module.ts</code>), add the following lines:</p> <pre class="lang-ts prettyprint-override"><code>import {MatIconRegistry} from '@angular/material/icon'; import {DomSanitizer} from '@angular/platform-browser'; ... export class AppModule { constructor(private matIconRegistry: MatIconRegistry, private domSanitizer: DomSanitizer){ matIconRegistry.addSvgIconSet(domSanitizer.bypassSecurityResourceUrl('/assets/mdi.svg')); } } </code></pre> </li> <li><p>Make sure to include <code>assets</code> folder under <code>.angular-cli.json</code> in <code>assets</code> (Although by default, it will be there):</p> <pre class="lang-json prettyprint-override"><code>{ &quot;apps&quot;: [ { ... &quot;assets&quot;: [ &quot;assets&quot; ] } ] } </code></pre> </li> <li><p>Finally, use it via the <code>MatIcon</code> component with the <code>svgIcon</code> input:</p> <pre class="lang-html prettyprint-override"><code>&lt;mat-icon svgIcon=&quot;open-in-new&quot;&gt;&lt;/mat-icon&gt; </code></pre> </li> </ol>
21,522,493
What was the difference between WSDL & Mex Endpoint in WCF
<p>I have couple of question on mex endpoint.</p> <ol> <li><p>In legacy web services, we create a proxy using wsdl. The WSDL exposes the web service's meta data. In wcf, another term comes that mex endpoint, which also exposes meta data, but wsdl is still alive in wcf. I am new to wcf, and I am confused regarding the <code>difference between wsdl &amp; mex endpoint</code>?</p></li> <li><p>What is the meaning of <code>httpGetEnabled="false" or httpGetEnabled="true"</code>?</p></li> <li><p>If I set <code>httpGetEnabled="false"</code> then what will happen? Does it mean the client will not be able to add service reference from their IDE? But if I set <code>httpGetEnabled="false"</code>, and saw client can add service reference. What the <code>httpGetEnabled</code> setting does is very confusing.</p></li> <li><p>One guy said </p></li> </ol> <blockquote> <p>MEX and WSDL are two different schemes to tell potential clients about the structure of your service. So you can choose to either make your service contracts public as (MEX) or WSDL.</p> </blockquote> <p>If the above statement is true then tell me when to use MEX &amp; when to use <code>WSDL?</code></p> <ol> <li><p>How can I disable mex and expose my service only through WSDL?</p></li> <li><p><code>WSDL support all bidning like wshttp,wsdualhttp or tcp etc...</code> If possible please discuss about wsdl &amp; mex in details.</p></li> </ol> <h2>UPDATE</h2> <p>You said </p> <pre><code>5. How can I disable mex and expose my service only through WSDL? Do not specifiy a mex endpoint in your config and use httpGetEnabled. </code></pre> <p>Are you trying to mean that there should be no mex endpoint related entry in config and httpgetenable would look like the following?</p> <pre><code>&lt;serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8080/SampleService?wsdl"/&gt; </code></pre> <p>You said </p> <blockquote> <p>A WSDL is generally exposed through http or https get urls that you can't really configure (say for security limitations or for backward compatibility). MEX endpoints expose metadata over configurable endpoints, and can use different types of transports, such as TCP or HTTP, and different types of security mechanisms.</p> </blockquote> <p>You said mex is configurable, but the wsdl is not. What do you mean by <code>mex is configurable</code>? Please discuss what kind of configuration mex support and how it can be configured.</p> <p>If I set <code>httpGetEnabled="false" then the WSDL</code> will not be possible to generate?</p>
21,522,849
2
1
null
2014-02-03 08:17:39.88 UTC
14
2014-12-08 07:41:07.233 UTC
2014-06-25 03:33:44.753 UTC
null
299,327
null
508,127
null
1
43
c#|wcf|wsdl|mex
40,782
<blockquote> <p>1) in legacy web service we create proxy using wsdl. WSDL expose web service meta data. in wcf another term comes that mex endpoint which also expose meta data but wsdl is still live in wcf.i am new in wcf hence i am confusing what is the difference between wsdl &amp; mex endpoint?</p> </blockquote> <p>It's pretty the same thing but mex is designed to support non-HTTP protocols and for advanced configuration/security scenarios. WSDL is the legacy way and MEX is the new improved version with WCF.</p> <blockquote> <p>2) what is the meaning of httpGetEnabled="false" or httpGetEnabled="true"</p> </blockquote> <p>It will expose metadata via wsdl through the defautl url, even if you don't have defined a mex endpoint for your service.</p> <blockquote> <p>3) if i set httpGetEnabled="false" then what will happen? does it mean that client will not be able to add service reference from IDE? but i set httpGetEnabled="false" and saw client can add service reference. so it is very confusing for me that what httpGetEnabled is false or true does ?</p> </blockquote> <p>A client can add a reference in VS only if httpGetEnabled/httpsGetEnabled is enable or if you have define a mex endpoint in the configuration of your service. The best practice is to expose metadata on dev environnement but not on production. You can also distribute your service contracts via separate assemblies and use <code>ChannelFactory</code>.</p> <blockquote> <p>4) one guy said :- MEX and WSDL are two different schemes to tell potential clients about the structure of your service. So you can choose to either make your service contracts public as (MEX) or WSDL. if the above statement is true then tell me when to use MEX &amp; when to use WSDL? </p> </blockquote> <p>A WSDL is generally exposed through http or https get urls that you can't really configure (say for security limitations or for backward compatibility). MEX endpoints expose metadata over configurable endpoints, and can use different types of transports, such as TCP or HTTP, and different types of security mechanisms.</p> <p>So MEX are more configurable, while WSDL is more interoperable with older versions of clients and non-.net clients that work with WSDLs.</p> <blockquote> <p>5) how could i disable mex and expose my service through only WSDL</p> </blockquote> <p>Do not specifiy a mex endpoint in your config and use <code>httpGetEnabled</code></p> <blockquote> <p>6) WSDL support all bidning like wshttp,wsdualhttp or tcp etc...</p> </blockquote> <p>Exposing metadata is totally different that invoking the service.</p> <p><strong>UPDATE</strong></p> <blockquote> <p>re you try to mean that there should be no mex endpoint related entry in config and httpgetenable would look like</p> </blockquote> <p>Yes, you don't have to specify a mex endpoint AND httpGetEnabled. Only one is required to expose metadata. Do not specifiy httpGetUrl as this is depending on your hosting environment.</p> <blockquote> <p>you said mex is configurable but wsdl is not. what r u trying to means mex is configurable...please discuss what kind of configuration mex support &amp; how to configure.</p> </blockquote> <p>MEX endpoints are special endpoints that allow clients to receive the service’s metadata by using SOAP messages instead of http get requests. You can create MEX endpoint that can be accessed through http, https, tcp, and even named pipes. HttpGetEnable allow you to expose metadata through HTTP GET method, usually the service’s address with the suffix of ‘?wsdl'</p> <p>MEX and WSDL both output nearly the same thing.</p> <p>In most cases there is no need for MEX endpoint – using WSDLs with http get is usually enough.</p> <p>I understand your intention to understand this part, but do not spend to many times on this : there are so many others complicated features !</p>
32,647,215
Declaring static constants in ES6 classes?
<p>I want to implement constants in a <code>class</code>, because that's where it makes sense to locate them in the code.</p> <p>So far, I have been implementing the following workaround with static methods:</p> <pre><code>class MyClass { static constant1() { return 33; } static constant2() { return 2; } // ... } </code></pre> <p>I know there is a possibility to fiddle with prototypes, but many recommend against this.</p> <p>Is there a better way to implement constants in ES6 classes?</p>
32,647,583
18
2
null
2015-09-18 08:22:19.12 UTC
57
2022-09-22 14:24:46.583 UTC
2015-09-18 16:59:54.13 UTC
null
2,039,244
null
520,957
null
1
382
javascript|class|constants|ecmascript-6
349,071
<p>Here's a few things you could do:</p> <p>Export a <code>const</code> from the <em>module</em>. Depending on your use case, you could just:</p> <pre><code>export const constant1 = 33; </code></pre> <p>And import that from the module where necessary. Or, building on your static method idea, you could declare a <code>static</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get" rel="noreferrer">get accessor</a>:</p> <pre><code>const constant1 = 33, constant2 = 2; class Example { static get constant1() { return constant1; } static get constant2() { return constant2; } } </code></pre> <p>That way, you won't need parenthesis:</p> <pre><code>const one = Example.constant1; </code></pre> <p><a href="https://babeljs.io/repl/#?experimental=true&amp;evaluate=true&amp;loose=false&amp;spec=false&amp;code=const%20constant1%20%3D%2033%2C%0A%20%20%20%20%20%20constant2%20%3D%202%3B%0Aclass%20Example%20%7B%0A%20%20%0A%20%20static%20get%20constant1()%20%7B%0A%20%20%20%20return%20constant1%3B%0A%20%20%7D%0A%20%20%0A%20%20static%20get%20constant2()%20%7B%0A%20%20%20%20return%20constant2%3B%0A%20%20%7D%0A%7D%0Aconsole.log(Example.constant1%2C%20Example.constant2)%3B" rel="noreferrer">Babel REPL Example</a></p> <p>Then, as you say, since a <code>class</code> is just syntactic sugar for a function you can just add a non-writable property like so:</p> <pre><code>class Example { } Object.defineProperty(Example, 'constant1', { value: 33, writable : false, enumerable : true, configurable : false }); Example.constant1; // 33 Example.constant1 = 15; // TypeError </code></pre> <p>It may be nice if we could just do something like:</p> <pre><code>class Example { static const constant1 = 33; } </code></pre> <p>But unfortunately this <a href="https://github.com/jeffmo/es-class-properties" rel="noreferrer">class property syntax</a> is only in an ES7 proposal, and even then it won't allow for adding <code>const</code> to the property.</p>
9,067,993
Upload to s3 with curl using pre-signed URL (getting 403)
<p>I'm using curl to call into a Java ReST API to retrieve a URL. Java then generates a pre-signed URL for S3 upload using my S3 credentials, and returns that in the ReST reply. Curl takes the URL and uses that for upload to S3, but S3 returns 403 "The request signature we calculated does not match the signature you provided. Check your key and signing method."</p> <p>Here is the code I'm using to generate the pre-signed URL:</p> <pre><code>public class S3Util { static final AmazonS3 s3 = new AmazonS3Client( new AWSCredentials() { @Override public String getAWSAccessKeyId() { return "XXXXXXX"; } @Override public String getAWSSecretKey() { return "XXXXXXXXXXXXXX"; } }); static final String BUCKET = "XXXXXXXXXXXXXXXXXXXXXXXXXXX"; static public URL getMediaChunkURL( MediaChunk mc, HttpMethod method ) { String key = ... //way in the future (for testing)... Date expiration = new Date( System.currentTimeMillis() + CalendarUtil.ONE_MINUTE_IN_MILLISECONDS*60*1000 ); GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(BUCKET, key, method); req.setExpiration(expiration); req.addRequestParameter("Content-Type", "application/octet-stream"); //this gets passed to the end user: return s3.generatePresignedUrl(req); } } </code></pre> <p>and in curl, run from bash, I execute this:</p> <pre><code>echo Will try to upload chunk to ${location} curl -i -X POST \ -F 'Content-Type=application/octet-stream' \ -F "file=@${fileName}" \ ${location} || (echo upload chunk failed. ; exit 1 ) </code></pre> <p>Among other things, I have tried PUT, and I have tried "Content-type" (lowercase T). I realize I'm missing something (or somethings) obvious, but after reading the appropriate docs, googling and looking at lots of similar questions I'm not sure what that is. I see lots of hints about required headers, but I thought the resigned URL was supposed to eliminate those needs. Maybe not?</p> <p>TIA!</p> <p><strong>Update:</strong></p> <p>Just to be clear, I have tested downloads, and that works fine.</p> <p>Java looks like:</p> <pre><code>GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(BUCKET, key, HttpMethod.GET); req.setExpiration(expiration); </code></pre> <p>and curl is simply:</p> <pre><code>curl -i ${location} </code></pre>
9,085,141
4
0
null
2012-01-30 17:24:43.123 UTC
3
2015-03-28 09:47:58.867 UTC
2012-01-30 19:14:22.41 UTC
null
547,291
null
547,291
null
1
26
java|bash|curl|amazon-s3
38,059
<p>I've been able to generate a pre-signed URL via C# and upload it thereafter via <a href="http://curl.haxx.se/">curl</a> as expected. Given my tests I suspect you are indeed not using <em>curl</em> correctly - I've been able to upload a file like so:</p> <pre><code>curl -v --upload-file ${fileName} ${location} </code></pre> <p>The parameter <code>-v</code> dumps both request and response headers (as well as the SSL handshake) for debugging and illustration purposes:</p> <pre><code>&gt; PUT [...] HTTP/1.1 &gt; User-Agent: curl/7.21.0 [...] &gt; Host: [...] &gt; Accept: */* &gt; Content-Length: 12 &gt; Expect: 100-continue </code></pre> <p>Please note, that <code>--upload-file</code> (or <code>-T</code>) facilitates <code>PUT</code>as expected, but adds more headers as appropriate, yielding a proper response in return:</p> <pre><code>&lt; HTTP/1.1 100 Continue &lt; HTTP/1.1 200 OK &lt; x-amz-id-2: [...] &lt; x-amz-request-id: [...] &lt; Date: Tue, 31 Jan 2012 18:34:56 GMT &lt; ETag: "253801c0d260f076b0d5db5b62c54824" &lt; Content-Length: 0 &lt; Server: AmazonS3 </code></pre>
52,332,747
What are the supported Swift String format specifiers?
<p>In Swift, I can format a String with format specifiers:</p> <pre><code>// This will return "0.120" String(format: "%.03f", 0.12) </code></pre> <p>But the official documentation is not giving any information or link regarding the supported format specifiers or how to build a template similar to <code>"%.03f"</code>: <a href="https://developer.apple.com/documentation/swift/string/3126742-init" rel="noreferrer">https://developer.apple.com/documentation/swift/string/3126742-init</a></p> <p>It only says:</p> <blockquote> <p>Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.</p> </blockquote>
52,332,748
3
2
null
2018-09-14 13:11:00.487 UTC
33
2022-06-22 09:29:29.853 UTC
2019-03-07 14:58:18.587 UTC
null
1,033,581
null
1,033,581
null
1
60
swift|string|string-formatting
44,196
<p>The format specifiers for <code>String</code> formatting in Swift are the same as those in Objective-C <code>NSString</code> format, itself identical to those for <code>CFString</code> format and are buried deep in the archives of Apple Documentation (same content for both pages, both originally from year 2002 or older):</p> <ul> <li><a href="https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFStrings/formatSpecifiers.html" rel="noreferrer">https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFStrings/formatSpecifiers.html</a></li> <li><a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html" rel="noreferrer">https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html</a></li> </ul> <p>But this documentation page itself is incomplete, for instance the <em>flags</em>, the <em>precision</em> specifiers and the <em>width</em> specifiers aren't mentioned. Actually, it claims to follow <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html" rel="noreferrer">IEEE printf specifications (Issue 6, 2004 Edition)</a>, itself aligned with the ISO C standard. So those specifiers should be identical to what we have with C <code>printf</code>, with the addition of the <code>%@</code> specifier for Objective-C objects, and the addition of the poorly documented <code>%D</code>, <code>%U</code>, <code>%O</code> specifiers and <code>q</code> length modifier.</p> <hr> <h2>Specifiers</h2> <blockquote> <p>Each conversion specification is introduced by the '%' character or by the character sequence "%n$".</p> </blockquote> <p><code>n</code> is the index of the parameter, like in:</p> <pre><code>String(format: "%2$@ %1$@", "world", "Hello") </code></pre> <h2>Format Specifiers</h2> <blockquote> <p>%@&nbsp;&nbsp;&nbsp;&nbsp;Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise.</p> </blockquote> <p>Actually, you may also use some Swift types, but they must be defined inside the standard library in order to conform to the CVarArg protocol, and I believe they need to support bridging to Objective-C objects: <a href="https://developer.apple.com/documentation/foundation/object_runtime/classes_bridged_to_swift_standard_library_value_types" rel="noreferrer">https://developer.apple.com/documentation/foundation/object_runtime/classes_bridged_to_swift_standard_library_value_types</a>.</p> <pre><code>String(format: "%@", ["Hello", "world"]) </code></pre> <blockquote> <p>%%&nbsp;&nbsp;&nbsp;&nbsp;'%' character.</p> </blockquote> <pre><code>String(format: "100%% %@", true.description) </code></pre> <blockquote> <p>%d, %i&nbsp;&nbsp;&nbsp;&nbsp;Signed 32-bit integer (int).</p> </blockquote> <pre><code>String(format: "from %d to %d", Int32.min, Int32.max) </code></pre> <blockquote> <p>%u, %U, %D&nbsp;&nbsp;&nbsp;&nbsp;Unsigned 32-bit integer (unsigned int).</p> </blockquote> <pre><code>String(format: "from %u to %u", UInt32.min, UInt32.max) </code></pre> <blockquote> <p>%x&nbsp;&nbsp;&nbsp;&nbsp;Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f.</p> </blockquote> <pre><code>String(format: "from %x to %x", UInt32.min, UInt32.max) </code></pre> <blockquote> <p>%X&nbsp;&nbsp;&nbsp;&nbsp;Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F.</p> </blockquote> <pre><code>String(format: "from %X to %X", UInt32.min, UInt32.max) </code></pre> <blockquote> <p>%o, %O&nbsp;&nbsp;&nbsp;&nbsp;Unsigned 32-bit integer (unsigned int), printed in octal.</p> </blockquote> <pre><code>String(format: "from %o to %o", UInt32.min, UInt32.max) </code></pre> <blockquote> <p>%f&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in decimal notation. Produces "inf", "infinity", or "nan".</p> </blockquote> <pre><code>String(format: "from %f to %f", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%F&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in decimal notation. Produces "INF", "INFINITY", or "NAN".</p> </blockquote> <pre><code>String(format: "from %F to %F", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%e&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent.</p> </blockquote> <pre><code>String(format: "from %e to %e", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%E&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent.</p> </blockquote> <pre><code>String(format: "from %E to %E", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%g&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.</p> </blockquote> <pre><code>String(format: "from %g to %g", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%G&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.</p> </blockquote> <pre><code>String(format: "from %G to %G", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%c&nbsp;&nbsp;&nbsp;&nbsp;8-bit unsigned character (unsigned char).</p> </blockquote> <pre><code>String(format: "from %c to %c", "a".utf8.first!, "z".utf8.first!) </code></pre> <blockquote> <p>%C&nbsp;&nbsp;&nbsp;&nbsp;16-bit UTF-16 code unit (unichar).</p> </blockquote> <pre><code>String(format: "from %C to %C", "爱".utf16.first!, "终".utf16.first!) </code></pre> <blockquote> <p>%s&nbsp;&nbsp;&nbsp;&nbsp;Null-terminated array of 8-bit unsigned characters.</p> </blockquote> <pre><code>"Hello world".withCString { String(format: "%s", $0) } </code></pre> <blockquote> <p>%S&nbsp;&nbsp;&nbsp;&nbsp;Null-terminated array of 16-bit UTF-16 code units.</p> </blockquote> <pre><code>"Hello world".withCString(encodedAs: UTF16.self) { String(format: "%S", $0) } </code></pre> <blockquote> <p>%p&nbsp;&nbsp;&nbsp;&nbsp;Void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x.</p> </blockquote> <pre><code>var hello = "world" withUnsafePointer(to: &amp;hello) { String(format: "%p", $0) } </code></pre> <blockquote> <p>%n&nbsp;&nbsp;&nbsp;&nbsp;The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of the fprintf() functions.</p> </blockquote> <p><strong><em>The <code>n</code> format specifier seems unsupported in Swift 4+</em></strong></p> <blockquote> <p>%a&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent.</p> </blockquote> <pre><code>String(format: "from %a to %a", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <blockquote> <p>%A&nbsp;&nbsp;&nbsp;&nbsp;64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent.</p> </blockquote> <pre><code>String(format: "from %A to %A", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude) </code></pre> <h2>Flags</h2> <blockquote> <p>'&nbsp;&nbsp;&nbsp;&nbsp;The integer portion of the result of a decimal conversion ( %i, %d, %u, %f, %F, %g, or %G ) shall be formatted with thousands' grouping characters. For other conversions the behavior is undefined. The non-monetary grouping character is used.</p> </blockquote> <p><strong><em>The <code>'</code> flag seems unsupported in Swift 4+</em></strong></p> <blockquote> <p>-&nbsp;&nbsp;&nbsp;&nbsp;The result of the conversion shall be left-justified within the field. The conversion is right-justified if this flag is not specified.</p> </blockquote> <pre><code>String(format: "from %-12f to %-12d.", Double.leastNonzeroMagnitude, Int32.max) </code></pre> <blockquote> <p>+&nbsp;&nbsp;&nbsp;&nbsp;The result of a signed conversion shall always begin with a sign ( '+' or '-' ). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified.</p> </blockquote> <pre><code>String(format: "from %+f to %+d", Double.leastNonzeroMagnitude, Int32.max) </code></pre> <blockquote> <p>&lt;space>&nbsp;&nbsp;&nbsp;&nbsp;If the first character of a signed conversion is not a sign or if a signed conversion results in no characters, a &lt;space> shall be prefixed to the result. This means that if the &lt;space> and '+' flags both appear, the &lt;space> flag shall be ignored.</p> </blockquote> <pre><code>String(format: "from % d to % d.", Int32.min, Int32.max) </code></pre> <blockquote> <p>&num;&nbsp;&nbsp;&nbsp;&nbsp;Specifies that the value is to be converted to an alternative form. For o conversion, it increases the precision (if necessary) to force the first digit of the result to be zero. For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g , and G conversion specifiers, the result shall always contain a radix character, even if no digits follow the radix character. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.</p> </blockquote> <pre><code>String(format: "from %#a to %#x.", Double.leastNonzeroMagnitude, UInt32.max) </code></pre> <blockquote> <p>0&nbsp;&nbsp;&nbsp;&nbsp;For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed. If the '0' and '-' flags both appear, the '0' flag is ignored. For d, i, o, u, x, and X conversion specifiers, if a precision is specified, the '0' flag is ignored. If the '0' and '" flags both appear, the grouping characters are inserted before zero padding. For other conversions, the behavior is undefined.</p> </blockquote> <pre><code>String(format: "from %012f to %012d.", Double.leastNonzeroMagnitude, Int32.max) </code></pre> <h2>Width modifiers</h2> <blockquote> <p>If the converted value has fewer bytes than the field width, it shall be padded with spaces by default on the left; it shall be padded on the right if the left-adjustment flag ( '-' ) is given to the field width. The field width takes the form of an asterisk ( '*' ) or a decimal integer.</p> </blockquote> <pre><code>String(format: "from %12f to %*d.", Double.leastNonzeroMagnitude, 12, Int32.max) </code></pre> <h2>Precision modifiers</h2> <blockquote> <p>An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversion specifiers; the number of digits to appear after the radix character for the a, A, e, E, f, and F conversion specifiers; the maximum number of significant digits for the g and G conversion specifiers; or the maximum number of bytes to be printed from a string in the s and S conversion specifiers. The precision takes the form of a period ( '.' ) followed either by an asterisk ( '*' ) or an optional decimal digit string, where a null digit string is treated as zero. If a precision appears with any other conversion specifier, the behavior is undefined.</p> </blockquote> <pre><code>String(format: "from %.12f to %.*d.", Double.leastNonzeroMagnitude, 12, Int32.max) </code></pre> <h2>Length modifiers</h2> <blockquote> <p>h&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a short or unsigned short argument.</p> </blockquote> <pre><code>String(format: "from %hd to %hu", CShort.min, CUnsignedShort.max) </code></pre> <blockquote> <p>hh&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument.</p> </blockquote> <pre><code>String(format: "from %hhd to %hhu", CChar.min, CUnsignedChar.max) </code></pre> <blockquote> <p>l&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a long or unsigned long argument.</p> </blockquote> <pre><code>String(format: "from %ld to %lu", CLong.min, CUnsignedLong.max) </code></pre> <blockquote> <p>ll, q&nbsp;&nbsp;&nbsp;&nbsp;Length modifiers specifying that a following d, o, u, x, or X conversion specifier applies to a long long or unsigned long long argument.</p> </blockquote> <pre><code>String(format: "from %lld to %llu", CLongLong.min, CUnsignedLongLong.max) </code></pre> <blockquote> <p>L&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.</p> </blockquote> <p><strong><em>I wasn't able to pass a CLongDouble argument to <code>format</code> in Swift 4+</em></strong></p> <blockquote> <p>z&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a size_t.</p> </blockquote> <pre><code>String(format: "from %zd to %zu", size_t.min, size_t.max) </code></pre> <blockquote> <p>t&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a ptrdiff_t.</p> </blockquote> <pre><code>String(format: "from %td to %tu", ptrdiff_t.min, ptrdiff_t.max) </code></pre> <blockquote> <p>j&nbsp;&nbsp;&nbsp;&nbsp;Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a intmax_t or uintmax_t argument.</p> </blockquote> <pre><code>String(format: "from %jd to %ju", intmax_t.min, uintmax_t.max) </code></pre>
47,272,164
No .bash_profile on my Mac
<p>I'm trying to develop using Eclipse/Maven on my Mac and while setting environment variables there is no .bash_profile. I do ls -a and still not there. I see a .bash_history and .bash_sessions. Where am I supposed to set my JAVA_HOME and PATH?</p> <p>Thank you!</p>
47,272,189
3
1
null
2017-11-13 19:35:44.813 UTC
null
2021-06-12 02:59:21.883 UTC
null
null
null
null
398,107
null
1
14
eclipse|bash|macos|terminal
58,224
<p>In your terminal:</p> <pre><code>touch ~/.bash_profile; open ~/.bash_profile </code></pre> <p>Then make your edits and save. This is generic so make sure your path is correct in the above example.</p>
22,601,414
How to set a frequency for the fm radio in android?
<p>In my android app I am using this intent to start fm radio</p> <pre><code>Intent i = new Intent(Intent.ACTION_MAIN); PackageManager manager = getPackageManager(); i = manager.getLaunchIntentForPackage("com.sec.android.app.fm"); i.addCategory(Intent.CATEGORY_LAUNCHER); startActivity(i); </code></pre> <p>Is it possible to <strong>set a manual frequency</strong> and open the fm radio? Thanks</p>
22,652,799
2
1
null
2014-03-24 05:01:06.653 UTC
8
2021-01-25 01:57:04.893 UTC
2014-03-25 04:54:05.277 UTC
null
2,219,371
null
2,219,371
null
1
10
java|android
5,753
<p>There is currently no native Android API for playing FM radio.</p> <p>You need to use 3rd party apps to play FM radio, and each phone vendor / app vendor has it's own API.</p> <p>You best option is to contact them directly and ask for the relevant API to suit your needs.</p> <p>Hope this helped!</p>
7,068,388
OAuth callbacks in iPhone web apps
<p>I'm building a full-screen iPhone optimized web app. It gets launched from the homepage like a native app and behaves like a standalone app via the following directive, but it's just plain HTML/CSS/JavaScript, no PhoneGap involved.</p> <pre class="lang-html prettyprint-override"><code>&lt;meta name="apple-mobile web-app-capable" content="yes" /&gt; </code></pre> <p>When trying to authenticate over OAuth, the redirect to Twitter (or any other OAuth provider) takes me out of my full-screen web app and into Mobile Safari. Once the Twitter auth completes, the redirect back to my app does not launch my homepage app, instead just redirects within Mobile Safari. Is it possible to do OAuth inside an iPhone homepage web app? Short of that, can I get the OAuth callback to re-launch my homepage web app?</p>
7,262,955
2
3
null
2011-08-15 17:35:00.02 UTC
11
2019-05-02 01:16:27.477 UTC
2012-01-28 10:19:30.073 UTC
null
918,414
null
20,476
null
1
14
iphone|oauth|twitter-oauth|iphone-web-app|iphone-standalone-web-app
4,078
<p>I've had a similar problem recently, and found that if you set the URL in Javascript with a <code>window.location.href="http://example.com/whatever"</code> then iOS doesn't switch to Safari. I've managed to get PayPal checkout and Facebook login working in standalone web apps without switching to safari using this method! If you're submitting a form, do that via JS too and get the redirect URL from the response then set the location. As for handing back to your app afterwards, it depends on how the external service works.</p> <p>If that's no good, you could do a pop-up <code>alert('You will be passed to Safari for authentication. Reload this app afterwards.')</code> before they get switched to Safari. Not great, but better than surprising them with automatically switching apps! </p>
7,440,334
How do Gravity values effect PopupWindow.showAtLocation() in Android
<p>How do the different Gravity values effect PopupWindow.showAtLocation() in Android?</p> <p>I can't find good docs on PopupWindows showAtLocation and Gravity.</p>
10,610,949
2
0
null
2011-09-16 05:00:09.333 UTC
20
2018-05-07 03:56:10.907 UTC
2013-02-26 23:56:13.19 UTC
null
552,958
null
552,958
null
1
42
android
35,856
<p>After hacking for a few hours trying some black magic maths to calculate centers and try to align the view using Gravity.TOP I found a post that used Gravity.CENTER. I'm collecting my findings here in the hopes it saves someone else some pain.</p> <pre><code>popupWindow.showAtLocation(anyViewOnlyNeededForWindowToken, Gravity.CENTER, 0, 0); </code></pre> <p>The view is only needed for the window token, it has no other impact on the location.</p> <p>Gravity tells the layout manager where to start the coordinate system and how to treat those coordinates. I can't find the docs but hacking is showing me that:</p> <ul> <li>CENTER uses the middle of the popup to be aligned to the x,y specified. So 0,0 is screen centered, with no adjustments for the size of the notification bar.</li> </ul> <p><img src="https://i.stack.imgur.com/yvGxh.png" alt="Gravity.CENTER 0,0"></p> <ul> <li>BOTTOM uses the bottom of the popup to be aligned to the x,y specified. So 0,0 has the popup bottom aligned with the screen bottom. If you want 10px padding then y=10 (not -10) to move the popup up the screen 10 pixels.</li> </ul> <p><img src="https://i.stack.imgur.com/CMzOx.png" alt="Gravity.BOTTOM 0,10"></p> <ul> <li>TOP uses the top of the popup to be aligned to the x,y specified. So 0,0 has the popup top aligned with the screen top. If you want 10px padding then y=10. <strong>NOTE</strong> If you are not in full screen mode then you must also make adjustments for the notification bar.</li> </ul> <p><img src="https://i.stack.imgur.com/ypwai.png" alt="Gravity.TOP 0,48"></p> <ul> <li>Gravity.LEFT and Gravity.RIGHT should be obvious now, for my example images they are too big to fit on the screen so they are clamped to the screen size minus the padding I am using.</li> </ul>
23,406,956
What is percent of authorship in TortoiseSVN statistics?
<p>In statistics section of TortoiseSVN, there is something called percent of authorship. What is this? How is this calculated? and how can it be useful?</p>
24,437,494
1
1
null
2014-05-01 10:34:30.667 UTC
2
2014-06-26 18:20:55.947 UTC
2014-06-26 18:20:55.947 UTC
null
395,857
danrah
235,171
null
1
32
svn|tortoisesvn
6,704
<p>The percent of authorship is a metric that aims at <a href="http://tigris-scm.10930.n7.nabble.com/Percent-of-authorship-td35688.html">quantifying the contribution of each committer</a>.</p> <blockquote> <p>In theory, it should be indeed lines-changes, but aggregated through the entire history of the file, with diminishing weight. Additionally, some kind of heuristic may be applied to reduce the weight of whitespace-only changes such as indentation fixes. Roughly speaking, this metric should answer the question "which person should I talk to if I want to understand/fix/improve this part of code".</p> </blockquote> <p>In practice here is <a href="https://code.google.com/p/tortoisesvn/source/browse/branches/1.7.x/src/TortoiseProc/LogDialog/StatGraphDlg.cpp">the actual code</a>:</p> <pre><code>void CStatGraphDlg::GatherData() { // Sanity check if ((m_parAuthors==NULL)||(m_parDates==NULL)||(m_parFileChanges==NULL)) return; m_nTotalCommits = m_parAuthors-&gt;GetCount(); m_nTotalFileChanges = 0; // Update m_nWeeks and m_minDate UpdateWeekCount(); // Now create a mapping that holds the information per week. m_commitsPerUnitAndAuthor.clear(); m_filechangesPerUnitAndAuthor.clear(); m_commitsPerAuthor.clear(); int interval = 0; __time64_t d = (__time64_t)m_parDates-&gt;GetAt(0); int nLastUnit = GetUnit(d); double AllContributionAuthor = 0; // Now loop over all weeks and gather the info for (LONG i=0; i&lt;m_nTotalCommits; ++i) { // Find the interval number __time64_t commitDate = (__time64_t)m_parDates-&gt;GetAt(i); int u = GetUnit(commitDate); if (nLastUnit != u) interval++; nLastUnit = u; // Find the authors name CString sAuth = m_parAuthors-&gt;GetAt(i); if (!m_bAuthorsCaseSensitive) sAuth = sAuth.MakeLower(); tstring author = tstring(sAuth); // Increase total commit count for this author m_commitsPerAuthor[author]++; // Increase the commit count for this author in this week m_commitsPerUnitAndAuthor[interval][author]++; CTime t = m_parDates-&gt;GetAt(i); m_unitNames[interval] = GetUnitLabel(nLastUnit, t); // Increase the file change count for this author in this week int fileChanges = m_parFileChanges-&gt;GetAt(i); m_filechangesPerUnitAndAuthor[interval][author] += fileChanges; m_nTotalFileChanges += fileChanges; //calculate Contribution Author double contributionAuthor = CoeffContribution((int)m_nTotalCommits - i -1) * fileChanges; AllContributionAuthor += contributionAuthor; m_PercentageOfAuthorship[author] += contributionAuthor; } // Find first and last interval number. if (!m_commitsPerUnitAndAuthor.empty()) { IntervalDataMap::iterator interval_it = m_commitsPerUnitAndAuthor.begin(); m_firstInterval = interval_it-&gt;first; interval_it = m_commitsPerUnitAndAuthor.end(); --interval_it; m_lastInterval = interval_it-&gt;first; // Sanity check - if m_lastInterval is too large it could freeze TSVN and take up all memory!!! assert(m_lastInterval &gt;= 0 &amp;&amp; m_lastInterval &lt; 10000); } else { m_firstInterval = 0; m_lastInterval = -1; } // Get a list of authors names LoadListOfAuthors(m_commitsPerAuthor); // Calculate percent of Contribution Authors for (std::list&lt;tstring&gt;::iterator it = m_authorNames.begin(); it != m_authorNames.end(); ++it) { m_PercentageOfAuthorship[*it] = (m_PercentageOfAuthorship[*it] *100)/ AllContributionAuthor; } // All done, now the statistics pages can retrieve the data and // extract the information to be shown. } </code></pre> <p>The metric was inspired by <a href="http://repo.or.cz/w/git-stats.git/blob/HEAD:/doc/use-cases.txt">some ideas of Git statistics</a> (I copy them here as I find them interesting but links get broken easily):</p> <pre><code>Terminology There are four types of users: Maintainers, Developers, Bug-fixers, and regular Users. The first three are all Contributors. Name: Maintainer (Contributor) Description: The Maintainer reviews commits and branches from other Contributors and decided which ones to integrate into a 'master' branch. Name: Developer (Contributor) Description: The Developer contributes enhancements to the project, e.g. they add new content or improve existing content. Name: Bug-fixer (Contributor) Description: The Bug-fixer locates 'bugs' (as something unwanted that needs to be corrected) in the content and 'fixes' them. Name: User Description: The User uses the content, be it in their daily work or every now and then for a specific purpose. Use cases A model where other Contributors review commits is assumed in all use cases. When referenced are made to a Contributor addressing another Contributor to adjust their behavior as the result of data mined, it should be kept in mind that the Contributor should foremost be the one to do this. Using this information to, say, spend more time checking ones own commits for bugs when working on a specific part of the content on ones own accord is is often more effective then doing so only after being asked. &lt;/disclaimer&gt;? :P Name: Finding a Contributor that is active in a specific bit of content. Description: Whenever a Contributor needs to know about other Contributors that are active in a specific part of the content they query git for this information. This could be used to figure out whom to send a copy of a commit (someone who has recently worked on the content a commit modifies is likely to be interested in such a commit). This information may be easily gathered with, say, git blame. Aggregating it's output (in the background if need be to maintain speedy response times), it is trivial to determine whether a Contributor has more commits/lines of change than a predefined amount. The main difference with git blame is that it's output is aggregated over the history of the content, for a specific Contributor, whereas git blame only shows the latest changes. Name: Finding which commits touches the parts of the content that a commit touches. Description: There are several reasons that one might want to know which commit touches the parts of the content that a commit touches. This may be implemented similar to how git blame works only instead of 'stopping' after having found the author of a line, the search continues up to a certain date in the past. Name: Integrating the found 'bug introducing' commit with the git commit message system. Description: When a Bug-fixer sends out a commit to fix a bug it might be useful for them to find out where exactly the bug was introduced. Using the 'which commit touched the content this commit touches' technique optional candidates may be retrieved. After picking which of the found commits caused the bug, this information may then automatically added to the commit's description. This does not only allow the Bug-fixer to make clear the origin of their commit, but also make it possible to later unambiguously determine a bug/fix pair. Note that this is automated, no user input is required to determine which commit caused the bug, only the picking of 'cause' commits requires input from the user. Name: Finding the Author that introduce a lot of/almost no bugs to the content. Description: Contributors might be interested to know which of the Developers introduce a lot of bugs, or the contrary, which introduce almost no bugs to the content. This information is highly relevant to the Maintainer as they may now focus the time they spend on reviewing commits on those that stem from Developers that turn out to often introduce bugs. On the other hand, Developers that usually do not introduce bugs need less reviewing time. While such information is usually known to the experienced Maintainer (as they know their main contributors well), it can be helpful to new maintainers, or as a pointer that the opinion of the Maintainer about a specific Developer needs to be adjusted. Bug-fixers on the other hand can use this information to address the Developer that introduces most of the bugs they fix, perhaps with advice on how to prevent future bugs from being introduced. Name: Finding the Contributor that accepted a lot of/almost no bugs into the content. Description: Similar to the finding Authors that write the bugs, there are other Contributors that 'accept' the commit. Either passively, by not commenting when the commit is sent out for review, or actively, by 'acknowledging' (acked-by), 'signing off' (signed-off-by) or 'testing' (tested-by) a commit. When actively doing so, this can later be traced and then be used in the same ways as for Authors. Name: Finding parts of the content in which a lot of bugs are introduced and fixed Description: When a Developer decides to change part of the content, it would be interesting for them to know that many before them introduced bugs when working on that part of the content. Knowing this the Developer might ask for all such buggy commits to try and learn from the mistakes made by others and prevent making the same mistake. A Maintainer might use this information to spend extra time reviewing a commit from a 'bug prone' part of the content. Name: Finding parts of the content a particular Contributor introduces a lot of/almost no bugs to. Description: When trying to decide whether to ask a specific Contributor to work on part of the content it might be useful to not only know how active they work on that part of the content, but also if they introduced a lot of bugs to that part, or perhaps fixed many. Similar to the more general case, this can be split out between modifying content and 'accepting' modifications. This information may be used to decide to ask a Contributor to spend more time on a specific part of the content before sending in a commit for review. Name: Finding how many bugs were introduced/fixed in a period of time Description: As bugs are recognized by their fixes, it is always possible to match a bug to it's fix. Both commits have a time stamp and with those the time between bug and fix can be calculated. Aggregating this data over all known bug(fixes) the amount of unfixed bugs may be found over a specified period of time. For example, finding the amount of fixed bugs between two releases, or how many bugs were not fixed within one release cycle. This number might then be calculated over several time frames (say, each release), after which it is possible to track 'content quality' throughout releases. If this information is then graphed one can find extremes in this figure (for example, a release cycle in which a lot of bugs were fixed, or one that introduced many). Knowing this the Contributors may then determine the cause of such and learn from that. Name: Finding how much work a contributor has done over a period of time. Description: When working in a team in which everybody is expected to do approximately the same amount of work it is interesting to see how much work each Contributor actually does. This allows the team to discuss any extremes and attempt to handle these as to distribute the work more evenly. When work is being done by a large group of people it is interesting to know the most active Contributors since these usually are the ones with most knowledge on the content. The other way around, it is possible to determine if a specific Contributor is 'active enough' for a specific task (such as mentoring). Name: Finding whether a Contributor is mostly a Developer or a Bug-fixer. Description: To all Contributors it is interesting to know if they spend most of their time fixing bugs, or contributing enhancements to the content. This information could also be queried over a specific time frame, for example 'weekends vs. workdays' or 'holidays vs. non-holidays'. </code></pre> <p><img src="https://i.stack.imgur.com/KIblD.png" alt="enter image description here"></p>
31,948,189
Material ripple effect hidden by other view in layout
<p>I added a ripple effect on a <code>ImageButton</code>, however it is hidden by an <code>ImageView</code> used as a background for the parent view <code>RelativeLayout</code>.</p> <p>Here's the layout file:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="172dp" android:orientation="vertical" android:theme="@style/ThemeOverlay.AppCompat.Dark"&gt; &lt;ImageView android:id="@+id/drawerBackgroundImageView" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/drawer_background"/&gt; [...] &lt;ImageButton android:id="@+id/drawerLogoutButton" android:layout_width="32dp" android:layout_height="32dp" android:layout_alignBottom="@id/drawerEmailTextView" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginEnd="@dimen/activity_horizontal_margin" android:layout_marginRight="@dimen/activity_horizontal_margin" style="@style/FlatButtonStyle" android:scaleType="centerInside" android:src="@drawable/ic_logout_white_24dp"/&gt; &lt;/RelativeLayout&gt; </code></pre> <p>(there's a bunch of other views but they're irrelevant here)</p> <p>I'm using an <code>ImageView</code> as the background for the <code>RelativeLayout</code> as I need to set a specific <code>scaleType</code> for the image, so I can't use the basic <code>android:background</code> property.</p> <p>The ripple effect is hidden as it doesn't have a mask layer (I want it to extend out of the button's bounds) and thus uses the <code>ImageButton</code>'s parent view to be displayed. The effect is perfectly visible if I remove the <code>ImageView</code>.</p> <p>Is there a way to get the ripple effect to be shown above the problematic <code>ImageView</code>?</p>
37,757,154
5
2
null
2015-08-11 17:25:12.333 UTC
10
2021-02-23 07:57:44.377 UTC
null
null
null
null
352,876
null
1
18
android|android-layout|material-design|rippledrawable
11,941
<p><em>I had exactly the same issue and solved it using this thread: <a href="https://code.google.com/p/android/issues/detail?id=155880" rel="noreferrer">https://code.google.com/p/android/issues/detail?id=155880</a></em></p> <p><strong>Issue preview:</strong></p> <p><em>Before solved:</em></p> <p><a href="https://i.stack.imgur.com/nd7Yy.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/nd7Yy.gif" alt="Before"></a></p> <p><em>After solved:</em></p> <p><a href="https://i.stack.imgur.com/U4kEt.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/U4kEt.gif" alt="After"></a></p> <p><strong>Explanation:</strong></p> <p>"Borderless buttons draw their content on the closest background. Your button might not be having background between itself and the <code>ImageView</code>, so it draws underneath the <code>ImageView</code>."</p> <p><strong>Solution:</strong></p> <p>"Use a transparent background (<code>android:background="@android:color/transparent"</code>) on some layout containing the button (beneath the <code>ImageView</code>). This will dictate what the maximum bounds of the ripple effect is."</p> <pre><code>&lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" ...&gt; &lt;!-- Your background ImageView --&gt; &lt;ImageView android:id="@+id/drawerBackgroundImageView" android:src="@drawable/drawer_background" ... /&gt; &lt;!-- ... --&gt; &lt;!-- HERE, you need a container for the button with the transparent background. Let's say you'll use a FrameLayout --&gt; &lt;FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent"&gt; &lt;!-- Maybe more items --&gt; &lt;!-- Button with borderless ripple effect --&gt; &lt;ImageButton android:id="@+id/drawerLogoutButton" android:background="?selectableItemBackgroundBorderless" ... /&gt; &lt;/FrameLayout&gt; &lt;/FrameLayout&gt; </code></pre> <p>Hope it helps.</p>
31,587,770
PowerMockito mocking static method fails when calling method on parameter
<p>I'm trying to test a class which uses a calculator class with a number of static methods. I've successfully mocked another class in a similar way, but this one is proving more stubborn.</p> <p>It seems that if the mocked method contains a method call on one of the passed in arguments the static method is not mocked (and the test breaks). Removing the internal call is clearly not an option. Is there something obvious I'm missing here?</p> <p>Here's a condensed version which behaves the same way...</p> <pre><code>public class SmallCalculator { public static int getLength(String string){ int length = 0; //length = string.length(); // Uncomment this line and the mocking no longer works... return length; } } </code></pre> <p>And here's the test...</p> <pre><code>import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.solveit.aps.transport.model.impl.SmallCalculator; @RunWith(PowerMockRunner.class) @PrepareForTest({ SmallCalculator.class}) public class SmallTester { @Test public void smallTest(){ PowerMockito.spy(SmallCalculator.class); given(SmallCalculator.getLength(any(String.class))).willReturn(5); assertEquals(5, SmallCalculator.getLength("")); } } </code></pre> <p>It seems there's some confusion about the question, so I've contrived a more 'realistic' example. This one adds a level of indirection, so that it doesn't appear that I'm testing the mocked method directly. The SmallCalculator class is unchanged:</p> <pre><code>public class BigCalculator { public int getLength(){ int length = SmallCalculator.getLength("random string"); // ... other logic return length; } public static void main(String... args){ new BigCalculator(); } } </code></pre> <p>And here's the new test class...</p> <pre><code>import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.solveit.aps.transport.model.impl.BigCalculator; import com.solveit.aps.transport.model.impl.SmallCalculator; @RunWith(PowerMockRunner.class) @PrepareForTest({ SmallCalculator.class}) public class BigTester { @Test public void bigTest(){ PowerMockito.spy(SmallCalculator.class); given(SmallCalculator.getLength(any(String.class))).willReturn(5); BigCalculator bigCalculator = new BigCalculator(); assertEquals(5, bigCalculator.getLength()); } } </code></pre>
31,588,929
4
3
null
2015-07-23 12:43:58.833 UTC
5
2015-07-23 13:55:02.263 UTC
2015-07-23 13:10:24.12 UTC
null
872,206
null
872,206
null
1
10
java|unit-testing|powermockito
40,173
<p>I've found the answer here <a href="https://blog.codecentric.de/en/2011/11/testing-and-mocking-of-static-methods-in-java/">https://blog.codecentric.de/en/2011/11/testing-and-mocking-of-static-methods-in-java/</a></p> <p>Here's the final code which works. I've tested this approach in the original code (as well as the contrived example) and it works great. Simples...</p> <pre><code>import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({ SmallCalculator.class}) public class BigTester { @Test public void bigTest(){ PowerMockito.mockStatic(SmallCalculator.class); PowerMockito.when(SmallCalculator.getLength(any(String.class))).thenReturn(5); BigCalculator bigCalculator = new BigCalculator(); assertEquals(5, bigCalculator.getLength()); } } </code></pre>
18,833,649
Error using nuget in VS2012 "missing packages"
<p>When I build my project from within VS2012 I get the following error message</p> <pre><code>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. </code></pre> <p>I have the nuget options set for NuGet to download missing packages.</p> <p><img src="https://i.stack.imgur.com/Wa05O.jpg" alt="picture of nugget options"></p> <p>Yet I still get the error. I have nugget 2.7 installed. With VS2012 update 3</p>
18,995,655
8
1
null
2013-09-16 17:11:43.75 UTC
4
2017-11-24 13:17:16.693 UTC
2013-09-16 17:26:08.19 UTC
null
61,623
null
61,623
null
1
30
visual-studio|nuget|nuget-package-restore
44,583
<p>As Dan was alluding to, if your solution has a .nuget folder (from enabling package restore), then nuget 2.7's automatic package restore feature is disabled, as per <a href="http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore">http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore</a>.</p> <p>If automatic package restore is disabled, then any package that installs a project target files will cause your build to fail until you manually restore that package in your solution, as described by <a href="http://blogs.msdn.com/b/dotnet/archive/2013/06/12/nuget-package-restore-issues.aspx">http://blogs.msdn.com/b/dotnet/archive/2013/06/12/nuget-package-restore-issues.aspx</a>. (Note that the workarounds described in the link are out-dated now that nuget 2.7 automatic package restore is available.)</p> <p>So, if both these things are true, then delete the NuGet.targets file in the .nuget folder, and Nuget will then restore the missing package before invoking MSBuild. You can delete nuget.exe in the .nuget folder as well, as it will no longer be used.</p>
37,785,154
How to enable maven artifact caching for GitLab CI runner?
<p>We use GitLab CI with shared runners to do our continuous integration. For each build, the runner downloads tons of maven artifacts.</p> <p>Is there a way to configure GitLab CI to cache those artifacts so we can speed up the building process by preventing downloading the same artifact over and over again?</p>
40,024,602
8
1
null
2016-06-13 08:37:17.87 UTC
24
2021-07-01 16:02:03.947 UTC
2021-07-01 16:02:03.947 UTC
null
557,091
null
978,392
null
1
85
maven|gitlab-ci|gitlab-ci-runner
69,034
<p>Gitlab CI allows you to define certain paths, which contain data that should be cached between builds, on a per job or build basis (see <a href="https://docs.gitlab.com/ce/ci/yaml/README.html#cache" rel="noreferrer">here</a> for more details). In combination with khmarbaise's recommendation, this can be used to cache dependencies between multiple builds.</p> <p>An example that caches all job dependencies in your build:</p> <pre><code>cache: paths: - .m2/repository variables: MAVEN_OPTS: "-Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository" maven_job: script: - mvn clean install </code></pre>
21,262,309
RSpec: how to test if a method was called?
<p>When writing RSpec tests, I find myself writing a lot of code that looks like this in order to ensure that a method was called during the execution of a test (for the sake of argument, let's just say I can't really interrogate the state of the object after the call because the operation the method performs is not easy to see the effect of).</p> <pre><code>describe "#foo" it "should call 'bar' with appropriate arguments" do called_bar = false subject.stub(:bar).with("an argument I want") { called_bar = true } subject.foo expect(called_bar).to be_true end end </code></pre> <p>What I want to know is: Is there a nicer syntax available than this? Am I missing some funky RSpec awesomeness that would reduce the above code down to a few lines? <code>should_receive</code> sounds like it should do this but reading further it sounds like that's not exactly what it does. </p>
21,263,118
4
2
null
2014-01-21 15:27:45.103 UTC
16
2020-04-26 10:36:11.51 UTC
2017-02-24 14:15:22.75 UTC
null
3,257,186
null
705,589
null
1
134
ruby-on-rails|ruby|rspec
153,549
<pre><code>it "should call 'bar' with appropriate arguments" do expect(subject).to receive(:bar).with("an argument I want") subject.foo end </code></pre>