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
14,461,623
Laravel Fluent queries - How do I perform a 'SELECT AS' using Fluent?
<p>I have a query to select all the rows from the hire table and display them in a random order.</p> <pre><code>DB::table('hire_bikes')-&gt;order_by(\DB::raw('RAND()'))-&gt;get(); </code></pre> <p>I now want to be able to put</p> <pre><code>concat(SUBSTRING_INDEX(description, &quot; &quot;,25), &quot;...&quot;) AS description </code></pre> <p>into the SELECT part of the query, so that I can <code>select *</code> from the table and a shortened description.</p> <p>I know this is possible by running a raw query, but I was hoping to be able to do this using Fluent or at least partial Fluent (like above).</p> <p>How can I do it?</p>
14,502,165
3
4
null
2013-01-22 15:05:15.93 UTC
3
2021-01-12 02:14:59.243 UTC
2021-01-12 02:09:10.743 UTC
null
63,550
null
1,685,347
null
1
23
mysql|laravel|fluent
38,309
<p>You can do this by adding a <code>DB::raw()</code> to a select an array in your fluent query. I tested this locally and it works fine.</p> <pre><code>DB::table('hire_bikes') -&gt;select( array( 'title', 'url', 'image', DB::raw('concat(SUBSTRING_INDEX(description, &quot; &quot;,25),&quot;...&quot;) AS description'), 'category' ) ) -&gt;order_by(\DB::raw('RAND()')) -&gt;get(); </code></pre>
14,662,526
Why Git is not allowing me to commit even after configuration?
<p>This question seems like a duplicate but it's really not. Just a slight difference that keeps on repeating. git keeps on telling me: "please tell me who you are", even after setting it up. when I run <code>git commit</code>, this is what I get....</p> <pre><code>$ git commit *** Please tell me who you are. Run git config --global user.email "[email protected]" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set the identity only in this repository. fatal: unable to auto-detect email address (got 'Obby@ObbyWorkstation.(none)') </code></pre> <p>But when I run <code>git config --global -l</code>, it gives me all my details...</p> <pre><code>$ git config --global -l user.name=myname [email protected] http.proxy=proxy.XX.XX.XX:XXXX </code></pre> <p>I have changed my name, email and proxy but they are appearing fine when I run the command, even in the .gitconfig file I can see the values are set. what could be the missing thing, because I cannot commit at all. Every time it keeps asking me who I am ?</p> <p>@sheu told me something that i changed, but still the same problem. when i set <code>--local</code>, still <code>git commit</code> asks me the same question. this is the output</p> <pre><code>$ git config --local -l core.repositoryformatversion=0 core.filemode=false core.bare=false core.logallrefupdates=true core.symlinks=false core.ignorecase=true core.hidedotfiles=dotGitOnly user.name=myname [email protected] </code></pre>
14,662,703
4
4
null
2013-02-02 13:47:37.647 UTC
19
2021-08-10 11:41:48.243 UTC
2014-02-02 16:59:14.927 UTC
null
147,562
null
1,788,917
null
1
96
git|github|commit|config
143,541
<p>That’s a typo. You’ve accidently set <code>user.mail</code> with no <strong>e</strong> in <strong>e</strong>mail. Fix it by setting <code>user.email</code> in the global configuration with</p> <pre><code>git config --global user.email &quot;[email protected]&quot; </code></pre>
2,372,311
How to invalidate an user session when he logs twice with the same credentials
<p>I'm using JSF 1.2 with Richfaces and Facelets.</p> <p>I have an application with many session-scoped beans and some application beans.</p> <p>The user logs in with, let's say, Firefox. A session is created with ID="A"; Then he opens Chrome and logs in again with the same credentials. A session is created with ID="B".</p> <p>When the session "B" is created, I want to be able to destroy session "A". How to do that?</p> <p>Also. when the user in Firefox does anything, I want to be able to display a popup or some kind of notification saying "You have been logged out because you have logged in from somewhere else".</p> <p>I have a sessionListener who keeps track of the sessions created and destroyed. The thing is, I could save the HTTPSession object in a application-scoped bean and destroy it when I detect that the user has logged in twice. But something tells me that is just wrong and won't work.</p> <p>Does JSF keep track of the sessions somewhere on the server side? How to access them by identifier? If not, how to kick out the first log in of an user when he logs in twice?</p>
2,372,990
3
0
null
2010-03-03 15:04:48.787 UTC
12
2016-03-01 20:40:44.243 UTC
2013-06-17 11:05:27.407 UTC
null
157,882
null
222,851
null
1
20
java|session|jsf|richfaces|facelets
24,125
<p>The DB-independent approach would be to let the <code>User</code> have a <code>static Map&lt;User, HttpSession&gt;</code> variable and implement <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html" rel="noreferrer"><code>HttpSessionBindingListener</code></a> (and <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-" rel="noreferrer"><code>Object#equals()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--" rel="noreferrer"><code>Object#hashCode()</code></a>). This way your webapp will still function after an unforeseen crash which may cause that the DB values don't get updated (you can of course create a <code>ServletContextListener</code> which resets the DB on webapp startup, but that's only more and more work).</p> <p>Here's how the <code>User</code> should look like:</p> <pre><code>public class User implements HttpSessionBindingListener { // All logins. private static Map&lt;User, HttpSession&gt; logins = new ConcurrentHashMap&lt;&gt;(); // Normal properties. private Long id; private String username; // Etc.. Of course with public getters+setters. @Override public boolean equals(Object other) { return (other instanceof User) &amp;&amp; (id != null) ? id.equals(((User) other).id) : (other == this); } @Override public int hashCode() { return (id != null) ? (this.getClass().hashCode() + id.hashCode()) : super.hashCode(); } @Override public void valueBound(HttpSessionBindingEvent event) { HttpSession session = logins.remove(this); if (session != null) { session.invalidate(); } logins.put(this, event.getSession()); } @Override public void valueUnbound(HttpSessionBindingEvent event) { logins.remove(this); } } </code></pre> <p>When you login the <code>User</code> as follows:</p> <pre><code>User user = userDAO.find(username, password); if (user != null) { sessionMap.put("user", user); } else { // Show error. } </code></pre> <p>then it will invoke the <code>valueBound()</code> which will remove any previously logged in user from the <code>logins</code> map and invalidate the session.</p> <p>When you logout the <code>User</code> as follows:</p> <pre><code>sessionMap.remove("user"); </code></pre> <p>or when the session is timed out, then the <code>valueUnbound()</code> will be invoked which removes the user from the <code>logins</code> map.</p>
2,622,069
How does SQL Server treat statements inside stored procedures with respect to transactions?
<p>Say I have a stored procedure consisting of several separate SELECT, INSERT, UPDATE and DELETE statements. There is no explicit BEGIN TRANS / COMMIT TRANS / ROLLBACK TRANS logic. </p> <p>How will SQL Server handle this stored procedure transaction-wise? Will there be an implicit connection for each statement? Or will there be one transaction for the stored procedure?</p> <p>Also, how could I have found this out on my own using T-SQL and / or SQL Server Management Studio?</p> <p>Thanks!</p>
2,622,157
3
1
null
2010-04-12 12:40:10.227 UTC
4
2020-06-25 15:30:52.417 UTC
2010-07-02 14:22:46.26 UTC
null
5,696,608
null
189,971
null
1
53
sql|sql-server|stored-procedures|transactions
30,457
<p>There will only be one connection, it is what is used to run the procedure, no matter how many SQL commands within the stored procedure.</p> <p>since you have no explicit BEGIN TRANSACTION in the stored procedure, each statement will run on its own with no ability to rollback any changes if there is any error.</p> <p>However, if you before you call the stored procedure you issue a BEGIN TRANSACTION, then all statements are grouped within a transaction and can either be COMMITted or ROLLBACKed following stored procedure execution.</p> <p>From within the stored procedure, you can determine if you are running within a transaction by checking the value of the system variable <a href="http://msdn.microsoft.com/en-us/library/ms187967.aspx" rel="noreferrer">@@TRANCOUNT (Transact-SQL)</a>. A zero means there is no transaction, anything else shows how many nested level of transactions you are in. Depending on your sql server version you could use <a href="http://msdn.microsoft.com/en-us/library/ms189797.aspx" rel="noreferrer">XACT_STATE (Transact-SQL)</a> too.</p> <p>If you do the following:</p> <pre><code>BEGIN TRANSACTION EXEC my_stored_procedure_with_5_statements_inside @Parma1 COMMIT </code></pre> <p>everything within the procedure is covered by the transaction, all 6 statements (the EXEC is a statement covered by the transaction, 1+5=6). If you do this:</p> <pre><code>BEGIN TRANSACTION EXEC my_stored_procedure_with_5_statements_inside @Parma1 EXEC my_stored_procedure_with_5_statements_inside @Parma1 COMMIT </code></pre> <p>everything within the two procedure calls are covered by the transaction, all 12 statements (the 2 EXECs are both statement covered by the transaction, 1+5+1+5=12).</p>
2,905,886
What makes an input vulnerable to XSS?
<p>I've been reading about XSS and I made a simple form with a text and submit input, but when I execute <code>&lt;script&gt;alert();&lt;/script&gt;</code> on it, nothing happens, the server gets that string and that's all. </p> <p>What do I have to do for make it vulnerable?? (then I'll learn what I shouldn't do hehe)</p> <p>Cheers.</p>
2,906,297
5
1
null
2010-05-25 15:04:20.893 UTC
3
2020-12-03 05:52:52.16 UTC
2010-05-25 18:54:16.177 UTC
null
176,741
null
307,976
null
1
8
javascript|html|security|xss
42,476
<p>Indeed just let the server output it so that the input string effectively get embedded in HTML source which get returned to the client.</p> <p>PHP example:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt;&lt;title&gt;XSS test&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;form&gt;&lt;input type="text" name="xss"&gt;&lt;input type="submit"&gt;&lt;/form&gt; &lt;p&gt;Result: &lt;?= $_GET['xss'] ?&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>JSP example:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt;&lt;title&gt;XSS test&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;form&gt;&lt;input type="text" name="xss"&gt;&lt;input type="submit"&gt;&lt;/form&gt; &lt;p&gt;Result: ${param.xss}&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Alternatively you can redisplay the value in the input elements, that's also often seen:</p> <pre><code>&lt;input type="text" name="xss" value="&lt;?= $_GET['xss'] ?&gt;"&gt; </code></pre> <p>resp.</p> <pre><code>&lt;input type="text" name="xss" value="${param.xss}"&gt; </code></pre> <p>This way "weird" attack strings like <code>"/&gt;&lt;script&gt;alert('xss')&lt;/script&gt;&lt;br class="</code> will work because the server will render it after all as </p> <pre><code>&lt;input type="text" name="xss" value=""/&gt;&lt;script&gt;alert('xss')&lt;/script&gt;&lt;br class=""&gt; </code></pre> <p>XSS-prevention solutions are among others <a href="http://php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer"><code>htmlspecialchars()</code></a> and <a href="http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/escapeXml.fn.html" rel="noreferrer"><code>fn:escapeXml()</code></a> for PHP and JSP respectively. Those will replace among others <code>&lt;</code>, <code>&gt;</code> and <code>"</code> by <code>&amp;lt;</code>, <code>&amp;gt;</code> and <code>&amp;quot;</code> so that enduser input doesn't end up to be literally embedded in HTML source but instead just got displayed as it was entered.</p>
46,200,841
Why are there recovered references in my xcode project file?
<p>I have a react native app and just noticed that a few lines were added for <code>Recovered References</code> in my <code>project.pbxproj</code> file in Xcode.</p> <p>I don't remember adding or deleting any references and the recovered references show libraries that I normally use. I'm hesitant to check in the local changes to git without knowing what these changes were. Should I just discard these changes?</p> <p>Can someone explain why these lines might be added if I didn't add or remove these packages myself? Does this mean some references were deleted to later be recovered? The only thing I can think of is that I ran react-native link, would that have made these changes?</p> <p>This line was added</p> <pre><code>E3C5B1001F6966D2006296E1 /* Recovered References */, </code></pre> <p>This entire section is new:</p> <pre><code>E3C5B1001F6966D2006296E1 /* Recovered References */ = { isa = PBXGroup; children = ( E602D61E379048BF92DC0C6D /* libRNDeviceInfo.a */, DEE39860F1B042208F193884 /* libRNVectorIcons.a */, C193FEFE9F3B45388016E921 /* libRNShare.a */, 58B3A26CAB2543FB941C3D8D /* libRNFIRMessaging.a */, 0BFBA42D662C492EBC1957A0 /* libreact-native-branch.a */, 4BC248DD95524DE091A41CEC /* libCodePush.a */, 6DB0E4FE64B34B68A29B262E /* libRNImagePicker.a */, E1502CC537D94CF4A5711814 /* libRNAddCalendarEvent.a */, 065361D30B3F47D4A5101A1D /* libRNAccountKit.a */, ); name = "Recovered References"; sourceTree = "&lt;group&gt;"; }; </code></pre>
46,465,477
5
1
null
2017-09-13 14:59:52.363 UTC
4
2020-02-03 09:02:42.15 UTC
2020-02-03 09:02:42.15 UTC
null
1,033,581
null
611,750
null
1
49
xcode
18,263
<p>From: Release Notes for Xcode 9 Beta 2:</p> <blockquote> <p>When a project is opened, Xcode will detect if any build files in targets in the project represent file references which are not present in that project’s group tree. Any such references will be added to a file group named “Recovered References” , which will be created if necessary. These references should be manually reorganized in the project as appropriate. (22924751)</p> </blockquote>
59,087,200
google-chrome Failed to move to new namespace
<p>Im trying to run google-chrome --headless inside a docker container as a non-root user to execute some tests. Everytime Im trying to start it, it throws following error:</p> <p><strong>google-chrome --headless</strong></p> <p><em>Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted Failed to generate minidump.Illegal instruction</em></p> <p>Its a docker container running in k8s cluster. Operating system is Ubuntu 16.04.</p> <p>Namespaces are enabled, user is non-root</p> <p>I do not want to use --no-sandbox option as this is a security issue.</p> <p>I cannot use docker run --security-opt=syscomp:unconfined as its being deployed using helm.</p> <p>Is there a system permission missing that I need to setup for chrome within the container itself?</p>
59,154,049
2
0
null
2019-11-28 10:54:12.25 UTC
6
2021-11-22 20:52:04.163 UTC
2020-10-23 08:23:07.163 UTC
null
8,678,740
null
1,173,498
null
1
32
linux|docker|google-chrome|kubernetes-helm|google-chrome-headless
23,853
<p>After researching extensively internet I think I found the answer:</p> <p><strong>Sandboxing</strong>  <em>For security reasons, Google Chrome is unable to provide sandboxing when it is running in the container-based environment. To use Chrome in the container-based environment, pass the --no-sandbox flag to the chrome executable</em></p> <p>So it looks like there is no better solution than --no-sandbox for me, even though its not being very secure, there are people on the internet claiming that it is still safe to use "--no-sandbox" as its running within container which is extra protected any way.</p>
30,093,744
mongorestore Failed: no reachable servers
<p>I tried to restore mongo from dump but failed:</p> <pre><code>mongorestore --port 27133 dump 2015-05-07T09:39:11.760+0300 Failed: no reachable servers </code></pre> <p>Although I can connect to it without any problem:</p> <pre><code>$ mongo --port 27133 MongoDB shell version: 3.0.1 connecting to: 127.0.0.1:27133/test </code></pre> <p>In a log file there is nothing special:</p> <pre><code>2015-05-07T09:37:00.350+0300 I NETWORK [initandlisten] connection accepted from 127.0.0.1:44901 #1 (1 connection now open) 2015-05-07T09:37:13.935+0300 I NETWORK [conn1] end connection 127.0.0.1:44901 (0 connections now open) 2015-05-07T09:39:08.752+0300 I NETWORK [initandlisten] connection accepted from 127.0.0.1:44906 #2 (1 connection now open) 2015-05-07T09:39:11.763+0300 I NETWORK [conn2] end connection 127.0.0.1:44906 (0 connections now open) 2015-05-07T09:39:52.365+0300 I NETWORK [initandlisten] connection accepted from 127.0.0.1:44907 #3 (1 connection now open) 2015-05-07T09:39:55.064+0300 I NETWORK [conn3] end connection 127.0.0.1:44907 (0 connections now open) 2015-05-07T09:40:11.272+0300 I NETWORK [initandlisten] connection accepted from 127.0.0.1:44909 #4 (1 connection now open) 2015-05-07T09:40:14.281+0300 I NETWORK [conn4] end connection 127.0.0.1:44909 (0 connections now open) </code></pre> <h1>Update</h1> <p>Host <code>127.0.0.1</code> didn't help</p> <pre><code>$ mongorestore --host=127.0.0.1 --port=27132 dump 2015-12-16T18:52:33.270+0300 Failed: no reachable servers </code></pre> <p>Although I can still connect using <code>mongo</code> command:</p> <pre><code>$ mongo --host=127.0.0.1 --port=27133 MongoDB shell version: 3.2.0 connecting to: 127.0.0.1:27133/test &gt; ^C bye </code></pre> <p>Host <code>0.0.0.0</code> didn't help as well:</p> <pre><code>$ mongorestore --host=0.0.0.0 --port=27133 dump </code></pre> <p>I have 3.2 version of MongoDb:</p> <pre><code>$ mongorestore --version mongorestore version: 3.2.0-rc5 git version: 6186100ad0500c122a56f0a0e28ce1227ca4fc88 </code></pre>
34,316,860
12
0
null
2015-05-07 06:45:15.05 UTC
6
2020-04-11 22:16:32.323 UTC
2015-12-16 16:04:11.173 UTC
null
1,024,794
null
1,024,794
null
1
50
mongodb
63,278
<p>The problem occured because <code>--replSet</code> was enabled in configuration. But the node wasn't yet in any replica set. </p> <p>After I removed <code>--replSet</code> from configuration, relaunched mongodb server, <code>mongorestore</code> started to work without any <code>--host</code> parameter.</p>
35,991,046
How to get value from a specific cell from XLSX file using java Apache POI library
<p>I am writing a Java program to read data from excel sheet (having XLSX extension) using Apache POI library. I am able to iterate through all the cells and get all the values. But I am unable to get a specific cell value, say E10. Is there any way to do this?</p> <p>Please see the code below that I used for iterating through the cells.</p> <pre><code>package application; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadFromXLSX { public static void readXLSXFile() throws IOException { InputStream ExcelFileToRead = new FileInputStream(&quot;C:\\Test.xlsx&quot;); XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFWorkbook test = new XSSFWorkbook(); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { row=(XSSFRow) rows.next(); Iterator cells = row.cellIterator(); while (cells.hasNext()) { cell=(XSSFCell) cells.next(); if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { System.out.print(cell.getStringCellValue()+&quot; &quot;); } else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { System.out.print(cell.getNumericCellValue()+&quot; &quot;); } else { } } System.out.println(); } } } </code></pre>
35,991,228
5
0
null
2016-03-14 15:03:23.117 UTC
5
2021-01-28 06:47:15.067 UTC
2021-01-28 06:47:15.067 UTC
null
5,297,266
null
5,297,266
null
1
11
java|excel
86,324
<p>For example, to get E10 of the first worksheet:</p> <pre><code>wb.getSheetAt(0).getRow(9).getCell(4); </code></pre> <p>Note: subtract one because the indices are null-based.</p> <p>You can also use this convenience method to map E to 4.</p> <pre><code>wb.getSheetAt(0).getRow(9).getCell(CellReference.convertColStringToIndex("E")); </code></pre>
34,740,652
Postgres: ERROR: operator does not exist: character varying = bigint
<p>My query is something like this. I try to get a status for a list of ids.</p> <pre><code>select order_number, order_status_name from data.order_fact s join data.order_status_dim l on s.order_status_key = l.order_status_key where order_number in (1512011196169,1512011760019,1512011898493,1512011972111) </code></pre> <p>I get an error though that says:</p> <pre><code>ERROR: operator does not exist: character varying = bigint LINE 6: order_number in (1512011196169,1512011760019,1512011898493,1... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. </code></pre> <p>Do you have any clue on how I should reform the ids to get it work? Thanks a lot!</p>
34,740,676
2
0
null
2016-01-12 10:06:19.123 UTC
1
2020-06-06 01:05:53.007 UTC
null
null
null
null
5,753,417
null
1
22
postgresql
95,491
<p>Your <code>order_number</code> is a varchar, you can't compare that to a number (<code>123</code> is a number in SQL, <code>'123'</code> is a string constant)</p> <p>You need to use string literals:</p> <pre><code>order_number in ('1512011196169','1512011760019','1512011898493','1512011972111') </code></pre> <p>More details in the manual:<br> <a href="http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS" rel="noreferrer">http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS</a></p>
54,774,143
How to set a radio button checked by default in Flutter?
<p>By default Flutter shows all the radio buttons empty (unchecked).</p> <p>How to set a radio button checked by default?</p> <p>I'm posting this question to document my solution, that may help some one, and also start a topic about this, because I didn't find anything about it here.</p> <p>Below the radio button code:</p> <pre><code>class _ProductTypeScreen extends State&lt;ProductType&gt; { String _radioValue; //Initial definition of radio button value String choice; void radioButtonChanges(String value) { setState(() { _radioValue = value; switch (value) { case 'one': choice = value; break; case 'two': choice = value; break; case 'three': choice = value; break; default: choice = null; } debugPrint(choice); //Debug the choice in console }); } // Now in the BuildContext... body widget: @override Widget build(BuildContext context) { //First of the three radio buttons Row( children: &lt;Widget&gt;[ Radio( value: 'one', groupValue: _radioValue, onChanged: radioButtonChanges, ), Text( "One selected", ), ], ), </code></pre>
54,776,829
4
0
null
2019-02-19 20:06:40.383 UTC
4
2022-07-28 20:13:20.183 UTC
2019-02-20 08:38:29.293 UTC
null
4,156,841
null
6,036,169
null
1
11
flutter|radio-button|flutter-layout
44,672
<p>add an initial state</p> <pre><code>class _ProductTypeScreen extends State&lt;ProductType&gt; { String _radioValue; //Initial definition of radio button value String choice; // ------ [add the next block] ------ @override void initState() { setState(() { _radioValue = "one"; }); super.initState(); } // ------ end: [add the next block] ------ void radioButtonChanges(String value) { setState(() { _radioValue = value; switch (value) { case 'one': choice = value; break; case 'two': choice = value; break; case 'three': choice = value; break; default: choice = null; } debugPrint(choice); //Debug the choice in console }); } @override Widget build(BuildContext context) { </code></pre>
29,074,820
How do I change the font size of ticks of matplotlib.pyplot.colorbar.ColorbarBase?
<p>I would like to know how to change the font size of ticks of <code>ColorbarBase</code> of <code>matplotlib</code>. The following lines are a relevant part in my analysis script, in which <code>ColorbarBase</code> is used.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import matplotlib as mpl axcb = fig.add_axes([0.9, 0.135, 0.02, 0.73]) cb = mpl.colorbar.ColorbarBase(axcb, norm=LogNorm(vmin=7e-5, vmax=1), cmap=plt.cm.CMRmap) cb.set_label("Relative Photon Intensity", labelpad=-1, size=14) </code></pre> <p>I am using <code>matplotlib</code> ver 1.4.3 with Python 2.7 on OS X.</p>
29,074,915
2
0
null
2015-03-16 10:42:21.83 UTC
2
2020-12-21 03:09:04.9 UTC
null
null
null
null
1,600,278
null
1
30
matplotlib
54,106
<p>You can change the tick size using:</p> <pre><code>font_size = 14 # Adjust as appropriate. cb.ax.tick_params(labelsize=font_size) </code></pre> <p>See the <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params">docs</a> for <code>ax.tick_params</code> here for more parameters that can be modified.</p>
44,917,675
How to delete column name
<p>I want to delete to just column name (x,y,z), and use only data.</p> <pre><code>In [68]: df Out[68]: x y z 0 1 0 1 1 2 0 0 2 2 1 1 3 2 0 1 4 2 1 0 </code></pre> <p>I want to print result to same as below.</p> <pre><code>Out[68]: 0 1 0 1 1 2 0 0 2 2 1 1 3 2 0 1 4 2 1 0 </code></pre> <p>Is it possible? How can I do this?</p>
44,917,686
5
0
null
2017-07-05 05:31:04.01 UTC
1
2021-10-05 08:30:31.413 UTC
2021-10-05 08:30:31.413 UTC
null
466,862
null
5,972,973
null
1
25
python|pandas
103,196
<p>In pandas by default need column names.</p> <p>But if really want <code>'remove'</code> columns what is strongly not recommended, because get duplicated column names is possible assign empty strings:</p> <pre><code>df.columns = [''] * len(df.columns) </code></pre> <hr> <p>But if need write <code>df</code> to file without columns and index add parameter <code>header=False</code> and <code>index=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="noreferrer"><code>to_csv</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="noreferrer"><code>to_excel</code></a>.</p> <pre><code>df.to_csv('file.csv', header=False, index=False) df.to_excel('file.xlsx', header=False, index=False) </code></pre>
32,042,938
Elegant mapping from POJOs to vertx.io's JsonObject?
<p>I am currently working on a <a href="http://vertx.io">vertx.io</a> application and wanted to use the provide mongo api for data storage. I currently have a rather clunky abstraction on top of the stock JsonObject classes where all <code>get</code> and <code>set</code> methods are replaced with things like:</p> <pre><code>this.backingObject.get(KEY_FOR_THIS_PROPERTY); </code></pre> <p>This is all well and good for now, but it won't scale particularly well. it also seems dirty, specifically when using nested arrays or objects. For example, if I want to be able to fill fields only when actual data is known, I have to check if the array exists, and if it doesn't create it and store it in the object. Then I can add an element to the list. For example:</p> <pre><code>if (this.backingObject.getJsonArray(KEY_LIST) == null) { this.backingObject.put(KEY_LIST, new JsonArray()); } this.backingObject.getJsonArray(KEY_LIST).add(p.getBackingObject()); </code></pre> <p>I have thought about potential solutions but don't particularly like any of them. Namely, I <em>could</em> use Gson or some similar library with annotation support to handle loading the object for the purposes of manipulating the data in my code, and then using the serialize and unserialize function of both Gson and Vertx to convert between the formats <code>(vertx to load data -&gt; json string -&gt; gson to parse json into pojos -&gt; make changes -&gt; serialize to json string -&gt; parse with vertx and save)</code> but that's a really gross and inefficient workflow. I could also probably come up with some sort of abstract wrapper that extends/implements the vertx json library but passes all the functionality through to gson, but that also seems like a lot of work.</p> <p>Is there any good way to achieve more friendly and maintainable serialization using vertx?</p>
42,003,953
6
0
null
2015-08-17 04:44:55.603 UTC
4
2019-11-29 17:57:14.09 UTC
null
null
null
null
385,033
null
1
28
java|json|vert.x
32,337
<p>I just submitted a patch to Vert.x that defines two new convenience functions for converting between JsonObject and Java object instances without the inefficiency of going through an intermediate JSON string representation. This will be in version 3.4.</p> <pre><code>// Create a JsonObject from the fields of a Java object. // Faster than calling `new JsonObject(Json.encode(obj))`. public static JsonObject mapFrom(Object obj) // Instantiate a Java object from a JsonObject. // Faster than calling `Json.decodeValue(Json.encode(jsonObject), type)`. public &lt;T&gt; T mapTo(Class&lt;T&gt; type) </code></pre> <p>Internally this uses <code>ObjectMapper#convertValue(...)</code>, see Tim Putnam's answer for caveats of this approach. The code is <a href="https://github.com/eclipse/vert.x/blob/ca84f6cae7e789c833c61be8f2698cbfe29d1b58/src/main/java/io/vertx/core/json/JsonObject.java#L82" rel="noreferrer">here</a>.</p>
44,392,027
webRTC convert webm to mp4 with ffmpeg.js
<p>I am trying to convert webM files to mp4 with ffmpeg.js. I am recording a video from canvas(overlayer with some information) and recording the audio data from the video.</p> <pre><code>stream = new MediaStream(); var videoElem = document.getElementById('video'); var videoStream = videoElem.captureStream(); stream.addTrack(videoStream.getAudioTracks()[0]); stream.addTrack(canvas.captureStream().getVideoTracks()[0]); var options = {mimeType: 'video/webm'}; recordedBlobs = []; mediaRecorder = new MediaRecorder(stream, options); mediaRecorder.onstop = handleStop; mediaRecorder.ondataavailable = handleDataAvailable; mediaRecorder.start(100); // collect 100ms of data function handleDataAvailable(event) { if (event.data &amp;&amp; event.data.size &gt; 0) { recordedBlobs.push(event.data); } } mediaRecorder.stop(); </code></pre> <p>This code works as expected and returns a webm video</p> <pre><code>var blob = new Blob(recordedBlobs, {type: 'video/webm'}); </code></pre> <p>Now I want a mp4 file and checked the <a href="https://github.com/muaz-khan/WebRTC-Experiment/tree/master/ffmpeg" rel="noreferrer">ffmpeg.js</a> from muaz-khan. The examples just show how to convert to mp4 when you have 2 single streams (audio and video). But I have one stream with an additional audio track. Can I convert such a stream to mp4? How can that be done?</p>
44,398,123
1
0
null
2017-06-06 13:56:25.53 UTC
12
2022-06-30 02:51:54.973 UTC
null
null
null
null
4,869,573
null
1
13
ffmpeg|webrtc|mp4|mediarecorder|mediastream
23,072
<p>As per the provided code sample, your recorder stream is having only one audio &amp; one video tracks. </p> <p>If your input file is having both Audio &amp; Video, then you need to specify output codec for both tracks <a href="https://github.com/muaz-khan/WebRTC-Experiment/blob/master/ffmpeg/webm-to-mp4.html#L206" rel="noreferrer">here</a> as following.</p> <pre><code>worker.postMessage({ type: 'command', arguments: [ '-i', 'audiovideo.webm', '-c:v', 'mpeg4', '-c:a', 'aac', // or vorbis '-b:v', '6400k', // video bitrate '-b:a', '4800k', // audio bitrate '-strict', 'experimental', 'audiovideo.mp4' ], files: [ { data: new Uint8Array(fileReaderData), name: 'audiovideo.webm' } ] }); </code></pre> <blockquote> <p>Trans-coding the video inside browser is not recommend, as it will consume more CPU Time &amp; Memory. And ffmpeg_asm.js is heavy. May be ok for POC :)</p> </blockquote> <p>What is your use case? webm(vp8/vp9) is widely using these days. </p> <p>Chrome will support following mime types: </p> <pre><code>"video/webm" "video/webm;codecs=vp8" "video/webm;codecs=vp9" "video/webm;codecs=h264" "video/x-matroska;codecs=avc1" </code></pre> <p>So you can get mp4 recording directly from chrome MediaRecorder with following hack</p> <pre><code>var options = {mimeType: 'video/webm;codecs=h264'}; mediaRecorder = new MediaRecorder(stream, options); ..... //Before merging blobs change output mime var blob = new Blob(recordedBlobs, {type: 'video/mp4'}); // And name your file as video.mp4 </code></pre>
65,844,419
Vue Composition API: Defining emits
<p>When <a href="https://v3.vuejs.org/guide/component-custom-events.html#defining-custom-events" rel="noreferrer">defining custom events</a> Vue encourages us to define emitted events on the component via the <code>emits</code> option:</p> <pre><code>app.component('custom-form', { emits: ['inFocus', 'submit'] }) </code></pre> <p>Using Vue 3's composition API, when a standalone composition function emits custom events, is it possible to define these in the composition function?</p>
65,844,650
4
0
null
2021-01-22 11:36:54.137 UTC
10
2022-05-26 15:21:54.897 UTC
2022-03-13 09:08:39.257 UTC
null
8,172,857
null
119,750
null
1
37
vue.js|vuejs3|vue-composition-api|vue-script-setup
56,671
<p>No, because composition functions are used inside the <code>setup</code> hook which doesn't have access to the other options like <code>methods</code> and <code>emits</code>:</p> <pre class="lang-js prettyprint-override"><code>export default defineComponent({ name: &quot;layout&quot;, emits: ['showsidebar'], setup(props, { emit }) { const showSidebar = ref(true); const { breakpoints } = useBreakpoint(); watch(breakpoints, (val) =&gt; { showSidebar.value = !(val.is === &quot;xs&quot; || val.is === &quot;sm&quot;); emit('showsidebar',showSidebar.value); }); return { showSidebar, }; }, data() { // ... }, }); </code></pre> <p>In the example, <code>useBreakpoint</code> offers only some logic that the component could use. If there was a way to define the <code>emits</code> option in the composition function, then the function would always emit the event, even if the function is only used inside the component that defines the handler of the emitted event.</p> <p>with the new script setup syntax you could do it as follows:</p> <pre class="lang-html prettyprint-override"><code>&lt;script setup&gt; import { defineEmits,watch,ref } from 'vue' const emit = defineEmits(['showsidebar']) const showSidebar = ref(true); const { breakpoints } = useBreakpoint(); watch(breakpoints, (val) =&gt; { showSidebar.value = !(val.is === &quot;xs&quot; || val.is === &quot;sm&quot;); emit('showsidebar',showSidebar.value); }); &lt;/script&gt; </code></pre>
50,962,628
Is it possible to trigger a Redux action from outside a component?
<p>I'm building a React app and am calling a custom handler library to make calls to our REST API.</p> <p>Within these (non-React) functions, I'd like to trigger Redux actions to update the store with the endpoint response, but can't figure out how to trigger the Redux action without the usual 'mapDispatchToProps'/connect() method.</p> <p>Is this possible?</p> <p>Thanks</p>
50,962,763
2
0
null
2018-06-21 07:20:36.347 UTC
3
2020-08-01 16:20:46.1 UTC
null
null
null
null
9,927,889
null
1
46
reactjs|redux|react-redux
34,684
<p>In order to dispatch and action from outside of the scope of <a href="https://reactjs.org/docs/react-component.html" rel="noreferrer"><code>React.Component</code></a> you need to get the store instance and call <a href="https://redux.js.org/api-reference/store#dispatch-action" rel="noreferrer"><code>dispatch</code></a> on it like</p> <pre><code>import { store } from '/path/to/createdStore'; ​ function testAction(text) { return { type: 'TEST_ACTION', text } } ​ store.dispatch(testAction('StackOverflow')); </code></pre>
31,671,846
converting array of string to json object in C#
<p>I have got following scenario where i have a array of strings and i need to pass this data as json object. How can I convert array of string to json object using DataContractJsonSerializer.</p> <p>code is :</p> <pre><code>string[] request = new String[2]; string[1] = "Name"; string[2] = "Occupaonti"; </code></pre>
31,672,247
2
1
null
2015-07-28 09:05:11.177 UTC
2
2015-07-28 09:24:31.093 UTC
null
null
null
null
5,109,612
null
1
18
c#|json
78,151
<p>I would recommend using the Newtonsoft.Json NuGet package, as it makes handling JSON trivial. You could do the following:</p> <pre><code>var request = new String[2]; request[0] = "Name"; request[1] = "Occupaonti"; var json = JsonConvert.SerializeObject(request); </code></pre> <p>Which would produce:</p> <pre><code>["Name","Occupaonti"] </code></pre> <p>Notice that in your post you originally were trying to index into the string type, and also would have received an IndexOutOfBounds exception since indexing is zero-based. I assume you will need values assigned to the Name and Occupancy, so I would change this slightly:</p> <pre><code>var name = "Pooja Kuntal"; var occupancy = "Software Engineer"; var person = new { Name = name, Occupancy = occupancy }; var json = JsonConvert.SerializeObject(person); </code></pre> <p>Which would produce:</p> <pre><code>{ "Name": "Pooja Kuntal", "Occupancy": "Software Engineer" } </code></pre>
41,875,679
Get the days, hours and minutes in Moment.js
<p>So This is my first time using Moment.js and I encountered the following problem, so I have this following dates:</p> <pre><code>now: 2017-01-26T14:21:22+0000 expiration: 2017-01-29T17:24:22+0000 </code></pre> <p>What I want to get is:</p> <pre><code>Day: 3 Hours: 3 Mins: 3 </code></pre> <p>I tried the following code:</p> <pre><code>const now = moment(); const exp = moment(expire_date); console.log(expire_date); days = exp.diff(now, 'days'); hours = exp.diff(now, 'hours') - (days * 24); minutes = exp.diff(now, 'minutes') - ((days * 1440) + (hours * 24) * 60); </code></pre> <p>I know I did something wrong (maybe my calculation or I used the wrong method), but I can't figure out what it is. </p>
41,876,250
4
0
null
2017-01-26 14:26:24.043 UTC
3
2018-04-18 10:33:45.953 UTC
2017-01-27 10:36:47.89 UTC
null
6,563,812
null
2,784,493
null
1
36
javascript|momentjs
55,837
<p>MomentJS can calculate all that for you without you doing any logic.</p> <ul> <li>First find the difference between the two moments</li> <li>Express it as a Duration</li> <li>Then display whichever component <code>.days()</code>, <code>.hours()</code> of the duration that you want.</li> </ul> <p>Note: You can also express the entire duration <code>.asDays()</code>, <code>.asHours()</code> etc if you want.</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-js lang-js prettyprint-override"><code>const now = moment("2017-01-26T14:21:22+0000"); const expiration = moment("2017-01-29T17:24:22+0000"); // get the difference between the moments const diff = expiration.diff(now); //express as a duration const diffDuration = moment.duration(diff); // display console.log("Days:", diffDuration.days()); console.log("Hours:", diffDuration.hours()); console.log("Minutes:", diffDuration.minutes());</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://momentjs.com/downloads/moment.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
42,095,625
What does the function control_dependencies do?
<p>I would like to have an example illustrating the use of the function <a href="https://www.tensorflow.org/api_docs/python/tf/control_dependencies" rel="noreferrer"><code>tf.control_dependencies</code></a>. For example, I want to create two tensors <code>X</code> and <code>Y</code> and if they are equal do or print something. </p> <pre><code>import tensorflow as tf session = tf.Session() X = tf.constant(5) Y = tf.constant(50) with tf.control_dependencies([tf.assert_equal(X, Y)]): print('X and Y are equal!') </code></pre> <p>In the code above, <code>X</code> is clearly not equal to <code>Y</code>. What is <code>tf.control_dependencies</code> doing in this case?</p>
42,095,969
1
0
null
2017-02-07 16:56:35.97 UTC
8
2018-07-08 14:15:52.383 UTC
2018-07-08 14:15:52.383 UTC
null
3,924,118
null
5,540,159
null
1
27
python|tensorflow
18,047
<p><code>control_dependencies</code> is not a conditional. It is a mechanism to add dependencies to whatever ops you create in the <code>with</code> block. More specifically, what you specify in the argument to <code>control_dependencies</code> is ensured to be evaluated before anything you define in the <code>with</code> block. </p> <p>In your example, you don't add any (TensorFlow) operations in the <code>with</code> block, so the block does nothing.</p> <p><a href="https://stackoverflow.com/a/33950177/524436">This answer</a> has an example of how to use <code>control_dependencies</code>, where it is used to make sure the assignments happen before the batchnorm operations are evaluated.</p>
51,450,462
pyspark addPyFile to add zip of .py files, but module still not found
<p>Using <code>addPyFiles()</code> seems to not be adding desiered files to spark job nodes (new to spark so may be missing some basic usage knowledge here).</p> <p>Attempting to run a script using pyspark and was seeing errors that certain modules are not found for import. Never used spark before, but other posts (from package in question <a href="https://github.com/cerndb/dist-keras/issues/36#issuecomment-378918484" rel="noreferrer">https://github.com/cerndb/dist-keras/issues/36#issuecomment-378918484</a> and <a href="https://stackoverflow.com/a/39779271/8236733">https://stackoverflow.com/a/39779271/8236733</a>) recommended zipping the module and adding to the spark job via <code>sparkContext.addPyFiles(mymodulefiles.zip)</code>, yet still getting error. The relevant code snippets being...</p> <pre class="lang-or-tag-here prettyprint-override"><code>from distkeras.trainers import * from distkeras.predictors import * from distkeras.transformers import * from distkeras.evaluators import * from distkeras.utils import * </code></pre> <p>(where the package I'm importing here cann be found at <a href="https://github.com/cerndb/dist-keras" rel="noreferrer">https://github.com/cerndb/dist-keras</a>),</p> <pre class="lang-or-tag-here prettyprint-override"><code>conf = SparkConf() conf.set("spark.app.name", application_name) conf.set("spark.master", master) #master='yarn-client' conf.set("spark.executor.cores", `num_cores`) conf.set("spark.executor.instances", `num_executors`) conf.set("spark.locality.wait", "0") conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); if using_spark_2: from pyspark.sql import SparkSession sc = SparkSession.builder.config(conf=conf) \ .appName(application_name) \ .getOrCreate() sc.sparkContext.addPyFile("/home/me/Downloads/distkeras.zip") # see https://github.com/cerndb/dist-keras/issues/36#issuecomment-378918484 and https://forums.databricks.com/answers/10207/view.html print sc.version </code></pre> <p>(distkeras.zip being a zipped file of this dir.: <a href="https://github.com/cerndb/dist-keras/tree/master/distkeras" rel="noreferrer">https://github.com/cerndb/dist-keras/tree/master/distkeras</a>), and</p> <pre class="lang-or-tag-here prettyprint-override"><code>transformer = OneHotTransformer(output_dim=nb_classes, input_col="label_index", output_col="label") dataset = transformer.transform(dataset) """throwing error... ..... File "/opt/mapr/spark/spark-2.1.0/python/pyspark/serializers.py", line 458, in loads return pickle.loads(obj) ImportError: No module named distkeras.utils at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193) ..... """ </code></pre> <p>From the docs and examples I could find (<a href="http://spark.apache.org/docs/2.1.0/api/python/pyspark.html#pyspark.SparkContext.addPyFile" rel="noreferrer">http://spark.apache.org/docs/2.1.0/api/python/pyspark.html#pyspark.SparkContext.addPyFile</a> and <a href="https://forums.databricks.com/questions/10193/the-proper-way-to-add-in-dependency-py-files.html" rel="noreferrer">https://forums.databricks.com/questions/10193/the-proper-way-to-add-in-dependency-py-files.html</a>), the code above seems like it should work to me (again, never used spark before). Anyone have any idea what I'm doing wrong here? Any more info that could be posted that would be useful for debugging? </p>
51,508,990
2
0
null
2018-07-20 21:15:32.097 UTC
9
2020-03-27 15:41:52.703 UTC
2018-07-24 23:37:55.487 UTC
null
8,236,733
null
8,236,733
null
1
24
apache-spark|pyspark
32,772
<p>Fixed problem. Admittedly, solution is not totally spark-related, but leaving question posted for the sake of others who may have similar problem, since the given error message did not make my mistake totally clear from the start.</p> <p><strong>TLDR</strong>: Make sure the package contents (so they should include an __init.py__ in each dir.) of the zip file being loaded in are structured and named the way your code expects.</p> <hr> <p>The package I was trying to load into the spark context via zip was of the form</p> <pre><code>mypkg file1.py file2.py subpkg1 file11.py subpkg2 file21.py </code></pre> <p>my zip when running <code>less mypkg.zip</code>, showed</p> <p><code>file1.py file2.py subpkg1 subpkg2</code></p> <p>So two things were wrong here.</p> <ol> <li>Was not zipping the toplevel dir. that was the main package that the coded was expecting to work with</li> <li>Was not zipping the lower level dirs.</li> </ol> <p>Solved with <code>zip -r mypkg.zip mypkg</code></p> <p>More specifically, had to make 2 zip files</p> <ol> <li><p>for the dist-keras package: </p> <p><code>cd dist-keras; zip -r distkeras.zip distkeras</code></p></li> </ol> <p>see <a href="https://github.com/cerndb/dist-keras/tree/master/distkeras" rel="noreferrer">https://github.com/cerndb/dist-keras/tree/master/distkeras</a></p> <ol start="2"> <li><p>for the keras package used by distkeras (which is not installed across the cluster): </p> <p><code>cd keras; zip -r keras.zip keras</code></p></li> </ol> <p>see <a href="https://github.com/keras-team/keras/tree/master/keras" rel="noreferrer">https://github.com/keras-team/keras/tree/master/keras</a></p> <p>So declaring the spark session looked like</p> <pre class="lang-py prettyprint-override"><code>conf = SparkConf() conf.set("spark.app.name", application_name) conf.set("spark.master", master) #master='yarn-client' conf.set("spark.executor.cores", `num_cores`) conf.set("spark.executor.instances", `num_executors`) conf.set("spark.locality.wait", "0") conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); # Check if the user is running Spark 2.0 + if using_spark_2: from pyspark.sql import SparkSession sc = SparkSession.builder.config(conf=conf) \ .appName(application_name) \ .getOrCreate() sc.sparkContext.addPyFile("/home/me/projects/keras-projects/exploring-keras/keras-dist_test/dist-keras/distkeras.zip") sc.sparkContext.addPyFile("/home/me/projects/keras-projects/exploring-keras/keras-dist_test/keras/keras.zip") print sc.version </code></pre>
56,473,539
Retrofit 2.6.0 exception: java.lang.IllegalArgumentException: Unable to create call adapter for kotlinx.coroutines.Deferred
<p>I have a project with Kotlin coroutines and Retrofit.</p> <p>I had these dependencies:</p> <pre><code>implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2' </code></pre> <p>Today I have updated <strong>Retrofit</strong> to <strong>2.6.0</strong> in the project. In <a href="https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter" rel="noreferrer">https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter</a> it is written that it is deprecated now. In <a href="https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05" rel="noreferrer">https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05</a> it is written that Retrofit currently supports <code>suspend</code>.</p> <p>So, I removed <code>retrofit2-kotlin-coroutines-adapter:0.9.2</code> and in Retrofit client changed these lines:</p> <pre><code> retrofit = Retrofit.Builder() .baseUrl(SERVER_URL) .client(okHttpClient) .addConverterFactory(MyGsonFactory.create(gson)) //.addCallAdapterFactory(CoroutineCallAdapterFactory()) - removed it. .build() </code></pre> <p>When run, the first request catches an exception:</p> <pre><code>java.lang.IllegalArgumentException: Unable to create call adapter for kotlinx.coroutines.Deferred&lt;com.package.model.response.UserInfoResponse&gt; for method Api.getUserInfo </code></pre> <p>As I understood, instead of <code>CoroutineCallAdapterFactory()</code> I could use <code>CallAdapter.Factory()</code>, but it is abstract.</p> <p>If in Api class I change a request adding <code>suspend</code> in the beginning:</p> <pre><code>@FormUrlEncoded @POST("user/info/") suspend fun getUserInfo(@Field("token") token: String): Deferred&lt;UserInfoResponse&gt; override suspend fun getUserInfo(token: String): Deferred&lt;UserInfoResponse&gt; = service.getUserInfo(token) </code></pre> <p>I get this exception:</p> <pre><code>java.lang.RuntimeException: Unable to invoke no-args constructor for kotlinx.coroutines.Deferred&lt;com.package.model.response.UserInfoResponse&gt;. Registering an InstanceCreator with Gson for this type may fix this problem. </code></pre>
56,473,934
2
0
null
2019-06-06 08:21:16.627 UTC
1
2021-09-07 02:45:30.057 UTC
2019-10-02 09:14:03.743 UTC
null
2,914,140
null
2,914,140
null
1
30
android|retrofit2|kotlin-coroutines
12,557
<p>Reading <a href="https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05" rel="noreferrer">https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05</a> I saw:</p> <blockquote> <p>New: Support suspend modifier on functions for Kotlin! This allows you to express the asynchrony of HTTP requests in an idiomatic fashion for the language.</p> <p>@GET("users/{id}") suspend fun user(@Path("id") long id): User</p> <p>Behind the scenes this behaves as if defined as fun user(...): Call and then invoked with Call.enqueue. You can also return Response for access to the response metadata.</p> <p>Currently this integration only supports non-null response body types. Follow issue 3075 for nullable type support.</p> </blockquote> <p>I changed requests so: added <code>suspend</code> and removed <code>Deferred</code>:</p> <pre><code>@FormUrlEncoded @POST("user/info/") suspend fun getUserInfo(@Field("token") token: String): UserInfoResponse override suspend fun getUserInfo(token: String): UserInfoResponse = service.getUserInfo(token) </code></pre> <p>Then in interactor (or simply when called the method <code>getUserInfo(token)</code>) removed <code>await()</code>:</p> <pre><code>override suspend fun getUserInfo(token: String): UserInfoResponse = // api.getUserInfo(token).await() - was before. api.getUserInfo(token) </code></pre> <p>UPDATE</p> <p>Once I encountered a situation when downloading PDF files required removing <code>suspend</code> in Api class. See <a href="https://stackoverflow.com/questions/56974908/how-to-download-pdf-file-with-retrofit-and-kotlin-coroutines">How to download PDF file with Retrofit and Kotlin coroutines?</a>.</p>
23,535,289
Bootstrap 3 - disable navbar collapse
<p>This is my simple navbar:</p> <pre><code>&lt;div class="navbar navbar-fixed-top myfont" role="navigation"&gt; &lt;div class=""&gt; &lt;ul class="nav navbar-nav navbar-left"&gt; &lt;li&gt; &lt;a class="navbar-brand" href="#"&gt; &lt;img src="assets/img/logo.png"/&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;button class="btn btn-navbar"&gt; &lt;i class="fa fa-edit"&gt;&lt;/i&gt; Create &lt;/button&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li data-match-route="/"&gt;&lt;a href="#/page-one"&gt;Login&lt;/a&gt;&lt;/li&gt; &lt;li data-match-route="/"&gt;&lt;a href="#/page-two/sub-a"&gt;Signup&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I just would like to prevent this to collapse, cause I don't need it, how to do?</p> <p>I would like to avoid writing 300K lines of CSS for overriding the default styles.</p> <p>Any suggestion?</p>
23,536,146
6
0
null
2014-05-08 07:22:28.033 UTC
24
2019-07-06 18:53:45.477 UTC
2015-04-27 12:54:55.963 UTC
null
196,688
null
895,174
null
1
92
css|twitter-bootstrap-3|navbar|collapse|preventdefault
137,846
<p>After close examining, not 300k lines but there are around 3-4 CSS properties that you need to override:</p> <pre class="lang-css prettyprint-override"><code>.navbar-collapse.collapse { display: block!important; } .navbar-nav&gt;li, .navbar-nav { float: left !important; } .navbar-nav.navbar-right:last-child { margin-right: -15px !important; } .navbar-right { float: right!important; } </code></pre> <p>And with this your menu won't collapse.</p> <p><strong><a href="http://www.responsinator.com/?url=http%3A%2F%2Fjsfiddle.net%2Ft4ym3%2Fembedded%2Fresult%2F">DEMO</a></strong> (<em><a href="http://jsfiddle.net/t4ym3/">jsfiddle</a></em>)</p> <p><strong>EXPLANATION</strong></p> <p>The four CSS properties do the respective:</p> <ol> <li><p>The default <code>.collapse</code> property in bootstrap hides the right-side of the menu for tablets(landscape) and phones and instead a toggle button is displayed to hide/show it. Thus this property overrides the default and persistently shows those elements.</p></li> <li><p>For the right-side menu to appear on the same line along with the left-side, we need the left-side to be floating left.</p></li> <li><p>This property is present by default in bootstrap but not on tablet(portrait) to phone resolution. You can skip this one, it's likely to not affect your overall navbar.</p></li> <li><p>This keeps the right-side menu to the right while the inner elements (<code>li</code>) will follow the property 2. So we have left-side <em>float left</em> and right-side <em>float right</em> which brings them into one line.</p></li> </ol>
1,180,076
Implicit user creation with Authlogic and Authlogic OAuth plugin
<p>I'm trying to write a simple OAuth consumer app in Rails. I'm using Authlogic for handling authentication and the Authlogic OAuth plugin to do the oauth thing.</p> <p>The oauth plugin provides a couple of helpers to render the sign in button: oauth_login_button and oauth_register_button. Together with the Authlogic logics and the plugin's request filters these two buttons somehow create the session/user. </p> <p>What happens next is as follows: - if I use the oauth_login_button helper, then the session object fails to save as there's no such user locally. - if I use the oauth_register_button helper, then, on any login after the first one, Rails complains that the token has been taken already... that means it can't create the second copy for the same user, which is right.</p> <p>The issue is: I don't want to have BOTH Register AND Login buttons on my site.</p> <p>On the user side, what I want to achieve is a single button on the start page, saying smth. like "Sign In with Twitter", which the user must click to proceed to inner pages of the site.</p> <p>On the server side, I want to implicitly create the local user account, if the user is a first time visitor to my site.</p> <p>Any hints on how to do this?</p> <p>All the samples on Authlogic+OAuth I was able to find don't seem to care about having only a single button for sign in. :(</p>
1,180,675
1
0
null
2009-07-24 20:45:40.72 UTC
25
2015-02-28 16:23:37.73 UTC
2015-02-28 16:23:37.73 UTC
null
355,357
null
355,357
null
1
17
ruby-on-rails|ruby|oauth|authlogic
3,318
<p>Seems like I'm going to answer the question myself.</p> <p>I use the following code to generate the Sign In button (in HAML):</p> <pre><code>- form_tag({:controller =&gt; "users", :action =&gt; "create"}, {:method =&gt; "post"}) do = oauth_register_button :value =&gt; "Sign In with Twitter" </code></pre> <p>and then I simply create the user's session object in the create method of the UsersController class, if the user already exists:</p> <pre><code>def create @user = User.new(params[:user]) @user.save do |result| # LINE A if result flash[:notice] = "Account registered!" redirect_to some_inner_path else unless @user.oauth_token.nil? @user = User.find_by_oauth_token(@user.oauth_token) unless @user.nil? UserSession.create(@user) flash.now[:message] = "Welcome back!" redirect_to some_inner_path else redirect_back_or_default root_path end else redirect_back_or_default root_path end end end end </code></pre> <p>If the user is a first time visitor, then the user object is successfully saved in the LINE A. And if it's not and there's an oauth token available, then we try to fetch the user from the DB and log him/her in.</p>
2,369,913
jQuery: selecting grandparents
<p>Is there a better way to select grandparent elements in jQuery in order to avoid this ?</p> <pre><code>$(this).parent().parent().parent().parent().parent().children(".title, .meta").fadeIn("fast"); </code></pre> <p>Thanks.</p>
2,369,931
6
2
null
2010-03-03 09:12:00.77 UTC
8
2022-02-27 09:36:40.373 UTC
2013-02-23 11:06:29.667 UTC
null
20,578
null
257,022
null
1
55
jquery|jquery-selectors
75,631
<p>You can use the <code>parents()</code> method which matches parents against a selector</p> <p><a href="http://api.jquery.com/parents/" rel="noreferrer">http://api.jquery.com/parents/</a></p> <p>Or if you're using 1.4 there is a new <code>parentsUntil()</code> method</p> <p><a href="http://api.jquery.com/parentsUntil/" rel="noreferrer">http://api.jquery.com/parentsUntil/</a></p>
2,623,118
Inspect attached event handlers for any DOM element
<p>Is there any way to view what functions / code are attached to any event for a DOM element? Using Firebug or any other tool.</p>
2,623,352
7
2
null
2010-04-12 15:16:33.51 UTC
21
2020-09-06 12:29:46.25 UTC
2010-04-12 15:27:16.983 UTC
null
245,860
null
245,860
null
1
108
javascript|events
69,161
<p>Event handlers attached using traditional <code>element.onclick= handler</code> or HTML <code>&lt;element onclick="handler"&gt;</code> can be retrieved trivially from the <code>element.onclick</code> property from script or in-debugger.</p> <p>Event handlers attached using DOM Level 2 Events <code>addEventListener</code> methods and IE's <code>attachEvent</code> cannot currently be retrieved from script at all. DOM Level 3 once proposed <code>element.eventListenerList</code> to get all listeners, but it is unclear whether this will make it to the final specification. There is no implementation in any browser today.</p> <p>A debugging tool as browser extension <em>could</em> get access to these kinds of listeners, but I'm not aware of any that actually do.</p> <p>Some JS frameworks leave enough of a record of event binding to work out what they've been up to. <a href="http://www.sprymedia.co.uk/article/Visual+Event" rel="noreferrer">Visual Event</a> takes this approach to discover listeners registered through a few popular frameworks.</p>
2,703,984
What is the difference between the add and offer methods in a Queue in Java?
<p>Take the <code>PriorityQueue</code> for example <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)</a></p> <p>Can anyone give me an example of a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Queue.html" rel="noreferrer"><code>Queue</code></a> where the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#add-E-" rel="noreferrer"><code>add</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#offer-E-" rel="noreferrer"><code>offer</code></a> methods are different?</p> <p>According to the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html" rel="noreferrer"><code>Collection</code></a> doc, the <code>add</code> method will often seek to ensure that an element exists within the <code>Collection</code> rather than adding duplicates. So my question is, what is the difference between the <code>add</code> and <code>offer</code> methods?</p> <p>Is it that the <code>offer</code> method will add duplicates regardless? (I doubt that it is because if a <code>Collection</code> should only have distinct elements this would circumvent that).</p> <p>EDIT: In a <code>PriorityQueue</code> the <code>add</code> and <code>offer</code> methods are the same method (see my answer below). Can anyone give me an example of a class where the <code>add</code> and <code>offer</code> methods are different?</p>
2,704,023
9
0
null
2010-04-24 09:46:19.273 UTC
36
2022-04-27 18:09:28.26 UTC
2016-12-13 05:37:43.623 UTC
null
2,421,906
null
282,706
null
1
141
java|queue|add
116,927
<p>I guess the difference is in the contract, that when element can not be added to collection the <code>add</code> method throws an exception and <code>offer</code> doesn't.</p> <p>From: <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#add%28E%29" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#add%28E%29</a></p> <blockquote> <p>If a collection refuses to add a particular element for any reason other than that it already contains the element, it <strong>must throw</strong> an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.</p> </blockquote> <p>From: <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html#offer%28E%29" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html#offer%28E%29</a></p> <blockquote> <p>Inserts the specified element into this queue, if possible. When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), which can fail to insert an element only by throwing an exception.</p> </blockquote>
2,738,734
Get current orientation of iPad?
<p>In a given event handler (not the "shouldAutorotateToInterfaceOrientation" method) how do I detect the current iPad orientation? I have a text field I have to animate up (when keyboard appears) in the Landscape view, but not in the portrait view and want to know which orientation I'm in to see if the animation is necessary.</p>
2,738,815
11
0
null
2010-04-29 15:49:31.86 UTC
23
2013-04-12 20:07:28.317 UTC
2010-05-21 12:11:49.077 UTC
null
21,234
null
36,680
null
1
64
ipad|orientation
50,714
<p>Orientation information isn't very consistent, and there are several approaches. If in a view controller, you can use the <code>interfaceOrientation</code> property. From other places you can call:</p> <pre><code>[[UIDevice currentDevice] orientation] </code></pre> <p>Alternatively, you can request to receive orientation change notifications:</p> <pre><code>[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; </code></pre> <p>Some people also like to check the status bar orientation:</p> <pre><code>[UIApplication sharedApplication].statusBarOrientation </code></pre>
3,099,219
ggplot with 2 y axes on each side and different scales
<p>I need to plot a bar chart showing counts and a line chart showing rate all in one chart, I can do both of them separately, but when I put them together, I scale of the first layer (i.e. the <code>geom_bar</code>) is overlapped by the second layer (i.e. the <code>geom_line</code>).</p> <p>Can I move the axis of the <code>geom_line</code> to the right?</p>
3,117,319
18
3
null
2010-06-23 05:52:19.9 UTC
126
2021-11-09 22:07:00.413 UTC
2019-05-27 19:58:38.6 UTC
null
6,461,462
null
373,908
null
1
310
r|ggplot2|r-faq
471,207
<p>Sometimes a client wants two y scales. Giving them the "flawed" speech is often pointless. But I do like the ggplot2 insistence on doing things the right way. I am sure that ggplot is in fact educating the average user about proper visualization techniques.</p> <p>Maybe you can use faceting and scale free to compare the two data series? - e.g. look here: <a href="https://github.com/hadley/ggplot2/wiki/Align-two-plots-on-a-page" rel="noreferrer">https://github.com/hadley/ggplot2/wiki/Align-two-plots-on-a-page</a> </p>
40,042,711
How to calculate cumulative sum?
<p>I have data containing columns <code>biweek</code> and <code>Total</code>, I want to get cumulative sum on <code>biweek</code> basis. My data is like:</p> <pre><code>biweek Total 0 3060.913 1 4394.163 2 3413.748 3 2917.548 4 3442.055 5 3348.398 6 1771.722 </code></pre> <p>and I want to get output like :</p> <pre><code>biweek Total 0 3060.913 1 7455.076 2 10868.824 3 13786.372 4 17228.427 5 20576.825 6 22348.547 </code></pre> <p>So it there a possible way to achieve it?</p>
40,042,778
1
1
null
2016-10-14 12:01:42.493 UTC
0
2018-01-24 02:42:24.967 UTC
2018-01-24 02:42:24.967 UTC
null
3,962,914
null
6,559,913
null
1
6
r|cumulative-sum
77,093
<pre><code># replace the second column for the cumsum of the initial second column data[, 2] &lt;- cumsum(data[, 2]) </code></pre>
10,443,461
c# Array.FindAllIndexOf which FindAll IndexOf
<p>I know c# has <a href="http://msdn.microsoft.com/en-us/library/1kkxfxdd.aspx"><code>Array.FindAll</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.array.indexof.aspx"><code>Array.IndexOf</code></a>.</p> <p>Is there a <code>Array.FindAllIndexOf</code> which returns <code>int[]</code>?</p>
10,443,540
9
0
null
2012-05-04 06:02:33.637 UTC
6
2020-01-03 14:38:25.65 UTC
2014-05-05 15:51:59.983 UTC
null
505,893
null
939,713
null
1
32
c#|arrays|indexof
33,918
<pre><code>string[] myarr = new string[] {"s", "f", "s"}; int[] v = myarr.Select((b,i) =&gt; b == "s" ? i : -1).Where(i =&gt; i != -1).ToArray(); </code></pre> <p>This will return 0, 2</p> <p>If the value does not exist in the array then it will return a int[0].</p> <p>make an extension method of it</p> <pre><code>public static class EM { public static int[] FindAllIndexof&lt;T&gt;(this IEnumerable&lt;T&gt; values, T val) { return values.Select((b,i) =&gt; object.Equals(b, val) ? i : -1).Where(i =&gt; i != -1).ToArray(); } } </code></pre> <p>and call it like</p> <pre><code>string[] myarr = new string[] {"s", "f", "s"}; int[] v = myarr.FindAllIndexof("s"); </code></pre>
10,568,281
Mongoose - using Populate on an array of ObjectId
<p>I've got a schema that looks a bit like:</p> <pre><code>var conversationSchema = new Schema({ created: { type: Date, default: Date.now }, updated: { type: Date, default: Date.now }, recipients: { type: [Schema.ObjectId], ref: 'User' }, messages: [ conversationMessageSchema ] }); </code></pre> <p>So my recipients collection, is a collection of object id's referencing my user schema / collection.</p> <p>I need to populate these on query, so i'm trying this:</p> <pre><code>Conversation.findOne({ _id: myConversationId}) .populate('user') .run(function(err, conversation){ //do stuff }); </code></pre> <p>But obviously 'user' isn't populating...</p> <p>Is there a way I can do this?</p>
10,591,407
2
0
null
2012-05-12 23:46:32.55 UTC
10
2014-01-27 08:29:01.28 UTC
null
null
null
null
131,809
null
1
42
mongodb|mongoose
45,976
<p>Use the name of the schema path instead of the collection name:</p> <pre><code>Conversation.findOne({ _id: myConversationId}) .populate('recipients') // &lt;== .exec(function(err, conversation){ //do stuff }); </code></pre>
30,978,114
Add a ListView or RecyclerView to new NavigationView
<p>I am using the new <a href="https://developer.android.com/reference/android/support/design/widget/NavigationView.html">NavigationView</a> from revision 22.2.0 of the <a href="https://developer.android.com/tools/support-library/index.html">support library</a> by Google. It works perfectly fine to generate a navigation drawer populated using a menu res.</p> <p>I was wondering is it possible to add a ListView or RecyclerView to the navigation drawer so that it can be populated using my custom adapter code, which allows for far greater flexibility than menu resources.</p> <p>Here is my current XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"&gt; &lt;FrameLayout android:id="@+id/content_view" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;include layout="@layout/main_toolbar" /&gt; &lt;/FrameLayout&gt; &lt;android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/navigation_drawer_header" app:menu="@menu/menu_navigation_drawer" /&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p>Where in my XML would I add the ListView or RecyclerView?</p> <p><strong>EDIT</strong></p> <p>As per Basant's suggestion, I nested a ListView into the NavigationView. You lose the ability to inflate from a menu res (as far as I know) but it succeeds in what I want it to do. The header XML is unchanged, it is just included into XML.</p> <p>New code:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"&gt; &lt;FrameLayout android:id="@+id/content_view" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;include layout="@layout/main_toolbar" /&gt; &lt;/FrameLayout&gt; &lt;android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start"&gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;include android:id="@+id/navigation_drawer_header_include" layout="@layout/navigation_drawer_header" /&gt; &lt;ListView android:id="@+id/navigation_drawer_list" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/navigation_drawer_header_include"/&gt; &lt;/RelativeLayout&gt; &lt;/android.support.design.widget.NavigationView&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre>
30,978,362
4
0
null
2015-06-22 10:52:43.03 UTC
9
2018-12-19 10:48:07.507 UTC
2015-06-22 11:34:01.763 UTC
null
2,897,361
null
2,897,361
null
1
21
android|listview|android-recyclerview|navigationview
28,840
<p>You can just nest the <code>ListView</code> or <code>RecyclerView</code> inside the <code>NavigationView</code>.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"&gt; &lt;FrameLayout android:id="@+id/content_view" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;include layout="@layout/main_toolbar" /&gt; &lt;/FrameLayout&gt; &lt;android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start"/&gt; &lt;ListView android:id="@+id/menuList" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p><strong>NOTE:</strong> Keep in mind that if you use use a ListView inside it, you can't use the NavigationView's header. You will have to use the header view of the ListView that you are adding. Don't forget to remove the <code>app:menu</code> and <code>app:header</code> fields.</p>
19,621,512
How to adjust title position in ggplot2
<p>Here is the code:</p> <pre><code>require(ggplot2) require(grid) # pdf("a.pdf") png('a.png') a &lt;- qplot(date, unemploy, data = economics, geom = "line") + opts(title='A') b &lt;- qplot(uempmed, unemploy, data = economics) + geom_smooth(se = F) + opts(title='B') c &lt;- qplot(uempmed, unemploy, data = economics, geom="path") + opts(title='C') grid.newpage() pushViewport(viewport(layout = grid.layout(2, 2))) vplayout &lt;- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y) print(a, vp = vplayout(1, 1:2)) print(b, vp = vplayout(2, 1)) print(c, vp = vplayout(2, 2)) dev.off() </code></pre> <p>And result:</p> <p><img src="https://i.stack.imgur.com/AYgxe.png" alt="enter image description here"></p> <p>While here is what I would like to have, i.e. to position titles near the top of y-axis:</p> <p><img src="https://i.stack.imgur.com/AmQk1.png" alt="enter image description here"></p>
19,621,638
1
0
null
2013-10-27 18:09:10.68 UTC
4
2013-10-27 18:30:01.453 UTC
null
null
null
null
562,222
null
1
19
r|ggplot2
42,399
<p>What you are looking for is <code>theme(plot.title = element_text(hjust = 0))</code>. For example, using the latest version of ggplot2 and <code>theme</code> instead of <code>opts</code> we have</p> <pre><code>a &lt;- qplot(date, unemploy, data = economics, geom = "line") + ggtitle("A") + theme(plot.title = element_text(hjust = 0)) </code></pre> <p>Alternatively, staying with <code>opts</code></p> <pre><code>a &lt;- qplot(date, unemploy, data = economics, geom = "line") + opts(title = "A", plot.title = element_text(hjust = 0)) </code></pre> <p><img src="https://i.stack.imgur.com/gwZQR.png" alt="enter image description here"></p>
30,079,590
use matplotlib color map for color cycle
<p>If I create colors by e.g:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt n = 6 color = plt.cm.coolwarm(np.linspace(0.1,0.9,n)) color </code></pre> <p>color is a numpy array:</p> <pre><code>array([[ 0.34832334, 0.46571115, 0.88834616, 1. ], [ 0.56518158, 0.69943844, 0.99663507, 1. ], [ 0.77737753, 0.84092121, 0.9461493 , 1. ], [ 0.93577377, 0.8122367 , 0.74715647, 1. ], [ 0.96049006, 0.61627642, 0.4954666 , 1. ], [ 0.83936494, 0.32185622, 0.26492398, 1. ]]) </code></pre> <p>However, If I plug in the RGB values (without the alpha value 1) as tuples in my <code>.mplstyle</code> file (<code>map(tuple,color[:,0:-1])</code>), I get an error similar to this one:</p> <pre><code>in file &quot;/home/moritz/.config/matplotlib/stylelib/ggplot.mplstyle&quot; Key axes.color_cycle: [(0.34832334141176474 does not look like a color arg (val, error_details, msg)) </code></pre> <p>Any ideas why?</p>
30,085,784
3
2
null
2015-05-06 14:24:57.737 UTC
11
2022-08-04 22:02:54.443 UTC
2020-08-04 13:42:06.497 UTC
null
2,749,397
null
3,608,005
null
1
20
python|matplotlib
47,024
<p><strong>Edit 04/2021:</strong> As of matplotlib 2.2.0, the key <code>axes.color_cycle</code> has been deprecated (<a href="https://matplotlib.org/stable/api/prev_api_changes/api_changes_2.2.0.html#id1" rel="nofollow noreferrer">source: API changes</a>). The new method is to use <code>set_prop_cycle</code> (<a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_prop_cycle.html" rel="nofollow noreferrer">source: matplotlib.axes.Axes.set_prop_cycle API</a>)</p> <hr /> <p>The details are in the matplotlibrc itself, actually: it needs a string rep (hex or letter or word, not tuple).</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl fig, ax1 = plt.subplots(1,1) ys = np.random.random((5, 6)) ax1.plot(range(5), ys) ax1.set_title('Default color cycle') plt.show() # From the sample matplotlibrc: #axes.color_cycle : b, g, r, c, m, y, k # color cycle for plot lines # as list of string colorspecs: # single letter, long name, or # web-style hex # setting color cycle after calling plt.subplots doesn't &quot;take&quot; # try some hex values as **string** colorspecs mpl.rcParams['axes.color_cycle'] = ['#129845','#271254', '#FA4411', '#098765', '#000009'] fig, ax2 = plt.subplots(1,1) ax2.plot(range(5), ys) ax2.set_title('New color cycle') n = 6 color = plt.cm.coolwarm(np.linspace(0.1,0.9,n)) # This returns RGBA; convert: hexcolor = map(lambda rgb:'#%02x%02x%02x' % (rgb[0]*255,rgb[1]*255,rgb[2]*255), tuple(color[:,0:-1])) mpl.rcParams['axes.color_cycle'] = hexcolor fig, ax3 = plt.subplots(1,1) ax3.plot(range(5), ys) ax3.set_title('Color cycle from colormap') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/PDXer.png" alt="enter image description here" /> <img src="https://i.stack.imgur.com/6PQ0A.png" alt="enter image description here" /> <img src="https://i.stack.imgur.com/VDeWZ.png" alt="enter image description here" /></p>
8,687,440
using favicon with css
<p>I want to set the favicon for a fairly large number of pages. But, instead of using the HTML <code>&lt;head&gt;</code> tag <code>&lt;link rel="shortcut icon" href="favicon.ico"&gt;</code>, I'd like to set it in the CSS file. I have limited access to some of the html files, and limited control to their life cycle.</p>
8,687,471
4
0
null
2011-12-31 09:45:58.403 UTC
7
2018-08-22 22:54:48.823 UTC
null
null
null
null
30,447
null
1
51
html|css|favicon
151,230
<p>You can't set a favicon from CSS - if you want to do this explicitly you have to do it in the markup as you described.</p> <p>Most browsers will, however, look for a <code>favicon.ico</code> file on the root of the web site - so if you access <a href="http://example.com" rel="noreferrer">http://example.com</a> most browsers will look for <a href="http://example.com/favicon.ico" rel="noreferrer">http://example.com/favicon.ico</a> automatically.</p>
30,476,447
MongoDB: ERROR: child process failed, exited with error number 14
<p>I run MongoDB on Mac:</p> <pre><code>Shave:mongodb_simple Logan$ ./bin/mongod -f conf/mongod.conf about to fork child process, waiting until server is ready for connections. forked process: 5110 ERROR: child process failed, exited with error number 14 </code></pre> <p>Is that because I shutdown it in wrong way?</p>
30,477,932
13
0
null
2015-05-27 07:58:01.667 UTC
5
2021-08-07 08:40:49.303 UTC
2018-04-15 07:26:03.3 UTC
null
1,033,581
null
4,943,599
null
1
15
mongodb
45,440
<p>It's because you haven't configured your <code>mongod</code> instance correctly in the config file that you passed to the <code>-f</code> option. Revisit your config file and make sure eveything is configured correctly.</p>
43,737,212
How to peek on an Optional?
<p>I want to use the fluent api of <code>Optional</code> and apply two <code>Consumer</code>s to it.</p> <p>I'm dreaming about something like this:</p> <pre><code>Optional.ofNullable(key) .map(Person::get) .ifPresent(this::printName) .ifPresent(this::printAddress); // not compiling, because ifPresent is void </code></pre> <p>How do I apply several <code>Consumer</code>s to an <code>Optional</code>?</p>
43,737,280
7
1
null
2017-05-02 11:54:12.483 UTC
4
2021-08-18 17:40:19.08 UTC
2018-10-25 15:47:04.773 UTC
null
476,791
null
476,791
null
1
40
java|option-type
11,083
<p>You can use this syntax:</p> <pre><code>ofNullable(key) .map(Person::get) .map(x -&gt; {printName(x);return x;}) .map(x -&gt; {printAddress(x);return x;}); </code></pre>
848,618
.NET Events for Process executable start
<p>Is there any way to register for an event that fires when an executable of a particular filename starts? I know it's easy enough to get an event when a process exits, by getting the process handle and registering for the exited event. But how can you be notified when a process, that isn't already running, starts...without polling all the running processes?</p>
857,946
3
0
null
2009-05-11 15:23:21.357 UTC
13
2016-06-06 17:26:08.233 UTC
null
null
null
null
194
null
1
20
c#|.net|events|process
16,358
<p>You could use the following:</p> <pre><code> private ManagementEventWatcher WatchForProcessStart(string processName) { string queryString = "SELECT TargetInstance" + " FROM __InstanceCreationEvent " + "WITHIN 10 " + " WHERE TargetInstance ISA 'Win32_Process' " + " AND TargetInstance.Name = '" + processName + "'"; // The dot in the scope means use the current machine string scope = @"\\.\root\CIMV2"; // Create a watcher and listen for events ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString); watcher.EventArrived += ProcessStarted; watcher.Start(); return watcher; } private ManagementEventWatcher WatchForProcessEnd(string processName) { string queryString = "SELECT TargetInstance" + " FROM __InstanceDeletionEvent " + "WITHIN 10 " + " WHERE TargetInstance ISA 'Win32_Process' " + " AND TargetInstance.Name = '" + processName + "'"; // The dot in the scope means use the current machine string scope = @"\\.\root\CIMV2"; // Create a watcher and listen for events ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString); watcher.EventArrived += ProcessEnded; watcher.Start(); return watcher; } private void ProcessEnded(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject) e.NewEvent.Properties["TargetInstance"].Value; string processName = targetInstance.Properties["Name"].Value.ToString(); Console.WriteLine(String.Format("{0} process ended", processName)); } private void ProcessStarted(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value; string processName = targetInstance.Properties["Name"].Value.ToString(); Console.WriteLine(String.Format("{0} process started", processName)); } </code></pre> <p>You would then call either WatchForProcessStart and/or WatchForProcessEnd passing in your process name (eg "notepad.exe").</p> <p>The ManagementEventWatcher object is returned from the two Watch* methods as it implements IDisposable and so you should call Dispose on these objects when you have finished with them to prevent issues.</p> <p>You could also change the polling value in the queries if you need the event to be raised more quickly after the process has started. To do this change the line "WITHIN 10" to be WITHIN something less than 10.</p>
558,147
Delphi MSBuild Build Configurations From Command Line
<p>Delphi 2009 uses <strong>build configurations</strong>. When you create a new project you have two default build configurations "Debug" and "Release".</p> <p>Now I asked myself how to automate builds using MSBuild (which is supported by Delphi since version 2007).</p> <p>You can start the "msbuild" command in the "RAD Studio Command Prompt" in some Delphi project directory and it will build the <strong>default</strong> build configuration (the last activated build configuration inside the Delphi IDE).</p> <p>Now, I want to specify a certain (non-default) build configuration by a command line parameter.</p> <p>The Delphi help asserts that the parameter is [/p:configuration=<code>&lt;configuration name</code>>], which is <strong>wrong</strong> (Delphi 2009, Help Update 1)!</p> <p>What is the right way?</p>
558,367
3
2
null
2009-02-17 18:30:13.22 UTC
15
2021-05-29 07:20:33.457 UTC
2010-05-18 22:01:50.83 UTC
ulrichb
50,890
ulrichb
50,890
null
1
31
delphi|msbuild|build-automation|delphi-2009|delphi-2007
17,164
<p>Now, if you want to change the build configuration you have to add the parameter<br> <strong>/p:config=<code>&lt;BUILD_CONFIG_NAME</code>></strong></p> <p>For example:</p> <pre>C:\Projects\TestDelphiApp001>msbuild /target:Build /p:config=Release</pre> <p>or</p> <pre>C:\Projects\TestDelphiApp001>msbuild /target:Build /p:config=Debug</pre> <hr> <p><em>Copied from original "question"; note community wiki.</em></p>
515,730
Getting the most out of Resharper - good tutorials/screencasts
<p>I've just installed Resharper, and I really don't know how to use it "correctly". I noticed that there are some demos and documents at their website, but I'm wondering..</p> <p>..how did you learn to use it efficiently? Are there any other good resources(demos/tutorials)?</p>
515,780
3
3
null
2009-02-05 12:35:44.81 UTC
12
2015-05-22 09:23:50.163 UTC
2009-02-05 13:10:33.553 UTC
l3dx
48,431
l3dx
48,431
null
1
33
resharper
12,080
<p>There is a <a href="http://dimecasts.net/Casts/ByTag/ReSharper" rel="noreferrer">series of screencasts</a> on the <a href="http://dimecasts.net/" rel="noreferrer">Dime Casts</a> website which are quite good as an introduction.</p> <p>There is also the <a href="http://blog.excastle.com/2007/01/31/blog-event-the-31-days-of-resharper/" rel="noreferrer">31 days of Resharper</a> and the <a href="http://www.jetbrains.com/resharper/documentation/index.html" rel="noreferrer">official demos</a> give you an idea of what's possible so you know to dive into the menu.</p>
282,429
Returning redirect as response to XHR request
<p>What happens if the browser receives a redirect response to an ajax request?</p>
2,573,589
3
1
null
2008-11-11 22:59:13.197 UTC
38
2020-12-10 01:29:00.713 UTC
null
null
null
Vasil
7,883
null
1
159
ajax|http
106,140
<p><em>What happens if the browser receives a redirect response to an ajax request?</em></p> <p>If the server sends a redirect (aka a 302 response plus a Location: header) the redirect is automatically followed by the browser. The response to the <em>second</em> request (assuming it also isn't another redirect) is what is exposed to your program.</p> <p>In fact, you don't have the ability to detect whether a 302 response has occurred. If the 302 redirect leads to a 200, then your program acts identically as if the original request led directly to a 200.</p> <p>This has been both my experience and the <a href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#infrastructure-for-the-send%28%29-method" rel="noreferrer">behavior called out in the spec</a>.</p> <p><strong>2016 Update:</strong> Time has passed, and the good news is that the new <a href="https://fetch.spec.whatwg.org/" rel="noreferrer">fetch() API</a> is spec'd to offer <a href="https://fetch.spec.whatwg.org/#concept-request-redirect-mode" rel="noreferrer">finer-grained control of how redirects are handled</a>, with default behavior similar to XHR. That said, it only works where fetch() is implemented <em>natively</em>. <a href="https://github.com/github/fetch" rel="noreferrer">Polyfill versions of fetch()</a>—which are based on XHR—<a href="https://github.com/github/fetch/issues/137" rel="noreferrer">continue to have XHR's limitations</a>. Fortunately, <a href="http://caniuse.com/#search=fetch" rel="noreferrer">native browser support</a> seems to be rounding out nicely.</p>
41,908,379
Keras - Plot training, validation and test set accuracy
<p>I want to plot the output of this simple neural network: </p> <pre><code>model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True) model.test_on_batch(x_test, y_test) model.metrics_names </code></pre> <p>I have plotted <em>accuracy</em> and <em>loss</em> of training and validation:</p> <pre><code>print(history.history.keys()) # "Accuracy" plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() # "Loss" plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() </code></pre> <p>Now I want to add and plot test set's accuracy from <code>model.test_on_batch(x_test, y_test)</code>, but from <code>model.metrics_names</code> I obtain the same value <em>'acc'</em> utilized for plotting accuracy on training data <code>plt.plot(history.history['acc'])</code>. How could I plot test set's accuracy?</p>
41,909,089
5
1
null
2017-01-28 09:46:13.64 UTC
28
2022-05-03 00:08:50.43 UTC
2022-04-28 21:57:16.467 UTC
null
7,758,804
null
7,387,749
null
1
73
python|matplotlib|keras
163,401
<p>It is the same because you are training on the test set, not on the train set. Don't do that, just train on the training set:</p> <pre><code>history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True) </code></pre> <p>Change into:</p> <pre><code>history = model.fit(x_train, y_train, nb_epoch=10, validation_split=0.2, shuffle=True) </code></pre>
42,049,147
Convert List to Pandas Dataframe Column
<p>I need to Convert my list into a one column pandas dataframe </p> <p>Current List (len=3):</p> <pre><code>['Thanks You', 'Its fine no problem', 'Are you sure'] </code></pre> <p>Required Pandas DF (shape =3,):</p> <pre><code>0 Thank You 1 Its fine no problem 2 Are you sure </code></pre> <p>Please note the numbers represent index in Required Pandas DF above.</p>
42,049,158
5
1
null
2017-02-05 06:19:02.003 UTC
40
2022-01-23 22:54:55.717 UTC
2019-01-30 22:26:07.97 UTC
null
4,909,087
null
6,469,175
null
1
142
python|list|pandas|dataframe
418,532
<p>Use:</p> <pre><code>L = ['Thanks You', 'Its fine no problem', 'Are you sure'] #create new df df = pd.DataFrame({'col':L}) print (df) col 0 Thanks You 1 Its fine no problem 2 Are you sure </code></pre> <hr> <pre><code>df = pd.DataFrame({'oldcol':[1,2,3]}) #add column to existing df df['col'] = L print (df) oldcol col 0 1 Thanks You 1 2 Its fine no problem 2 3 Are you sure </code></pre> <p>Thank you <a href="https://stackoverflow.com/questions/42049147/convert-list-to-pandas-dataframe/42049158#comment71270875_42049158">DYZ</a>:</p> <pre><code>#default column name 0 df = pd.DataFrame(L) print (df) 0 0 Thanks You 1 Its fine no problem 2 Are you sure </code></pre>
20,615,711
Run Visual Studio 2013 solution with Crystal Reports
<p>I have an MVC application originally developed in VS2010. We have Crystal Reports (CR) integrated into it and all works smoothly.</p> <p>Now, I need to setup some new workstations which will have only VS2013. I can run the site in VS2013, but only because I have VS2010 and previously installed the CR runtime files. The new stations won't have VS2010 installed and the SAP installer will not run unless VS2010 is on the machine. SAP will not provide a fix until early 2014 at the earliest.</p> <p>The new workstations don't need to be able to modify the reports, so I don't care if the full CR application is installed, I just need it to be able to reference the runtime files so they can debug other areas of the application.</p> <p>I cannot remove CR from the application at this time, and cannot install VS2010 on all the new workstations first.</p> <p>I have tried putting the dlls in the bin folder of the site. I have tried putting them in <code>C:/Windows/Microsoft.NET/ Framework/v4.0.30319/Temporary ASP.NET Files/root/dec0de27/fa4bed84/</code> Nothing seems to work.</p> <p>Where do I place the dlls so VS2013 can use them? I know there has to be some way to do this because my workstation can run the site in VS2013 eventhough SAP hasn't released a 2013 version.</p> <p>Here is the error when they try to run the applicaiton:</p> <pre><code>Server Error in '/' Application. Could not load file or assembly 'CrystalDecisions.ReportAppServer.ClientDoc' or one of its dependencies. An attempt was made to load a program with an incorrect format. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.BadImageFormatException: Could not load file or assembly 'CrystalDecisions.ReportAppServer.ClientDoc' or one of its dependencies. An attempt was made to load a program with an incorrect format. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Assembly Load Trace: The following information can be helpful to determine why the assembly 'CrystalDecisions.ReportAppServer.ClientDoc' could not be loaded. === Pre-bind state information === LOG: DisplayName = CrystalDecisions.ReportAppServer.ClientDoc (Partial) WRN: Partial binding information was supplied for an assembly: WRN: Assembly Name: CrystalDecisions.ReportAppServer.ClientDoc | Domain ID: 2 WRN: A partial bind occurs when only part of the assembly display name is provided. WRN: This might result in the binder loading an incorrect assembly. WRN: It is recommended to provide a fully specified textual identity for the assembly, WRN: that consists of the simple name, version, culture, and public key token. WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue. LOG: Appbase = file:///C:/Users/Office/Documents/GIT/Site/site/ LOG: Initial PrivatePath = C:\Users\Office\Documents\GIT\Site\site\bin Calling assembly : (Unknown). === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Users\Office\Documents\GIT\Site\site\web.config LOG: Using host configuration file: C:\Users\Office\Documents\IISExpress\config\aspnet.config LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/ Framework/v4.0.30319/Temporary ASP.NET Files/root/dec0de27/fa4bed84/ CrystalDecisions.ReportAppServer.ClientDoc.DLL. LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/ Framework/v4.0.30319/Temporary ASP.NET Files/root/dec0de27/fa4bed84/ CrystalDecisions.ReportAppServer.ClientDoc/ CrystalDecisions.ReportAppServer.ClientDoc.DLL. LOG: Attempting download of new URL file:///C:/Users/Office/Documents/GIT/ Site/site/bin/CrystalDecisions.ReportAppServer.ClientDoc.DLL. ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated. </code></pre> <p>This is the SAP discussion <a href="http://scn.sap.com/message/14614675#14614675" rel="nofollow">http://scn.sap.com/message/14614675#14614675</a></p>
23,672,126
4
0
null
2013-12-16 16:24:26.267 UTC
null
2014-12-28 09:50:27.68 UTC
2013-12-19 00:57:00.81 UTC
null
1,161,703
null
1,161,703
null
1
5
asp.net-mvc-3|visual-studio|crystal-reports
42,124
<p>Crystal report is updated support for VS 2013 <a href="http://scn.sap.com/docs/DOC-7824" rel="nofollow">Updated version document</a></p>
19,426,742
Don't navigate to other pages in WebView,disable links and references
<p>I have a webView in Android, and I open a html webpage in it. But it's full of links and images, and when I click one of them, it loads in my webview. I want to disable this behaviour, so if I click on a link, don't load it. I've tried this <a href="https://stackoverflow.com/questions/11526676/disable-click-link-or-button-in-a-webview-android">solution</a> and edited a bit for myselft, but not worked. My webviewclient code:</p> <pre><code>private boolean loaded = false; @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if(loaded == false){ view.loadUrl(url); loaded = true; return true; }else{ return false; } } </code></pre> <p>My webview implementation and settings.</p> <pre><code>WebView wv = (WebView) findViewById(R.id.recipeWv); ourWebViewClient webViewClient = new ourWebViewClient(); webViewClient.shouldOverrideUrlLoading(wv, URLsave); wv.setWebViewClient(webViewClient); wv.setFocusableInTouchMode(false); wv.setFocusable(false); wv.setClickable(false); WebSettings settings = wv.getSettings(); settings.setDefaultTextEncodingName("utf-8"); settings.setLoadWithOverviewMode(true); settings.setBuiltInZoomControls(true); </code></pre> <p>Example: If the user open in my webview the StackOverflow homepage and clicks on one of the links(like "Questions") then the webview should stay on the StackOverflow homepage.</p>
19,552,580
8
0
null
2013-10-17 12:27:02.037 UTC
8
2022-04-29 06:00:43.867 UTC
2017-05-23 10:31:14.013 UTC
null
-1
null
2,591,288
null
1
32
android|html|webview
38,926
<p>You should save in a class variable your current url and check if it's the same with the loaded one. When the user clicks on a link the <code>shouldOverrideUrlLoading</code> is called and check the website. Something like this:</p> <pre><code>private String currentUrl; public ourWebViewClient(String currentUrl) { this.currentUrl = currentUrl; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.equals(currentUrl)) { view.loadUrl(url); } return true; } </code></pre> <p><strong>Important:</strong> don't forget set the <code>WebViewClient</code> to your <code>WebView</code>.</p> <pre><code>ourWebViewClient webViewClient = new ourWebViewClient(urlToLoad); wv.setWebViewClient(webViewClient); </code></pre>
2,798,215
Hide TabControl buttons to manage stacked Panel controls
<p>I need to handle multiple panels, containing variuous data masks. Each panel shall be visible using a TreeView control.</p> <p>At this time, I handle the panels visibility manually, by making the selected one visible and bring it on top.</p> <p>Actually this is not much confortable, especially in the UI designer, since when I add a brand new panel I have to resize every panel and then design it...</p> <p>A good solution would be using a TabControl, and each panel is contained in a TabPage. But I cannot find any way to hide the TabControl buttons, since I already have a TreeView for selecting items.</p> <p>Another solution would be an ipotethic "StackPanelControl", where the Panels are arranged using a stack, but I couldn't find it anywhere.</p> <p>What's the best solution to handle this kind of UI?</p>
2,798,241
2
0
null
2010-05-09 15:55:35.577 UTC
10
2018-07-12 11:02:01.05 UTC
2010-05-09 16:03:02.093 UTC
null
161,554
null
161,554
null
1
15
c#|winforms|tabcontrol|stackpanel
6,578
<p>You need a wee bit of Win32 API magic. The tab control sends the TCM_ADJUSTRECT message to allow the app to adjust the tab size. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.</p> <p>You'll get the tabs at design time so you can easily switch between pages. The tabs are hidden at runtime, use the SelectedIndex or SelectedTab property to switch between "views".</p> <pre><code>using System; using System.Windows.Forms; class StackPanel : TabControl { protected override void WndProc(ref Message m) { // Hide tabs by trapping the TCM_ADJUSTRECT message if (m.Msg == 0x1328 &amp;&amp; !DesignMode) m.Result = (IntPtr)1; else base.WndProc(ref m); } } </code></pre>
2,768,527
Getting width and height of image in model in the Ruby Paperclip GEM
<p>Trying to get the width and height of the uploaded image while still in the model on the initial save.</p> <p>Any way to do this?</p> <p>Here's the snippet of code I've been testing with from my model. Of course it fails on "instance.photo_width".</p> <pre><code>has_attached_file :photo, :styles =&gt; { :original =&gt; "634x471&gt;", :thumb =&gt; Proc.new { |instance| ratio = instance.photo_width/instance.photo_height min_width = 142 min_height = 119 if ratio &gt; 1 final_height = min_height final_width = final_height * ratio else final_width = min_width final_height = final_width * ratio end "#{final_width}x#{final_height}" } }, :storage =&gt; :s3, :s3_credentials =&gt; "#{RAILS_ROOT}/config/s3.yml", :path =&gt; ":attachment/:id/:style.:extension", :bucket =&gt; 'foo_bucket' </code></pre> <p>So I'm basically trying to do this to get a custom thumbnail width and height based on the initial image dimensions.</p> <p>Any ideas?</p>
2,769,219
2
0
null
2010-05-04 19:52:55.42 UTC
12
2015-05-20 08:04:52.393 UTC
2014-12-23 22:42:38.857 UTC
null
117,259
null
290,699
null
1
17
ruby-on-rails|paperclip
14,463
<p>Ahh, figured it out. I just needed to make a proc.</p> <p>Here's the code from my model:</p> <pre><code>class Submission &lt; ActiveRecord::Base #### Start Paperclip #### has_attached_file :photo, :styles =&gt; { :original =&gt; "634x471&gt;", :thumb =&gt; Proc.new { |instance| instance.resize } }, :storage =&gt; :s3, :s3_credentials =&gt; "#{RAILS_ROOT}/config/s3.yml", :path =&gt; ":attachment/:id/:style.:extension", :bucket =&gt; 'foo_bucket' #### End Paperclip #### def resize geo = Paperclip::Geometry.from_file(photo.to_file(:original)) ratio = geo.width/geo.height min_width = 142 min_height = 119 if ratio &gt; 1 # Horizontal Image final_height = min_height final_width = final_height * ratio "#{final_width.round}x#{final_height.round}!" else # Vertical Image final_width = min_width final_height = final_width * ratio "#{final_height.round}x#{final_width.round}!" end end end </code></pre>
33,091,013
How do you delete files older than specific date in Linux?
<p>I used the below command to delete files older than a year.</p> <pre><code> find /path/* -mtime +365 -exec rm -rf {} \; </code></pre> <p>But now I want to delete all files whose modified time is older than <em>01 Jan 2014.</em> How do I do this in Linux?</p>
33,091,121
4
0
null
2015-10-12 22:08:32.69 UTC
16
2021-02-05 13:58:59.457 UTC
2020-12-14 09:37:35.457 UTC
null
2,671,341
null
4,438,637
null
1
60
linux|find|delete-file
87,860
<p>You can touch your timestamp as a file and use that as a reference point:</p> <p>e.g. for 01-Jan-2014:</p> <pre><code>touch -t 201401010000 /tmp/2014-Jan-01-0000 find /path -type f ! -newer /tmp/2014-Jan-01-0000 | xargs rm -rf </code></pre> <p>this works because <code>find</code> has a <code>-newer</code> switch that we're using. </p> <p>From <code>man find</code>:</p> <pre><code>-newer file File was modified more recently than file. If file is a symbolic link and the -H option or the -L option is in effect, the modification time of the file it points to is always used. </code></pre>
33,324,302
What are Elixir Bang Functions?
<p>I first noticed a function with a trailing exclamation-mark/bang(!) while going through the Phoenix tutorial (in the <a href="http://www.phoenixframework.org/docs/channels#section-incoming-events">Incoming Events</a> section) </p> <pre><code>def handle_in("new_msg", %{"body" =&gt; body}, socket) do broadcast! socket, "new_msg", %{body: body} {:noreply, socket} end </code></pre> <p><strong>What does the trailing exclamation mark mean? Does it do anything?</strong> I've been searching around and tried looking but I'm not sure I'm using the right terms. So far it seems that the function only as convention will raise an error if it fails, but does always it always mean that.</p> <p>The only mentions I see of it appear in "Programming Elixir" by Dave Thomas:</p> <pre><code>Identifiers in Elixir are combinations of upper and lower case ASCII characters, digits, and underscores. Function names may end with a question mark or an exclamation point. </code></pre> <p>And also in <a href="http://elixir-lang.org/getting-started/io-and-the-file-system.html">the documentation</a> it mentions:</p> <pre><code>Notice that when the file does not exist, the version with ! raises an error. The version without ! is preferred when you want to handle different outcomes using pattern matching... </code></pre> <p>Neither of these explains if this is a convention that other elixirists or alchemists or whatever use. Please help.</p>
33,326,895
3
0
null
2015-10-24 23:05:50.673 UTC
5
2015-10-25 07:56:46.44 UTC
2015-10-25 02:27:01.877 UTC
null
2,128,265
null
2,128,265
null
1
42
elixir|phoenix-framework
9,789
<p>This:</p> <blockquote> <p>Notice that when the file does not exist, the version with ! raises an error. The version without ! is preferred when you want to handle different outcomes using pattern matching...</p> </blockquote> <p>will be more clear if you will look at the source code. The <code>!</code> symbol in a function name is just a syntactic agreement. If you see a function which contains the <code>!</code> symbol in its name, it means that likely there is a function with the same name, but without <code>!</code> symbol. Both of these functions will do the same thing, but they will handle errors in a different way.</p> <p>The function without <code>!</code> will just return an error to you. You will be need to know a type of error and handle it depends on your type. Look on the <code>broadcast/3</code> function (<a href="https://github.com/phoenixframework/phoenix/blob/4178dfc9e574762525c0cc29289fa8f9a3588940/lib/phoenix/pubsub.ex#L145" rel="noreferrer">variant</a> without <code>!</code>):</p> <pre><code> def broadcast(server, topic, message) when is_atom(server), do: call(server, :broadcast, [:none, topic, message]) </code></pre> <p>It just makes call to the given server and will return its result. The <code>broadcast!/3</code> function will do the same, but: it will call <code>broadcast</code> function without <code>!</code>, will check its result and raise the <code>BroadcastError</code> <a href="http://elixir-lang.org/getting-started/try-catch-and-rescue.html" rel="noreferrer">exception</a>:</p> <pre><code> def broadcast!(server, topic, message) do case broadcast(server, topic, message) do :ok -&gt; :ok {:error, reason} -&gt; raise BroadcastError, message: reason end end </code></pre>
2,073,427
Convert coordinates between parent/child UIView after CGAffineTransform
<p>Before I go into doing everything by hand I would like to ask if there is some help to get from the framework.</p> <p>I have a UIView that holds another UIView with a map. The parent UIView holds some legends for the map. Initially I define some coordinates in the map view. e.g. (100, 40), and place a piece of graphics there in the parent view (like a tack in google maps etc.). The parent view and the child view are both 300x200 and have the same origin. This means that (100, 40) is the same point in both views.</p> <p>Now I zoom and move the child UIView(the map) using CGAffineTransform and the coordinate (100, 40) is now situated somewhere else. The parent view is effectively a mask here.</p> <p><strong>Can I use the CGAffineTransform Matrix or another part of the framework to calculate and inform the parent view where to place the tack now that the point has moved?</strong></p> <p><em>i.e. (100, 400) in the child view compared to (100, 40) in the parent view, what does it compare to after the transformation?</em></p> <p>Thank you for suggestions or help given.</p> <p>The animation of the child UIView</p> <pre><code> [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; CGAffineTransform transform = CGAffineTransformMakeScale(1.8f, 1.8f); worldMap.transform = transform; worldMap.bounds.origin = newPos; [UIView commitAnimations]; </code></pre>
2,073,508
1
0
null
2010-01-15 17:11:59.703 UTC
8
2010-01-15 18:22:11.06 UTC
null
null
null
null
191,731
null
1
33
iphone|objective-c|uiview|cgaffinetransform
20,706
<p>UIView's <code>-convertPoint:toView:</code> and <code>-convertPoint:fromView:</code> should work for you.</p>
30,165,475
How to compress/minimize size of JSON/Jsonify with Flask in Python?
<p>I'm sending a huge JSON string (with jsonify in Flask) to my webpage pretty often, so I would like to reduce the data. The easiest option is probably to remove all line breaks and space characters, but just to give you an example of this: </p> <p>Normal jsonify: 361KB<br> Removing all line breaks and space characters: 118KB (wow).<br> Zip the original file: 35KB (double wow). </p> <p>So I basically wonder if there is an easy way to come close to the 35KB. I couldn't find a solution so far which I could easily implement in python and javascript (to decompress). </p> <p>Right now, I send around 4-5MB of data every second, which is - you guessed right - a "little bit" too much.</p>
30,165,707
5
0
null
2015-05-11 10:35:18.96 UTC
8
2022-01-08 18:02:34.2 UTC
2016-01-16 18:34:48.72 UTC
null
4,675,937
null
4,847,357
null
1
23
javascript|python|json|flask
22,943
<p>Web requests do support GZip and you could implement it in python.</p> <p>Here is someone who asked that exact question. <a href="https://stackoverflow.com/questions/9622998/how-to-use-content-encoding-gzip-with-python-simplehttpserver">How to use Content-Encoding: gzip with Python SimpleHTTPServer</a></p> <p>According to the flask-compress repo</p> <blockquote> <p>The preferred solution is to have a server (like Nginx) automatically compress the static files for you.</p> </blockquote> <p>But you can do it in flask: <a href="https://github.com/colour-science/flask-compress" rel="noreferrer">https://github.com/colour-science/flask-compress</a>.</p> <p>If you go the gzip route you will not need to remove line breaks and white space, but if you still want to then according to the flask documentation you can disable pretty print by setting JSONIFY_PRETTYPRINT_REGULAR to false.</p>
20,407,326
BlueZ vs Bluedroid bluetooth stack
<p>BlueZ have a lot of documentations and all. And from the same, i understood BlueZ supports A2DP sink support. And at the same time an android device can be made act as an A2DP sink by modifying the audio.conf file inside the same.</p> <p>I also came to know that from android 4.2 onwards, the BlueZ stack was replaced by Broadcom's Bluedroid stack. I searched a lot about Bluedroid stack. But i was not able to find much details about the same.</p> <p>Hope someone can help me with the following doubts.</p> <p>1). Whether Bluedroid have A2DP sink support?</p> <p>2). Whether the audio.conf file will be available for devices having bluedroid stack?</p> <p>3). I am going to write an A2DP sink support for an android device by directly calling API's of BlueZ stack. But my final question is whether the same can be used with Bluedroid stack also? Hope Bluedroid is just an expansion of BlueZ.</p> <p>Please help.</p>
20,417,300
4
0
null
2013-12-05 18:00:38.04 UTC
10
2016-10-24 10:47:18.84 UTC
2013-12-05 18:14:37.827 UTC
null
2,437,164
null
2,441,654
null
1
17
android|bluetooth|android-bluetooth|bluez|a2dp
28,774
<p>Bluedroid is a stack provided by Broadcom and is now opensource in android . Bluedroid is not related with bluez in any respect, it has few advantages over bluez(i differ to that). </p> <p>[1]. Bluedroid does not have a2dp sink support as of now, as per code available <a href="http://source.android.com/devices/reference/bt__av_8h_source.html">source code</a> only a2dp source support is available</p> <p>[2]. Audio.conf file is for bluez stack, it is not a part of bluedroid</p> <p>[3]. Directly calling Bluez API-- i think you will use dbus calls but bluedroid does not support dbus method calls, it has a callback mechanism implemented, so it will not work, bluedroid is not an expansion of bluez.</p>
18,860,281
Is there another way to concatenate instead of using the CONCATENATE keyword?
<p>Is there another way to concatenate in ABAP instead of using the <a href="http://help.sap.com/abapdocu_731/en/abapconcatenate_shortref.htm"><code>CONCATENATE</code> keyword</a>?</p> <p>An example using <code>CONCATENATE</code>:</p> <pre><code>DATA: foo TYPE string, bar TYPE string, foobar TYPE string. foo = 'foo'. bar = 'bar'. CONCATENATE foo 'and' bar INTO foobar SEPARATED BY space. </code></pre>
18,868,316
5
0
null
2013-09-17 21:34:12.147 UTC
3
2020-09-08 15:09:18.347 UTC
2020-09-08 15:09:18.347 UTC
null
5,846,045
null
1,779,281
null
1
15
abap
49,963
<p>You can (starting with ABAP 7.02) use <a href="https://help.sap.com/http.svc/rc/abapdocu_753_index_htm/7.53/en-US/index.htm?file=abenstring_operators.htm" rel="noreferrer"><code>&amp;&amp;</code></a> to concatenate two strings.</p> <pre><code>Data: foo TYPE string, bar TYPE string, foobar TYPE string. foo = 'foo'. bar = 'bar'. foobar = foo &amp;&amp; bar. </code></pre> <p>This also works with <a href="https://help.sap.com/doc/abapdocu_753_index_htm/7.53/en-US/index.htm?file=abenuntyped_character_literals.htm" rel="noreferrer">character literals</a>:</p> <pre><code>foobar = 'foo' &amp;&amp; 'bar'. </code></pre> <p>For preserving spaces, use this kind of character literal named "text string literal" which is defined with two <a href="https://en.wikipedia.org/wiki/Grave_accent" rel="noreferrer">grave accents</a> (U+0060):</p> <pre><code>foobar = foo &amp;&amp; ` and ` &amp;&amp; bar </code></pre>
24,378,646
Finding Max with Lambda Expression in Java
<p>This is my code</p> <pre><code> List&lt;Integer&gt; ints = Stream.of(1,2,4,3,5).collect(Collectors.toList()); Integer maxInt = ints.stream() .max(Comparator.comparing(i -&gt; i)) .get(); System.out.println("Maximum number in the set is " + maxInt); </code></pre> <p>output:</p> <pre><code>Maximum number in the set is 5 </code></pre> <p>I cannot make distingues between two <code>i</code> in below section of my code</p> <pre><code>Comparator.comparing(i -&gt; i) </code></pre> <p>can anyone be kind and explain the difference between two <code>i</code>?</p>
24,394,288
3
0
null
2014-06-24 05:01:18.317 UTC
3
2018-10-11 14:54:22.38 UTC
2018-10-11 14:54:22.38 UTC
null
2,097,529
null
2,097,529
null
1
17
java|lambda|max|java-8
51,045
<p>The method <code>Comparator.comparing(…)</code> is intended to create a <code>Comparator</code> which uses an order based on a property of the objects to compare. When using the lambda expression <code>i -&gt; i</code>, which is a short writing for <code>(int i) -&gt; { return i; }</code> here, as a property provider function, the resulting <code>Comparator</code> will compare the values itself. This works when the objects to compare have a <em>natural order</em> as <code>Integer</code> has.</p> <p>So</p> <pre><code>Stream.of(1,2,4,3,5).max(Comparator.comparing(i -&gt; i)) .ifPresent(maxInt-&gt;System.out.println("Maximum number in the set is " + maxInt)); </code></pre> <p>does the same as</p> <pre><code>Stream.of(1,2,4,3,5).max(Comparator.naturalOrder()) .ifPresent(maxInt-&gt;System.out.println("Maximum number in the set is " + maxInt)); </code></pre> <p>though the latter is more efficient as it is implemented as singleton for all types which have a natural order (and implement <code>Comparable</code>).</p> <p>The reason why <code>max</code> requires a <code>Comparator</code> at all, is because you are using the generic class <code>Stream</code> which might contain arbitrary objects.</p> <p>This allows, e.g. to use it like <code>streamOfPoints.max(Comparator.comparing(p-&gt;p.x))</code> to find the point with the largest <code>x</code> value while <code>Point</code> itself does not have a natural order. Or do something like <code>streamOfPersons.sorted(Comparator.comparing(Person::getAge))</code>.</p> <p>When using the specialized <code>IntStream</code> you can use the natural order directly which is likely to be more efficient:</p> <pre><code>IntStream.of(1,2,4,3,5).max() .ifPresent(maxInt-&gt;System.out.println("Maximum number in the set is " + maxInt)); </code></pre> <hr> <p>To illustrate the difference between “natural order” and a property based order:</p> <pre><code>Stream.of("a","bb","aaa","z","b").max(Comparator.naturalOrder()) .ifPresent(max-&gt;System.out.println("Maximum string in the set is " + max)); </code></pre> <p>this will print</p> <blockquote> <p>Maximum string in the set is z</p> </blockquote> <p>as the natural order of <code>String</code>s is the lexicographical order where <code>z</code> is greater than <code>b</code> which is greater than <code>a</code></p> <p>On the other hand</p> <pre><code>Stream.of("a","bb","aaa","z","b").max(Comparator.comparing(s-&gt;s.length())) .ifPresent(max-&gt;System.out.println("Maximum string in the set is " + max)); </code></pre> <p>will print</p> <blockquote> <p>Maximum string in the set is aaa</p> </blockquote> <p>as <code>aaa</code> has the maximum <em>length</em> of all <code>String</code>s in the stream. This is the intended use case for <code>Comparator.comparing</code> which can be made even more readable when using method references, i.e. <code>Comparator.comparing(String::length)</code> which almost speaks for itself…</p>
44,646,186
Save file in document directory in swift 3?
<p>I am saving files in a document directory in swift 3 with this code:</p> <pre><code>fileManager = FileManager.default // let documentDirectory = fileManager?.urls(for: .documentDirectory, in: .userDomainMask).first as String var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String path = path + name let image = #imageLiteral(resourceName: "Notifications") let imageData = UIImageJPEGRepresentation(image, 0.5) let bool = fileManager?.createFile(atPath: path, contents: imageData, attributes: nil) print("bool is \(bool)") return true </code></pre> <p>But as you can see, I am not using <code>filemanager</code> to get document directory path as <code>filemanager</code> gives only URL not string.</p> <p>Questions:</p> <ul> <li>How to get string from file manager? </li> <li>Is there any chance of crash in my code?</li> </ul>
44,646,672
4
1
null
2017-06-20 07:11:29.333 UTC
9
2020-11-20 14:16:35.14 UTC
2018-05-23 04:25:10.65 UTC
null
5,175,709
null
2,210,442
null
1
40
ios|swift|nsfilemanager|nsdocumentdirectory
86,569
<p>Please think the other way round. </p> <p><code>URL</code> is the recommended way to handle file paths because it contains all convenience methods for appending and deleting path components and extensions – rather than <code>String</code> which Apple has removed those methods from.</p> <p>You are discouraged from concatenating paths like <code>path = path + name</code>. It's error-prone because you are responsible for all slash path separators.</p> <p>Further you don't need to create a file with <code>FileManager</code>. <code>Data</code> has a method to write data to disk.</p> <pre><code>let fileManager = FileManager.default do { let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false) let fileURL = documentDirectory.appendingPathComponent(name) let image = #imageLiteral(resourceName: "Notifications") if let imageData = image.jpegData(compressionQuality: 0.5) { try imageData.write(to: fileURL) return true } } catch { print(error) } return false </code></pre>
48,129,222
matplotlib: make plots in functions and then add each to a single subplot figure
<p>I haven't been able to find a solution to this.. Say I define some plotting function so that I don't have to copy-paste tons of code every time I make similar plots... </p> <p>What I'd like to do is use this function to create a few different plots individually and then put them together as subplots into one figure. Is this even possible? I've tried the following but it just returns blanks:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # function to make boxplots def make_boxplots(box_data): fig, ax = plt.subplots() box = ax.boxplot(box_data) #plt.show() return ax # make some data: data_1 = np.random.normal(0,1,500) data_2 = np.random.normal(0,1.1,500) # plot it box1 = make_boxplots(box_data=data_1) box2 = make_boxplots(box_data=data_2) plt.close('all') fig, ax = plt.subplots(2) ax[0] = box1 ax[1] = box2 plt.show() </code></pre>
48,129,456
1
0
null
2018-01-06 16:11:45.88 UTC
20
2018-01-06 16:37:22.137 UTC
null
null
null
null
7,728,410
null
1
21
python|matplotlib
20,792
<p>I tend to use the following template</p> <pre><code>def plot_something(data, ax=None, **kwargs): ax = ax or plt.gca() # Do some cool data transformations... return ax.boxplot(data, **kwargs) </code></pre> <p>Then you can experiment with your plotting function by simply calling <code>plot_something(my_data)</code> and you can specify which axes to use like so.</p> <pre><code>fig, (ax1, ax2) = plt.subplots(2) plot_something(data1, ax1, color='blue') plot_something(data2, ax2, color='red') </code></pre> <p>Adding the <code>kwargs</code> allows you to pass in arbitrary parameters to the plotting function such as labels, line styles, or colours.</p> <p>The line <code>ax = ax or plt.gca()</code> uses the axes you have specified or gets the current axes from matplotlib (which may be new axes if you haven't created any yet).</p>
34,592,141
Using Carthage and CocoaPods in the same project
<p>I'm currently looking at a library which only supports Carthage as a package manager. The project I'm looking to integrate it with already has some CocoaPods dependencies. Has anybody tried using both of these managers at the same time?</p> <p>It strikes me as a bad idea, but I'd love to hear if this is the case in practice.</p>
34,630,099
2
0
null
2016-01-04 13:20:26.147 UTC
5
2020-04-23 22:29:25.98 UTC
null
null
null
null
2,799,670
null
1
35
cocoapods|carthage
12,272
<p>The main issue you will run into is that CocoaPods and Carthage are not aware of each other. This means that if a dependency managed by CocoaPods and a dependency by Carthage share a common dependency, conflicts <em>may</em> arise. </p> <p>Carthage requires that you manually add frameworks to a project which means that you can probably get away with not linking any shared dependency and relying on the framework added by CocoaPods, but you won't get dependency version resolution across the two dependency managers and it won't be clear how it all works. </p> <p>With that said, there aren't any inherent reasons why you can't use both, and if the library you want to include has few or no dependencies, it's probably still preferable to use Carthage rather than including the library as a submodule or even copying the source in. </p> <p>My recommendation, if possible, is to include your other dependencies via Carthage, or to create a podspec for the library so that you can use Carthage or CocoaPods exclusively. </p>
26,079,591
What's the point of declaring an object as "final"?
<p>I just noticed that it's possible to declare objects as <code>final</code> in Scala:</p> <pre><code>final object O </code></pre> <p>What's the point of doing that? One cannot inherit from objects anyway:</p> <pre><code>object A object B extends A // not found: type A </code></pre>
26,081,039
2
0
null
2014-09-27 21:57:57.27 UTC
7
2014-09-29 07:10:34.427 UTC
2014-09-28 02:28:31.127 UTC
null
2,074,608
null
252,000
null
1
46
scala|object|inheritance|final
3,766
<p>Not that anyone does this, but:</p> <pre><code>$ scala -Yoverride-objects Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11). Type in expressions to have them evaluated. Type :help for more information. scala&gt; trait A { object O } ; trait B extends A { override object O } defined trait A defined trait B scala&gt; trait A { final object O } ; trait B extends A { override object O } &lt;console&gt;:8: error: overriding object O in trait A; object O cannot override final member trait A { final object O } ; trait B extends A { override object O } ^ </code></pre> <p>Possibly sometimes people want to do it. (<a href="https://groups.google.com/d/msg/scala-user/adbwUoNoHps/jQI2AggVDDkJ">For instance.</a>)</p>
22,222,566
C Hello world: Code Blocks IDE, MinGW C compiler on windows
<p>I can't get Code Blocks IDE to compile the hello world C program it creates when you create a new C project. I've installed MinGW and it was recognised by the IDE. But when I try to build I get the following output:</p> <pre><code>-------------- Build: Debug in TestC3 (compiler: GNU GCC Compiler)--------------- mingw32-gcc.exe -Wall -g -c C:\Users\jody\codeblocks\testc3\TestC3\main.c -o obj\Debug\main.o mingw32-g++.exe -o bin\Debug\TestC3.exe obj\Debug\main.o Execution of 'mingw32-g++.exe -o bin\Debug\TestC3.exe obj\Debug\main.o' in 'C:\Users\jody\codeblocks\testc3\TestC3' failed. </code></pre> <p>Why is it trying to run <code>mingw32-g++.exe</code> as well as <code>mingw32-gcc.exe</code>? (And if it shouldn't be doing this, how can I configure it not to?)</p>
22,224,218
3
0
null
2014-03-06 11:04:47.08 UTC
null
2020-06-29 13:50:54.057 UTC
2014-03-06 11:05:50.32 UTC
null
28,169
null
708,436
null
1
5
c|windows|gcc|mingw|codeblocks
46,873
<p>The <code>mingw32-gcc.exe</code> step is the compile step. The <code>mingw32-g++.exe</code> is the link step. This is the correct sequence and will work if your <code>mingw32</code> installation is "normal" and correct - where "normal" means you have installed the C++ as well as the C tools.</p> <p>The link step is failing for you because <code>mingw32-g++.exe</code> cannot be executed, most likely because it does not exist on your <code>PATH</code>. Try running <code>mingw32-g++.exe</code> at the command prompt to check. Look in the directory where <code>mingw32-gcc.exe</code> resides to see if <code>mingw32-g++.exe</code> is also there.</p> <p>If your mingw32 installation has got broken somehow I suggest you uninstall and reinstall.</p> <p>If you have <em>intentionally</em> installed only the C tools then that will explain what you are seeing, and it is easily fixed:</p> <p>Both <code>mingw32-gcc.exe</code> and <code>mingw32-g++.exe</code> are just tool driver programs. When invoked with compilation options for <code>.c</code> files, <code>mingw32-gcc.exe</code> invokes the C compiler. When invoked with compilation options for <code>.cpp|cxx|...</code> files, <code>mingw32-g++.exe</code> invokes the C++ compiler. If either of them is invoked with linkage options then it invokes the linker. </p> <p>Codeblocks by default configures <code>mingw32-g++.exe</code> to invoke the linker because it will do equally well for C projects, C++ projects and C/C++ projects, and it assumes you have the full C/C++ toolchain.</p> <p>If you have not installed C++ tools and only want to build C, then you can use <code>mingw32-gcc.exe</code> to invoke both the C compiler and the linker. To configure this in the CodeBlocks IDE:</p> <ul> <li>Navigate <strong>Settings</strong> -> <strong>Compiler</strong></li> <li>Ensure that the <strong>Selected Compiler</strong> is <code>GNU GCC</code></li> <li>Tab to <strong>Toolchain executables</strong></li> <li>Change <strong>Linker for dynamic libs</strong> from <code>mingw32-g++.exe</code> to <code>mingw32-gcc.exe</code></li> <li>OK out of <strong>Settings</strong> and rebuild your project.</li> </ul>
21,997,728
Horizontal Menu with Vertical Submenu (HTML/CSS Only)
<p>I'm having a difficult time trying to make my submenu vertical instead of horizontal. Any help would be much appreciated.</p> <p>HTML:</p> <pre><code>&lt;ul id="menu"&gt; &lt;li&gt;&lt;a href="/" title="HOME"&gt;HOME&lt;/a&gt;&lt;/li&gt; &lt;li&gt; &lt;a href="/" title="ECO ENERGY"&gt;ECO ENERGY&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/Evaluations" title="Evaluations"&gt;Evaluations&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Incentives" title="Incentives"&gt;Incentives&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/HouseFiles" title="House Files"&gt;House Files&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/UpdateSubmissions" title="Update Submissions"&gt;Update Submissions&lt;/a&gt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="/" title="NEW HOMES"&gt;NEW HOMES&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/NH" title="Evaluations"&gt;Evaluations&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>#menu { background-color: #206676; float: left; width: 100%; height: 60px; } ul#menu { font-size: 1.3em; font-weight: 600; margin: 0 0 5px; padding: 0; text-align: left; } ul#menu li { display: inline; list-style: none; padding-left: 15px; float: left; } ul#menu li a { background: none; color: #FFF; text-decoration: none; } ul#menu li a:hover { color: #FFF; text-decoration: none; } ul#menu ul { display: none; } ul#menu li { display: inline; } ul#menu li:hover ul { display: block; } ul#menu li:hover ul li a { display: block; color: red; } </code></pre> <p>I have it to the point where I can toggle the colour when hovered over the main menu items, but just can't get them vertical. </p> <p><a href="http://jsfiddle.net/L5wB3/" rel="nofollow noreferrer">fiddle HERE</a></p>
21,997,973
4
0
null
2014-02-24 19:59:06.053 UTC
1
2016-11-07 14:00:39.917 UTC
2016-11-07 13:48:25.747 UTC
null
3,478,852
null
2,933,388
null
1
3
html|css|html-lists|horizontallist
52,043
<pre class="lang-css prettyprint-override"><code>ul#menu ul { display:none; position:absolute; left:0; top:20px; } ul#menu li { display:block; } </code></pre> <p>Most important changes. JSFIDDLE> <a href="http://jsfiddle.net/LSbvJ/" rel="nofollow noreferrer">http://jsfiddle.net/LSbvJ/</a> (You will have to tweak paddings, margins, text-align... but this is good start, I hope.)</p>
46,292,391
Authenticate users from more than two tables in laravel 5
<p>As I know <code>Auth::attempt</code> is used to authenticate users from <code>users</code> table, but i want to authenticate another users from <code>managers</code> table and admin from <code>admins</code> table. I know there are <code>laravel-multiauth</code> plugin already exist. But can we create our own <code>AuthServiceProvider</code> for authenticating users from multiple tables..?</p>
46,440,975
4
0
null
2017-09-19 05:21:22.06 UTC
11
2019-01-31 10:13:54.41 UTC
2017-09-21 05:35:54.397 UTC
null
5,662,524
null
5,662,524
null
1
36
php|laravel|authentication|laravel-5.2
34,995
<p>First create Admin Authenticatable in <code>Illuminate\Foundation\Auth</code> like </p> <pre><code> &lt;?php namespace Illuminate\Foundation\Auth; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class Admin extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword; } </code></pre> <p>Then create Admin Model by extending <code>Authenticatable</code> Admin Model :-</p> <pre><code> &lt;?php namespace App; use Illuminate\Foundation\Auth\Admin as Authenticatable; class Admin extends Authenticatable { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; } </code></pre> <p>After that you need to modify <code>config/auth.php</code> like below Add in <strong>providers</strong> array</p> <pre><code>'admins' =&gt; [ 'driver' =&gt; 'eloquent', 'model' =&gt; App\Admin::class, ], </code></pre> <p>and Add in <strong>guards</strong> array.</p> <pre><code> 'user' =&gt; [ 'driver' =&gt; 'session', 'provider' =&gt; 'users', ], 'admin' =&gt; [ 'driver' =&gt; 'session', 'provider' =&gt; 'admins', ], </code></pre> <p>Now to authenticate from <strong>user</strong> table </p> <pre><code> if (Auth::guard('user')-&gt;attempt(['email' =&gt; $email, 'password' =&gt; $password])) { $details = Auth::guard('user')-&gt;user(); $user = $details['original']; return $user; } else { return 'auth fail'; } </code></pre> <p>And to authenticate from <strong>Admin</strong> table</p> <pre><code> if (Auth::guard('admin')-&gt;attempt(['email' =&gt; $email, 'password' =&gt; $password])) { $details = Auth::guard('admin')-&gt;user(); $user = $details['original']; return $user; } else { return 'auth fail'; } </code></pre>
36,461,089
Time CountDown in angular 2
<p>I want to have a date countdown like this:</p> <p><a href="http://codepen.io/garethdweaver/pen/eNpWBb" rel="noreferrer">http://codepen.io/garethdweaver/pen/eNpWBb</a></p> <p>but in angular 2, I found this plunkr that adds 1 to a number each 500 miliseconds:</p> <p><a href="https://plnkr.co/edit/pVMEbbGSzMwSBS4XEXJI?p=preview" rel="noreferrer">https://plnkr.co/edit/pVMEbbGSzMwSBS4XEXJI?p=preview</a></p> <p>this is the code:</p> <pre><code>import {Component,Input} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'my-app', template: ` &lt;div&gt; {{message}} &lt;/div&gt; ` }) export class AppComponent { constructor() { Observable.interval(1000) .map((x) =&gt; x+1) .subscribe((x) =&gt; { this.message = x; }): } } </code></pre> <p>But I want to have a date taking one second until reach 0.</p>
36,466,740
6
0
null
2016-04-06 19:52:54.343 UTC
16
2019-11-22 07:42:59.293 UTC
2018-05-21 22:07:59.383 UTC
null
286,258
null
2,573,961
null
1
18
javascript|angular
38,037
<pre><code>import { Component, NgOnInit, ElementRef, OnInit, OnDestroy } from 'angular2/core'; import { Observable, Subscription } from 'rxjs/Rx'; @Component({ selector: 'my-app', template: ` &lt;div&gt; {{message}} &lt;/div&gt; ` }) export class AppComponent implements OnInit, OnDestroy { private future: Date; private futureString: string; private counter$: Observable&lt;number&gt;; private subscription: Subscription; private message: string; constructor(elm: ElementRef) { this.futureString = elm.nativeElement.getAttribute('inputDate'); } dhms(t) { var days, hours, minutes, seconds; days = Math.floor(t / 86400); t -= days * 86400; hours = Math.floor(t / 3600) % 24; t -= hours * 3600; minutes = Math.floor(t / 60) % 60; t -= minutes * 60; seconds = t % 60; return [ days + 'd', hours + 'h', minutes + 'm', seconds + 's' ].join(' '); } ngOnInit() { this.future = new Date(this.futureString); this.counter$ = Observable.interval(1000).map((x) =&gt; { return Math.floor((this.future.getTime() - new Date().getTime()) / 1000); }); this.subscription = this.counter$.subscribe((x) =&gt; this.message = this.dhms(x)); } ngOnDestroy(): void { this.subscription.unsubscribe(); } } </code></pre> <p>HTML:</p> <pre><code> &lt;my-app inputDate="January 1, 2018 12:00:00"&gt;Loading...&lt;/my-app&gt; </code></pre>
41,648,467
Getting json body in aws Lambda via API gateway
<p>I'm currently using NodeJS to build a bot on AWS lambda via AWS Api Gateway and I'm running into an issue with POST requests and JSON data. My api uses 'Use Lambda Proxy integration' and even when I test the proxy sending a content-type of Application/json and some json in the body e.g <code>{"foo":"bar"}</code> I can't access the object without parsing it first</p> <p>e.g</p> <pre><code> var json = JSON.parse(event.body); console.log(json.foo); </code></pre> <p>Now I know this doesn't seem a big deal just running it through JSON.parse, but I've seen a number of other examples where this isn't the case at all. see here <a href="https://github.com/pinzler/fb-messenger-bot-aws-lambda/blob/master/index.js" rel="noreferrer">https://github.com/pinzler/fb-messenger-bot-aws-lambda/blob/master/index.js</a></p> <p>Do I need to add anything to my API gateway to handle this correctly? my 'request body' step in the 'post method request' section has a content-type of application/json set-up for the request body. </p> <p>The readme for the example above doesn't seem to use proxy integration as far as I can tell so I'm not sure what I should be doing here</p>
41,656,022
5
0
null
2017-01-14 09:23:36.247 UTC
19
2022-05-10 14:06:02.963 UTC
2021-06-05 22:20:38.977 UTC
null
4,281,353
null
597,384
null
1
120
amazon-web-services|aws-lambda|aws-api-gateway
181,447
<p>There are two different Lambda integrations you can configure in API Gateway:</p> <ol> <li>Lambda non-proxy integration (<a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-custom-integrations.html" rel="noreferrer">docs</a>), also called Lambda custom integration</li> <li>Lambda proxy integration (<a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html" rel="noreferrer">docs</a>)</li> </ol> <p>For <strong>Lambda non-proxy integration</strong>, you can customise what you are going to pass to Lambda in the payload that you don't need to parse the body, but when you are using <strong>Lambda Proxy integration</strong> in API Gateway, API Gateway will proxy everything to Lambda in payload like this:</p> <pre><code>{ &quot;message&quot;: &quot;Hello me!&quot;, &quot;input&quot;: { &quot;path&quot;: &quot;/test/hello&quot;, &quot;headers&quot;: { &quot;Accept&quot;: &quot;text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8&quot;, &quot;Accept-Encoding&quot;: &quot;gzip, deflate, lzma, sdch, br&quot;, &quot;Accept-Language&quot;: &quot;en-US,en;q=0.8&quot;, &quot;CloudFront-Forwarded-Proto&quot;: &quot;https&quot;, &quot;CloudFront-Is-Desktop-Viewer&quot;: &quot;true&quot;, &quot;CloudFront-Is-Mobile-Viewer&quot;: &quot;false&quot;, &quot;CloudFront-Is-SmartTV-Viewer&quot;: &quot;false&quot;, &quot;CloudFront-Is-Tablet-Viewer&quot;: &quot;false&quot;, &quot;CloudFront-Viewer-Country&quot;: &quot;US&quot;, &quot;Host&quot;: &quot;wt6mne2s9k.execute-api.us-west-2.amazonaws.com&quot;, &quot;Upgrade-Insecure-Requests&quot;: &quot;1&quot;, &quot;User-Agent&quot;: &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48&quot;, &quot;Via&quot;: &quot;1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)&quot;, &quot;X-Amz-Cf-Id&quot;: &quot;nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==&quot;, &quot;X-Forwarded-For&quot;: &quot;192.168.100.1, 192.168.1.1&quot;, &quot;X-Forwarded-Port&quot;: &quot;443&quot;, &quot;X-Forwarded-Proto&quot;: &quot;https&quot; }, &quot;pathParameters&quot;: {&quot;proxy&quot;: &quot;hello&quot;}, &quot;requestContext&quot;: { &quot;accountId&quot;: &quot;123456789012&quot;, &quot;resourceId&quot;: &quot;us4z18&quot;, &quot;stage&quot;: &quot;test&quot;, &quot;requestId&quot;: &quot;41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9&quot;, &quot;identity&quot;: { &quot;cognitoIdentityPoolId&quot;: &quot;&quot;, &quot;accountId&quot;: &quot;&quot;, &quot;cognitoIdentityId&quot;: &quot;&quot;, &quot;caller&quot;: &quot;&quot;, &quot;apiKey&quot;: &quot;&quot;, &quot;sourceIp&quot;: &quot;192.168.100.1&quot;, &quot;cognitoAuthenticationType&quot;: &quot;&quot;, &quot;cognitoAuthenticationProvider&quot;: &quot;&quot;, &quot;userArn&quot;: &quot;&quot;, &quot;userAgent&quot;: &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48&quot;, &quot;user&quot;: &quot;&quot; }, &quot;resourcePath&quot;: &quot;/{proxy+}&quot;, &quot;httpMethod&quot;: &quot;GET&quot;, &quot;apiId&quot;: &quot;wt6mne2s9k&quot; }, &quot;resource&quot;: &quot;/{proxy+}&quot;, &quot;httpMethod&quot;: &quot;GET&quot;, &quot;queryStringParameters&quot;: {&quot;name&quot;: &quot;me&quot;}, &quot;stageVariables&quot;: {&quot;stageVarName&quot;: &quot;stageVarValue&quot;}, &quot;body&quot;: &quot;{\&quot;foo\&quot;:\&quot;bar\&quot;}&quot;, &quot;isBase64Encoded&quot;: false } } </code></pre> <p>For the example you are referencing, it is not getting the body from the original request. It is constructing the response body back to API Gateway. It should be in this format:</p> <pre><code>{ &quot;statusCode&quot;: httpStatusCode, &quot;headers&quot;: { &quot;headerName&quot;: &quot;headerValue&quot;, ... }, &quot;body&quot;: &quot;...&quot;, &quot;isBase64Encoded&quot;: false } </code></pre>
5,655,574
Converting string to ascii using ord()
<p>I must preface this by saying that I am a neophyte (learning), so please waive the omission of the obvious in deference to a man who has had limited exposure to your world (Python).</p> <p>My objective is to get string from a user and convert it to Hex and Ascii string. I was able to accomplish this successfully with hex (<code>encode("hex")</code>), but not so with ascii. I found the <code>ord()</code> method and attempted to use that, and if I just use: <code>print ord(i)</code>, the loop iterates the through and prints the values to the screen vertically, not where I want them. So, I attempted to capture them with a string array so I can concat them to a line of string, printing them horizontally under the 'Hex" value. I've just about exhausted my resources on figuring this out ... any help is appreciated. Thanks!</p> <pre><code>while True: stringName = raw_input("Convert string to hex &amp; ascii(type stop to quit): ") if stringName == 'stop': break else: convertedVal = stringName.encode("hex") new_list = [] convertedVal.strip() #converts string into char for i in convertedVal: new_list = ord(i) print "Hex value: " + convertedVal print "Ascii value: " + new_list </code></pre>
5,655,635
3
3
null
2011-04-13 21:00:35.887 UTC
3
2017-10-06 15:18:25.28 UTC
2011-04-13 21:09:17.107 UTC
null
9,453
null
706,808
null
1
6
python
43,581
<p>Is this what you're looking for?</p> <pre><code>while True: stringName = raw_input("Convert string to hex &amp; ascii(type stop to quit): ").strip() if stringName == 'stop': break print "Hex value: ", stringName.encode('hex') print "ASCII value: ", ', '.join(str(ord(c)) for c in stringName) </code></pre>
6,280,495
Populate HTML Table using Javascript
<p>I want to populate a predefined html table using JavaScript:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th scope="col"&gt;ID&lt;/th&gt; &lt;th scope="col"&gt;Name&lt;/th&gt; &lt;/tr&gt; &lt;div id='data'/&gt; &lt;/table&gt; </code></pre> <p>using </p> <pre><code>document.getElementById('data').innerHTML = .... </code></pre> <p>But since <code>&lt;div&gt;</code> is not allowed inside of <code>&lt;table&gt;</code> above code doesn't work. What is the correct way to achieve this?</p>
6,280,579
3
2
null
2011-06-08 14:35:00.907 UTC
4
2018-09-16 18:44:41.547 UTC
2018-09-16 18:44:41.547 UTC
null
4,370,109
null
43,960
null
1
17
javascript|html-table
64,463
<p>Instead of Div you can use tr and td.</p> <pre><code> &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function addRow(content,morecontent) { if (!document.getElementsByTagName) return; tabBody=document.getElementsByTagName("tbody").item(0); row=document.createElement("tr"); cell1 = document.createElement("td"); cell2 = document.createElement("td"); textnode1=document.createTextNode(content); textnode2=document.createTextNode(morecontent); cell1.appendChild(textnode1); cell2.appendChild(textnode2); row.appendChild(cell1); row.appendChild(cell2); tabBody.appendChild(row); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table border='1' id='mytable'&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;22&lt;/td&gt;&lt;td&gt;333&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;22&lt;/td&gt;&lt;td&gt;333&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;button onClick='addRow("123","456");return false;'&gt; Add Row&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
5,901,706
the bytes type in python 2.7 and PEP-358
<p>According to <a href="http://www.python.org/dev/peps/pep-0358/">PEP 358</a>, a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case.</p> <p>However, my python 2.7 says otherwise</p> <pre><code>&gt;&gt;&gt; bytes([1,2,3]) '[1, 2, 3]' &gt;&gt;&gt; bytes([280]) '[280]' &gt;&gt;&gt; bytes is str True &gt;&gt;&gt; bytes &lt;type 'str'&gt; </code></pre> <p>Does anyone have a clue on the reason why the PEP is declared Final, but the implementation does not conform ?</p>
5,901,849
3
0
null
2011-05-05 17:19:16.44 UTC
6
2014-10-30 11:43:57.927 UTC
2014-10-30 11:43:57.927 UTC
null
2,174,742
null
78,374
null
1
30
python|types
57,205
<p>The <code>bytes</code> type was introduced in Python 3, but what's being discussed in the PEP is a mutable sequence (<code>bytes</code> is immutable) which was introduced in Python 2.6 under the name <code>bytearray</code>.</p> <p>The PEP clearly wasn't implemented as stated (and it does say that it was partially superseded by <a href="http://www.python.org/dev/peps/pep-3137/" rel="noreferrer">PEP 3137</a>) but I think it's only a question of things being renamed, not features missing. In Python 2 <code>bytes</code> is just an alias for <code>str</code> to aid forward compatibility and so is a red-herring here.</p> <p>Example bytearray usage:</p> <pre><code>&gt;&gt;&gt; a = bytearray([1,2,3]) &gt;&gt;&gt; a[0] = 5 &gt;&gt;&gt; a bytearray(b'\x05\x02\x03') </code></pre>
5,819,305
XPathSelectElement always returns null
<p>Why is this Xpath not working using XDocument.XPathSelectElement?</p> <p>Xpath:</p> <pre><code>//Plugin/UI[1]/PluginPageCategory[1]/Page[1]/Group[1]/CommandRef[2] </code></pre> <p>XML</p> <pre><code>&lt;Plugin xmlns="http://www.MyNamespace.ca/MyPath"&gt; &lt;UI&gt; &lt;PluginPageCategory&gt; &lt;Page&gt; &lt;Group&gt; &lt;CommandRef&gt; &lt;Images&gt; &lt;/Images&gt; &lt;/CommandRef&gt; &lt;CommandRef&gt; &lt;Images&gt; &lt;/Images&gt; &lt;/CommandRef&gt; &lt;/Group&gt; &lt;/Page&gt; &lt;/PluginPageCategory&gt; &lt;/UI&gt; &lt;/Plugin&gt; </code></pre> <p>C# Code:</p> <pre><code>myXDocument.XPathSelectElement("//Plugin/UI[1]/PluginPageCategory[1]/Page[1]/Group[1]/CommandRef[2]", myXDocument.Root.CreateNavigator()); </code></pre>
5,819,560
4
6
null
2011-04-28 13:22:59.16 UTC
2
2018-10-23 18:17:54.273 UTC
null
null
null
null
613,568
null
1
38
c#|xml|xpath
21,582
<p>When namespaces are used, these must be used in the XPath query also. Your XPath query would only work against elements with no namespace (as can be verified by removing the namespace from your XML).</p> <p>Here's an example showing how you create and pass a namespace manager:</p> <pre><code>var xml = ... XML from your post ...; var xmlReader = XmlReader.Create( new StringReader(xml) ); // Or whatever your source is, of course. var myXDocument = XDocument.Load( xmlReader ); var namespaceManager = new XmlNamespaceManager( xmlReader.NameTable ); // We now have a namespace manager that knows of the namespaces used in your document. namespaceManager.AddNamespace( "prefix", "http://www.MyNamespace.ca/MyPath" ); // We add an explicit prefix mapping for our query. var result = myXDocument.XPathSelectElement( "//prefix:Plugin/prefix:UI[1]/prefix:PluginPageCategory[1]/prefix:Page[1]/prefix:Group[1]/prefix:CommandRef[2]", namespaceManager ); // We use that prefix against the elements in the query. Console.WriteLine(result); // &lt;CommandRef ...&gt; element is printed. </code></pre> <p>Hope this helps.</p>
2,023,408
How to implement the greater than or equal SQL statement in iBatis?
<p>Let's say in my sql statement I want to do:</p> <pre><code>WHERE numberOfCookies &gt;= 10 </code></pre> <p>How do I do this in iBatis? </p>
2,023,450
2
3
null
2010-01-07 20:27:49.33 UTC
3
2016-10-04 05:25:44.477 UTC
2010-01-07 21:25:05.05 UTC
null
39,371
null
39,371
null
1
22
sql|ibatis
41,094
<p>Because the SQL is written in xml, you cannot just use the symbol ">", you need to write it as:</p> <pre><code>WHERE numberOfCookies &amp;gt;= 10 </code></pre> <p><strong>Update:</strong></p> <p><code>&amp;gt;</code> for greater than</p> <p><code>&amp;lt;</code> for less than</p>
6,154,539
How can I wait for any/all pthreads to complete?
<p>I just want my main thread to wait for any and all my (p)threads to complete before exiting. </p> <p>The threads come and go a lot for different reasons, and I really don't want to keep track of all of them - I just want to know when they're all gone.</p> <p>wait() does this for child processes, returning ECHILD when there are no children left, however wait does not (appear to work with) (p)threads.</p> <p>I really don't want to go through the trouble of keeping a list of every single outstanding thread (as they come and go), then having to call pthread_join on each.</p> <p>As there a quick-and-dirty way to do this?</p>
6,155,499
5
0
null
2011-05-27 15:35:59.173 UTC
10
2015-06-18 13:38:53.35 UTC
null
null
null
null
221,768
null
1
36
c|linux|multithreading|pthreads|posix-api
59,306
<p>The proper way is to keep track of all of your pthread_id's, but you asked for a quick and dirty way so here it is. Basically:</p> <ul> <li>just keep a total count of running threads, </li> <li>increment it in the main loop before calling pthread_create, </li> <li>decrement the thread count as each thread finishes. </li> <li>Then sleep at the end of the main process until the count returns to 0.</li> </ul> <p>.</p> <pre><code>volatile int running_threads = 0; pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER; void * threadStart() { // do the thread work pthread_mutex_lock(&amp;running_mutex); running_threads--; pthread_mutex_unlock(&amp;running_mutex); } int main() { for (i = 0; i &lt; num_threads;i++) { pthread_mutex_lock(&amp;running_mutex); running_threads++; pthread_mutex_unlock(&amp;running_mutex); // launch thread } while (running_threads &gt; 0) { sleep(1); } } </code></pre>
5,868,850
creating list of objects in Javascript
<p>Is it possible to do create a <code>list</code> of your own objects in <code>Javascript</code>? This is the type of data I want to store :</p> <pre><code>Date : 12/1/2011 Reading : 3 ID : 20055 Date : 13/1/2011 Reading : 5 ID : 20053 Date : 14/1/2011 Reading : 6 ID : 45652 </code></pre>
5,868,876
6
1
null
2011-05-03 11:35:11.41 UTC
16
2021-10-03 19:54:28.523 UTC
2018-07-23 13:11:32.28 UTC
null
5,835,763
null
517,406
null
1
118
javascript
596,995
<pre><code>var list = [ { date: '12/1/2011', reading: 3, id: 20055 }, { date: '13/1/2011', reading: 5, id: 20053 }, { date: '14/1/2011', reading: 6, id: 45652 } ]; </code></pre> <p>and then access it:</p> <pre><code>alert(list[1].date); </code></pre>
5,779,561
Is it always best practice to declare a variable?
<p>I'm new to C# and any form of programming, and I have a question that seems to divide those in the know in my university faculty. That question is simply: do I always have to declare a variable? As a basic example of what I'm talking about: If I have <code>int pounds</code> and <code>int pence</code> do I need to declare <code>int money</code> into which to put the answer or is it ok to just have: </p> <pre><code>textbox1.Text = (pounds + pence).ToString(); </code></pre> <p>I know both work but i'm thinking in terms of best practice.</p> <p>Thanks in advance.</p>
5,779,612
10
3
null
2011-04-25 14:48:51.807 UTC
1
2011-04-27 10:05:09.58 UTC
2011-04-25 14:55:09.837 UTC
null
214
null
632,318
null
1
28
c#|variables|coding-style
4,368
<p>In my opinion the answer is "no". You should, however, use variables in some cases:</p> <ul> <li>Whenever a value is used multiple times</li> <li>When a call to an expensive function is done, or one that has side-effects</li> <li>When the expression needs to be made more self-explaining, variable (with meaningful names) do help</li> </ul> <p>Basically, follow your common sense. The code should be self-explaining and clear, if introducing variables helps with that then use them.</p>
5,967,412
Issue with C++ constructor
<p><strong>EDIT:</strong> This question came up and I think I aced it! Go StackOverflow!! :D</p> <p>I have exams coming up, and one of the questions on last year's exams was to spot the problem with implementation of the following constructor and to write a corrected one.</p> <pre><code>Rectangle::Rectangle(string col, int len, int br) { setColour(col); length =len; breadth=br; } </code></pre> <p>The class definitions are as follows:</p> <pre><code>class Polygon { public: Polygon(string col="red"); void printDetails(); // prints colour only virtual double getArea()=0; void setColour(string col); private: string colour; }; class Rectangle : public Polygon { public: Rectangle(string, int, int); void printDetails(); // prints colour and area // for part 3, delete the line below double getArea(); private: int length; int breadth; }; </code></pre> <p>I've written the code into the compiler and it runs fine. I'm guessing the question is relating to inheritance, since <code>string colour;</code> is private, but <code>setColour</code> is public so I cant figure it out. Unless its <code>Rectangle::Rectangle(string col, int len, int br):length(len), breadth(br)</code> and then set the colour inside the construcor or something.</p> <p>Its only worth 3 marks so its not that big a deal if nobody wants to answer, but I figure if I'm going to have a career as a programmer, its in my interest to know as much as possible. ;)</p> <p>Thanks for any help.</p> <p><strong>PS</strong>, see <code>getArea()</code> in <code>Rectangle</code>. When I remove that it tells me it "cannot instantiate the abstract class". What does that mean?</p> <p>EDIT: Here's the main:</p> <pre><code>void main (void) { Rectangle rect1 ("blue",5,6); Rectangle *prect2 = new Rectangle("red",5,6); rect1.setColour("red"); rect1.printDetails(); prect2-&gt;printDetails(); } </code></pre>
5,967,492
10
3
null
2011-05-11 16:15:12.267 UTC
3
2014-03-05 17:02:49.9 UTC
2014-03-05 17:02:49.9 UTC
null
2,954,323
null
652,410
null
1
37
c++|constructor
923
<p>I don't see anything wrong, though you could make it more efficient by using an initialization list (otherwise your private members of both classes get initialized twice):</p> <pre><code>Rectangle::Rectangle(string col, int len, int br) : Polygon(col), length(len), breadth(br) { } </code></pre> <p>Notice that the initialization list can call the constructor of Polygon as well.</p> <p>See <a href="https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list/926795#926795">Why should I prefer to use member initialization list?</a> for a complete description of the advantages of using initialization lists.</p>
5,957,822
How to clear basic authentication details in chrome
<p>I'm working on a site that uses basic authentication. Using Chrome I've logged in using the basic auth. I now want to remove the basic authentication details from the browser and try a different login.</p> <p>How do you clear the current basic authentication details when using Chrome?</p>
6,224,994
26
7
null
2011-05-11 00:05:07.8 UTC
71
2022-04-07 05:43:01.58 UTC
2016-10-12 12:34:42.993 UTC
null
4,823,977
null
162,337
null
1
461
google-chrome|basic-authentication
274,390
<p>It seems chrome will always show you the login prompt if you include a username in the url e.g.</p> <p><a href="http://[email protected]" rel="noreferrer">http://[email protected]</a></p> <p>This is not a real full solution, see <a href="https://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome#comment16379705_6224994">Mike's comment</a> below.</p>
46,207,530
Filtering pandas dataframe with multiple Boolean columns
<p>I am trying to filter a df using several Boolean variables that are a part of the df, but have been unable to do so. </p> <p>Sample data:</p> <pre><code>A | B | C | D John Doe | 45 | True | False Jane Smith | 32 | False | False Alan Holmes | 55 | False | True Eric Lamar | 29 | True | True </code></pre> <p>The dtype for columns C and D is Boolean. I want to create a new df (df1) with only the rows where either C or D is True. It should look like this:</p> <pre><code>A | B | C | D John Doe | 45 | True | False Alan Holmes | 55 | False | True Eric Lamar | 29 | True | True </code></pre> <p>I've tried something like this, which faces issues because it cant handle the Boolean type: </p> <pre><code>df1 = df[(df['C']=='True') or (df['D']=='True')] </code></pre> <p>Any ideas?</p>
46,207,540
5
1
null
2017-09-13 22:06:40.257 UTC
12
2019-10-08 17:07:56.663 UTC
2018-01-10 22:58:19.923 UTC
null
5,741,205
null
8,570,909
null
1
32
python|pandas|numpy|dataframe|boolean
91,101
<pre><code>In [82]: d Out[82]: A B C D 0 John Doe 45 True False 1 Jane Smith 32 False False 2 Alan Holmes 55 False True 3 Eric Lamar 29 True True </code></pre> <p><strong>Solution 1:</strong></p> <pre><code>In [83]: d.loc[d.C | d.D] Out[83]: A B C D 0 John Doe 45 True False 2 Alan Holmes 55 False True 3 Eric Lamar 29 True True </code></pre> <p><strong>Solution 2:</strong></p> <pre><code>In [94]: d[d[['C','D']].any(1)] Out[94]: A B C D 0 John Doe 45 True False 2 Alan Holmes 55 False True 3 Eric Lamar 29 True True </code></pre> <p><strong>Solution 3:</strong></p> <pre><code>In [95]: d.query("C or D") Out[95]: A B C D 0 John Doe 45 True False 2 Alan Holmes 55 False True 3 Eric Lamar 29 True True </code></pre> <p>PS If you change your solution to:</p> <pre><code>df[(df['C']==True) | (df['D']==True)] </code></pre> <p>it'll work too</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer">Pandas docs - boolean indexing</a></p> <hr> <blockquote> <p><a href="https://stackoverflow.com/questions/46207530/filtering-pandas-dataframe-with-multiple-boolean-columns/46207540?noredirect=1#comment101065544_46207540">why we should NOT use "PEP complaint" <code>df["col_name"] is True</code> instead of <code>df["col_name"] == True</code>?</a></p> </blockquote> <pre><code>In [11]: df = pd.DataFrame({"col":[True, True, True]}) In [12]: df Out[12]: col 0 True 1 True 2 True In [13]: df["col"] is True Out[13]: False # &lt;----- oops, that's not exactly what we wanted </code></pre>
5,586,564
ASP.NET - Access Session from static method/static class?
<p>I would like to access the session object without passing it to my static helper function. </p> <p>This is so I can save and load things from the session object automatically with minimum extra fluff.</p> <p>Is it possible/how can I access the session object from within a static method in a static class?</p>
5,586,590
1
0
null
2011-04-07 19:34:02.233 UTC
6
2014-06-29 10:00:45.247 UTC
null
null
null
null
299,408
null
1
44
asp.net|session|static
28,653
<pre><code>HttpContext.Current.Session </code></pre> <p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current%28v=vs.110%29.aspx">http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current(v=vs.110).aspx</a></p>
27,773,805
What does /p mean in set /p?
<p>What does <code>/p</code> stand for in <code>set /p=</code>? I know that <code>/</code> enables a switch, and I'm fairly sure that I know <code>/a</code> is for <code>arithmetic</code>. I've heard numerous rumours, some saying <code>/p</code> is for <code>prompt</code>, others stating it stands for <code>print</code>. The only reason I slightly doubt it is <code>prompt</code> is because in many cases it does not ask for a prompt, yet prints on the screen, such as</p> <pre><code>&lt;nul set /p=This will not generate a new line </code></pre> <p>But what I want to know is: <strong>Do we really know what it stands for?</strong></p>
27,773,874
2
1
null
2015-01-05 05:18:16.47 UTC
3
2022-04-12 16:24:36.287 UTC
2022-01-27 15:44:56.06 UTC
null
3,689,450
null
4,390,980
null
1
47
windows|batch-file|abbreviation
156,401
<p>For future reference, you can get help for any command by using the <code>/?</code> switch, which should explain what switches do what.</p> <p>According to the <code>set /?</code> screen, the format for <code>set /p</code> is <code>SET /P variable=[promptString]</code> which would indicate that the p in <code>/p</code> is &quot;prompt.&quot; It just prints in your example because <code>&lt;nul</code> passes in a nul character which immediately ends the prompt so it just <em>acts</em> like it's printing. It's still technically prompting for input, it's just immediately receiving it.</p> <hr> NOTE: The answers below this point are for a previous version of the question. <p><code>/L</code> in <code>for /L</code> generates a <strong>L</strong>ist of numbers.</p> <p>From <code>ping /?</code>:</p> <pre><code>Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [[-j host-list] | [-k host-list]] [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name Options: -t Ping the specified host until stopped. To see statistics and continue - type Control-Break; To stop - type Control-C. -a Resolve addresses to hostnames. -n count Number of echo requests to send. -l size Send buffer size. -f Set Don't Fragment flag in packet (IPv4-only). -i TTL Time To Live. -v TOS Type Of Service (IPv4-only. This setting has been deprecated and has no effect on the type of service field in the IP Header). -r count Record route for count hops (IPv4-only). -s count Timestamp for count hops (IPv4-only). -j host-list Loose source route along host-list (IPv4-only). -k host-list Strict source route along host-list (IPv4-only). -w timeout Timeout in milliseconds to wait for each reply. -R Use routing header to test reverse route also (IPv6-only). -S srcaddr Source address to use. -4 Force using IPv4. -6 Force using IPv6. </code></pre>
42,247,434
How to add mixins to ES6 javascript classes?
<p>In an ES6 class with some instance variables and methods, how can you add a mixin to it? I've given an example below, though I don't know if the syntax for the mixin object is correct.</p> <pre><code>class Test { constructor() { this.var1 = 'var1' } method1() { console.log(this.var1) } test() { this.method2() } } var mixin = { var2: 'var2', method2: { console.log(this.var2) } } </code></pre> <p>If I run <code>(new Test()).test()</code>, it will fail because there's no <code>method2</code> on the class, as it's in the mixin, that's why I need to add the mixin variables and methods to the class.</p> <p>I see there's a lodash mixin function <a href="https://lodash.com/docs/4.17.4#mixin" rel="noreferrer">https://lodash.com/docs/4.17.4#mixin</a>, but I don't know how I could use it with ES6 classes. I'm fine with using lodash for the solution, or even plain JS with no libraries to provide the mixin functionality.</p>
42,250,080
4
2
null
2017-02-15 10:59:10.697 UTC
11
2022-05-14 08:07:01.937 UTC
null
null
null
null
779,159
null
1
27
javascript|node.js|class|ecmascript-6|lodash
22,491
<p>Javascript's object/property system is much more dynamic than most languages, so it's very easy to add functionality to an object. As functions are first-class objects, they can be added to an object in exactly the same way. <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign" rel="noreferrer"><code>Object.assign</code></a> is the way to add the properties of one object to another object. (Its behaviour is in many ways comparable to <code>_.mixin</code>.)</p> <p>Classes in Javascript are only syntactic sugar that makes adding a constructor/prototype pair easy and clear. The functionality hasn't changed from pre-ES6 code.</p> <p>You can add the property to the prototype:</p> <pre><code>Object.assign(Test.prototype, mixin); </code></pre> <p>You could add it in the constructor to every object created:</p> <pre><code>constructor() { this.var1 = 'var1'; Object.assign(this, mixin); } </code></pre> <p>You could add it in the constructor based on a condition:</p> <pre><code>constructor() { this.var1 = 'var1'; if (someCondition) { Object.assign(this, mixin); } } </code></pre> <p>Or you could assign it to an object after it is created:</p> <pre><code>let test = new Test(); Object.assign(test, mixin); </code></pre>
9,044,970
How to change the background color of android status bar
<p>I want to change the background color of the status bar by writing an application. My android device has black color, I want to change it to some other color. I saw some posts related to it here, but they are telling about notification background.</p> <p>If any body knows about this please help me.</p> <p>The default status bar</p> <p><img src="https://i.stack.imgur.com/DGTX0.png" alt="enter image description here"></p> <p>After using a drawable as background to status bar</p> <p><img src="https://i.stack.imgur.com/k6Kzp.jpg" alt="enter image description here"></p>
9,045,146
5
0
null
2012-01-28 11:40:25.873 UTC
7
2021-06-20 19:35:39.153 UTC
2016-10-17 17:21:55.113 UTC
null
6,371,758
null
1,070,591
null
1
21
android|statusbar
51,150
<p>Sorry, unless you are making a custom ROM this isn't possible, unless you only want the status bar changed for your app.</p> <p>This would require a heck of a lot of work.</p> <p>First you will need to add Theme.NoTitleBar.Fullscreen to your manifest</p> <pre><code>&lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" &gt; </code></pre> <p>Then once you have done that you need to create a standard layout which represents the status bar, this would mean that you have to add the time, and also receive all the notifications from other apps, I do not personally know how to do that but I'm sure there is a way.</p> <p>If you really want to do this goodluck, you have a hard time ahead of you.</p> <hr> <p>Sorry, unless you have the knowledge how to build custom ROMS I do not think this is possible</p>
9,345,792
CMake executable location
<p>I have a very simple directory structure:</p> <pre><code>Project Project/src Project/build </code></pre> <p>Source files are in <code>Project/src</code>, and I do the out-of-src build in <code>Project/build</code>. After running <code>cmake ../ ; make</code>, I can run the executable thusly: <code>Project/build$ src/Executable</code> - that is, the <code>Executable</code> is created in the <code>build/src</code> directory. </p> <p>How do I set the location of the executable in the <code>CMakeLists.txt</code> file? I've attempted to follow some of the examples found at <code>cmake.org</code>, but the links that work don't seem to show this behaviour. </p> <p>My <code>Project/src/CMakeLists.txt</code> file is listed here. </p> <pre><code> include_directories(${SBSProject_SOURCE_DIR}/src) link_directories(${SBSProject_BINARY_DIR}/src) set ( SBSProject_SOURCES main.cpp ) add_executable( TIOBlobs ${SBSProject_SOURCES}) </code></pre> <p>And the top-level <code>Project/CMakeLists.txt</code>:</p> <pre><code> cmake_minimum_required (VERSION 2.6) project (SBSProject) set (CMAKE_CXX_FLAGS "-g3 -Wall -O0") add_subdirectory(src) </code></pre>
9,346,717
3
0
null
2012-02-19 01:21:35.057 UTC
3
2020-08-18 01:25:11.993 UTC
null
null
null
null
1,084,945
null
1
30
cmake
57,209
<p>You have a couple of choices.</p> <p>To change the default location of executables, set <code>CMAKE_RUNTIME_OUTPUT_DIRECTORY</code> to the desired location. For example, if you add</p> <pre><code>set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) </code></pre> <p>to your <code>Project/CMakeLists.txt</code> <strong>before</strong> the <code>add_subdirectory</code> command, your executable will end up in <code>Project/build</code> for Unix builds or <code>build/&lt;config type&gt;</code> for Win32 builds. For further details, run:</p> <pre><code>cmake --help-property RUNTIME_OUTPUT_DIRECTORY </code></pre> <p>Another option for a project of this size is to have just one CMakeLists.txt. You could more or less replace <code>add_subdirectory(src)</code> with the contents of <code>Project/src/CMakeLists.txt</code> to achieve the same output paths.</p> <p>However, there are a couple of further issues.</p> <p>You probably want to avoid using <code>link_directories</code> generally. For an explanation, run</p> <pre><code>cmake --help-command link_directories </code></pre> <p>Even if you do use <code>link_directories</code>, it's unlikely that any libraries will be found in <code>${SBSProject_BINARY_DIR}/src</code></p> <p>Another issue is that the <code>CMAKE_CXX_FLAGS</code> apply to Unix builds, so should probably be wrapped in an <code>if (UNIX) ... endif()</code> block. Of course, if you're not planning on building on anything other than Unix, this is a non-issue.</p> <p>Finally, I'd recommend requiring CMake 2.8 as a minimum unless you have to use 2.6 - CMake is an actively-developed project and the current version has many significant improvements over 2.6</p> <p>So a single replacement for <code>Project/CMakeLists.txt</code> could look like:</p> <pre><code>cmake_minimum_required (VERSION 2.8) project (SBSProject) if (UNIX) set (CMAKE_CXX_FLAGS "-g3 -Wall -O0") endif () include_directories (${SBSProject_SOURCE_DIR}/src) set (SBSProject_SOURCES ${SBSProject_SOURCE_DIR}/src/main.cpp ) add_executable (TIOBlobs ${SBSProject_SOURCES}) </code></pre>
9,323,738
Unable to get MacPort functionality after installing Xcode 4.3
<p>I am having trouble getting MacPorts to function properly. I just installed OSX Lion 10.7.3 I downloaded and installed MacPorts first, and then after reading the requirements, I downloaded Xcode4.3 from the App Store, and then installed it. I launched Xcode and it looks to be operational and functional. However when I attempted to port with MacPorts, it gave me this error message(excerpt):</p> <pre><code>Warning: xcodebuild exists but failed to execute Warning: Xcode does not appear to be installed; most ports will likely fail to build. </code></pre> <p>I followed the advice from:</p> <p><a href="https://stackoverflow.com/questions/7442447/how-do-i-install-additional-packages-for-xcode-on-osx-lion-to-allow-macports-to">How do i install additional packages for Xcode on OSX Lion to allow MacPorts to work</a></p> <p>and installed command_line_tools_for_xcode from the Preferences within Xcode. I closed Xcode, and again got the errors:</p> <pre><code>$ sudo port install libsocketsPassword: Warning: xcodebuild exists but failed to execute Warning: Xcode does not appear to be installed; most ports will likely fail to build. ---&gt; Computing dependencies for libsockets ---&gt; Dependencies to be installed: openssl zlib ---&gt; Extracting zlib Error: Couldn't determine your Xcode version (from '/usr/bin/xcodebuild -version'). Error: Error: If you have not installed Xcode, install it now; see: Error: http://guide.macports.org/chunked/installing.xcode.html Error: Error: Target org.macports.extract returned: unable to find Xcode Error: Failed to install zlib Log for zlib is at: /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_archivers_zlib/zlib/main.log Error: The following dependencies were not installed: openssl zlib Error: Status 1 encountered during processing. </code></pre> <p>I am uncertain where to go next with this. How do i trouble shoot my Xcode and MacPort interface? </p>
9,420,894
17
0
null
2012-02-17 06:14:32.99 UTC
29
2013-10-04 06:33:18.707 UTC
2017-05-23 10:30:44.547 UTC
null
-1
null
814,661
null
1
62
xcode|osx-lion|xcode4.3|macports
57,230
<p>In theory this should work if you have Xcode4.3 installed (in /Applications):</p> <pre><code>$ sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer/ </code></pre> <p>(And you've installed the optional command line tools)</p>
34,294,431
Using layer-list to display some drawable images
<blockquote> <p>Android studio 2.0 Preview 3b</p> </blockquote> <p>Hello,</p> <p>I have created the following layout that I want to use for a background for my app. I am using the <code>layer-list</code> and I want to display a bowl of peas in 2 locations. Everything looks ok in the preview, but when I run on genymotion or some cheap Chinese devices the image stretches across the screen. However, on the Android AVD, everything looks fine and on my Nexus 5 (real device) everything works ok.</p> <p>This is what I want and this is how it's displayed in the AVD and Nexus 5. As you can see there is no problem. <a href="https://i.stack.imgur.com/OvAjb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OvAjb.png" alt=""></a></p> <pre><code>&lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;shape&gt; &lt;gradient android:centerX="0.5" android:centerY="0.3" android:endColor="#08e25b" android:gradientRadius="300dp" android:startColor="#b7e9c9" android:type="radial" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item android:width="48dp" android:height="48dp" android:left="350dp" android:top="400dp"&gt; &lt;bitmap android:src="@drawable/peas" /&gt; &lt;/item&gt; &lt;item android:width="68dp" android:height="68dp" android:drawable="@drawable/peas" android:left="-20dp" android:top="480dp" /&gt; &lt;/layer-list&gt; </code></pre> <p>I have placed <code>peas.png</code> file in <code>drawable-nodpi</code> and just add the width and height in the <code>layer-list</code></p> <p>And when I run on the genymotion and some cheap smart devices I get the following: <a href="https://i.stack.imgur.com/9JT9f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9JT9f.png" alt="enter image description here"></a></p> <blockquote> <pre><code>Just quick summary. Nexus 5 real device and AVD devices works ok Genymotion and cheap smart devices doesn't display correctly </code></pre> </blockquote> <p>I am just confused in what I should believe. I have tried to use the bitmap as well to see if that would make any difference.</p> <p>Many thanks for any suggestions.</p>
34,373,777
2
1
null
2015-12-15 16:28:43.827 UTC
9
2022-04-18 12:33:56.537 UTC
2015-12-26 16:49:28.09 UTC
null
5,669,840
null
70,942
null
1
40
android|drawable|android-drawable|genymotion|layer-list
48,102
<p>Update your layer-list as follows</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt; &lt;item&gt; &lt;shape&gt; &lt;gradient android:centerX=&quot;0.5&quot; android:centerY=&quot;0.1&quot; android:endColor=&quot;#08e25b&quot; android:gradientRadius=&quot;300dp&quot; android:startColor=&quot;#b7e9c9&quot; android:type=&quot;radial&quot; /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item android:width=&quot;48dp&quot; android:height=&quot;48dp&quot; android:bottom=&quot;68dp&quot; android:right=&quot;-20dp&quot;&gt; &lt;bitmap android:gravity=&quot;bottom|right&quot; android:src=&quot;@drawable/peas&quot; /&gt; &lt;/item&gt; &lt;item android:width=&quot;68dp&quot; android:height=&quot;68dp&quot; android:bottom=&quot;-20dp&quot; android:left=&quot;-20dp&quot;&gt; &lt;bitmap android:gravity=&quot;bottom|left&quot; android:src=&quot;@drawable/peas&quot; /&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre>
10,379,622
How to run iPhone emulator WITHOUT starting Xcode?
<p>On my old Mac running Snow Leopard, I could type "ios" into spotlight and it would start up the iPhone/iPad emulator by itself.</p> <p>I have since had to get a new machine running Lion. I have installed Xcode for Lion, I have installed the developer tool options from the preferences panel.</p> <p>But the "ios" option is no longer there :( The only way now seems to be to run Xcode, create an empty project and then launch emulator with the run option.</p> <p>I have searched and searched the intertubes and the facewebs, but nothing helps.</p> <p>Does anyone know how to run only the emulator on Lion?</p> <p>UPDATE: THIS IS RESPONSE TO @ike_love thread below. THAT answer is not assured to work on all Yosemite machines.</p> <p><a href="https://i.stack.imgur.com/mtMeC.png"><img src="https://i.stack.imgur.com/mtMeC.png" alt="enter image description here"></a></p>
14,919,903
19
1
null
2012-04-30 06:53:03.76 UTC
86
2020-10-02 15:14:38.967 UTC
2016-06-16 23:31:39.28 UTC
null
809,944
null
796,446
null
1
262
xcode|osx-lion|ios-simulator
197,381
<p>The easiest way without fiddling with command line:</p> <ol> <li>launch Xcode once.</li> <li>run ios simulator</li> <li>drag the ios simulator icon to dock it. </li> </ol> <p>Next time you want to use it, just click on the ios simulator icon in the dock.</p>
10,636,120
Check if bool is defined in mixed C/C++
<p>So I'm having issues with some code that I've inherited. This code was building fine in a C-only environment, but now I need to use C++ to call this code. The header <code>problem.h</code> contains:</p> <pre><code>#ifndef _BOOL typedef unsigned char bool; static const bool False = 0; static const bool True = 1; #endif struct astruct { bool myvar; /* and a bunch more */ } </code></pre> <p>When I compile it as C++ code, I get <code>error C2632: 'char' followed by 'bool' is illegal</code></p> <p>I get the same error if I wrap the <code>#include "problem.h"</code> in <code>extern "C" { ... }</code> (which I don't understand, because there should be no keyword <code>bool</code> when compiling as C?)</p> <p>I tried removing the block from <code>#ifndef _BOOL</code> to <code>#endif</code>, and compiling as C++, and I get errors:</p> <p><code>error C2061: C requires that a struct or union has at least one member</code><br> <code>error C2061: syntax error: identifier 'bool'</code></p> <p>I just don't understand how the C++ compiler is complaining about a redefinition of <code>bool</code>, yet when I remove the redefinition and try to just use <code>bool</code> to define variables, it doesn't find anything.</p> <p>Any help is greatly appreciated.</p>
10,636,154
4
1
null
2012-05-17 12:54:14.61 UTC
5
2014-10-23 01:41:04.153 UTC
null
null
null
null
422,674
null
1
15
c++|c
39,279
<p>Because <code>bool</code> is a basic type in C++ (but not in C), and can't be redefined.</p> <p>You can surround your code with</p> <pre><code>#ifndef __cplusplus typedef unsigned char bool; static const bool False = 0; static const bool True = 1; #endif </code></pre>
10,623,114
Operation on ... may be undefined?
<p>I have the following code</p> <pre><code>FRAME frameArray[5][10]; // Create the array of frames int trackBufferFull[5] = {0, 0, 0, 0, 0};// Keeps track of how full the buffer for each node is int trackFront[5] = {0, 0, 0, 0, 0}; // Array to keep track of which is the front of the array int trackTail[5] = {0, 0, 0, 0, 0}; // Function to add to the array (CHANGE int frame) void addFrame (int nodeNumber, FRAME frame) { //Calc tail int tail = trackTail[nodeNumber-1]; // Calc frames in buffer int framesinBuffer = trackBufferFull[nodeNumber-1]; if (framesinBuffer == 10) { printf("Buffer is full\n"); } else { // Add frame to frameArray frameArray[nodeNumber-1][tail] = frame; printf("\nAdded a frame in node: %i to the buffer\n", nodeNumber); // Increment the count trackBufferFull[nodeNumber-1]++; trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10; } } </code></pre> <p>The arrays I use for frameArray is a wrap-around/cyclic array of length 10, hence why I have the code</p> <pre><code>trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10; </code></pre> <p>Everything works perfectly in a standalone file, however when run inside of a larger file, I get the following compile errors:</p> <pre><code>$ cnet GARETH -m 30 compiling gareth.c gareth.c: In function ‘addFrame’: gareth.c:77:27: error: operation on ‘trackTail[nodeNumber + -0x00000000000000001]’ may be undefined [-Werror=sequence-point] gareth.c: In function ‘removeFirstFrame’: gareth.c:98:28: error: operation on ‘trackFront[nodeNumber + -0x00000000000000001]’ may be undefined [-Werror=sequence-point] gareth.c:105:1: error: control reaches end of non-void function [-Werror=return-type] cc1: all warnings being treated as errors </code></pre> <p>Line 77 is the line </p> <pre><code>trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10; </code></pre> <p>Help. </p> <p>To see the code with line numbers and the errors side by side, I've uploaded an image to: <a href="https://i.imgur.com/wyO5a.png" rel="noreferrer">http://i.imgur.com/wyO5a.png</a></p>
10,623,165
3
1
null
2012-05-16 16:51:25.347 UTC
7
2018-07-15 13:06:51.44 UTC
2018-07-15 13:06:51.44 UTC
null
5,473,170
null
333,733
null
1
52
c|undefined-behavior
40,015
<blockquote> <p>Line 77 is the line</p> <pre><code>trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10; </code></pre> </blockquote> <p>You are changing <code>trackTail[nodeNumber-1]</code> twice between <a href="http://c-faq.com/expr/seqpoints.html" rel="noreferrer">sequence points</a>: once through <code>++</code>, and once through assignment.</p> <p>This is <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="noreferrer">undefined behaviour</a>.</p> <p>The remedy is to rephrase the statement, for example like so:</p> <pre><code>trackTail[nodeNumber-1] = (trackTail[nodeNumber-1] + 1) % 10; </code></pre> <p>or like so:</p> <pre><code>trackTail[nodeNumber-1]++; trackTail[nodeNumber-1] %= 10; </code></pre>
19,237,878
subsetting a Python DataFrame
<p>I am transitioning from R to Python. I just began using Pandas. I have an R code that subsets nicely:</p> <pre><code>k1 &lt;- subset(data, Product = p.id &amp; Month &lt; mn &amp; Year == yr, select = c(Time, Product)) </code></pre> <p>Now, I want to do similar stuff in Python. this is what I have got so far:</p> <pre><code>import pandas as pd data = pd.read_csv("../data/monthly_prod_sales.csv") #first, index the dataset by Product. And, get all that matches a given 'p.id' and time. data.set_index('Product') k = data.ix[[p.id, 'Time']] # then, index this subset with Time and do more subsetting.. </code></pre> <p>I am beginning to feel that I am doing this the wrong way. perhaps, there is an elegant solution. Can anyone help? I need to extract month and year from the timestamp I have and do subsetting. Perhaps there is a one-liner that will accomplish all this:</p> <pre><code>k1 &lt;- subset(data, Product = p.id &amp; Time &gt;= start_time &amp; Time &lt; end_time, select = c(Time, Product)) </code></pre> <p>thanks.</p>
19,237,920
5
1
null
2013-10-08 02:04:52.023 UTC
25
2020-06-16 18:32:38.47 UTC
2018-12-06 20:01:40.053 UTC
null
4,909,087
null
1,717,931
null
1
66
python|pandas|subset
181,435
<p>I'll assume that <code>Time</code> and <code>Product</code> are columns in a <code>DataFrame</code>, <code>df</code> is an instance of <code>DataFrame</code>, and that other variables are scalar values:</p> <p>For now, you'll have to reference the <code>DataFrame</code> instance:</p> <pre><code>k1 = df.loc[(df.Product == p_id) &amp; (df.Time &gt;= start_time) &amp; (df.Time &lt; end_time), ['Time', 'Product']] </code></pre> <p>The parentheses are also necessary, because of the precedence of the <code>&amp;</code> operator vs. the comparison operators. The <code>&amp;</code> operator is actually an overloaded bitwise operator which has the same precedence as arithmetic operators which in turn have a higher precedence than comparison operators.</p> <p>In <code>pandas</code> 0.13 a new experimental <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer"><code>DataFrame.query()</code></a> method will be available. It's extremely similar to subset modulo the <code>select</code> argument:</p> <p>With <code>query()</code> you'd do it like this:</p> <pre><code>df[['Time', 'Product']].query('Product == p_id and Month &lt; mn and Year == yr') </code></pre> <p>Here's a simple example:</p> <pre><code>In [9]: df = DataFrame({'gender': np.random.choice(['m', 'f'], size=10), 'price': poisson(100, size=10)}) In [10]: df Out[10]: gender price 0 m 89 1 f 123 2 f 100 3 m 104 4 m 98 5 m 103 6 f 100 7 f 109 8 f 95 9 m 87 In [11]: df.query('gender == "m" and price &lt; 100') Out[11]: gender price 0 m 89 4 m 98 9 m 87 </code></pre> <p>The final query that you're interested will even be able to take advantage of chained comparisons, like this:</p> <pre><code>k1 = df[['Time', 'Product']].query('Product == p_id and start_time &lt;= Time &lt; end_time') </code></pre>
17,963,962
Plot size and resolution with R markdown, knitr, pandoc, beamer
<p>Doesn't fit on the slide by default, doesn't even print by any other means.</p> <p>Here's the .Rmd: <strong>Edit: it seems you have to use plot() in every chunk. Second plot now prints.</strong></p> <pre><code># Plot should show at high resolution ```{r echo=FALSE, comment = ""} # load some data require(plyr) rbi &lt;- ddply(baseball, .(year), summarise, mean_rbi = mean(rbi, na.rm = TRUE)) ``` ```{r} # plot plot(mean_rbi ~ year, type = "l", data = rbi) ``` # Second attempt ```{r, fig.width = 2, fig.height = 2} plot(mean_rbi ~ year, type = "l", data = rbi) ``` # Third attempt ```{r, out.width = 2, out.height = 2} plot(mean_rbi ~ year, type = "l", data = rbi) ``` # Fourth attempt ```{r, out.width = '200px', out.height = '200px'} plot(mean_rbi ~ year, type = "l", data = rbi) ``` # Fifth attempt ```{r, out.width = '\\maxwidth'} plot(mean_rbi ~ year, type = "l", data = rbi) ``` </code></pre> <p>Save that as <code>test.Rmd</code> Then compile to tex using beamer:</p> <pre><code>knit("test.Rmd") system("pandoc -s -t beamer --slide-level 1 test.md -o test.tex") </code></pre> <p>Open <code>test.tex</code> in RStudio and click "Compile PDF".</p> <p>I've read Yihui's <a href="http://yihui.name/knitr/options#chunk_options">documentation</a> and hope I haven't missed something really obvious.</p> <p><strong>Edit</strong> new code incorporating Yihui's suggestions.</p> <pre><code>```{r setup, include=FALSE} opts_chunk$set(dev = 'pdf') ``` # Plot should show at high resolution ```{r echo=FALSE, comment = ""} # load some data require(plyr) rbi &lt;- ddply(baseball, .(year), summarise, mean_rbi = mean(rbi, na.rm = TRUE)) ``` ```{r} # plot plot(mean_rbi ~ year, type = "l", data = rbi) ``` # Second attempt ```{r, fig.width = 4, fig.height = 4} plot(mean_rbi ~ year, type = "l", data = rbi) ``` </code></pre> <p><code>sessionInfo()</code></p> <pre><code> R version 3.0.1 (16/05/2013) Platform: x86_64-pc-linux-gnu (64-bit) Local: [1] LC_CTYPE = en_US.UTF-8 LC_NUMERIC = C LC_TIME = C LC_COLLATE = C [5] LC_MONETARY=C LC_MESSAGES=C LC_PAPER=C LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=C LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] plyr_1.8 markdown_0.6 knitr_1.2 rCharts_0.3.51 slidify_0.3.52 loaded via a namespace (and not attached): [1] RJSONIO_1.0-3 codetools_0.2-8 digest_0.6.3 evaluate_0.4.3 formatR_0.8 [6] grid_3.0.1 lattice_0.20-15 stringr_0.6.2 tools_3.0.1 whisker_0.3-2 [11] yaml_2.1.7 </code></pre>
17,964,587
2
1
null
2013-07-31 07:16:58.777 UTC
22
2019-05-30 03:53:43.85 UTC
2013-07-31 09:01:56.257 UTC
null
559,676
null
937,932
null
1
73
r|knitr|pandoc|beamer|r-markdown
117,143
<p>I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from <code>knitr</code>), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:</p> <pre><code>```{r setup, include=FALSE} knitr::opts_chunk$set(dev = 'pdf') ``` </code></pre> <p>Then all the images will be written as PDF files, and LaTeX will be happy.</p> <p>Your second problem is you are mixing up the HTML units with LaTeX units in <code>out.width</code> / <code>out.height</code>. LaTeX and HTML are very different technologies. You should not expect <code>\maxwidth</code> to work in HTML, or <code>200px</code> in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set <code>out.width</code> / <code>out.height</code> (use <code>fig.width</code> / <code>fig.height</code> and let LaTeX use the original size).</p>
35,781,197
Generating a random, fixed-length byte array in Go
<p>I have a byte array, with a fixed length of 4.</p> <pre><code>token := make([]byte, 4) </code></pre> <p>I need to set each byte to a random byte. How can I do so, in the most efficient matter? The <code>math/rand</code> methods do not provide a Random Byte function, as far as I am concerned. </p> <p>Perhaps there is a built-in way, or should I go with generating a random string and converting it to a byte array?</p>
35,781,353
3
1
null
2016-03-03 19:24:25.343 UTC
7
2019-08-01 19:46:37.457 UTC
2018-07-14 20:05:18.553 UTC
null
1,705,598
null
3,902,473
null
1
44
arrays|go|random|slice
43,099
<blockquote> <p><a href="https://golang.org/pkg/math/rand/" rel="noreferrer">Package rand</a></p> <pre><code>import "math/rand" </code></pre> <p><a href="https://golang.org/pkg/math/rand/#Read" rel="noreferrer">func Read</a></p> <pre><code>func Read(p []byte) (n int, err error) </code></pre> <p>Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error.</p> <p>f<a href="https://golang.org/pkg/math/rand/#Rand.Read" rel="noreferrer">unc (*Rand) Read</a></p> <pre><code>func (r *Rand) Read(p []byte) (n int, err error) </code></pre> <p>Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error.</p> </blockquote> <p>For example,</p> <pre><code>package main import ( "math/rand" "fmt" ) func main() { token := make([]byte, 4) rand.Read(token) fmt.Println(token) } </code></pre> <p>Output:</p> <pre><code>[187 163 35 30] </code></pre>
3,817,997
How to reset mysql pointer back to the first row in PHP?
<pre><code>while($row = mysql_fetch_array($result)){ echo $row['id'];} </code></pre> <p>If I use the above code two times consecutively, the row does not get printed twice.</p> <p>How to reset it?</p>
3,818,019
1
0
null
2010-09-29 00:32:48.25 UTC
6
2016-07-07 15:29:59.787 UTC
null
null
null
user244333
null
null
1
23
php|mysql
44,840
<p>use <a href="http://ca2.php.net/manual/en/function.mysql-data-seek.php" rel="noreferrer">mysql_data_seek</a>. This function will allow you to move the internal result pointer.</p>
3,629,259
How do I do a JPQL SubQuery?
<p>It is possible to do the equivalent of this sql query in JPQL?</p> <pre><code>SELECT * FROM COUNTRIES c WHERE COUNTRY_ID IN ( SELECT DISTINCT COUNTRY_ID FROM PORTS p WHERE p.COUNTRY_ID = c.COUNTRY_ID AND STATE = 'A' ) </code></pre>
3,629,921
1
0
null
2010-09-02 16:45:57.903 UTC
9
2017-11-02 12:37:01.377 UTC
2017-03-21 13:18:28.673 UTC
null
4,823,977
null
405,739
null
1
29
java|orm|jpa|jpql
85,350
<p>You need to test it with <a href="http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/jpa_langref.html#jpa_langref_in" rel="noreferrer">IN</a> and <a href="http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/jpa_langref.html#jpa_langref_subqueries" rel="noreferrer">subquery</a> since both do work in JPQL (according to syntax reference they do work together). You may also look at <a href="http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/jpa_langref.html#jpa_langref_collection_member" rel="noreferrer">MEMBER OF expressions</a>.</p> <p>But there is a better approach in my opinion. Such queries are called correlated sub-queries and one can always re-write them using EXISTS:</p> <pre><code>SELECT * FROM COUNTRIES c WHERE EXISTS ( SELECT 'found' FROM PORTS p WHERE p.COUNTRY_ID = c.COUNTRY_ID AND STATE = 'A' ) </code></pre> <p>JPQL supports <a href="http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/jpa_langref.html#jpa_langref_exists" rel="noreferrer">EXISTS with subqueries</a>.</p>
21,349,984
How to make Bootstrap carousel slider use mobile left/right swipe
<p><a href="http://jsfiddle.net/KY5Tu/1/"><strong>DEMO JSSFIDDLE</strong></a></p> <pre><code> &lt;div class="col-md-4"&gt; &lt;!--Carousel--&gt; &lt;div id="sidebar-carousel-1" class="carousel slide" data-ride="carousel"&gt; &lt;ol class="carousel-indicators grey"&gt; &lt;li data-target="#sidebar-carousel-1" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#sidebar-carousel-1" data-slide-to="1"&gt;&lt;/li&gt; &lt;li data-target="#sidebar-carousel-1" data-slide-to="2"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;div class="carousel-inner"&gt; &lt;div class="item active"&gt; &lt;a href="" data-lightbox="image-1" title=""&gt; &lt;img src="http://shrani.si/f/3D/13b/1rt3lPab/2/img1.jpg" alt="..."&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;a href="" data-lightbox="image-1" title=""&gt; &lt;img src="http://shrani.si/f/S/jE/UcTuhZ6/1/img2.jpg" alt="..."&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;a href="" data-lightbox="image-1" title=""&gt; &lt;img src="http://shrani.si/f/h/To/1yjUEZbP/img3.jpg" alt="..."&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Controls --&gt; &lt;a class="left carousel-control" href="#sidebar-carousel-1" data-slide="prev"&gt; &lt;span class="glyphicon glyphicon-chevron-left"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#sidebar-carousel-1" data-slide="next"&gt; &lt;span class="glyphicon glyphicon-chevron-right"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt;&lt;!--/Carousel--&gt;&lt;/div&gt; </code></pre> <p>What I want to do is to add left/right touch swipe functionality for mobile devices only. How can I do that?</p> <p>Also, how do I make prev/next buttons, that appear on hover, smaller for mobile/ipad versions?</p> <p>Thanks</p>
21,350,139
10
2
null
2014-01-25 11:33:57.55 UTC
46
2020-12-12 05:48:43.203 UTC
2014-02-18 12:48:12.62 UTC
null
1,053,103
null
3,187,469
null
1
72
jquery|html|css|twitter-bootstrap-3|carousel
243,704
<p><strong>UPDATE:</strong></p> <p>I came up with this solution when I was pretty new to web design. Now that I am older and wiser, the answer <strong>Liam</strong> gave seems to be a better option. See the next top answer; it is a more productive solution.</p> <p>I worked on a project recently and this example worked perfectly. I am giving you the link below.</p> <p>First you have to add jQuery mobile:</p> <p><a href="http://jquerymobile.com/" rel="noreferrer">http://jquerymobile.com/</a></p> <p>This adds the touch functionality, and then you just have to make events such as swipe:</p> <pre><code>&lt;script&gt; $(document).ready(function() { $(&quot;#myCarousel&quot;).swiperight(function() { $(this).carousel('prev'); }); $(&quot;#myCarousel&quot;).swipeleft(function() { $(this).carousel('next'); }); }); &lt;/script&gt; </code></pre> <p>The link is below, where you can find the tutorial I used:</p> <p><a href="http://lazcreative.com/blog/how-to/how-to-adding-swipe-support-to-bootstraps-carousel/" rel="noreferrer">http://lazcreative.com/blog/how-to/how-to-adding-swipe-support-to-bootstraps-carousel/</a></p>
28,215,625
android:load svg file from web and show it on image view
<p>I want to load a svg file from the web and show this file in an ImageView. For non vector images I use the <a href="http://square.github.io/picasso/" rel="noreferrer">Picasso</a> library. </p> <p>Is it possible to use this library for svg files as well?<br> Is there any way to load svg files from the web and show it in an ImageView?<br> I use the <a href="https://code.google.com/p/svg-android/" rel="noreferrer">svg-android</a> library to show svg files but i don't know how to get svg images from the web all the examples for this library use local files.</p>
28,215,776
8
1
null
2015-01-29 13:11:31.79 UTC
16
2021-12-25 16:38:27.63 UTC
2019-11-06 11:16:56.94 UTC
null
114,066
null
377,983
null
1
35
android|svg|imageview|picasso|svg-android
53,280
<p>Please refer to <a href="https://stackoverflow.com/questions/18356098/having-issue-on-real-device-using-vector-image-in-android-svg-android">Having issue on Real Device using vector image in android. SVG-android</a></p> <p>In the users post he asks a similar question and suggest he uses:</p> <p>Create a member variable for the ImageView in your layout file;</p> <pre><code>private ImageView mImageView; // intialize in onCreate(Bundle savedInstanceState) mImageView = (ImageView) findViewById(R.id.image_view); </code></pre> <p>Download the image</p> <pre><code>private class HttpImageRequestTask extends AsyncTask&lt;Void, Void, Drawable&gt; { @Override protected Drawable doInBackground(Void... params) { try { final URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/e/e8/Svg_example3.svg"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); SVG svg = SVGParser. getSVGFromInputStream(inputStream); Drawable drawable = svg.createPictureDrawable(); return drawable; } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } return null; } @Override protected void onPostExecute(Drawable drawable) { // Update the view updateImageView(drawable); } } </code></pre> <p>Then Apply the drawable to the Imageview</p> <pre><code>@SuppressLint("NewApi") private void updateImageView(Drawable drawable){ if(drawable != null){ // Try using your library and adding this layer type before switching your SVG parsing mImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); mImageView.setImageDrawable(drawable); } } </code></pre> <p>SVGParser is available at <a href="https://github.com/pents90/svg-android" rel="noreferrer">https://github.com/pents90/svg-android</a></p>
28,322,464
In Java 8, transform Optional<String> of an empty String in Optional.empty
<p>Given a String I need to get an Optional, whereby if the String is null or empty the result would be Optional.empty. I can do it this way:</p> <pre><code>String ppo = ""; Optional&lt;String&gt; ostr = Optional.ofNullable(ppo); if (ostr.isPresent() &amp;&amp; ostr.get().isEmpty()) { ostr = Optional.empty(); } </code></pre> <p>But surely there must be a more elegant way.</p>
28,322,647
6
1
null
2015-02-04 13:19:42.977 UTC
7
2018-11-08 17:17:58.817 UTC
2015-02-04 18:30:44.937 UTC
null
829,571
null
1,090,394
null
1
54
java|java-8|option-type
71,343
<p>You could use a filter:</p> <pre><code>Optional&lt;String&gt; ostr = Optional.ofNullable(ppo).filter(s -&gt; !s.isEmpty()); </code></pre> <p>That will return an empty Optional if <code>ppo</code> is null or empty.</p>
28,338,775
What is ios::in|ios::out?
<p>I was reading some project code and I found this,here <code>MembersOfLibrary()</code> is a constructor of <code>class MenberOfLibrary</code></p> <pre class="lang-cpp prettyprint-override"><code>class MembersOfLibrary { public: MembersOfLibrary(); ~MembersOfLibrary() {} void addMember(); void removeMember(); unsigned int searchMember(unsigned int MembershipNo); void searchMember(unsigned char * name); void displayMember(); private: Members libMembers; }; MembersOfLibrary::MembersOfLibrary() { fstream memberData; memberData.open(&quot;member.txt&quot;, ios::in|ios::out); if(!memberData) { cout&lt;&lt;&quot;\nNot able to create a file. MAJOR OS ERROR!! \n&quot;; } memberData.close(); } </code></pre> <p>What is <code>ios::in|ios::out</code>?</p>
28,338,924
3
1
null
2015-02-05 07:52:26.903 UTC
9
2021-08-08 13:56:02.79 UTC
2021-08-08 13:56:02.79 UTC
null
11,573,842
null
4,479,716
null
1
23
c++|file-handling
66,271
<ul> <li><code>ios::in</code> allows input (read operations) from a stream.</li> <li><code>ios::out</code> allows output (write operations) to a stream.</li> <li><code>|</code> (bitwise OR operator) is used to combine the two <code>ios</code> flags,<br> meaning that passing <code>ios::in | ios::out</code> to the constructor<br> of <code>std::fstream</code> enables <em>both</em> input and output for the stream.</li> </ul> <hr> <p><strong>Important things to note:</strong></p> <ul> <li><code>std::ifstream</code> automatically has the <code>ios::in</code> flag set.</li> <li><code>std::ofstream</code> automatically has the <code>ios::out</code> flag set.</li> <li><code>std::fstream</code> has neither <code>ios::in</code> or <code>ios::out</code> automatically<br> set. That's why they're explicitly set in your example code.</li> </ul>
1,844,510
C# string to float?
<p>I have this bit of code here:</p> <pre><code>int i = 0; StreamReader re = File.OpenText("TextFile1.txt"); string input = null; while ((input = re.ReadLine()) != null) { string[] sites = input.Split(' '); for (int j = 0; j &lt; sites.Length; j++) { MyArray[i, j] = Convert.ToInt32(sites[j]); } i++; } for (int a = 0; a &lt; 5; a++) { for (int j = 0; j &lt; 5; j++) { Console.Write(MyArray[a, j] + " "); } Console.WriteLine(); } </code></pre> <p>My problem is this line of code</p> <pre><code>MyArray[i, j] = Convert.ToInt32(sites[j]); </code></pre> <p>Its getting converted to an int, how do I convert it to a float?</p>
1,844,515
3
1
null
2009-12-04 02:33:45.18 UTC
null
2009-12-04 02:50:57.1 UTC
null
null
null
null
128,860
null
1
9
c#
61,691
<pre><code>MyArray[i, j] = Convert.ToSingle(sites[j]); </code></pre>
1,366,953
which eclipse project/workspace files should be added to source control?
<p>I want to share an eclipse project with the rest of my team through SVN. Which files should I add to subversion? In the workspace, there are <em>many</em> files which IMHO are not supposed to be on source control - they are a few megabytes in size.</p> <p>When adding just the project, another user who checks out the code still has to import the project into the workspace.</p> <p><strong><em>Edit:</em></strong> maybe the correct question here, is how can I share my eclipse <strong>workspace</strong> using subversion?</p>
1,366,966
3
1
null
2009-09-02 10:40:22.303 UTC
10
2016-06-24 18:33:31.88 UTC
null
null
null
null
38,557
null
1
17
eclipse|svn|workspace
9,982
<p>With Eclipse, you always have to import a project - there is no other way to do it - Eclipse won't detect projects if you just switch workspaces unless you've created/imported the project in that workspace before.</p> <p>You will need at a <strong>minimum</strong>:</p> <ul> <li>.project</li> <li>.classpath</li> </ul> <p>Personally I also add the settings folder, but its up to you:</p> <ul> <li>.settings</li> </ul> <p>Then other users choose <em>Import project</em> and select the <code>.project</code> file.</p>
1,875,800
element.setAttribute('style', 'attribute :value;') vs. element.attribute = 'value'
<p>In javascript is there any difference between using </p> <pre><code>element.style.setAttribute('width', '150px'); </code></pre> <p>and</p> <pre><code>element.style.width = '150px'; </code></pre> <p>? </p> <p>I have seen that keywords won't work with the first way (like <a href="http://www.quirksmode.org/bugreports/archives/2005/03/setAttribute_does_not_work_in_IE_when_used_with_th.html" rel="noreferrer">this</a>), but for non-keyword attributes is there a difference?</p>
1,875,824
3
0
null
2009-12-09 18:22:03.527 UTC
7
2021-05-10 10:45:36.977 UTC
2018-06-01 02:37:17.137 UTC
user9078605
null
null
225,085
null
1
23
javascript|html|internet-explorer|safari
66,339
<p>Both are perfectly valid. Can you give some examples which doesn't work in second way? Are you aware that attribute names needs to be <em>camelcased</em> first? E.g. <code>element.style.marginTop</code> instead of incorrectly <code>element.style.margin-top</code>. The hyphen is namely an invalid identifier in Javascript.</p>
1,404,131
How to get unique users across multiple Django sites powered by the "sites" framework?
<p>I am building a Django site framework which will power several independent sites, all using the same apps but with their own templates. I plan to accomplish this by using multiple settings-files and setting a unique SITE_ID for them, like suggested in the Django docs for the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/sites/" rel="noreferrer">django.contrib.sites framework</a> </p> <p>However, I don't want a user from site A to be able to login on site B. After inspecting the user table created by syncdb, I can see no column which might restrict a user to a specific site. I have also tried to create a user, 'bob', on one site and then using the shell command to list all users on the other side and sure enough, bob shows up there. </p> <p>How can I ensure all users are restricted to their respective sites?</p>
1,405,902
3
1
null
2009-09-10 08:46:00.57 UTC
18
2012-12-18 01:28:35.033 UTC
null
null
null
null
3,999
null
1
26
django|django-sites
4,705
<p>The most compatible way to do this would be to create a <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="noreferrer">user Profile model</a> that includes a foreign key to the Site model, then write a <a href="http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend" rel="noreferrer">custom auth backend</a> that checks the current site against the value of that FK. Some sample code:</p> <p>Define your profile model, let's say in app/models.py:</p> <pre><code>from django.db import models from django.contrib.sites.models import Site from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) site = models.ForeignKey(Site) </code></pre> <p>Write your custom auth backend, inheriting from the default one, let's say in app/auth_backend.py:</p> <pre><code>from django.contrib.auth.backends import ModelBackend from django.contrib.sites.models import Site class SiteBackend(ModelBackend): def authenticate(self, **credentials): user_or_none = super(SiteBackend, self).authenticate(**credentials) if user_or_none and user_or_none.userprofile.site != Site.objects.get_current(): user_or_none = None return user_or_none def get_user(self, user_id): try: return User.objects.get( pk=user_id, userprofile__site=Site.objects.get_current()) except User.DoesNotExist: return None </code></pre> <p>This auth backend assumes all users have a profile; you'd need to make sure that your user creation/registration process always creates one.</p> <p>The overridden <code>authenticate</code> method ensures that a user can only login on the correct site. The <code>get_user</code> method is called on every request to fetch the user from the database based on the stored authentication information in the user's session; our override ensures that a user can't login on site A and then use that same session cookie to gain unauthorized access to site B. (Thanks to Jan Wrobel for pointing out the need to handle the latter case.)</p>
1,746,092
Do I need to reset a stream(C#) back to the start?
<p>I don't know too much about streams in C#. Right now I have a stream that I put into a stream reader and read it. Later on in some other method I need to read the stream(same stream object) but this time I get this error</p> <pre><code>System.ArgumentException was unhandled by user code Message="Stream was not readable." Source="mscorlib" StackTrace: at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) at System.IO.StreamReader..ctor(Stream stream) at ExtractTitle(Stream file) in :line 33 at GrabWebPage(String webPath) in :line 62 at lambda_method(ExecutionScope , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.&lt;&gt;c__DisplayClassa.&lt;InvokeActionMethodWithFilters&gt;b__7() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) InnerException: </code></pre> <p>So I am thinking maybe by reading the stream it goes to the end. Then when I try to read it again it is at the end of the stream and thats why I am getting this error.</p> <p>So can anyone shed some light on this?</p> <p>Thanks</p>
1,746,108
3
0
null
2009-11-17 01:48:24.587 UTC
6
2018-01-11 19:30:15.807 UTC
2018-01-11 19:30:15.807 UTC
null
23,528
null
130,015
null
1
67
c#|.net
62,850
<p>When you read a stream to the end, specifically with <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx" rel="noreferrer"><code>StreamReader</code></a>'s <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx" rel="noreferrer"><code>ReadToEnd</code></a> method, you have to <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.seek.aspx" rel="noreferrer"><code>Seek</code></a> it back to the beginning. This can be done like so:</p> <pre><code>StreamReader sr = new StreamReader(stream); sr.ReadToEnd(); stream.Seek(0, SeekOrigin.Begin); //StreamReader doesn't have the Seek method, stream does. sr.ReadToEnd(); // This now works </code></pre>
8,781,531
CSS file link is not working on PHP page
<p>I have a Php page the code for which is below, I am trying to apply this signup.css but its not working. In PHP admin I can see the CSS shows up under Styles as SignUp.css, I have just placed this css in my theme directory under my theme as SignUp.css, I have tried "Signup.css" , created a css folder and put this css in there and tried "css/SignUp.css" but that did not work either. Please help . Thanks for your time</p> <pre><code>&lt;html&gt; &lt;link href="Styles/Signup.css" media="all" rel="stylesheet" type="text/css"/&gt; &lt;head&gt; &lt;title&gt;Create&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php if($_POST['action']=='create'){ //include database configuration $dbhost = "localhost"; $dbuser = "abc"; $dbpass = "xyz"; $dbname = "test"; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname) or die ('Unable to select database!'); //sql insert statement $sql="insert into user ( firstname, lastname, username, Email, password ) values ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['Email']}','{$_POST['username']}','{$_POST['password']}')"; //insert query to the database if(mysql_query($sql)){ //if successful query echo "New record was saved."; }else{ //if query failed die($sql."&gt;&gt;".mysql_error()); } } ?&gt; &lt;!--we have our html form here where user information will be entered--&gt; &lt;div id="stylized" class="myform"&gt; &lt;form id="form" name="form" method="post" action="index.html"&gt; &lt;h1&gt;Sign-up form&lt;/h1&gt; &lt;label&gt;Name &lt;span class="small"&gt;&lt;/span&gt; &lt;/label&gt; &lt;input type="text" name="name" id="name" /&gt; &lt;label&gt;Email &lt;span class="small"&gt;&lt;/span&gt; &lt;/label&gt; &lt;input type="text" name="email" id="email" /&gt; &lt;label&gt;Password &lt;span class="small"&gt;Min. size 6 chars&lt;/span&gt; &lt;/label&gt; &lt;input type="text" name="password" id="password" /&gt; &lt;button type="submit"&gt;Sign-up&lt;/button&gt; &lt;div class="spacer"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
8,782,149
3
1
null
2012-01-08 21:31:30.697 UTC
2
2020-03-18 17:21:15.437 UTC
null
null
null
null
1,137,572
null
1
4
php|css
49,732
<p>From you comments on existing answers, it doesn't look like something we could find out based on the provided code. Here are a couple of things that could help you diagnose the problem though.</p> <p>In your browser, open up developer tools. (For Firefox, get <a href="http://getfirebug.com/" rel="noreferrer">Firebug</a> and hit F12, For Chrome or Opera, just hit F12 for the built in tools.)</p> <p>Then you want to open up the network tab ('Net' in Firebug, 'Network' in Chrome)</p> <p>Once you have that open, reload the page and look at the server requests. One of them will be for your CSS file. What you want to look for is the HTTP status. If that Status is anything starting with a 4, you've got trouble. Either it's a 403 which means you don't have the correct permissions to load the file, or you'll have a 404, as we all know, 'not found', which would indicate that your URL is faulty.</p> <hr /> <p>Another way to quickly find out whether the file is actually loading is to view the source of the page in the browser, and click the link to the CSS file. In Firefox, doing that makes the source viewer load the contents of the CSS file instead. If that doesn't work out, you also get an idea that it can't be accessed. It's worth noting that the first method will make it clearer what exactly the issue is though.</p> <p>Most likely I assume you have a typo in your capitalisation of the file name or path. If it is hosted on a non-windows server, that almost certainly makes a difference.</p>