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
2,430,084
PHP: get number of decimal digits
<p>Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using <code>explode</code>)</p>
2,430,144
18
0
null
2010-03-12 02:17:10.103 UTC
10
2021-10-01 15:48:31.03 UTC
2018-06-23 22:34:08.74 UTC
null
2,370,483
null
243,231
null
1
70
php|decimal
79,954
<pre><code>$str = "1.23444"; print strlen(substr(strrchr($str, "."), 1)); </code></pre>
2,953,462
Pinging servers in Python
<p>In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?</p>
32,684,938
32
1
null
2010-06-01 21:27:21.747 UTC
64
2022-05-05 07:34:27.763 UTC
null
null
null
null
338,794
null
1
233
python|python-3.x|ping|icmp
722,451
<p><strong>This function works in any OS (Unix, Linux, macOS, and Windows)</strong><br> <strong>Python 2 and Python 3</strong></p> <p>EDITS:<br> By <a href="https://stackoverflow.com/users/797396/radato">@radato</a> <code>os.system</code> was replaced by <code>subprocess.call</code>. This avoids <a href="https://en.wikipedia.org/wiki/Shell_injection#Shell_injection" rel="noreferrer">shell injection</a> vulnerability in cases where your hostname string might not be validated.</p> <pre><code>import platform # For getting the operating system name import subprocess # For executing a shell command def ping(host): """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. """ # Option for the number of packets as a function of param = '-n' if platform.system().lower()=='windows' else '-c' # Building the command. Ex: "ping -c 1 google.com" command = ['ping', param, '1', host] return subprocess.call(command) == 0 </code></pre> <p>Note that, according to @ikrase on Windows this function will still return <code>True</code> if you get a <code>Destination Host Unreachable</code> error.</p> <p><strong>Explanation</strong></p> <p>The command is <code>ping</code> in both Windows and Unix-like systems.<br> The option <code>-n</code> (Windows) or <code>-c</code> (Unix) controls the number of packets which in this example was set to 1.</p> <p><a href="https://docs.python.org/library/platform.html#platform.system" rel="noreferrer"><code>platform.system()</code></a> returns the platform name. Ex. <code>'Darwin'</code> on macOS.<br> <a href="https://docs.python.org/library/subprocess.html#subprocess.call" rel="noreferrer"><code>subprocess.call()</code></a> performs a system call. Ex. <code>subprocess.call(['ls','-l'])</code>. </p>
25,279,646
How to Set Height of PdfPTable in iTextSharp
<p>i downloaded the last version of iTextSharp dll. I generated a PdfPTable object and i have to set it's height. Despite to set width of PdfPTable, im not able to set height of it. Some authors suggest to use 'setFixedHeight' method. But the last version of iTextSharp.dll has not method as 'setFixedHeight'. It's version is 5.5.2. How can i do it?</p>
25,287,384
3
0
null
2014-08-13 06:43:04.687 UTC
null
2016-12-15 10:42:31.77 UTC
null
null
null
null
2,545,946
null
1
9
height|itextsharp|pdfptable
53,381
<p>Setting a table's height doesn't make sense once you start thinking about it. Or, it makes sense but leaves many questions unanswered or unanswerable. For instance, if you set a two row table to a height of 500, does that mean that each cell get's 250 for a height? What if a large image gets put in the first row, should the table automatically respond by splitting 400/100? Then what about large content in both rows, should it squish those? Each of these scenarios produces different results that make knowing what a table will actually do unreliable. If you look at <a href="http://www.w3.org/TR/html401/struct/tables.html#h-11.2.1">the HTML spec</a> you'll see that they don't even allow setting a fixed height for tables.</p> <p>However, there's a simple solution and that's just setting the fixed height of the cells themselves. As long as you aren't using <code>new PdfPCell()</code> you can just set <code>DefaultCell.FixedHeight</code> to whatever you want.</p> <pre><code>var t = new PdfPTable(2); t.DefaultCell.FixedHeight = 100f; t.AddCell("Hello"); t.AddCell("World"); t.AddCell("Hello"); t.AddCell("World"); doc.Add(t); </code></pre> <p>If you are manually creating cells then you need to set the <code>FixedHeight</code> on each:</p> <pre><code>var t = new PdfPTable(2); for(var i=0;i&lt;4;i++){ var c = new PdfPCell(new Phrase("Hello")); c.FixedHeight = 75f; t.AddCell(c); } doc.Add(t); </code></pre> <p>However, if you want normal table-ness and must set a fixed height that chops things that don't fit you can also use a <code>ColumnText</code>. I wouldn't recommend this but you might have a case for it. The code below will only show six rows.</p> <pre><code>var ct = new ColumnText(writer.DirectContent); ct.SetSimpleColumn(100, 100, 200, 200); var t = new PdfPTable(2); for(var i=0;i&lt;100;i++){ t.AddCell(i.ToString()); } ct.AddElement(t); ct.Go(); </code></pre>
10,352,211
VBA, ADO.Connection and query parameters
<p>I have excel VBA script:<br></p> <pre><code>Set cоnn = CreateObject("ADODB.Connection") conn.Open "report" Set rs = conn.Execute("select * from table" ) </code></pre> <p>Script work fine, but i want to add parameter to it. For example " where (parentid = <em>myparam</em>)", where <em>myparam</em> setted outside query string. How can i do it?</p> <p>Of course i can modify query string, but i think it not very wise.</p>
10,353,908
2
0
null
2012-04-27 14:09:26.813 UTC
9
2017-12-18 18:13:37.223 UTC
null
null
null
null
420,959
null
1
27
vba|ado
86,502
<p>You need to use an ADODB.Command object that you can add parameters to. Here's basically what that looks like</p> <pre><code>Sub adotest() Dim Cn As ADODB.Connection Dim Cm As ADODB.Command Dim Pm As ADODB.Parameter Dim Rs as ADODB.Recordset Set Cn = New ADODB.Connection Cn.Open "mystring" Set Cm = New ADODB.Command With Cm .ActiveConnection = Cn .CommandText = "SELECT * FROM table WHERE parentid=?;" .CommandType = adCmdText Set Pm = .CreateParameter("parentid", adNumeric, adParamInput) Pm.Value = 1 .Parameters.Append Pm Set Rs = .Execute End With End Sub </code></pre> <p>The question mark in the CommandText is the placeholder for the parameter. I believe, but I'm not positive, that the order you Append parameters must match the order of the questions marks (when you have more than one). Don't be fooled that the parameter is named "parentid" because I don't think ADO cares about the name other than for identification.</p>
5,794,968
In Node.js, am I creating a new object when "Require"?
<p>So, what I'm not sure is that. if in <strong>ModuleA</strong>, I have:</p> <pre><code>var mongoose = require('mongoose'); mongoose.connect(pathA); </code></pre> <p>And in <strong>ModuleB</strong>, I have:</p> <pre><code>var mongoose = require('mongoose'); mongoose.connect(pathB); </code></pre> <p>And in the main program, I have:</p> <pre><code>var mA = require('./moduleA.js'), mB = require('./moduleB.js'); </code></pre> <p>So, when I run the main program, I guess I will create two mongoose "instances"; one connecting to pathA and one connecting to pathB, is that right?</p> <p>Also, in Module B, before I connect to pathB, is it connected to pathA or nothing? </p> <p>Thanks. </p>
5,795,896
2
0
null
2011-04-26 18:45:20.34 UTC
10
2018-09-01 19:24:43.917 UTC
2018-09-01 19:24:43.917 UTC
null
3,313,298
null
196,874
null
1
25
node.js|require|mongoose
15,226
<p>I just did a couple of tests with the latest node V0.4.6. I confirmed the following:</p> <ol> <li>The variable returned from "require" is a singleton. </li> <li>Subsequent changes will change the data of the required module among all other modules that include it. </li> <li>Mongoose's connection is a bit weird. Even if you disconnect and set it to a new connection path, it still uses the old connection path.</li> </ol> <p>So, what I mean by the above points 1 and 2 is:</p> <p>If you have a <strong>Module Master</strong>:</p> <pre><code>var myStr = 'ABC'; module.exports.appendStr = function(data) { myStr += ' ' + data; }; module.exports.output = function() { console.log("Output: " + myStr); }; </code></pre> <p>And if you have two other modules:</p> <p><strong>Module A</strong></p> <pre><code>var mc = require('./moduleMaster.js'); var ma = function() {mc.appendStr(' MA '); }; ma.prototype.output = function() { mc.output(); } module.exports.create = function() { return new ma(); }; module.exports._class = ma; </code></pre> <p><strong>Module B</strong></p> <pre><code>var mc = require('./moduleMaster.js'); var mb = function() {mc.appendStr(' MB '); }; ma.prototype.output = function() { mc.output(); } module.exports.create = function() { return new mb(); }; module.exports._class = mb; </code></pre> <p>Now when you run a test script that requires both Module A and Module B, instantiate them and output:</p> <pre><code>mTestA.output(); mTestB.output(); </code></pre> <p>You will get the following output:</p> <pre><code>ABC MA ABC MA MB </code></pre> <p>instead of</p> <pre><code>ABC MA ABC MB </code></pre> <p>Therefore, it is a singleton. not just local to the module. </p>
5,809,239
Query a MySQL db using java
<p>Guys, simply put, I have a java application with a text output box. I'd like to query a Db and display the output into a text box. </p> <p>Example I have a Db with two columns <code>food</code> and <code>color</code></p> <p>I'd like to :</p> <pre><code>SELECT * in Table WHERE color = 'blue' </code></pre> <p>Any suggestions?</p>
5,809,314
2
1
null
2011-04-27 19:09:44.193 UTC
5
2016-11-29 05:22:22.3 UTC
2011-04-27 19:25:41.837 UTC
null
1,415,812
null
460,677
null
1
25
java|mysql|database|entitymanager
80,849
<p>Beginners generally face problems understanding how to connect to MySQL from Java. This is the code snippet that can get you up and running quickly. You have to get the mysql jdbc driver jar file from somewhere (google it) and add it to the classpath. </p> <pre><code>Class.forName("com.mysql.jdbc.Driver") ; Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DBNAME", "usrname", "pswd") ; Statement stmt = conn.createStatement() ; String query = "select columnname from tablename ;" ; ResultSet rs = stmt.executeQuery(query) ; </code></pre>
60,451,957
What is the MUI Box component for?
<p>Try as I might, I cannot wrap my head around the description given <a href="https://mui.com/components/box/#main-content" rel="noreferrer">here</a>.</p> <blockquote> <p>The Box component serves as a wrapper component for most of the CSS utility needs.</p> </blockquote> <p>What are 'the' CSS utility needs?</p> <p>What is the use case for this component? What problem does it solve? How do you use it?</p> <p>I find the MUI docs very limited and hard to understand. I have googled, but generally only found fairly lightweight blog posts on how to use material UI. In addition to help understanding this component, I would really appreciate any good resources (something like a better version of their own documentation, if such a thing exists).</p> <p>(Background, I generally understand React, JS, CSS, HTML etc, with less strength in the latter two).</p>
62,521,728
4
0
null
2020-02-28 12:42:51.21 UTC
11
2022-06-15 07:56:30.06 UTC
2021-11-01 06:30:22.173 UTC
null
9,449,426
null
6,423,036
null
1
98
reactjs|material-ui
50,055
<p><em>EDIT: This was written in the MUI v4 days. In MUI v5, all MUI components allow you to define CSS styles via the <code>sx</code> prop, not just <code>Box</code>; but <code>Box</code> also accepts styling props at top-level, as well as within <code>sx</code>.</em></p> <p>The other answers don't really explain the motivation for using <code>Box</code>.</p> <p><code>Box</code> renders a <code>&lt;div&gt;</code> you can apply CSS styles to directly via React props, for the sake of convenience, since alternatives like separate CSS files, CSS-in-JS, or inline styles can be more typing and hassle to use.</p> <p>For example, consider this component that uses JSS:</p> <pre><code>import * as React from 'react' import { makeStyles } from '@material-ui/styles' const useStyles = makeStyles(theme =&gt; ({ root: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: theme.spacing(1), } })) const Example = ({children, ...props}) =&gt; { const classes = useStyles(props); return ( &lt;div className={classes.root}&gt; {children} &lt;/div&gt; ) } </code></pre> <p>It's much shorter to do this with <code>Box</code> by passing the props you want to it:</p> <pre><code>import * as React from 'react' import Box from '@material-ui/core/Box' const Example = ({children}) =&gt; ( &lt;Box display=&quot;flex&quot; flexDirection=&quot;column&quot; alignItems=&quot;stretch&quot; padding={1}&gt; {children} &lt;/Box&gt; ) </code></pre> <p>Notice also how <code>padding={1}</code> is a shorthand for <code>theme.spacing(1)</code>. <code>Box</code> provides various conveniences for working with Material-UI themes like this.</p> <p>In larger files it can be more of a hassle to jump back and forth from the rendered elements to the styles than if the styles are right there on the element.</p> <p>Cases where you <em>wouldn't</em> want to use <code>Box</code> (MUI v4):</p> <ul> <li>You want the enclosing component to be able to override styles by passing <code>classes</code> (<code>makeStyles</code> enables this. <code>&lt;Example classNames={{ root: 'alert' }} /&gt;</code> would work in the <code>makeStyles</code> example, but not the <code>Box</code> example.)</li> <li>You need to use nontrivial selectors (example JSS selectors: <code>$root &gt; li &gt; a</code>, <code>$root .third-party-class-name</code>)</li> </ul>
23,103,567
Bootstrap dropdown checkbox select
<p>I'm trying to customize a bootstrap dropdown with checkboxes and if I select a checkbox from dropdown the label name I want to be written on input dropdown delimited with '<code>;</code>' like in uploaded picture when <code>dropdown</code> is closed.</p> <p>Here is a <a href="http://jsfiddle.net/D2RLR/5649/" rel="noreferrer"><strong>fiddle example</strong></a>.</p> <p><img src="https://i.stack.imgur.com/Dbeh2.png" alt="enter image description here"></p>
23,103,954
3
0
null
2014-04-16 08:09:17.643 UTC
8
2019-09-22 18:18:12.077 UTC
2014-05-02 22:00:17.043 UTC
null
2,680,216
null
1,192,687
null
1
27
javascript|jquery|html|css|twitter-bootstrap
94,338
<p>Not the most elegant solution - you will probably want to refine this somewhat, but this might get you started:</p> <pre><code>$(document).ready(function() { $("ul.dropdown-menu input[type=checkbox]").each(function() { $(this).change(function() { var line = ""; $("ul.dropdown-menu input[type=checkbox]").each(function() { if($(this).is(":checked")) { line += $("+ span", this).text() + ";"; } }); $("input.form-control").val(line); }); }); }); </code></pre>
19,708,330
Serving a websocket in Go
<p>I'm starting to play around with websockets + go and well I think I'm misunderstanding something quite basic with websockets in Go.</p> <p>I'd like to simply listen for a websocket connection and process accordingly. However all examples I see in Go using websocket is serving the web page that then connects to the websocket, is this a requirement?</p> <p>The following is a basic echo server I have setup:</p> <pre><code>package main import ( "fmt" "code.google.com/p/go.net/websocket" "net/http" ) func webHandler(ws *websocket.Conn) { var s string fmt.Fscan(ws, &amp;s) fmt.Println("Received: ", s) } func main() { fmt.Println("Starting websock server: ") http.Handle("/echo", websocket.Handler(webHandler)) err := http.ListenAndServe(":8080", nil) if err != nil { panic("ListenAndServe: " + err.Error()) } } </code></pre> <p>This is the javascript used to connect: </p> <pre><code>ws = new WebSocket("ws://localhost:8080/echo"); ws.onmessage = function(e) { console.log("websock: " + e.data); }; </code></pre> <p>However this results in: WebSocket connection to 'ws://localhost:8080/echo' failed: Unexpected response code: 403 </p>
19,709,019
2
0
null
2013-10-31 13:49:19.25 UTC
9
2014-08-23 08:54:01.297 UTC
null
null
null
null
996,911
null
1
13
websocket|go
18,835
<p>When working with websockets from Javascript, you will seldom have to read the frames directly. To be honest, I am not even sure how to do that.</p> <p>Fortunately, the websocket package already has a type, <code>Codec</code> that does this for you. My suggestion is to use the predefined websocket.Message codec to <code>Recieve</code> and <code>Send</code> messages instead.</p> <blockquote> <p>Message is a codec to send/receive text/binary data in a frame on WebSocket connection. To send/receive text frame, use string type. To send/receive binary frame, use []byte type.</p> </blockquote> <p>Using websocket.Message, your webHandler would look something like this:</p> <pre><code>func webHandler(ws *websocket.Conn) { var in []byte if err := websocket.Message.Receive(ws, &amp;in); err != nil { return } fmt.Printf("Received: %s\n", string(in)) websocket.Message.Send(ws, in) } </code></pre> <p>And, no, it is not a requirement that Go serves the webpage. The 403 error you received does not have to do with Go or the websocket package.</p>
19,622,063
Adding vertical line in plot ggplot
<p>I am plotting a graph using the following piece of code:</p> <pre><code>library (ggplot2) png (filename = "graph.png") stats &lt;- read.table("processed-r.dat", header=T, sep=",") attach (stats) stats &lt;- stats[order(best), ] sp &lt;- stats$A / stats$B index &lt;- seq (1, sum (sp &gt;= 1.0)) stats &lt;- data.frame (x=index, y=sp[sp&gt;=1.0]) ggplot (data=stats, aes (x=x, y=y, group=1)) + geom_line() dev.off () </code></pre> <p><img src="https://i.stack.imgur.com/XGS1b.png" alt="enter image description here"></p> <p>1 - How one can add a vertical line in the plot which intersects at a particular value of y (for example 2)?</p> <p>2 - How one can make the y-axis start at 0.5 instead of 1?</p>
19,622,114
2
0
null
2013-10-27 18:55:07.09 UTC
8
2013-10-27 20:11:04.93 UTC
null
null
null
null
1,067,360
null
1
65
r|ggplot2
110,302
<p>You can add vertical line with <code>geom_vline()</code>. In your case:</p> <pre><code>+ geom_vline(xintercept=2) </code></pre> <p>If you want to see also number 0.5 on your y axis, add <code>scale_y_continuous()</code> and set <code>limits=</code> and <code>breaks=</code></p> <pre><code>+ scale_y_continuous(breaks=c(0.5,1,2,3,4,5),limits=c(0.5,6)) </code></pre>
47,479,522
How to create a grouped boxplot in R?
<p>I want to merge the three datasets grouped and obtain a graph with only two boxes, 1 for A and 1 for B. Can you suggest how to get that?</p> <p>I'm tryng to create a grouped boxplot in R. I have 2 groups: A and B, in each group I have 3 subgroups with 5 measurements each.</p> <p>The following is the way that I constructed the boxplot, but if someone has a better, shorter or easy way to do, I'll appreciate</p> <pre><code>A1 &lt;- c(1,2,9,6,4) A2 &lt;- c(5,1,9,2,3) A3 &lt;- c(1,2,3,4,5) B1 &lt;- c(2,4,6,8,10) B2 &lt;- c(0,3,6,9,12) B3 &lt;- c(1,1,2,8,7) DF &lt;- data.frame(A1, A2, A3, B1, B2, B3) boxplot(DF, col = rainbow(3, s = 0.5)) axis(side = 1, at = c(2,5), labels = c("A","B")) legend("topleft", fill = rainbow(3, s = 0.5), legend = c(1,2,3), horiz = T) </code></pre> <p><a href="https://i.stack.imgur.com/nIWAb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nIWAb.png" alt="enter image description here"></a></p> <p>How can I group correctly (joint) the boxes in A and B, and fix the axis title to simple A and B as I tryed?</p> <p>I'd like something like</p> <p><a href="https://i.stack.imgur.com/jbFOD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jbFOD.png" alt="enter image description here"></a></p>
47,479,817
3
0
null
2017-11-24 20:16:46.21 UTC
5
2019-12-10 11:20:13.227 UTC
2019-02-15 11:51:22.897 UTC
null
-1
null
7,769,755
null
1
24
r|plot|customization|boxplot
79,313
<p>It's easier to group them like this when data is in a <em>long</em> format vice <em>wide</em>. Starting with your vectors:</p> <pre><code>DF2 &lt;- data.frame( x = c(c(A1, A2, A3), c(B1, B2, B3)), y = rep(c("A", "B"), each = 15), z = rep(rep(1:3, each=5), 2), stringsAsFactors = FALSE ) str(DF2) # 'data.frame': 30 obs. of 3 variables: # $ x: num 1 2 9 6 4 5 1 9 2 3 ... # $ y: chr "A" "A" "A" "A" ... # $ z: int 1 1 1 1 1 2 2 2 2 2 ... cols &lt;- rainbow(3, s = 0.5) boxplot(x ~ z + y, data = DF2, at = c(1:3, 5:7), col = cols, names = c("", "A", "", "", "B", ""), xaxs = FALSE) legend("topleft", fill = cols, legend = c(1,2,3), horiz = T) </code></pre> <p>The use of <code>at</code> manually controls the placement, so the "visual grouping" is not very robust. (You can control the spacing between them with <code>width</code> and/or <code>boxwex</code>.)</p> <p><a href="https://i.stack.imgur.com/p1HnV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/p1HnV.png" alt="base R boxplot"></a></p> <p>You might also choose <code>ggplot2</code>:</p> <pre><code>library(ggplot2) ggplot(DF2, aes(y, x, fill=factor(z))) + geom_boxplot() </code></pre> <p><a href="https://i.stack.imgur.com/EBQKi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EBQKi.png" alt="ggplot boxplot"></a></p>
33,992,479
Java 8 Stream API to find Unique Object matching a property value
<p>Find the object matching with a Property value from a Collection using Java 8 Stream. </p> <pre><code>List&lt;Person&gt; objects = new ArrayList&lt;&gt;(); </code></pre> <p>Person attributes -> Name, Phone, Email. </p> <p>Iterate through list of Persons and find object matching email. Saw that this can be done through Java 8 stream easily. But that will still return a collection?</p> <p>Ex: </p> <pre><code>List&lt;Person&gt; matchingObjects = objects.stream. filter(p -&gt; p.email().equals("testemail")). collect(Collectors.toList()); </code></pre> <p>But I know that it will always have one unique object. Can we do something instead of <code>Collectors.toList</code> so that i got the actual object directly.Instead of getting the list of objects. </p>
33,993,343
4
1
null
2015-11-30 06:16:26.79 UTC
20
2022-06-25 12:37:01.787 UTC
2018-10-30 02:01:58.733 UTC
null
2,613,141
null
1,389,382
null
1
101
java|filter|java-8|java-stream
216,346
<p>Instead of using a collector try using <code>findFirst</code> or <code>findAny</code>.</p> <pre><code>Optional&lt;Person&gt; matchingObject = objects.stream(). filter(p -&gt; p.email().equals("testemail")). findFirst(); </code></pre> <p>This returns an <code>Optional</code> since the list might not contain that object.</p> <p>If you're sure that the list always contains that person you can call:</p> <pre><code>Person person = matchingObject.get(); </code></pre> <p><strong>Be careful though!</strong> <code>get</code> throws <code>NoSuchElementException</code> if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with <code>isPresent</code> or better, use <code>ifPresent</code>, <code>map</code>, <code>orElse</code> or any of the other alternatives found in the <code>Optional</code> class).</p> <p>If you're okay with a <code>null</code> reference if there is no such person, then:</p> <pre><code>Person person = matchingObject.orElse(null); </code></pre> <p>If possible, I would try to avoid going with the <code>null</code> reference route though. Other alternatives methods in the Optional class (<code>ifPresent</code>, <code>map</code> etc) can solve many use cases. Where I have found myself using <code>orElse(null)</code> is only when I have existing code that was designed to accept <code>null</code> references in some cases.</p> <hr> <p>Optionals have other useful methods as well. Take a look at <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Optional.html" rel="noreferrer">Optional javadoc</a>.</p>
20,939,648
Issue pushing new code in Github
<p>I created a new repository on Github which has only Readme.md file now.</p> <p>I have a newly created RoR project which I wanted to push to this repository. Following are the commands I gave in my Terminal to execute this along with the error I am getting.</p> <pre><code>git remote add origin https://github.com/aniruddhabarapatre/learn-rails.git </code></pre> <p>After which I entered my username and password</p> <pre><code>git push -u origin master </code></pre> <p>Error ---</p> <pre><code>To https://github.com/aniruddhabarapatre/learn-rails.git ! [rejected] master -&gt; master (fetch first) error: failed to push some refs to 'https://github.com/aniruddhabarapatre/learn-rails.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first merge the remote changes (e.g., hint: 'git pull') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. </code></pre> <p>This is my first time pushing my code to a Github repository and I'm lost with the errors. I searched few other questions that are asked here, but none of them had issues first time.</p>
20,939,732
14
1
null
2014-01-05 21:51:41.777 UTC
78
2020-08-21 23:06:01.237 UTC
2014-01-05 22:37:49.347 UTC
null
78,845
null
205,377
null
1
149
git|github|git-push
205,706
<p>When you created <a href="https://github.com/aniruddhabarapatre/learn-rails" rel="noreferrer">your repository on GitHub</a>, you created a <a href="https://github.com/aniruddhabarapatre/learn-rails/blob/master/README.md" rel="noreferrer">README.md</a>, which is <a href="https://github.com/aniruddhabarapatre/learn-rails/commit/36a470d070cc79dc97570254debb0d577627baa2" rel="noreferrer">a new commit</a>.</p> <p>Your local repository doesn't know about this commit yet. Hence:</p> <blockquote> <p>Updates were rejected because the remote contains work that you do not have locally.</p> </blockquote> <p>You may want to find to follow this advice:</p> <blockquote> <p>You may want to first merge the remote changes (e.g., '<code>git pull</code>') before pushing again.</p> </blockquote> <p>That is:</p> <pre><code>git pull # Fix any merge conflicts, if you have a `README.md` locally git push -u origin master </code></pre>
20,960,407
OpenShift: How to connect to postgresql from my PC
<p>I have an openshift app, and I just installed a postgresql DB on the same cartridge.</p> <p>I have the postgresql DB installed but now I want to connect to the DB from my PC so I can start creating new tables.</p> <p>Using port forwarding I found my IP for the postgresql db to be</p> <p>127.3.146.2:5432</p> <p>under my webaccount I see my Database: txxx User: admixxx Password: xxxx</p> <p>Then Using RazorSQl I try to setup a new connection</p> <p>keeps coming as user password incorrect.</p> <p>If I try and use the local IP to connect such as the 127.0.0.1 then I can connect fine.</p> <p>How can I resolve this issue, all I am trying to do is connect to this DB so that I can create new tables. </p>
20,965,511
1
1
null
2014-01-06 22:21:28.59 UTC
13
2014-12-10 19:53:38.24 UTC
2014-01-06 23:46:08.643 UTC
null
2,705,169
null
2,705,169
null
1
21
postgresql|openshift
14,757
<p>As shown below, after running the "rhc port-forward $appname" command, you would need to connect to the ip address of 127.0.0.1 and port that shows up next to it to connect to the service you want to reach, such as postgresql. In the below example, i would connect to 127.0.0.1, port 5432. If you already have something running locally on the postgresql port, it will select another port and display it in the table. But the connection will be forwarded to your openshift gear and postgresql on your gear.</p> <pre><code>Corey-Red-Hat:~ cdaley$ rhc port-forward rt2 Checking available ports ... done Forwarding ports ... To connect to a service running on OpenShift, use the Local address Service Local OpenShift ---------- -------------- ---- --------------- httpd 127.0.0.1:8080 =&gt; 127.7.74.1:8080 postgresql 127.0.0.1:5432 =&gt; 127.7.74.2:5432 Press CTRL-C to terminate port forwarding </code></pre> <p>You can refer to the OpenShift Developer Portal for more information about using the PostgreSQL cartridge here: <a href="https://developers.openshift.com/en/databases-postgresql.html">https://developers.openshift.com/en/databases-postgresql.html</a></p>
54,301,624
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
<p>I'm working with PostgreSQL and NodeJS with its "PG Module". CRUD works but sometimes doesn't update automatically the views when i save or delete some item. this is my code and I think that the error is here but i cannot find it, i tried everything :'( </p> <p>Error Message:</p> <p><a href="https://i.stack.imgur.com/icQff.png" rel="noreferrer"><img src="https://i.stack.imgur.com/icQff.png" alt="enter image description here"></a></p> <pre><code>const controller = {}; const { Pool } = require('pg'); var connectionString = 'postgres://me:system@localhost/recipebookdb'; const pool = new Pool({ connectionString: connectionString, }) controller.list = (request, response) =&gt; { pool.query('SELECT * FROM recipes', (err, result) =&gt; { if (err) { return next(err); } return response.render('recipes', { data: result.rows }); }); }; controller.save = (req, res) =&gt; { pool.query('INSERT INTO recipes(name, ingredients, directions) VALUES ($1, $2, $3)', [req.body.name, req.body.ingredients, req.body.directions]); return res.redirect('/'); }; controller.delete = (req, res) =&gt; { pool.query('DELETE FROM RECIPES WHERE ID = $1', [req.params.id]); return res.redirect('/'); } module.exports = controller; </code></pre> <p>PD: CRUD works but sometimes appears that error.</p>
54,302,006
3
1
null
2019-01-22 05:13:57.983 UTC
4
2020-09-13 04:55:26.333 UTC
2019-01-22 05:40:37.797 UTC
null
1,364,007
null
10,948,185
null
1
15
javascript|node.js|postgresql
65,618
<p>This error occurs when you sent a response before and then you try to send response again. For this you have to check if there is any piece of code that is sending your response twice. Sometimes it happens due to asynchronous behavior of nodejs. Sometimes a process will be in event loop and we send response and when it finishes execution response will be sent again. So You can use callbacks or async await to wait for execution.</p> <p><strong>Callback</strong></p> <pre><code>const controller = {}; const { Pool } = require('pg'); var connectionString = 'postgres://me:system@localhost/recipebookdb'; const pool = new Pool({ connectionString: connectionString, }) controller.list = (request, response) =&gt; { pool.query('SELECT * FROM recipes', (err, result) =&gt; { if (err) { return next(err); } return response.render('recipes', { data: result.rows }); }); }; controller.save = (req, res) =&gt; { pool.query('INSERT INTO recipes(name, ingredients, directions) VALUES ($1, $2,$3)', [req.body.name, req.body.ingredients, req.body.directions],function(err,resp) { if(err){ console.log(err) }else{ return res.redirect('/'); } }); }; controller.delete = (req, res) =&gt; { pool.query('DELETE FROM RECIPES WHERE ID = $1', [req.params.id],function(err,resp){ if(err){ console.log(err) }else{ return res.redirect('/'); } }); } module.exports = controller; </code></pre> <p>Or You can also use async await to wait for execution and then send response.</p> <p><strong>Async/Await</strong></p> <pre><code>const controller = {}; const { Pool } = require('pg'); var connectionString = 'postgres://me:system@localhost/recipebookdb'; const pool = new Pool({ connectionString: connectionString, }) controller.list = async(request, response) =&gt; { try{ const result = await pool.query('SELECT * FROM recipes'); return response.render('recipes', { data: result.rows }); } catch(err){ return next(err); } }; controller.save = async(req, res) =&gt; { try{ await pool.query('INSERT INTO recipes(name, ingredients, directions) VALUES ($1, $2,$3)',[req.body.name, req.body.ingredients, req.body.directions]); return res.redirect('/'); } catch(err){ return next(err); } }; controller.delete = async(req, res) =&gt; { try{ await pool.query('DELETE FROM RECIPES WHERE ID = $1', [req.params.id]); return res.redirect('/'); }catch(err){ console.log(err); } } module.exports = controller; </code></pre>
46,814,158
Why there's a separate MutableLiveData subclass of LiveData?
<p>It looks like <code>MutableLiveData</code> differs from <code>LiveData</code> only by making the <code>setValue()</code> and <code>postValue()</code> methods public, whereas in <code>LiveData</code> they are protected.</p> <p>What are some reasons to make a separate class for this change and not simply define those methods as public in the <code>LiveData</code> itself?</p> <p>Generally speaking, is such a form of inheritance (increasing the visibility of certain methods being the only change) a well-known practice and what are some scenarios where it may be useful (assuming we have access to all the code)?</p>
46,814,399
3
1
null
2017-10-18 15:42:19.593 UTC
22
2020-08-20 08:31:22.723 UTC
2017-10-19 10:01:29.133 UTC
null
1,000,551
null
721,079
null
1
105
android|oop|android-architecture-components|android-livedata
40,294
<p>In <a href="https://developer.android.com/reference/androidx/lifecycle/LiveData.html" rel="noreferrer">LiveData - Android Developer Documentation</a>, you can see that for <code>LiveData</code>, <code>setValue()</code> &amp; <code>postValue()</code> methods are not public.</p> <p>Whereas, in <a href="https://developer.android.com/reference/androidx/lifecycle/MutableLiveData.html" rel="noreferrer">MutableLiveData - Android Developer Documentation</a>, you can see that, <code>MutableLiveData</code> extends <code>LiveData</code> internally and also the two magic methods of <code>LiveData</code> is <strong>publicly</strong> available in this and they are <code>setValue()</code> &amp; <code>postValue()</code>.</p> <p><code>setValue()</code>: set the value and dispatch the value to all the active observers, must be called from <strong>main thread</strong>.</p> <p><code>postValue()</code> : post a task to main thread to override value set by <code>setValue()</code>, must be called from <strong>background thread</strong>.</p> <p>So, <code>LiveData</code> is <strong>immutable</strong>. <code>MutableLiveData</code> is <code>LiveData</code> which is <strong>mutable</strong> &amp; <strong>thread-safe</strong>.</p>
25,766,747
Emulating aspect-fit behaviour using AutoLayout constraints in Xcode 6
<p>I want to use AutoLayout to size and layout a view in a manner that is reminiscent of UIImageView's aspect-fit content mode.</p> <p>I have a subview inside a container view in Interface Builder. The subview has some inherent aspect ratio which I wish to respect. The container view's size is unknown until runtime.</p> <p>If the container view's aspect ratio is wider than the subview, then I want the subview's height to equal the parent view's height.</p> <p>If the container view's aspect ratio is taller than the subview, then I want the subview's width to equal the parent view's width.</p> <p>In either case I wish the subview to be centered horizontally and vertically within the container view.</p> <p>Is there a way to achieve this using AutoLayout constraints in Xcode 6 or in previous version? Ideally using Interface Builder, but if not perhaps it is possible to define such constraints programmatically.</p>
25,768,875
8
0
null
2014-09-10 13:28:11.103 UTC
291
2020-07-28 13:16:46.707 UTC
2014-09-10 16:53:13.463 UTC
null
77,567
null
1,025,041
null
1
343
ios|objective-c|xcode|autolayout
95,397
<p>You're not describing scale-to-fit; you're describing aspect-fit. (I have edited your question in this regard.) The subview becomes as large as possible while maintaining its aspect ratio and fitting entirely inside its parent.</p> <p>Anyway, you can do this with auto layout. You can do it entirely in IB as of Xcode 5.1. Let's start with some views:</p> <p><img src="https://i.stack.imgur.com/hHDxR.png" alt="some views"></p> <p>The light green view has an aspect ratio of 4:1. The dark green view has an aspect ratio of 1:4. I'm going to set up constraints so that the blue view fills the top half of the screen, the pink view fills the bottom half of the screen, and each green view expands as much as possible while maintaining its aspect ratio and fitting in its container.</p> <p>First, I'll create constraints on all four sides of the blue view. I'll pin it to its nearest neighbor on each edge, with a distance of 0. I make sure to turn off margins:</p> <p><img src="https://i.stack.imgur.com/Yo2JF.gif" alt="blue constraints"></p> <p>Note that I <strong>don't</strong> update the frame yet. I find it easier to leave room between the views when setting up constraints, and just set the constants to 0 (or whatever) by hand.</p> <p>Next, I pin the left, bottom, and right edges of the pink view to its nearest neighbor. I don't need to set up a top edge constraint because its top edge is already constrained to the bottom edge of the blue view.</p> <p><img src="https://i.stack.imgur.com/SPiNs.gif" alt="pink constraints"></p> <p>I also need an equal-heights constraint between the pink and blue views. This will make them each fill half the screen:</p> <p><img src="https://i.stack.imgur.com/oelrv.gif" alt="enter image description here"></p> <p>If I tell Xcode to update all the frames now, I get this:</p> <p><img src="https://i.stack.imgur.com/9fbwL.png" alt="containers laid out"></p> <p>So the constraints I've set up so far are correct. I undo that and start work on the light green view.</p> <p>Aspect-fitting the light green view requires five constraints:</p> <ul> <li>A required-priority aspect ratio constraint on the light green view. You can create this constraint in a xib or storyboard with Xcode 5.1 or later.</li> <li>A required-priority constraint limiting the width of the light green view to be less than or equal to the width of its container.</li> <li>A high-priority constraint setting the width of the light green view to be equal to the width of its container.</li> <li>A required-priority constraint limiting the height of the light green view to be less than or equal to the height of its container.</li> <li>A high-priority constraint setting the height of the light green view to be equal to the height of its container.</li> </ul> <p>Let's consider the two width constraints. The less-than-or-equal constraint, by itself, is not sufficient to determine the width of the light green view; many widths will fit the constraint. Since there's ambiguity, autolayout will try to choose a solution that minimizes the error in the other (high-priority but not required) constraint. Minimizing the error means making the width as close as possible to the container's width, while not violating the required less-than-or-equal constraint.</p> <p>The same thing happens with the height constraint. And since the aspect-ratio constraint is also required, it can only maximize the size of the subview along one axis (unless the container happens to have the same aspect ratio as the subview).</p> <p>So first I create the aspect ratio constraint:</p> <p><img src="https://i.stack.imgur.com/4IhOw.gif" alt="top aspect"></p> <p>Then I create equal width and height constraints with the container:</p> <p><img src="https://i.stack.imgur.com/vycag.gif" alt="top equal size"></p> <p>I need to edit these constraints to be less-than-or-equal constraints:</p> <p><img src="https://i.stack.imgur.com/BC7rh.gif" alt="top less than or equal size"></p> <p>Next I need to create another set of equal width and height constraints with the container:</p> <p><img src="https://i.stack.imgur.com/U9HkM.gif" alt="top equal size again"></p> <p>And I need to make these new constraints less than required priority:</p> <p><img src="https://i.stack.imgur.com/I7DTE.gif" alt="top equal not required"></p> <p>Finally, you asked for the subview to be centered in its container, so I'll set up those constraints:</p> <p><img src="https://i.stack.imgur.com/4DTr1.gif" alt="top centered"></p> <p>Now, to test, I'll select the view controller and ask Xcode to update all the frames. This is what I get:</p> <p><img src="https://i.stack.imgur.com/KmtoY.png" alt="incorrect top layout"></p> <p>Oops! The subview has expanded to completely fill its container. If I select it, I can see that in fact it's maintained its aspect ratio, but it's doing an aspect-<strong>fill</strong> instead of an aspect-<strong>fit</strong>.</p> <p>The problem is that on a less-than-or-equal constraint, it matters which view is at each end of the constraint, and Xcode has set up the constraint opposite from my expectation. I could select each of the two constraints and reverse its first and second items. Instead, I'll just select the subview and change the constraints to be greater-than-or-equal:</p> <p><img src="https://i.stack.imgur.com/Mh4XM.gif" alt="fix top constraints"></p> <p>Xcode updates the layout:</p> <p><img src="https://i.stack.imgur.com/sRvqg.png" alt="correct top layout"></p> <p>Now I do all the same things to the dark green view on the bottom. I need to make sure its aspect ratio is 1:4 (Xcode resized it in a weird way since it didn't have constraints). I won't show the steps again since they're the same. Here's the result:</p> <p><img src="https://i.stack.imgur.com/kDj1r.png" alt="correct top and bottom layout"></p> <p>Now I can run it in the iPhone 4S simulator, which has a different screen size than IB used, and test rotation:</p> <p><img src="https://i.stack.imgur.com/HpA6w.gif" alt="iphone 4s test"></p> <p>And I can test in in the iPhone 6 simulator:</p> <p><img src="https://i.stack.imgur.com/OtBQ9.gif" alt="iphone 6 test"></p> <p>I've uploaded my final storyboard to <a href="https://gist.github.com/mayoff/d9320088ab4025c95e40">this gist</a> for your convenience.</p>
8,833,963
Allow - (dash) in regular expression
<p>I have the following regular expression but I want the text box to allow the dash character</p> <pre><code>^[0-9a-zA-Z \/_?:.,\s]+$ </code></pre> <p>Anyone know how I can do this?</p>
8,833,991
3
0
null
2012-01-12 11:01:06.063 UTC
3
2012-01-12 11:08:14.48 UTC
null
null
null
null
956,874
null
1
31
asp.net|regex
52,669
<p>The dash needs to be the first/last character in the character class in order to be used literally:</p> <pre><code>^[-0-9a-zA-Z \/_?:.,\s]+$ ^[0-9a-zA-Z \/_?:.,\s-]+$ </code></pre> <p>You could also escape it, if not the first/last:</p> <pre><code>^[0-9a-zA-Z\- \/_?:.,\s]+$ </code></pre>
8,652,715
Convert a string to regular expression ruby
<p>I need to convert string like "/[\w\s]+/" to regular expression.</p> <pre><code>"/[\w\s]+/" =&gt; /[\w\s]+/ </code></pre> <p>I tried using different <code>Regexp</code> methods like:</p> <p><code>Regexp.new("/[\w\s]+/") =&gt; /\/[w ]+\//</code>, similarly <code>Regexp.compile</code> and <code>Regexp.escape</code>. But none of them returns as I expected.</p> <p>Further more I tried removing backslashes:</p> <p><code>Regexp.new("[\w\s]+") =&gt; /[w ]+/</code> But not have a luck.</p> <p>Then I tried to do it simple:</p> <pre><code>str = "[\w\s]+" =&gt; "[w ]+" </code></pre> <p>It escapes. Now how could string remains as it is and convert to a regexp object?</p>
8,652,833
6
0
null
2011-12-28 06:39:12.533 UTC
20
2022-04-25 14:12:05.903 UTC
2017-06-19 15:18:00.233 UTC
null
5,025,116
null
767,166
null
1
132
ruby|regex|string|ruby-1.9.3
73,467
<p>Looks like here you need the initial string to be in single quotes (refer <a href="http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes" rel="noreferrer">this page</a>)</p> <pre><code>&gt;&gt; str = '[\w\s]+' =&gt; "[\\w\\s]+" &gt;&gt; Regexp.new str =&gt; /[\w\s]+/ </code></pre>
30,660,951
HTTP Status 415 - Cannot consume content type
<p>POST operation to the REST service with JSON body returning </p> <blockquote> <p>org.jboss.resteasy.spi.UnsupportedMediaTypeException</p> <p>: Cannot consume content type exception</p> </blockquote> <p>Both <code>@Consumes(MediaType.APPLICATION_JSON)</code> and <code>@Consumes("application/json")</code> returned same exception. </p> <p>I tried calling the service using Postman API client. </p> <p><img src="https://i.stack.imgur.com/OjmF6.png" alt="image"></p> <pre><code>@RolesAllowed("admin") @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/auth") public Response login(UserCl usr){ if(usr.getUsername().compareTo("user") == 0 &amp;&amp; usr.getPassword().compareTo("pass") == 0){ return Response.status(200).build(); } else{ return Response.status(401).build(); } } 12:44:07,322 WARN [org.jboss.resteasy.core.SynchronousDispatcher] (http-localhost-127.0.0.1-8080-1) Failed executing POST user-service/auth: org.jboss.resteasy.spi.UnsupportedMediaTypeException: Cannot consume content type at org.jboss.resteasy.core.registry.Segment.match(Segment.java:117) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.registry.SimpleSegment.matchSimple(SimpleSegment.java:33) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.registry.RootSegment.matchChildren(RootSegment.java:327) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.registry.SimpleSegment.matchSimple(SimpleSegment.java:44) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.registry.RootSegment.matchChildren(RootSegment.java:327) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.registry.RootSegment.matchRoot(RootSegment.java:374) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.registry.RootSegment.matchRoot(RootSegment.java:367) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:307) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:173) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:118) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55) [resteasy-jaxrs-2.3.2.Final.jar:] at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50) [resteasy-jaxrs-2.3.2.Final.jar:] at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:] at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_79] </code></pre>
30,661,324
2
0
null
2015-06-05 07:37:45.607 UTC
1
2022-04-02 20:59:58.41 UTC
2015-06-05 07:53:56.363 UTC
null
2,587,435
null
1,213,223
null
1
21
java|json|resteasy|postman
45,985
<p>You have not set the <code>Content-Type</code> header. Don't remember what the default is, but you can look in the Chrome developer tools to see the full request with headers. </p> <p>The <kbd>JSON</kbd> value in the drop-down is only for syntax highlighting. It doesn't actually set the header. So just add the header</p> <pre><code>Content-Type -&gt;&gt; application/json </code></pre>
1,303,750
(javascript) onClick="form.submit(); doesn't work on IE & Opera
<p>I have a code (see it below). It works perfectly in Firefox: it saves submitted information after clicking <strong>__JL_SAVE</strong> button and keeps user on same page. But in Internet Explorer &amp; Opera it only redirects to index page (index.php) and doesn't save submitted information. What can I do for solving this problem? Thanks.</p> <p>Here is my code: </p> <pre><code>&lt;form action="index.php" id="mosForm" method="post" enctype="multipart/form-data"&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;?=__JL_ABOUT_MYSELF?&gt;&lt;/legend&gt; &lt;span class="a" onclick="showHideLegend('about_myself_1')"&gt;&lt;?=__JL_EDIT_BLOCK;?&gt;&lt;/span&gt; &lt;div id="about_myself_descr" style="display: block"&gt;&lt;?=__JL_SELF_DESCR;?&gt;&lt;/div&gt; &lt;div id="about_myself_1" style="display: none"&gt;&lt;?php include "html/about_myself_fill.php"?&gt;&lt;/div&gt; &lt;div id="about_myself_2""&gt;&lt;?php include "html/about_myself_show.php"?&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;?=__JL_ABOUT_MYSELF?&gt;&lt;/legend&gt; &lt;span class="a" onclick="showHideLegend('type_1')"&gt;&lt;?=__JL_EDIT_BLOCK;?&gt;&lt;/span&gt; &lt;?php if ($typ_block) {?&gt; &lt;?php /* &lt;input type="checkbox" id="jl_type_block" name="jl_type_block" &lt;?php if ($roon_type_block) echo 'checked ';?&gt; /&gt; */ ?&gt; &lt;input type="checkbox" id="jl_type_block" name="jl_type_block" disabled &lt;?php echo 'checked ';?&gt; /&gt; &lt;label for="jl_type_block"&gt;&lt;?=__JL_ON_BLOCK?&gt;&lt;/label&gt; &lt;?php } else { echo __JL_OFF_BLOCK; }?&gt; &lt;div id="about_myself_descr" style="display: block"&gt;&lt;?=__JL_SELF_DESCR;?&gt;&lt;/div&gt; &lt;div id="type_1" style="display : none"&gt; &lt;?php include "html/type.php"?&gt; &lt;/div&gt; &lt;?php if ($typ_block) { ?&gt; &lt;div id="type_2"&gt; &lt;?php include "html/type_show.php"?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;?=__JL_INTEREST?&gt;&lt;/legend&gt; &lt;span class="a" onclick="showHideLegend('interest_1')"&gt;&lt;?=__JL_EDIT_BLOCK;?&gt;&lt;/span&gt; &lt;?php if ($interest_block) {?&gt; &lt;input type="checkbox" id="jl_interest_block" name="jl_interest_block" disabled &lt;?php echo 'checked ';?&gt; /&gt; &lt;label for="jl_interest_block"&gt;&lt;?=__JL_ON_BLOCK?&gt;&lt;/label&gt; &lt;?php } else echo __JL_OFF_BLOCK; ?&gt; &lt;div id="interest_descr" style="display:block"&gt;&lt;?=__JL_INTEREST_DESCR;?&gt;&lt;/div&gt; &lt;div id="interest_1" style="display:none"&gt; &lt;?php include "html/interest.php"?&gt; &lt;/div&gt; &lt;?php if ($interest_block) { ?&gt; &lt;div id="interest_2"&gt; &lt;?php include "html/interest_show.php"?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/fieldset&gt; &lt;input type="submit" name="save" value="__JL_SAVE" onClick="mosForm.submit();" /&gt; &lt;input type="hidden" name="option" value="com_joomlove" /&gt; &lt;input type="hidden" id="task" name="task" value="save_info" /&gt; &lt;/form&gt; </code></pre> <p>Full source available here: <a href="http://narkoz.pastebin.com/f4f036f5" rel="noreferrer">http://narkoz.pastebin.com/f4f036f5</a></p>
1,303,780
3
0
null
2009-08-20 03:11:53.58 UTC
1
2012-09-27 18:10:30.24 UTC
null
null
null
null
159,721
null
1
7
javascript|internet-explorer|firefox
52,708
<ol> <li><p>If you're not changing the behavior of the form, why use JavaScript to submit the form?, you're already in a submit button.</p></li> <li><p>You should try giving the form name="mosForm", not just id="mosForm", so that the DOM reference from that event handler can be found.</p></li> </ol>
60,680
How do I write a python HTTP server to listen on multiple ports?
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() </code></pre>
60,753
3
0
null
2008-09-13 16:42:38.153 UTC
16
2021-03-21 15:24:59.627 UTC
2009-07-27 03:11:58.223 UTC
J.F. Sebastian
2,567
JW
4,321
null
1
21
python|webserver
34,986
<p>Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <a href="http://localhost:1111/" rel="noreferrer">http://localhost:1111/</a> and <a href="http://localhost:2222/" rel="noreferrer">http://localhost:2222/</a></p> <pre><code>from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello World!") class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): daemon_threads = True def serve_on_port(port): server = ThreadingHTTPServer(("localhost",port), Handler) server.serve_forever() Thread(target=serve_on_port, args=[1111]).start() serve_on_port(2222) </code></pre> <p><em>update:</em></p> <p>This also works with Python 3 but three lines need to be slightly changed:</p> <pre><code>from socketserver import ThreadingMixIn from http.server import HTTPServer, BaseHTTPRequestHandler </code></pre> <p>and</p> <pre><code>self.wfile.write(bytes("Hello World!", "utf-8")) </code></pre>
304,049
Emacs 23 and iPython
<p>Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?</p>
312,741
3
0
null
2008-11-20 01:12:16.507 UTC
12
2012-06-22 05:15:09.227 UTC
2011-09-04 01:13:30.69 UTC
null
133
Richard Riley
37,370
null
1
24
python|emacs|ipython|emacs23
13,379
<p>I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter.</p> <p><a href="http://www.emacswiki.org/emacs/PythonMode#toc10" rel="nofollow noreferrer">http://www.emacswiki.org/emacs/PythonMode#toc10</a></p> <pre><code>(setq load-path (append (list nil "~/.emacs.d/python-mode-1.0/" "~/.emacs.d/pymacs/" "~/.emacs.d/ropemacs-0.6" ) load-path)) (setq py-shell-name "ipython") (defadvice py-execute-buffer (around python-keep-focus activate) "return focus to python code buffer" (save-excursion ad-do-it)) (setenv "PYMACS_PYTHON" "python2.5") (require 'pymacs) (pymacs-load "ropemacs" "rope-") (provide 'python-programming) </code></pre>
990,217
How to start Service-only Android app
<p>I am creating an application whose only component is a <code>service</code> which keeps on running in background (basically a proxy server) but I am not able to find a way how to start that service. Application can not have any UI or user interaction so I am not using Activity.<br> <code>Broadcast receiver</code> can listen to BOOT broadcast but how do I start service first time when it is installed and how can I keep it running? or is there a broadcast which I can listen after app is installed e.g. may be TIME_TICK but that has to be registered from activity I think.</p>
990,944
3
2
null
2009-06-13 07:25:46.69 UTC
35
2018-01-08 17:24:56.557 UTC
2017-08-24 06:34:13.683 UTC
null
-1
null
6,946
null
1
52
android|service
69,487
<p>Unfortunately right now there is no reliable way to receive a broadcast event after your applicaiton has been installed, the <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_PACKAGE_ADDED" rel="noreferrer">ACTION_PACKAGE_ADDED</a> Intent does not broadcast to the newly installed package.</p> <p>You will have to have a broadcast receiver class as well as your service in order to receive the <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_BOOT_COMPLETED" rel="noreferrer">ACTION_BOOT_COMPLETED</a> event. I would also recommend adding the <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_USER_PRESENT" rel="noreferrer">ACTION_USER_PRESENT</a> intent to be caught by that broadcast receiver, this requires Android 1.5 (minSDK=3), this will call your broadcast receiver whenever the user unlocks their phone. The last thing that you can do to try to keep your service running without having it easily be shut down automatically is to call <a href="http://developer.android.com/reference/android/app/Service.html#setForeground(boolean)" rel="noreferrer">Service.setForeground()</a> in your service onCreate to tell Android that your service shouldn't be stopped, this was added mainly for mp3 player type services that have to keep running but can be used by any service.</p> <p>Make sure you add the proper permissions for the boot_complete and user_present events in you manifest.</p> <p>Here is a simple class that you can use as a broadcast receiver for the events.</p> <pre><code>package com.snctln.util.WeatherStatus; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class WeatherStatusServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() != null) { if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) || intent.getAction().equals(Intent.ACTION_USER_PRESENT)) { context.startService(new Intent(context, WeatherStatusService.class)); } } } }; </code></pre> <p>Good luck.</p>
41,811,986
git move directory to another repository while keeping the history
<p>First - apologies for asking this question. There are a lot of topics about it already. But I'm not having much luck with them. My lack of familiarity with git is not much help.</p> <p>I'm moving a folder from one git repo to another (which already exists). e.g.</p> <pre><code>repo-1 ---- dir1 ---- dir2 ---- dir3 ---- dir-to-move ---- dir5 repo-2 ---- dir1 ---- dir2 ---- dir3 </code></pre> <p>In the end I want the repos to look like</p> <pre><code>repo-1 ---- dir1 ---- dir2 ---- dir3 ---- dir-to-move ---- dir5 repo-2 ---- dir1 ---- dir2 ---- dir3 ---- dir-to-move </code></pre> <p>i.e. For a time <em>dir-to-move</em> will exist in both repos. But eventually I'll migrate the latest changes to <em>repo-2</em> and remove <em>dir-to-move</em> from <em>repo-1</em>. </p> <p>My initial research made me believe that I needed to use <em>filter-branch</em>. e.g.</p> <p><a href="https://stackoverflow.com/questions/28830916/how-to-move-files-from-one-git-repo-to-another-preserving-history-using-git-for">How to move files from one git repo to another preserving history using `git format-patch`and `git am`</a></p> <p>I've since learnt that <em>subtree</em> superseded that approach. However it's not doing what I expected. I thought I'd be able to do something like</p> <p>In <em>repo-1</em> workspace</p> <pre><code>git subtree split -P dir-to-move -b split </code></pre> <p>to filter the <em>split</em> branch down to only <em>dir-to-move</em> and it's history. Then in <em>repo-2</em> workspace</p> <pre><code>git remote add repo-1 repo-1-url.git git subtree add --prefix dir-to-move split </code></pre> <p>This does move the code across. It also, sort of, includes the history</p> <p>e.g.</p> <pre><code>cd repo-2 git log </code></pre> <p>Shows commits from <em>repo-1</em></p> <p>but</p> <pre><code>cd repo-2 git log dir-to-move </code></pre> <p>Shows only an 'Add dir-to-move from commit ....'</p> <p>i.e. The history is included but does not show up when checked for the specific files/directories.</p> <p>How can I do this properly?</p>
41,814,257
8
1
null
2017-01-23 17:19:10.583 UTC
12
2021-11-29 14:55:15.31 UTC
2018-07-24 11:38:29.18 UTC
null
765,076
null
765,076
null
1
47
git
44,876
<p>I can't help you with <code>git subtree</code>, but with <code>filter-branch</code> it's possible.</p> <p>First you need to create a common repository that will contain both source and destination branches. This can be done by adding a new "remote" beside "origin" and fetching from the new remote.</p> <p>Use <code>filter-branch</code> on the source branch to <code>rm -rf</code> all directories except <code>dir-to-move</code>. After that you'll have a commit history that can be cleanly rebased or merged into the destination branch. I think the easiest way is to <code>cherry-pick</code> all non-empty commits from the source branch. The list of these commits can be obtained by running <code>git rev-list --reverse source-branch -- dir-to-move</code> </p> <p>Of course, if the history of <code>dir-to-move</code> is non-linear (already contains merge commits), then it won't be preserved by cherry-pick, so <code>git merge</code> can be used instead.</p> <p>Example create common repo:</p> <pre><code>cd repo-2 git remote add source ../repo-1 git fetch source </code></pre> <p>Example filter branch</p> <pre><code>cd repo-2 git checkout -b source-master source/master CMD="rm -rf dir1 dir2 dir3 dir5" git filter-branch --tree-filter "$CMD" </code></pre> <p>Example cherry-pick into destination master</p> <pre><code>cd repo-2 git checkout master git cherry-pick `git rev-list --reverse source-master -- dir-to-move` </code></pre>
42,022,735
warning: unknown escape sequence '\
<p>I'm trying to run a regex through a system command in the code, I have gone through the threads in StackOverflow on similar warnings but I couldn't understand on how to fix the below warnings, it seems to come only for the closed brackets on doing \\}. The warnings seem to disappear but not able to get the exact output in the redirected file.</p> <pre><code>#include&lt;stdio.h&gt; int main(){ FILE *in; char buff[512]; if(system("grep -o '[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}' /home/santosh/Test/text &gt;t2.txt") &lt; 0){ printf("system failed:"); exit(1); } } </code></pre> <p>Warnings: </p> <pre><code>dup.c:9:11: warning: unknown escape sequence '\}' dup.c:9:11: warning: unknown escape sequence '\}' dup.c:9:11: warning: unknown escape sequence '\}' dup.c:9:11: warning: unknown escape sequence '\}' dup.c: In function 'main': </code></pre>
42,022,766
1
2
null
2017-02-03 11:04:12.937 UTC
null
2017-02-03 11:19:35.933 UTC
2017-02-03 11:13:23.853 UTC
null
898,348
null
2,276,753
null
1
5
c|regex
49,298
<p>In C string literals the <code>\</code> has a special meaning, it's for representing characters such as line endings <code>\n</code>. If you want to put a <code>\</code> in a string, you need to use <code>\\</code>.</p> <p>For example</p> <pre><code>"\\Hello\\Test" </code></pre> <p>will actually result in "\Hello\Test".</p> <p>So your regexp needs to be written as:</p> <pre><code>"[0-9]\\{1,3\}\\\\.[0-9]\\{1,3\}\\\\.[0-9]\\{1,3\\}\\\\.[0-9]\\{1,3\\}" </code></pre> <p>instead of:</p> <pre><code>"[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}" </code></pre> <p>Sure this is painful because <code>\</code> is used as escape character for the regexp and again as escape character for the string literal.</p> <p>So basically: when you want to put a <code>\</code> you need to write <code>\\</code>.</p>
36,672,845
In Rust, is a vector an Iterator?
<p>Is it accurate to state that a vector (among other collection types) is an <code>Iterator</code>?</p> <p>For example, I can loop over a vector in the following way, because it implements the <code>Iterator</code> trait (as I understand it):</p> <pre><code>let v = vec![1, 2, 3, 4, 5]; for x in &amp;v { println!("{}", x); } </code></pre> <p>However, if I want to use functions that are part of the <code>Iterator</code> trait (such as <code>fold</code>, <code>map</code> or <code>filter</code>) why must I first call <code>iter()</code> on that vector?</p> <p>Another thought I had was maybe that a vector can be converted into an <code>Iterator</code>, and, in that case, the syntax above makes more sense.</p>
36,673,695
1
1
null
2016-04-17 04:58:32.38 UTC
2
2019-08-11 17:07:28.58 UTC
2018-02-01 18:07:21.667 UTC
null
3,924,118
null
71,079
null
1
32
iterator|rust
18,621
<p>No, a vector is not an iterator.</p> <p>But it implements the trait <a href="https://doc.rust-lang.org/std/iter/trait.IntoIterator.html" rel="noreferrer"><code>IntoIterator</code></a>, which the <code>for</code> loop uses to convert the vector into the required iterator.</p> <p>In the <a href="https://doc.rust-lang.org/std/vec/struct.Vec.html" rel="noreferrer">documentation for <code>Vec</code></a> you can see that <code>IntoIterator</code> is implemented in three ways: </p> <ul> <li>for <code>Vec&lt;T&gt;</code>, which is moved and the iterator returns items of type <code>T</code>, </li> <li>for a shared reference <code>&amp;Vec&lt;T&gt;</code>, where the iterator returns shared references <code>&amp;T</code>,</li> <li>and for <code>&amp;mut Vec&lt;T&gt;</code>, where mutable references are returned.</li> </ul> <p><a href="https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter" rel="noreferrer"><code>iter()</code></a> is just a method in <code>Vec</code> to convert <code>Vec&lt;T&gt;</code> directly into an iterator that returns shared references, without first converting it into a reference. There is a sibling method <a href="https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter_mut" rel="noreferrer"><code>iter_mut()</code></a> for producing mutable references.</p>
36,569,511
Is it possible to get pip to print the configuration it is using?
<p>Is there any way to get pip to print the config it will attempt to use? For debugging purposes it would be very nice to know that:</p> <ol> <li>config.ini files are in the correct place and pip is finding them.</li> <li>The precedence of the config settings is treated in the way one would expect from the <a href="https://pip.pypa.io/en/stable/user_guide/#config-file">docs</a></li> </ol>
37,973,134
3
2
null
2016-04-12 09:45:13.047 UTC
7
2018-11-28 14:54:01.497 UTC
2016-06-22 15:30:33.733 UTC
null
3,125,566
null
3,324,477
null
1
55
python|pip
35,384
<p><strong>For 10.0.x and higher</strong></p> <p>There is new <code>pip config</code> command, to list current configuration values</p> <pre><code>pip config list </code></pre> <p>(As pointed by @wmaddox in comments) To get the list of where pip looks for config files </p> <pre><code>pip config list -v </code></pre> <p><strong>Pre 10.0.x</strong></p> <p>You can start python console and do. (If you have virtaulenv don't forget to activate it first) </p> <pre><code>from pip import create_main_parser parser = create_main_parser() # print all config files that it will try to read print(parser.files) # reads parser files that are actually found and prints their names print(parser.config.read(parser.files)) </code></pre> <p><a href="https://github.com/pypa/pip/blob/master/pip/__init__.py#L116" rel="noreferrer"><code>create_main_parser</code></a> is function that creates <a href="https://github.com/pypa/pip/blob/master/pip/baseparser.py#L135" rel="noreferrer"><code>parser</code></a> which pip uses to read params from command line(<code>optparse</code>) and loading configs(<code>configparser</code>)</p> <p>Possible file names for configurations are generated in <a href="https://github.com/pypa/pip/blob/master/pip/baseparser.py#L151" rel="noreferrer"><code>get_config_files</code></a>. Including <code>PIP_CONFIG_FILE</code> environment variable if it set.</p> <p><code>parser.config</code> is instance of <a href="https://docs.python.org/3/library/configparser.html#configparser.RawConfigParser" rel="noreferrer"><code>RawConfigParser</code></a> so all generated file names in <code>get_config_files</code> are passed to <a href="https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read" rel="noreferrer"><code>parser.config.read</code></a> .</p> <blockquote> <p>Attempt to read and parse a list of filenames, returning a list of filenames which were successfully parsed. If filenames is a string, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify a list of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the list will be read. If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files:</p> </blockquote>
28,512,909
Why does jQuery mask say it's not a function?
<p>When trying to use the jQuery <code>mask()</code> function, I get the following error in the console:</p> <pre><code>TypeError: $(...).mask is not a function </code></pre> <p>This is a sample of my code where this is happening:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;input type='text' id='phone' /&gt; &lt;/body&gt; &lt;script src="http://code.jquery.com/jquery-1.11.2.min.js"&gt;&lt;/script&gt; &lt;script&gt; //alert($); $(document).ready(function(){ $("#phone").mask("(99) 9999-9999"); }); &lt;/script&gt; &lt;/html&gt; </code></pre> <p>How do I fix this?</p>
28,512,968
3
1
null
2015-02-14 05:56:28.637 UTC
5
2020-07-16 02:46:44.863 UTC
2017-02-27 16:56:11.913 UTC
null
4,099,675
null
800,123
null
1
23
javascript|jquery|jquery-mask
71,767
<p>Jquery mask is a plugin. You can directly add this line in your HTML if you want to use a CDN version:</p> <pre><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"&gt;&lt;/script&gt; </code></pre> <p>Another way is to use a package manager like npm or bower. To accomplish that, follow the instructions in the <a href="https://github.com/igorescobar/jQuery-Mask-Plugin" rel="noreferrer">README.md</a> file of the project.</p>
23,946,658
Error mixing types with Eigen matrices
<p>There was no quick find answer that I could see on stack for this problem so I thought I would add one. </p> <p>Say I have the following example code from the c++ Eigen Library:</p> <pre><code>Eigen::Matrix4d m1; Eigen::Matrix4f m2; m1 &lt;&lt; 1, 2, 3, 4 ... 16 m2 = m1; //Compile error here. </code></pre> <p>I get a compile error on the final line that boils down to this:</p> <pre><code>YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY </code></pre> <p>What is an easy way to fix this?</p>
23,946,659
1
0
null
2014-05-30 03:41:24.69 UTC
5
2014-05-30 03:41:24.69 UTC
null
null
null
null
1,294,207
null
1
29
c++|casting|eigen
18,118
<p>So the way to fix this which took me an annoyingly long time to find is to use the derived <code>cast</code> method described <a href="http://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#a660200abaf1fc4b888330a37d6132b76" rel="noreferrer">here</a>. Now the definition is this:</p> <pre><code>internal::cast_return_type&lt;Derived,const CwiseUnaryOp&lt;internal::scalar_cast_op&lt;typenameinternal::traits&lt;Derived&gt;::Scalar, NewType&gt;, const Derived&gt; &gt;::type cast() const </code></pre> <p>Which Ill admit, phased me a little. But turns out it is pretty easy (and the only explanation I could find was in the Eigen 2.0 doc which was frustrating). All you need to do is this:</p> <pre><code>m2 = m1.cast&lt;float&gt;(); </code></pre> <p>Problem solved. </p>
42,952,453
Visual Studio Code - Adjust import quotation setting
<p>When working in TypeScript in Visual Studio Code, the import suggestion on a type (triggered by space + period) will generate an import using double quotes.</p> <p>Our TypeScript linter verifies that single quotes are used where possible.</p> <p>As you can see below, the suggestion has double quotes ("@angular/...") <a href="https://i.stack.imgur.com/L9YvF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/L9YvF.png" alt="Import suggestion with double quotes"></a></p> <p>How can I adjust the setting of the import?</p>
42,952,975
11
1
null
2017-03-22 13:03:42.577 UTC
10
2022-07-06 17:31:52.873 UTC
null
null
null
null
5,722,607
null
1
134
typescript|visual-studio-code
51,036
<p>&quot;typescript.preferences.quoteStyle&quot;: &quot;single&quot;</p> <p>For more info see:</p> <p><a href="https://code.visualstudio.com/updates/v1_24#_preferences-for-auto-imports-and-generated-code" rel="noreferrer">https://code.visualstudio.com/updates/v1_24#_preferences-for-auto-imports-and-generated-code</a></p>
35,966,297
What is the difference between DOM parsing, loading, rendering, ready?
<p>I am trying to understand how the DOM is rendered, and resources and requested/loaded from the network. However when reading the resources found on internet, DOM parsing/loading/rendering/ready terms are used and I cant seem to grasp what is the order of these 'events'. </p> <p>When script, css or img file is requested from network, does it stop rendering dom only or stops parsing it also? Is Dom loading same as Dom rendering? and Is DomContentLoaded event equivalent to <code>jQuery.ready()</code>?</p> <p>Can someone please explain if some of these terms are synonymous and in what order they happen? </p>
35,966,477
1
1
null
2016-03-13 03:59:31.603 UTC
11
2019-05-06 13:37:09.51 UTC
null
null
null
null
5,249,729
null
1
10
javascript|dom
5,978
<p>When you open a browser <code>window</code>, that window needs to have a <code>document</code> loaded into it for the user to see and interact with. But, a user can navigate away from that <code>document</code> (while still keeping the same <code>window</code> open) and load up another <code>document</code>. Of course, the user can close the browser window as well. As such, you can say that the <code>window</code> and the <code>document</code> have a life-cycle.</p> <p>The <code>window</code> and the <code>document</code> are accessible to you via object APIs and you can get involved in the life-cycles of these objects by hooking up functions that should be called during key <code>events</code> in the life-cycle of these objects.</p> <p>The <code>window</code> object is at the top of the browser's object model - it is always present (you can't have a <code>document</code> if there's no <code>window</code> to load it into) and this means that it is the browser's <strong><em>Global</em></strong> Object. You can talk to it anytime in any JavaScript code.</p> <p>When you make a request for a document (that would be an HTTP or HTTPS request) and the resource is returned to the client, it comes back in an HTTP or HTTPS response - this is where the data payload (the text, html, css, JavaScript, JSON, XML, etc.) lives.</p> <p>Let's say that you've requested an .html page. As the browser begins to receive that payload it begins to read the HTML and construct an "in-memory" representation of the <code>document</code> object formed from the code. This representation is called The Document Object Model or the DOM.</p> <p>The act of reading/processing the HTML is called "<strong>parsing</strong>" and when the browser is done doing this, the DOM structure is now complete. This key moment in the life-cycle triggers the document object's <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event" rel="noreferrer"><strong>DOMContentLoaded</strong></a> event, which signifies that there is enough information for a fully formed <code>document</code> to be interactive. This event is synonymous with jQuery's <a href="http://learn.jquery.com/using-jquery-core/document-ready/" rel="noreferrer"><strong>document.ready</strong></a> event. </p> <p>But, before going on, we need to back up a moment... As the browser is parsing the HTML, it also "<strong>renders</strong>" that content to the screen, meaning that space in the document is allocated for the element and its content and that content is displayed. This doesn't happen AFTER all parsing is complete, the rendering engine works at the same time the parsing engine is working, just one step behind it - - if the parsing engine parses a table-row, for example, the rendering engine will then render it. However, when it comes to things like images, although the image element may have been parsed, the actual image file may not yet have finished downloading to the client. This is why you may sometimes initially see a page with no images and then as the images begin to appear, the rest of the content on the page has to shift to make room for the image -- the browser knew there was going to be an image, but it didn't necessarily know how much space it was going to need for that image until it arrived.</p> <p>CSS files, JS files, images and other resources required by the document download in the background, but most browsers/operating systems cap how many HTTP requests can be working simultaneously. I know for Windows, the Windows registry has a setting for IE that caps that at 10 requests at at time, so if a page has 11 images in it, the first 10 will download at the same time, but the 11th will have to wait. This is one of the reasons it is suggested that it's better to combine multiple CSS files into one file and to use image sprites, rather than separate images - - to reduce the overall amount of HTTP requests a page has to make.</p> <p>When all of the external resources required by the <code>document</code> have completed downloading (CSS files, JavaScript files, image files, etc.), the <code>window</code> will receive its <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event" rel="noreferrer">"<strong>load</strong>" event</a>, which signifies that, not only has the DOM structure been built, but all resources are available for use. This is the event to tap into when your code needs to interact with the content of an external resource - - it must wait for the content to arrive before consuming it.</p> <p>Now that the <code>document</code> is fully loaded in the <code>window</code>, anything can happen. The user may click things, press keys to provide input, scroll, etc. All these actions cause events to trigger and any or all of them can be tapped into to launch custom code at just the right time.</p> <p>When the browser <code>window</code> is asked to load a different <code>document</code>, there are events that are triggered that signify the end of the document's life, such as the window's <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event" rel="noreferrer"><strong><code>beforeunload</code></strong></a> event and ultimately its <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event" rel="noreferrer"><strong><code>unload</code></strong> event</a>.</p> <p>This is all still a simplification of the total process, but I think it should give you a good overview of how documents are loaded, parsed and rendered within their life-cycle.</p>
41,288,622
pyspark: Create MapType Column from existing columns
<p>I need to creeate an new Spark DF MapType Column based on the existing columns where column name is the key and the value is the value.</p> <p>As Example - i've this DF:</p> <pre><code>rdd = sc.parallelize([('123k', 1.3, 6.3, 7.6), ('d23d', 1.5, 2.0, 2.2), ('as3d', 2.2, 4.3, 9.0) ]) schema = StructType([StructField('key', StringType(), True), StructField('metric1', FloatType(), True), StructField('metric2', FloatType(), True), StructField('metric3', FloatType(), True)]) df = sqlContext.createDataFrame(rdd, schema) +----+-------+-------+-------+ | key|metric1|metric2|metric3| +----+-------+-------+-------+ |123k| 1.3| 6.3| 7.6| |d23d| 1.5| 2.0| 2.2| |as3d| 2.2| 4.3| 9.0| +----+-------+-------+-------+ </code></pre> <p>I'm already so far that i can create a structType from this:</p> <pre><code>nameCol = struct([name for name in df.columns if ("metric" in name)]).alias("metric") df2 = df.select("key", nameCol) +----+-------------+ | key| metric| +----+-------------+ |123k|[1.3,6.3,7.6]| |d23d|[1.5,2.0,2.2]| |as3d|[2.2,4.3,9.0]| +----+-------------+ </code></pre> <p>But what i need is an metric column with am MapType where the key is the column name:</p> <pre><code>+----+-------------------------+ | key| metric| +----+-------------------------+ |123k|Map(metric1 -&gt; 1.3, me...| |d23d|Map(metric1 -&gt; 1.5, me...| |as3d|Map(metric1 -&gt; 2.2, me...| +----+-------------------------+ </code></pre> <p>Any hints how i can transform the data?</p> <p>Thanks!</p>
41,291,156
1
0
null
2016-12-22 17:20:47.003 UTC
13
2019-08-08 21:54:24.67 UTC
null
null
null
null
7,331,347
null
1
21
python|apache-spark|pyspark
28,861
<p>In Spark 2.0 or later you can use <code>create_map</code>. First some imports:</p> <pre><code>from pyspark.sql.functions import lit, col, create_map from itertools import chain </code></pre> <p><code>create_map</code> expects an interleaved sequence of <code>keys</code> and <code>values</code> which can be created for example like this:</p> <pre><code>metric = create_map(list(chain(*( (lit(name), col(name)) for name in df.columns if "metric" in name )))).alias("metric") </code></pre> <p>and used with <code>select</code>:</p> <pre><code>df.select("key", metric) </code></pre> <p>With example data the result is:</p> <pre class="lang-none prettyprint-override"><code>+----+---------------------------------------------------------+ |key |metric | +----+---------------------------------------------------------+ |123k|Map(metric1 -&gt; 1.3, metric2 -&gt; 6.3, metric3 -&gt; 7.6) | |d23d|Map(metric1 -&gt; 1.5, metric2 -&gt; 2.0, metric3 -&gt; 2.2) | |as3d|Map(metric1 -&gt; 2.2, metric2 -&gt; 4.3, metric3 -&gt; 9.0) | +----+---------------------------------------------------------+ </code></pre> <p>If you use an earlier version of Spark you'll have to use UDF:</p> <pre><code>from pyspark.sql import Column from pyspark.sql.functions import struct from pyspark.sql.types import DataType, DoubleType, StringType, MapType def as_map(*cols: str, key_type: DataType=DoubleType()) -&gt; Column: args = [struct(lit(name), col(name)) for name in cols] as_map_ = udf( lambda *args: dict(args), MapType(StringType(), key_type) ) return as_map_(*args) </code></pre> <p>which could be used as follows:</p> <pre><code>df.select("key", as_map(*[name for name in df.columns if "metric" in name]).alias("metric")) </code></pre>
5,729,891
redis performance, store json object as a string
<p>I need to save a User model, something like:</p> <pre><code>{ "nickname": "alan", "email": ..., "password":..., ...} // and a couple of other fields </code></pre> <p>Today, I use a Set: users<br> In this Set, I have a member like user:alan<br> In this member I have the hash above </p> <p>This is working fine but I was just wondering if instead of the above approach that could make sense to use the following one:</p> <p>Still use users Set (to easily get the users (members) list)<br> In this set only use a key / value storage like: </p> <p>key: alan value : the stringify version of the above user hash</p> <p>Retrieving a record would then be easier (I will then have to Parse it with JSON).</p> <p>I'm very new to redis and I am not sure what could be the best. What do you think ?</p>
5,730,192
4
0
null
2011-04-20 12:02:36.157 UTC
12
2014-04-19 11:52:52.88 UTC
2011-04-20 12:07:36.837 UTC
null
231,957
null
231,957
null
1
25
node.js|redis
29,856
<p>You can use Redis <a href="http://redis.io/commands#hash" rel="nofollow noreferrer">hashes</a> data structure to store your JSON object fields and values. For example your "users" set can still be used as a list which stores all users and your individual JSON object can be stored into hash like this:</p> <pre><code>db.hmset("user:id", JSON.stringify(jsonObj)); </code></pre> <p>Now you can get by key all users or only specific one (from which you get/set only specified fields/values). Also <a href="https://stackoverflow.com/questions/5252456/storing-object-properties-in-redis">these</a> <a href="https://stackoverflow.com/questions/5701491/save-nested-hash-in-redis-via-a-node-js-app">two</a> questions are probably related to your scenario.</p> <p><strong>EDIT: (sorry I didn't realize that we talked about this earlier)</strong></p> <blockquote> <p>Retrieving a record would then be easier (I will then have to Parse it with JSON).</p> </blockquote> <p>This is true, but with hash data structure you can get/set only the field/value which you need to work with. Retrieving entire JSON object can result in decrease of performance (depends on how often you do it) if you only want to change part of the object (other thing is that you will need to stringify/parse the object everytime).</p>
5,991,732
Get all directories comma separated and send output to other script
<p>We use phpDocumentator to document our php code. The php code is in different dictionaries. The script which runs the phpDocumentator looks like this:</p> <pre><code>./phpdoc -d dir1,dir2,dir3,dir4 </code></pre> <p>Every time we add a new directory, I have to add this one to the script.</p> <p>I would like to do this dynamically. </p> <pre><code>ls -d ../*test* </code></pre> <p>this lists all needed directories but space separated and not comma separated.</p> <p><strong>Question:</strong></p> <p>How can I list the directories comma separated?</p> <p>how can I add this list as -d parameter to the phpdoc script?</p>
5,991,844
4
0
null
2011-05-13 12:21:36.58 UTC
9
2016-07-15 09:13:17.25 UTC
2016-07-15 04:12:34.067 UTC
null
445,131
null
606,496
null
1
28
linux|bash
34,751
<p>Use <code>ls -dm */</code> to generate a comma-separated list of directories. <code>-d</code> will return directories only and <code>-m</code> will output to a comma-separated list.</p> <p>You could then store the output in a variable and pass it along as an argument:</p> <pre><code>#!/bin/bash MY_DIRECTORY=/some/directory FOLDERS=`ls -dm $MY_DIRECTORY/*/ | tr -d ' '` phpdoc -d $FOLDERS </code></pre>
6,151,554
Text inside div not showing multiple white spaces between words
<p>Div is not showing multiple white spaces in between strings</p> <p>For Example:</p> <p>This string <code>'New Folder'</code> I would like to be displayed as 'New     Folder'</p>
6,151,617
4
1
null
2011-05-27 11:24:21.92 UTC
5
2021-01-29 16:55:52.383 UTC
2021-01-29 16:55:52.383 UTC
null
1,366,033
null
293,709
null
1
34
html|css
34,548
<p>That is how html works. Whitespace is collapsed. Look at the way your question is displayed to see an example.</p> <p>To work around this, wrap your text in a <code>&lt;pre&gt;</code> tag, or use <code>&amp;nbsp;</code> instead of space characters</p> <hr /> <p>Or add <code>white-space:pre</code> to the CSS for the div.</p>
1,500,397
How to obtain CURDATE() / NOW() on a JPA named query?
<p>I want to do a select from table where date = TODAY, on mysql that would be <code>where date &gt; CURDATE()</code>, how do I do this on a JPA named query?</p>
1,500,531
2
0
null
2009-09-30 20:13:21.253 UTC
1
2020-07-14 07:32:49.797 UTC
2017-10-09 11:00:00.067 UTC
null
1,429,387
null
182,077
null
1
24
java|date|jpa
47,550
<p>That depends on your JPA provider. Hibernate, for example, supports <a href="https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#jpql-standardized-functions" rel="noreferrer">current_date</a> function:</p> <pre><code>from MyEntity where myDateProperty &gt; current_date </code></pre>
46,004,291
How do I create an ethereum wallet in Python?
<p>I am building an application that would create a wallet for a user. One option is the <a href="https://web3py.readthedocs.io/en/latest/web3.personal.html#web3.personal.newAccount" rel="nofollow noreferrer">web3.personal API</a> in web3.py, which has a <code>newAccount('passphrase')</code> method. The method only returns the address of created account.</p> <p>What I'm looking for is a function similar to the <a href="https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#create" rel="nofollow noreferrer">eth.accounts API</a> in web3.js, which has a <code>create([entropy])</code> method. It returns an account object with 'address', '<strong>privatekey</strong>' and other details.</p>
46,005,492
2
2
null
2017-09-01 16:15:15.373 UTC
9
2022-05-30 19:55:08.13 UTC
2022-05-30 19:55:08.13 UTC
null
2,756,409
null
6,325,816
null
1
12
python|ethereum|web3py
11,093
<p><em>Edit: I removed the deprecated <code>pyethereum</code> solution, replaced with the better <code>eth-account</code> one.</em></p> <h2>Setup</h2> <p>At shell: <code>pip install eth_account</code></p> <h2>Generating Account</h2> <p>The <code>eth-account</code> library will help you <a href="http://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.create" rel="noreferrer">create a private key</a> with an attached address:</p> <pre><code>&gt;&gt;&gt; from eth_account import Account &gt;&gt;&gt; acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') &gt;&gt;&gt; acct.privateKey b"\xb2\}\xb3\x1f\xee\xd9\x12''\xbf\t9\xdcv\x9a\x96VK-\xe4\xc4rm\x03[6\xec\xf1\xe5\xb3d" &gt;&gt;&gt; acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' </code></pre> <p>Adding some of your own randomness above helps address potential limitations of <a href="https://python.readthedocs.io/en/latest/library/os.html#os.urandom" rel="noreferrer"><code>os.urandom</code></a>, which depends on your version of Python, and your operating system. Obviously use a different string of randomness than the <code>'KEYSMASH...'</code> one from above.</p> <p>For more information about using the private key, see <a href="http://web3py.readthedocs.io/en/stable/web3.eth.account.html#some-common-uses-for-local-private-keys" rel="noreferrer">this doc with common examples, like signing a transaction</a>.</p> <hr> <p><em>As a side-note, you may find more support at</em> <a href="http://ethereum.stackexchange.com">ethereum.stackexchange.com</a></p>
6,027,525
How do I accomplish an if/else in mustache.js?
<p>It seems rather odd that I can't figure how to do this in mustache. Is it supported?</p> <p>This is my sad attempt at trying:</p> <pre><code> {{#author}} {{#avatar}} &lt;img src="{{avatar}}"/&gt; {{/avatar}} {{#!avatar}} &lt;img src="/images/default_avatar.png" height="75" width="75" /&gt; {{/avatar}} {{/author}} </code></pre> <p>This obviously isn't right, but the documentation doesn't mention anything like this. The word "else" isn't even mentioned :(</p> <p>Also, why is mustache designed this way? Is this sort of thing considered bad? Is it trying to force me to set the default value in the model itself? What about the cases where that isn't possible?</p>
6,479,017
5
5
null
2011-05-17 07:19:25.94 UTC
36
2021-07-02 08:04:27.633 UTC
2013-05-21 14:27:27.963 UTC
null
949,265
null
331,439
null
1
297
javascript|templates|mustache
249,203
<p>This is how you do if/else in Mustache (perfectly supported):</p> <pre><code>{{#repo}} &lt;b&gt;{{name}}&lt;/b&gt; {{/repo}} {{^repo}} No repos :( {{/repo}} </code></pre> <p>Or in your case:</p> <pre><code>{{#author}} {{#avatar}} &lt;img src=&quot;{{avatar}}&quot;/&gt; {{/avatar}} {{^avatar}} &lt;img src=&quot;/images/default_avatar.png&quot; height=&quot;75&quot; width=&quot;75&quot; /&gt; {{/avatar}} {{/author}} </code></pre> <p>Look for inverted sections in the docs: <a href="https://github.com/janl/mustache.js#inverted-sections" rel="noreferrer">https://github.com/janl/mustache.js#inverted-sections</a></p>
6,152,446
Why don't I have to import a class I just made to use it in my main class? (Java)
<p>I am currently learning Java using the Deitel's book Java How to Program 8th edition (early objects version).</p> <p>I am on the chapter on creating classes and methods.</p> <p>However, I got really confused by the example provided there because it consists of two separate .java files and when one of them uses a method from the other one, it did not import the class. It just created an object of that class from the other .java file without importing it first. </p> <p>How does that work? Why don't I need to import it?</p> <p>Here is the code from the book (I removed most comments, to save typing space/time...): .java class:</p> <pre><code>//GradeBook.java public class GradeBook { public void displayMessage() { System.out.printf( "Welcome to the grade book!" ); } } </code></pre> <p>The main .java file:</p> <pre><code>//GradeBookTest.java public class GradeBookTest { public static void main( String[] args) { GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); } } </code></pre> <p>I thought I had to write </p> <pre><code>import GradeBook.java; </code></pre> <p>or something like that. How does the compiler know where GradeBook class and its methods are found and how does it know if it exists at all if we dont import that class?</p> <p>I did lots of Googling but found no answer. I am new to programming so please tolerate my newbie question.</p> <p>Thank you in advance.</p>
6,152,474
9
0
null
2011-05-27 12:48:56.913 UTC
8
2021-07-11 14:11:31.57 UTC
2017-08-09 11:25:15.36 UTC
null
355,274
null
773,063
null
1
34
java|class|import
31,271
<p>It is because both are in same package(folder). They are automatically imported no need to write import statement for that.</p>
17,729,703
How to extract file from zip without maintaining directory structure in Python?
<p>I'm trying to extract a specific file from a zip archive using python.</p> <p>In this case, extract an apk's icon from the apk itself.</p> <p>I am currently using</p> <pre><code>with zipfile.ZipFile('/path/to/my_file.apk') as z: # extract /res/drawable/icon.png from apk to /temp/... z.extract('/res/drawable/icon.png', 'temp/') </code></pre> <p>which does work, in my script directory it's creating <code>temp/res/drawable/icon.png</code> which is temp plus the same path as the file is inside the apk.</p> <p>What I actually want is to end up with <code>temp/icon.png</code>.</p> <p>Is there any way of doing this directly with a zip command, or do I need to extract, then move the file, then remove the directories manually?</p>
17,729,939
1
0
null
2013-07-18 16:59:49.63 UTC
8
2020-09-10 02:01:55.957 UTC
2020-09-10 02:00:20.933 UTC
null
5,780,109
null
2,240,706
null
1
37
python|zip|unzip|directory-structure
34,299
<p>You can use <a href="http://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.open" rel="noreferrer">zipfile.ZipFile.open</a>:</p> <pre><code>import shutil import zipfile with zipfile.ZipFile('/path/to/my_file.apk') as z: with z.open('/res/drawable/icon.png') as zf, open('temp/icon.png', 'wb') as f: shutil.copyfileobj(zf, f) </code></pre> <p>Or use <a href="http://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.read" rel="noreferrer">zipfile.ZipFile.read</a>:</p> <pre><code>import zipfile with zipfile.ZipFile('/path/to/my_file.apk') as z: with open('temp/icon.png', 'wb') as f: f.write(z.read('/res/drawable/icon.png')) </code></pre>
44,162,432
Analysis of the output from tf.nn.dynamic_rnn tensorflow function
<p>I am not able to understand the output from <code>tf.nn.dynamic_rnn</code> tensorflow function. The document just tells about the size of the output, but it doesn't tell what does each row/column means. From the documentation:</p> <blockquote> <p><strong>outputs</strong>: The RNN output <code>Tensor</code>.</p> <p>If time_major == False (default), this will be a <code>Tensor</code> shaped: <code>[batch_size, max_time, cell.output_size]</code>.</p> <p>If time_major == True, this will be a <code>Tensor</code> shaped: <code>[max_time, batch_size, cell.output_size]</code>.</p> <p>Note, if <code>cell.output_size</code> is a (possibly nested) tuple of integers or <code>TensorShape</code> objects, then <code>outputs</code> will be a tuple having the<br> same structure as <code>cell.output_size</code>, containing Tensors having shapes corresponding to the shape data in <code>cell.output_size</code>.</p> <p><strong>state</strong>: The final state. If <code>cell.state_size</code> is an int, this will be shaped <code>[batch_size, cell.state_size]</code>. If it is a<br> <code>TensorShape</code>, this will be shaped <code>[batch_size] + cell.state_size</code>.<br> If it is a (possibly nested) tuple of ints or <code>TensorShape</code>, this will be a tuple having the corresponding shapes.</p> </blockquote> <p>The <code>outputs</code> tensor is a 3-D matrix but what does each row/column represent?</p>
44,163,122
1
0
null
2017-05-24 15:15:08.557 UTC
12
2018-04-10 09:21:00.937 UTC
null
null
null
null
333,125
null
1
13
tensorflow
7,296
<p><a href="https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn" rel="noreferrer"><code>tf.dynamic_rnn</code></a> provides two outputs, <code>outputs</code> and <code>state</code>.</p> <ul> <li><code>outputs</code> contains the output of the RNN cell at every time instant. Assuming the default <code>time_major == False</code>, let's say you have an input composed of 10 examples with 7 time steps each and a feature vector of size 5 for every time step. Then your input would be 10x7x5 (<code>batch_size</code>x<code>max_time</code>x<code>features</code>). Now you give this as an input to a RNN cell with output size 15. Conceptually, each time step of each example is input to the RNN, and you would get a 15-long vector for each of those. So that is what <code>outputs</code> contains, a tensor in this case of size 10x7x15 (<code>batch_size</code>x<code>max_time</code>x<code>cell.output_size</code>) with the output of the RNN cell at each time step. If you are only interested in the last output of the cell, you can just slice the time dimension to pick just the last element (e.g. <code>outputs[:, -1, :]</code>).</li> <li><code>state</code> contains the state of the RNN after processing all the inputs. Note that, unlike <code>outputs</code>, this doesn't contain information about every time step, but only about the last one (that is, the state <em>after</em> the last one). Depending on your case, the state may or may not be useful. For example, if you have very long sequences, you may not want/be able to processes them in a single batch, and you may need to split them into several subsequences. If you ignore the <code>state</code>, then whenever you give a new subsequence it will be as if you are beginning a new one; if you remember the state, however (e.g. outputting it or storing it in a variable), you can feed it back later (through the <code>initial_state</code> parameter of <code>tf.nn.dynamic_rnn</code>) in order to correctly keep track of the state of the RNN, and only reset it to the initial state (generally all zeros) after you have completed the whole sequences. The shape of <code>state</code> can vary depending on the RNN cell that you are using, but, in general, you have some state for each of the examples (one or more tensors with size <code>batch_size</code>x<code>state_size</code>, where <code>state_size</code> depends on the cell type and size).</li> </ul>
4,902,313
Difference between boost::shared_ptr and std::shared_ptr from the standard <memory> file
<p>I was wondering if there are any differences between the <code>boost::shared_ptr</code> and the <code>std::shared_ptr</code> found in the standard <code>&lt;memory&gt;</code> file. </p>
4,902,467
1
8
null
2011-02-04 19:55:08.993 UTC
7
2012-07-05 16:46:34.247 UTC
2012-07-05 16:46:34.247 UTC
null
734,069
null
601,159
null
1
30
c++|boost|c++11
13,131
<p><code>std::shared_ptr</code> is the C++0x form of <code>tr1::shared_ptr</code>, and boost's <code>boost::shared_ptr</code> should behave the same.</p> <p>However, <code>std::shared_ptr</code>, in an implementation that conforms to C++0x standard, should/might have more convenience behavior on the <code>shared_ptr</code> class, as described in the following links:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/1086798/differences-between-different-flavours-of-shared-ptr">Differences between different flavours of shared_ptr</a></p></li> <li><p><a href="http://en.wikipedia.org/wiki/C%2B%2B0x#General-purpose_smart_pointers" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/C%2B%2B0x#General-purpose_smart_pointers</a></p></li> </ul> <blockquote> <p>The <code>shared_ptr</code> is a reference-counted pointer that acts as much as possible like a regular C++ data pointer. The TR1 implementation lacked certain pointer features such as aliasing and pointer arithmetic, but the C++0x version will add these.</p> </blockquote> <ul> <li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3225.pdf" rel="nofollow noreferrer">November 2010 Working Draft of C++0x</a></li> </ul> <p>Though from a quick cursory glance, I do not see <code>operator+</code> and similar arithmetic operations on the <code>shared_ptr</code> type.</p>
25,219,346
How to convert from (x, y) screen coordinates to LatLng (Google Maps)
<p>I am implementing an application using Google Maps and Leap Motion and what I want right now, and I am a bit stuck, is a way to convert (x, y) screen coordinates into a Google Maps LatLng object.</p> <p>I want to achieve this in order to start, for example, a panorama (Street View) at the point where the user is pointing with the Leap Motion.</p> <p>I know about the presence of fromPointToLatLng function, but I have no clue what is the right approach in using it and how can I translate my x and y coordinates into lat lng variables.</p> <p>Can you please help me with this? </p>
25,252,731
6
1
null
2014-08-09 14:02:40.733 UTC
12
2019-07-12 15:41:08.647 UTC
2018-08-20 06:01:15.077 UTC
null
995,862
null
2,810,099
null
1
25
javascript|google-maps|google-maps-api-3
35,669
<p>After some research and some fails I came up with a solution. Following the documentation from this <a href="https://developers.google.com/maps/documentation/javascript/maptypes#WorldCoordinates">link</a> I found out that the google Points are computed in the range of x:[0-256], y:[0-256] (a tile being 256x256 pixels) and the (0,0) point being the leftmost point of the map (check the link for more information).</p> <p>However, my approach is as it follows:</p> <ul> <li><p>having the x and y coordinates (which are coordinates on the screen - on the map) I computed the percentage where the x and y coordinates were placed in response to the div containing the map (in my case, the hole window)</p></li> <li><p>computed the NortEast and SouthWest LatLng bounds of the (visible) map</p></li> <li><p>converted the bounds in google Points</p></li> <li><p>computed the new lat and lng, in google points, with the help of the boundaries and percentage of x and y </p></li> <li><p>converted back to lat lng</p> <pre><code> // retrieve the lat lng for the far extremities of the (visible) map var latLngBounds = map.getBounds(); var neBound = latLngBounds.getNorthEast(); var swBound = latLngBounds.getSouthWest(); // convert the bounds in pixels var neBoundInPx = map.getProjection().fromLatLngToPoint(neBound); var swBoundInPx = map.getProjection().fromLatLngToPoint(swBound); // compute the percent of x and y coordinates related to the div containing the map; in my case the screen var procX = x/window.innerWidth; var procY = y/window.innerHeight; // compute new coordinates in pixels for lat and lng; // for lng : subtract from the right edge of the container the left edge, // multiply it by the percentage where the x coordinate was on the screen // related to the container in which the map is placed and add back the left boundary // you should now have the Lng coordinate in pixels // do the same for lat var newLngInPx = (neBoundInPx.x - swBoundInPx.x) * procX + swBoundInPx.x; var newLatInPx = (swBoundInPx.y - neBoundInPx.y) * procY + neBoundInPx.y; // convert from google point in lat lng and have fun :) var newLatLng = map.getProjection().fromPointToLatLng(new google.maps.Point(newLngInPx, newLatInPx)); </code></pre></li> </ul> <p>Hope this solution will help someone out also! :)</p>
24,743,562
Gradle not including dependencies in published pom.xml
<p>I have a Gradle project I'm using the <strong>maven-publisher</strong> plugin to install my android library to maven local and a maven repo. </p> <p>That works, but the generated pom.xml does not include any dependency information. Is there a workaround to include that information, or am I forced to go back to the <strong>maven</strong> plugin and do all the manual configuration that requires?</p> <hr> <p>Researching I realized that I'm not telling the publication where the dependencies are, I'm only specifying the output/artifact, so I need a way to link this <a href="http://www.gradle.org/docs/current/groovydoc/org/gradle/api/publish/maven/MavenPublication.html"><code>MavenPublication</code></a> to the dependencies, but I have not yet found how to do that in the documentation.</p> <pre> ------------------------------------------------------------ Gradle 1.10 ------------------------------------------------------------ Build time: 2013-12-17 09:28:15 UTC Build number: none Revision: 36ced393628875ff15575fa03d16c1349ffe8bb6 Groovy: 1.8.6 Ant: Apache Ant(TM) version 1.9.2 compiled on July 8 2013 Ivy: 2.2.0 JVM: 1.7.0_60 (Oracle Corporation 24.60-b09) OS: Mac OS X 10.9.2 x86_64 </pre> <p>Relevant build.gradle sections</p> <pre><code>//... apply plugin: 'android-library' apply plugin: 'robolectric' apply plugin: 'maven-publish' //... repositories { mavenLocal() maven { name "myNexus" url myNexusUrl } mavenCentral() } //... android.libraryVariants publishing { publications { sdk(MavenPublication) { artifactId 'my-android-sdk' artifact "${project.buildDir}/outputs/aar/${project.name}-${project.version}.aar" } } repositories { maven { name "myNexus" url myNexusUrl credentials { username myNexusUsername password myNexusPassword } } } } </code></pre> <p>Generated pom.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;org.example.android&lt;/groupId&gt; &lt;artifactId&gt;my-android-sdk&lt;/artifactId&gt; &lt;version&gt;gradle-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;aar&lt;/packaging&gt; &lt;/project&gt; </code></pre>
24,764,713
7
1
null
2014-07-14 18:44:42.153 UTC
32
2020-01-20 11:09:50.613 UTC
2014-07-15 11:46:51.917 UTC
null
16,487
null
16,487
null
1
56
android|maven|gradle|pom.xml
18,228
<p>I was able to work around this by having the script add the dependencies to the pom directly using <code>pom.withXml</code>.</p> <pre><code>//The publication doesn't know about our dependencies, so we have to manually add them to the pom pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') //Iterate over the compile dependencies (we don't want the test ones), adding a &lt;dependency&gt; node for each configurations.compile.allDependencies.each { def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', it.group) dependencyNode.appendNode('artifactId', it.name) dependencyNode.appendNode('version', it.version) } } </code></pre> <p><em>This works for my project, it may have unforeseen consequences in others.</em></p>
42,296,329
How to properly configure xstartup file for TightVNC with Ubuntu VPS GNOME environment
<p>I'd like to access my Ubuntu 16.10 VPS (Contabo) with using a GNOME environment with VNC, however I am still facing some issues that I couldn't solve so far. To install and configure the software I ran the following commands:</p> <pre><code>sudo apt-get install ubuntu-gnome-desktop sudo apt-get install tightvncserver xtightvncviewer tightvnc-java sudo locale-gen de_DE.UTF-8 sudo apt-get install xfonts-75dpi sudo apt-get install xfonts-100dpi sudo apt-get install gnome-panel sudo apt-get install metacity sudo apt-get install light-themes touch ~/.Xresources vncpasswd </code></pre> <p>File <strong>~/.vnc/xstartup</strong> initially contains the following lines:</p> <pre><code>#!/bin/sh xrdb $HOME/.Xresources xsetroot -solid grey #x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &amp; #x-window-manager &amp; # Fix to make GNOME work export XKL_XMODMAP_DISABLE=1 /etc/X11/Xsession </code></pre> <p>When I start the VNC server using <code>vncserver -geometry 1920x1200</code> everything looks fine according to the log file in <strong>~/.vnc</strong></p> <pre><code>17/02/17 11:47:48 Xvnc version TightVNC-1.3.10 17/02/17 11:47:48 Copyright (C) 2000-2009 TightVNC Group 17/02/17 11:47:48 Copyright (C) 1999 AT&amp;T Laboratories Cambridge 17/02/17 11:47:48 All Rights Reserved. 17/02/17 11:47:48 See http://www.tightvnc.com/ for information on TightVNC 17/02/17 11:47:48 Desktop name 'X' (host:1) 17/02/17 11:47:48 Protocol versions supported: 3.3, 3.7, 3.8, 3.7t, 3.8t 17/02/17 11:47:48 Listening for VNC connections on TCP port 5901 17/02/17 11:47:48 Listening for HTTP connections on TCP port 5801 </code></pre> <p>I can successfully connect from my Windows PC via VNCViewer and see a grey window.</p> <p>Now, what is not clear to me, is what I have to change in <strong>~/.vnc/xstartup</strong> to get Gnome running. I have tried many different settings.</p> <p>E.g. when I change <strong>xstartup</strong> to</p> <pre><code>#!/bin/sh xrdb $HOME/.Xresources xsetroot -solid grey x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &amp; #x-window-manager &amp; # Fix to make GNOME work export XKL_XMODMAP_DISABLE=1 /etc/X11/Xsession #gnome-session &amp; gnome-panel &amp; gnome-settings-daemon &amp; metacity &amp; nautilus &amp; </code></pre> <p>and connect via VNC, I get the following error messages in the vnc log file:</p> <pre><code>17/02/17 14:13:09 Xvnc version TightVNC-1.3.10 17/02/17 14:13:09 Copyright (C) 2000-2009 TightVNC Group 17/02/17 14:13:09 Copyright (C) 1999 AT&amp;T Laboratories Cambridge 17/02/17 14:13:09 All Rights Reserved. 17/02/17 14:13:09 See http://www.tightvnc.com/ for information on TightVNC 17/02/17 14:13:09 Desktop name 'X' (host:1) 17/02/17 14:13:09 Protocol versions supported: 3.3, 3.7, 3.8, 3.7t, 3.8t 17/02/17 14:13:09 Listening for VNC connections on TCP port 5901 17/02/17 14:13:09 Listening for HTTP connections on TCP port 5801 17/02/17 14:13:09 URL http://5801 (nautilus:7807): Gtk-WARNING **: Failed to register client: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files metacity-Message: could not find XKB extension. Window manager warning: Missing composite extension required for compositing (gnome-settings-daemon:7805): rfkill-plugin-WARNING **: Could not open RFKILL control device, please verify your installation ** (gnome-panel:7804): WARNING **: Failed to register client: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files (nautilus:7807): Gtk-WARNING **: Theme parsing error: &lt;broken file&gt;:1:0: Failed to import: The resource at '/org/gnome/libgd/tagged-entry/default.css' does not exist Xlib: extension "XInputExtension" missing on display ":1". Xlib: extension "XInputExtension" missing on display ":1". Xlib: extension "XInputExtension" missing on display ":1". Xlib: extension "XInputExtension" missing on display ":1". Xlib: extension "XInputExtension" missing on display ":1". Xlib: extension "XInputExtension" missing on display ":1". (gnome-settings-daemon:7805): media-keys-plugin-WARNING **: Unable to inhibit keypresses: GDBus.Error:org.freedesktop.DBus.Error.AccessDenied: Permission denied ** (gnome-settings-daemon:7805): WARNING **: Unable to register client: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files ** (process:7845): WARNING **: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files (gnome-settings-daemon:7805): GLib-GIO-CRITICAL **: g_task_return_error: assertion 'error != NULL' failed Xlib: extension "XInputExtension" missing on display ":1". Xlib: extension "XInputExtension" missing on display ":1". (gnome-settings-daemon:7805): sharing-plugin-WARNING **: Failed to StopUnit service: GDBus.Error:org.freedesktop.systemd1.NoSuchUnit: Unit rygel.service not loaded. Xlib: extension "XInputExtension" missing on display ":1". (gnome-panel:7804): Gtk-WARNING **: Allocating size to PanelToplevel 0x55e8b9e1fba0 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate? Xlib: extension "XInputExtension" missing on display ":1". Nautilus-Share-Message: Called "net usershare info" but it failed: Failed to execute child process "net" (No such file or directory) Xlib: extension "XInputExtension" missing on display ":1". </code></pre> <p>And this is what I can see with VNCViewer: <a href="https://i.stack.imgur.com/TZyoZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TZyoZ.png" alt="enter image description here"></a></p> <p>Until now I wasn't able to fix the issues in the log file. Thank you very much for your help.</p> <p><strong>UPDATE 1</strong></p> <p>If I adapt ~/.vnc/xstartup according to <strong>UPDATE 2</strong> of <strong>muktupavels</strong> answer my log file looks like this when I connect via vncviewer:</p> <pre><code>21/02/17 08:51:52 Xvnc version TightVNC-1.3.10 21/02/17 08:51:52 Copyright (C) 2000-2009 TightVNC Group 21/02/17 08:51:52 Copyright (C) 1999 AT&amp;T Laboratories Cambridge 21/02/17 08:51:52 All Rights Reserved. 21/02/17 08:51:52 See http://www.tightvnc.com/ for information on TightVNC 21/02/17 08:51:52 Desktop name 'X' (host:1) 21/02/17 08:51:52 Protocol versions supported: 3.3, 3.7, 3.8, 3.7t, 3.8t 21/02/17 08:51:52 Listening for VNC connections on TCP port 5901 21/02/17 08:51:52 Listening for HTTP connections on TCP port 5801 21/02/17 08:51:52 URL http://host:5801 21/02/17 08:51:58 Got connection from client xxx 21/02/17 08:51:58 Using protocol version 3.8 21/02/17 08:52:03 Full-control authentication passed by xxx 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 16 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 22 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 21 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 15 21/02/17 08:52:04 Using zlib encoding for client xxx 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding -314 21/02/17 08:52:04 Enabling full-color cursor updates for client xxx 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding -223 21/02/17 08:52:04 Pixel format for client xxx: 21/02/17 08:52:04 8 bpp, depth 8 21/02/17 08:52:04 uses a colour map (not true colour). 21/02/17 08:52:04 Using raw encoding for client xxx 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 22 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 21 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 16 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 15 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding -314 21/02/17 08:52:04 Enabling full-color cursor updates for client 141.83.54.107 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding -223 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 15 21/02/17 08:52:04 Using hextile encoding for client xxx 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 22 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 21 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding 16 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding -314 21/02/17 08:52:04 Enabling full-color cursor updates for client 141.83.54.107 21/02/17 08:52:04 rfbProcessClientNormalMessage: ignoring unknown encoding -223 21/02/17 08:52:04 Pixel format for client xxx: 21/02/17 08:52:04 32 bpp, depth 24, little endian 21/02/17 08:52:04 true colour: max r 255 g 255 b 255, shift r 16 g 8 b 0 21/02/17 08:52:04 no translation needed 21/02/17 08:52:08 KbdAddEvent: unknown KeySym 0xffeb - allocating KeyCode 89 </code></pre> <p>This a screenshot of the GUI: <a href="https://i.stack.imgur.com/bXnRN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bXnRN.png" alt="enter image description here"></a></p> <p>Now the clock etc. is visible on the top panel. However, the desktop is still grey and right mouse click doesn't work. </p> <p>Also some applications such as GNOME Terminal didn't start at first. When I tried to start Terminal using xterm I got the following error message:</p> <pre><code>Error constructing proxy for org.gnome.Terminal:/org/gnome/Terminal/Factory0: Error calling StartServiceByName for org.gnome.Terminal: GDBus.Error:org.freedesktop.DBus.Error.TimedOut: Failed to activate service 'org.gnome.Terminal': timed out </code></pre> <p>After executing the following commands and a reboot the GNOME Terminal and all the other programs work: </p> <pre><code>sudo locale-gen sudo localectl set-locale LANG="en_US.UTF-8" sudo reboot </code></pre> <p><strong>UPDATE 3</strong></p> <p>Added <code>--debug</code> parameter to <code>gnome-session</code> cmd in <code>~/.vnc/xstartup</code>. After restart of vncserver I got the following message in <code>~/.xsession-errors</code>:</p> <pre><code>Xsession: X session started for &lt;user&gt; at Di 21. Feb 08:35:01 CET 2017 dbus-update-activation-environment: setting DISPLAY=:1 dbus-update-activation-environment: warning: error sending to systemd: org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.freedesktop.systemd1 exited with status 1 X Error of failed request: BadValue (integer parameter out of range for operation) Major opcode of failed request: 109 (X_ChangeHosts) Value in failed request: 0x5 Serial number of failed request: 6 Current serial number in output stream: 8 localuser:&lt;user&gt; being added to access control list X Error of failed request: BadValue (integer parameter out of range for operation) Major opcode of failed request: 109 (X_ChangeHosts) Value in failed request: 0x5 Serial number of failed request: 6 Current serial number in output stream: 8 openConnection: connect: No such file or directory cannot connect to braille devices daemon brltty at :0 Incompatible XKB server support dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge dbus-update-activation-environment: warning: error sending to systemd: org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.freedesktop.systemd1 exited with status 1 dbus-update-activation-environment: setting QT_ACCESSIBILITY=1 dbus-update-activation-environment: setting QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1 dbus-update-activation-environment: warning: error sending to systemd: org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.freedesktop.systemd1 exited with status 1 Error: couldn't find RGB GLX visual or fbconfig OpenGL version not found. dbus-update-activation-environment: setting LESSOPEN=| /usr/bin/lesspipe %s dbus-update-activation-environment: setting VNCDESKTOP=X dbus-update-activation-environment: setting MAIL=/var/mail/&lt;user&gt; dbus-update-activation-environment: setting SSH_CLIENT=xx.xxx.xx.xx 54876 22 dbus-update-activation-environment: setting USER=&lt;user&gt; dbus-update-activation-environment: setting LANGUAGE=en_US: dbus-update-activation-environment: setting LC_TIME=de_DE.UTF-8 dbus-update-activation-environment: setting SHLVL=1 dbus-update-activation-environment: setting HOME=/home/&lt;user&gt; dbus-update-activation-environment: setting OLDPWD=/home/&lt;user&gt;/.vnc dbus-update-activation-environment: setting SSH_TTY=/dev/pts/0 dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge dbus-update-activation-environment: setting QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1 dbus-update-activation-environment: setting LC_MONETARY=de_DE.UTF-8 dbus-update-activation-environment: setting DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-x72bVPIADb,guid=db78e03690370c91adb4424458abeda5 dbus-update-activation-environment: setting IM_CONFIG_PHASE=1 dbus-update-activation-environment: setting LOGNAME=&lt;user&gt; dbus-update-activation-environment: setting _=/usr/bin/vncserver dbus-update-activation-environment: setting TERM=xterm dbus-update-activation-environment: setting PATH=/home/&lt;user&gt;/bin:/home/&lt;user&gt;/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games dbus-update-activation-environment: setting LC_ADDRESS=de_DE.UTF-8 dbus-update-activation-environment: setting XDG_RUNTIME_DIR=/run/user/1000 dbus-update-activation-environment: setting DISPLAY=:1 dbus-update-activation-environment: setting LC_TELEPHONE=de_DE.UTF-8 dbus-update-activation-environment: setting LANG=en_US dbus-update-activation-environment: setting XKL_XMODMAP_DISABLE=1 dbus-update-activation-environment: setting LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36: dbus-update-activation-environment: setting SHELL=/bin/bash dbus-update-activation-environment: setting SHELL=/bin/bash dbus-update-activation-environment: setting LC_NAME=de_DE.UTF-8 dbus-update-activation-environment: setting QT_ACCESSIBILITY=1 dbus-update-activation-environment: setting LESSCLOSE=/usr/bin/lesspipe %s %s dbus-update-activation-environment: setting LC_MEASUREMENT=de_DE.UTF-8 dbus-update-activation-environment: setting LC_IDENTIFICATION=de_DE.UTF-8 dbus-update-activation-environment: setting PWD=/home/&lt;user&gt; dbus-update-activation-environment: setting SSH_CONNECTION=xx.xxx.xx.xx 54876 xx.xxx.xx.xx 22 dbus-update-activation-environment: setting XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop dbus-update-activation-environment: setting LC_NUMERIC=de_DE.UTF-8 dbus-update-activation-environment: setting LC_PAPER=de_DE.UTF-8 dbus-update-activation-environment: warning: error sending to systemd: org.freedesktop.DBus.Error.Spawn.ChildExited: Process org.freedesktop.systemd1 exited with status 1 </code></pre>
42,317,659
3
2
null
2017-02-17 11:05:25.99 UTC
5
2018-03-21 17:45:01.18 UTC
2017-02-21 14:40:15.257 UTC
null
1,150,325
null
1,150,325
null
1
18
x11|ubuntu-16.04|gnome|xlib|vnc-server
52,304
<p>Your vnc log file tells you about problem. You need to install few packages:<br> <code>sudo apt-get install metacity gnome-panel</code></p> <p><strong>UPDATE 1:</strong> </p> <p>You need only <code>x-window-manager</code> or <code>metacity</code>. Both provides window manager and you need only one. From screenshot I see only two problems - grey screen and missing indicators.</p> <p>To fix missing indicators install one more package:<br> <code>sudo apt-get install indicator-applet-complete</code></p> <p>To fix grey screen you need <code>--force-desktop</code> commandline option. And if you don't want default nautilus window you can add <code>--no-default-window</code>:<br> <code>nautilus --force-desktop &amp;</code> or <code>nautilus --force-desktop --no-default-window</code></p> <p>Also <code>GNOME Flashback (Metacity)</code> session in Ubuntu 16.10 use <code>unity-settings-daemon</code> not <code>gnome-settings-daemon</code>. Don't forget to install it if you decide to change that.</p> <p>To get better working desktop you also need to exports:</p> <pre><code>export XDG_CURRENT_DESKTOP="GNOME-Flashback:GNOME" export XDG_MENU_PREFIX="gnome-flashback-" </code></pre> <p>If you decided to use <code>unity-settings-daemon</code> then <code>XDG_CURRENT_DESKTOP</code> should be <code>GNOME-Flashback:Unity</code>.</p> <p>In both cases you also need <code>gnome-flashback</code>. Install it and make sure it also started. Depending on settings daemon you might need to adjust / change GSettings. Defaults are configurated for <code>unity-settings-daemon</code>.</p> <p><strong>UPDATE 2:</strong> </p> <p>I would probably let gnome-session to start session:</p> <pre><code>#!/bin/sh xrdb $HOME/.Xresources xsetroot -solid grey export XKL_XMODMAP_DISABLE=1 export XDG_CURRENT_DESKTOP="GNOME-Flashback:Unity" export XDG_MENU_PREFIX="gnome-flashback-" gnome-session --session=gnome-flashback-metacity --disable-acceleration-check &amp; </code></pre> <p>And to install required packages just do <code>sudo apt-get install gnome-session-flashback</code></p> <p><strong>UPDATE 3:</strong> </p> <p>Looks like nautilus does not show desktop icons and background, because desktop icons are disabled.</p> <p>You can enable it with <code>gsettings set org.gnome.desktop.background show-desktop-icons true</code> or by installing <code>ubuntu-settings</code>.</p>
9,236,673
Ruby gems in stand-alone ruby scripts
<p>This is a really basic ruby gems question. I'm familiar with writing simple ruby scripts like this:</p> <pre><code>#!/usr/bin/ruby require 'time' t = Time.at(123) puts t </code></pre> <p>Now I'd like to use my own ruby gem in my script. In my rails project I can simply <code>require 'my_gem'</code>. However this doesn't work in a stand-alone script. <strong>What's the best/proper way to use my own gem in a stand-alone ruby script?</strong></p>
9,236,788
5
0
null
2012-02-11 00:28:11.123 UTC
6
2019-07-30 20:27:51.68 UTC
2013-03-13 05:08:05.647 UTC
null
918,414
null
879,664
null
1
30
ruby-on-rails|ruby|gem
22,675
<p>You should be able to simply require it directly in recent versions of Ruby.</p> <pre><code># optional, also allows you to specify version gem 'chronic', '~&gt;0.6' # just require and use it require 'chronic' puts Chronic::VERSION # yields "0.6.7" for me </code></pre> <p>If you are still on Ruby 1.8 (which does not require RubyGems by default), you will have to explicitly put this line above your attempt to load the gem:</p> <pre><code>require 'rubygems' </code></pre> <p>Alternatively, you can invoke the Ruby interpreter with the flag <code>-rubygems</code> which will have the same effect.</p> <p>See also:</p> <ul> <li><a href="http://docs.rubygems.org/read/chapter/3#page70" rel="noreferrer">http://docs.rubygems.org/read/chapter/3#page70</a></li> <li><a href="http://docs.rubygems.org/read/chapter/4" rel="noreferrer">http://docs.rubygems.org/read/chapter/4</a></li> </ul>
9,027,584
How to change the File Mode on GitHub?
<pre><code>$ git add test-file $ git commit -m 'first commit' create mode 100644 test-file $ git push </code></pre> <hr> <pre><code>$ git update-index --add --chmod=+x test-file $ git commit -m 'change mode' mode change 100644 =&gt; 100755 test-file $ git push </code></pre> <hr> <p>After that if you go to GitHub it still shows as 100644 no matter what.</p>
9,030,325
2
0
null
2012-01-27 00:40:02.727 UTC
13
2021-11-02 06:44:30.373 UTC
null
null
null
null
1,002,260
null
1
37
git|github
37,795
<p>MSYS is not the problem. Even if MSYS <code>chmod</code> doesn't work (it doesn't), Git has a built in way of getting around that problem, i.e. <code>git update-index --chmod=+x</code>. Let it be clear that <a href="https://git-scm.com/docs/git-update-index" rel="nofollow noreferrer"><code>git update-index</code></a> only messes with the index (staging area), not the local repository (working directory).</p> <p>I am convinced the problem is with GitHub. On GitHub if a file is <strong>initially</strong> pushed with mode 100775, all is well. If a file is <strong>initially</strong> pushed as 100644 it causes a problem. Attempts to change the file mode will succeed with <code>git add</code>, succeed with <code>git commit</code>, succeed with <code>git push</code>, and even show up in the GitHub file history, but <strong>not</strong> be reflected on the &quot;blob/master&quot; page on GitHub.</p> <p>Update</p> <blockquote> <p>From: Petros Amiridis (GitHub Staff)</p> <p>Subject: How to change FIle Mode on GitHub?</p> <p>I have some good news. Our awesome team has just confirmed it is a caching bug on our end. Our team has deployed a fix.</p> </blockquote>
9,013,786
What are Insertions & Deletions in Git?
<p>When I run git commands like <code>git commit</code> or <code>git log --shortstat</code> part of the output looks like:</p> <pre><code>2 files changed, 3 insertions(+), 11 deletions(-) </code></pre> <p>What is the meaning of an <strong>insertion</strong> or a <strong>deletion</strong>?</p>
9,014,393
1
0
null
2012-01-26 04:00:46.81 UTC
4
2021-01-04 22:23:07.537 UTC
null
null
null
null
193,896
null
1
47
git
22,476
<p>It is just number of lines inserted and number of lines deleted in that particular commit. Note that a modified line maybe treated as an insert and a delete.</p> <p><a href="https://git-scm.com/docs/git-log" rel="noreferrer">Git log manual</a>:</p> <blockquote> <p>--shortstat</p> <p>Output only the last line of the --stat format containing <strong>total number of modified files, as well as number of added and deleted lines.</strong></p> </blockquote>
9,444,745
JavaScript how to get tomorrows date in format dd-mm-yy
<p>I am trying to get JavaScript to display tomorrows date in format (dd-mm-yyyy)</p> <p>I have got this script which displays todays date in format (dd-mm-yyyy)</p> <pre><code>var currentDate = new Date() var day = currentDate.getDate() var month = currentDate.getMonth() + 1 var year = currentDate.getFullYear() document.write("&lt;b&gt;" + day + "/" + month + "/" + year + "&lt;/b&gt;") Displays: 25/2/2012 (todays date of this post) </code></pre> <p>But how do I get it to display tomorrows date in the same format i.e. <code>26/2/2012</code></p> <p>I tried this:</p> <pre><code>var day = currentDate.getDate() + 1 </code></pre> <p>However I could keep <code>+1</code> and go over 31 obviously there are not >32 days in a month</p> <p>Been searching for hours but seems to be no answer or solution around this?</p>
9,444,785
16
0
null
2012-02-25 14:17:37.003 UTC
15
2022-04-12 07:48:17.367 UTC
null
null
null
null
535,256
null
1
103
javascript
217,284
<p>This should fix it up real nice for you.</p> <p>If you pass the Date constructor a time it will do the rest of the work.</p> <p>24 hours 60 minutes 60 seconds 1000 milliseconds</p> <pre><code>var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000); var day = currentDate.getDate() var month = currentDate.getMonth() + 1 var year = currentDate.getFullYear() document.write("&lt;b&gt;" + day + "/" + month + "/" + year + "&lt;/b&gt;") </code></pre> <p>One thing to keep in mind is that this method will return the date exactly 24 hours from now, which can be inaccurate around daylight savings time.</p> <p>Phil's answer work's anytime:</p> <pre><code>var currentDate = new Date(); currentDate.setDate(currentDate.getDate() + 1); </code></pre> <p>The reason I edited my post is because I myself created a bug which came to light during DST using my old method.</p>
34,312,757
MySQL: SELECT UNIQUE VALUE
<p>In my table I have several duplicates. Ineed to find unique values in mysql table column.</p> <p><strong>SQL</strong></p> <pre><code>SELECT column FROM table WHERE column is unique SELECT column FROM table WHERE column = DISTINCT </code></pre> <p>I've been trying to Google, but almost all queries are more complex.</p> <p>The result I's like is all non duplicate values.</p> <p><strong>EDIT</strong> I'd like to have UNIQUE values...</p> <p>Not all values one time... (Distinct)</p>
34,312,817
4
1
null
2015-12-16 12:59:10.08 UTC
9
2022-03-10 09:05:38.42 UTC
2017-09-01 10:58:38.387 UTC
null
1,136,195
null
4,732,851
null
1
46
mysql
105,203
<p>Try to use <a href="http://dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html" rel="noreferrer">DISTINCT</a> like this:</p> <pre><code>SELECT DISTINCT mycolumn FROM mytable </code></pre> <p><strong>EDIT:</strong></p> <p>Try</p> <pre><code>select mycolumn, count(mycolumn) c from mytable group by mycolumn having c = 1 </code></pre>
22,599,301
Using Moment.js to find a specific day of the current week's date
<p><strong>Finding the date of a specific day of the current week with Moment.js</strong></p> <hr> <p>There are lots of ways to manipulate dates in javascript. I've been looking for the simplest, easiest way to do so without long, ugly code, so someone showed me <a href="http://momentjs.com/" rel="noreferrer">Moment.js</a>. </p> <p>I want to use the current date to discover the date of a specific day of the current week with this library. My attempt so far involves taking the difference between the current day number(days 0-6) and checking how many days are between it and monday(day 1), which is not right at all.</p> <p><a href="http://jsfiddle.net/5HSFN/1/" rel="noreferrer">Here's my fiddle.</a></p> <p>Here's my code:</p> <pre><code>var now = moment(); var day = now.day(); var week = [['sunday',0],['monday',1],['tuesday',2],['wednesday',3],['thursday',4],['friday',5],['saturday',6]]; var monday = moment().day(-(week[1][1] - day));//today minus the difference between monday and today $("#console").text(monday); //I need to know the date of the current week's monday //I need to know the date of the current week's friday </code></pre> <p>How can I do this? My method may be a terrible way to get this done, or it might be somewhat close. I do, however want the solution to be neat, small, dynamic, and simple, as all code should be. </p> <p>I'd prefer not to use native JS date functionality which produces ugly, messy code in every situation that I've seen.</p>
22,599,706
3
1
null
2014-03-24 00:52:27.543 UTC
11
2019-05-16 18:30:13.157 UTC
2014-03-24 01:03:45.417 UTC
user2700923
null
user2700923
null
null
1
40
javascript|jquery|date|momentjs
36,015
<p>this week's sunday</p> <pre><code>moment().startOf('week') </code></pre> <p>this week's monday</p> <pre><code>moment().startOf('isoweek') </code></pre> <p>this week's saturday</p> <pre><code>moment().endOf('week') </code></pre> <p>difference between the current day to sunday</p> <pre><code>moment().diff(moment().startOf('week'),'days') </code></pre> <p>this week's wedesday</p> <pre><code>moment().startOf('week').add('days', 3) </code></pre>
16,640,962
Convert string to XML using .Net
<p>I store the <code>XML</code> output to <code>String</code> and Again convert this string to XML .I successfully convert <code>XML</code> output to String, but i got problem again converting string to XML.</p> <p><em>sample code:</em></p> <pre><code> webservice.Service1 objService1 = new webservice.Service1(); String s = objService1.HelloWorld(); //Convert XML output into String XmlDocument xd = new XmlDocument(); xd.LoadXML(s); </code></pre> <p>I use <code>LoadXML()</code> method, but i got error</p> <pre><code>Data at the root level is invalid. Line 1 position 1. </code></pre> <p>Its grateful, if any body give right code to convert String To XML in c#. Thank you,</p>
16,641,003
2
2
null
2013-05-20 00:31:51.233 UTC
null
2015-04-10 05:21:52.08 UTC
2014-04-25 05:25:51.98 UTC
null
659,944
null
2,206,801
null
1
1
c#|asp.net|xml|vb.net
58,121
<p>You should use <strong>XDocument</strong>. <strong>XDocument</strong> is better than <strong>XMLDocument</strong>. It is very efficient, simple and easy to use.</p> <p>Your code : </p> <pre><code>webservice.Service1 objService1 = new webservice.Service1(); String s = objService1.HelloWorld(); //Convert XML output into String XmlDocument xd = new XmlDocument(); xd.LoadXml(s); </code></pre> <p><strong>Solution:</strong></p> <pre><code>XDocument xd = XDocument.Parse(s); </code></pre>
31,775,589
Get JSON from URL by PHP
<p>I have a URL that returns a JSON object like this:</p> <pre><code>[ { "idIMDB": "tt0111161", "ranking": 1, "rating": "9.2", "title": "The Shawshank Redemption", "urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg", "year": "1994" } ] </code></pre> <p>URL : <a href="http://www.myapifilms.com/imdb/top" rel="nofollow">http://www.myapifilms.com/imdb/top</a> </p> <p>I want to get all of the <code>urlPoster</code> value and set in a array's element, and convert array to JSON so echo it.</p> <p>How can I do it through PHP?</p>
31,775,692
4
1
null
2015-08-02 19:11:18.74 UTC
3
2015-08-03 01:14:43.23 UTC
2015-08-03 01:14:43.23 UTC
null
3,088,349
null
5,040,101
null
1
3
php|json|getjson
40,017
<pre><code>$json = file_get_contents('http://www.myapifilms.com/imdb/top'); $array = json_decode($json); $urlPoster=array(); foreach ($array as $value) { $urlPoster[]=$value-&gt;urlPoster; } print_r($urlPoster); </code></pre>
3,796,025
Fill SVG path element with a background-image
<p>Is it possible to set a <code>background-image</code> for an SVG <code>&lt;path&gt;</code> element?</p> <p>For instance, if I set the element <code>class="wall"</code>, the CSS style <code>.wall {fill: red;}</code> works, but <code>.wall{background-image: url(wall.jpg)}</code> does not, neither <code>.wall {background-color: red;}</code>.</p>
3,798,797
1
2
null
2010-09-25 23:48:03.09 UTC
70
2020-08-21 14:18:55.66 UTC
2017-10-12 22:01:47.463 UTC
null
195,835
null
230,636
null
1
205
html|css|image|svg|background-image
255,559
<p>You can do it by making the background into a <a href="http://www.w3.org/TR/SVG/pservers.html#Patterns" rel="noreferrer">pattern</a>:</p> <pre><code>&lt;defs&gt; &lt;pattern id=&quot;img1&quot; patternUnits=&quot;userSpaceOnUse&quot; width=&quot;100&quot; height=&quot;100&quot;&gt; &lt;image href=&quot;wall.jpg&quot; x=&quot;0&quot; y=&quot;0&quot; width=&quot;100&quot; height=&quot;100&quot; /&gt; &lt;/pattern&gt; &lt;/defs&gt; </code></pre> <p>Adjust the width and height according to your image, then reference it from the path like this:</p> <pre><code>&lt;path d=&quot;M5,50 l0,100 l100,0 l0,-100 l-100,0 M215,100 a50,50 0 1 1 -100,0 50,50 0 1 1 100,0 M265,50 l50,100 l-100,0 l50,-100 z&quot; fill=&quot;url(#img1)&quot; /&gt; </code></pre> <p><a href="http://www.boogdesign.com/examples/svg/path-pattern-fill.svg" rel="noreferrer">Working example</a></p>
41,007,060
Target another styled component on hover
<p>What is the best way to handle hovers in styled-components. I have a wrapping element that when hovered will reveal a button.</p> <p>I could implement some state on the component and toggle a property on hover but was wondering if there is a better way to do this with styled-cmponents.</p> <p>Something like the following doesn't work but would be ideal:</p> <pre><code>const Wrapper = styled.div` border-radius: 0.25rem; overflow: hidden; box-shadow: 0 3px 10px -3px rgba(0, 0, 0, 0.25); &amp;:not(:last-child) { margin-bottom: 2rem; } &amp;:hover { .button { display: none; } } ` </code></pre>
41,010,688
7
1
null
2016-12-06 23:51:49.897 UTC
44
2022-05-23 16:24:18.967 UTC
2017-09-01 08:46:02.037 UTC
null
2,115,623
null
2,605,300
null
1
141
reactjs|styled-components
194,491
<p>As of styled-components v2 you can interpolate other styled components to refer to their automatically generated class names. In your case you'll probably want to do something like this:</p> <pre><code>const Wrapper = styled.div` &amp;:hover ${Button} { display: none; } ` </code></pre> <p>See <a href="https://www.styled-components.com/docs/advanced#referring-to-other-components" rel="noreferrer">the documentation</a> for more information!</p> <p>The order of components is important. It will only work if <code>Button</code> is defined above/before <code>Wrapper</code>.</p> <hr> <p>If you're using v1 and you need to do this you can work around it by using a custom class name:</p> <pre><code>const Wrapper = styled.div` &amp;:hover .my__unique__button__class-asdf123 { display: none; } ` &lt;Wrapper&gt; &lt;Button className="my__unique__button__class-asdf123" /&gt; &lt;/Wrapper&gt; </code></pre> <p>Since v2 is a drop-in upgrade from v1 I'd recommend updating, but if that's not in the cards this is a fine workaround.</p>
40,808,493
How to add a SVG icon within an input?
<p>I need to place icons within the inputs for creating a new user. It's probably a really easy task for someone who knows their way around front end code. However I don't. Here is the wireframe and then I show my code.</p> <h2>WIREFRAME</h2> <p><a href="https://i.stack.imgur.com/hkgyb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hkgyb.png" alt="enter image description here" /></a></p> <p>As you can see. There are icons on the left side of the inputs. Right now I have the SVG's in my directory and ready to go I just need to know how to place them within the input. Here is the code for the form</p> <h2>FORM</h2> <pre><code>&lt;label clas=&quot;name-label&quot;&gt; &lt;%= f.text_field :name, placeholder: &quot;Name&quot;, class: &quot;form-labels&quot; %&gt; &lt;/label&gt; &lt;label class=&quot;email-label&quot;&gt; &lt;%= f.text_field :email, placeholder: &quot;Email&quot;, class: &quot;form-labels&quot; %&gt; &lt;/label&gt; </code></pre> <p>So I have the placeholder with a string which currently just printing that string. I need to put the icons within that I think? Here is the css I have for the icons.</p> <h2>CSS</h2> <pre><code>.icon-email { background-image: image-url('email-field.svg'); } .icon-name { background-image: image-url('name-field.svg'); } </code></pre> <p>Is there a way I can place these classes within the place holder?</p>
40,809,038
4
2
null
2016-11-25 15:46:38.057 UTC
9
2018-02-11 22:13:47.81 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
5,650,878
null
1
31
html|css|svg
65,388
<p>You can add a pseudo element in the <code>&lt;label&gt;</code> tag, and use some <code>position</code> and <code>padding</code> tricks for the visual. Using a svg for background is just the same as using an image.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>label { position: relative; } label:before { content: ""; position: absolute; left: 10px; top: 0; bottom: 0; width: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='25' height='25' viewBox='0 0 25 25' fill-rule='evenodd'%3E%3Cpath d='M16.036 18.455l2.404-2.405 5.586 5.587-2.404 2.404zM8.5 2C12.1 2 15 4.9 15 8.5S12.1 15 8.5 15 2 12.1 2 8.5 4.9 2 8.5 2zm0-2C3.8 0 0 3.8 0 8.5S3.8 17 8.5 17 17 13.2 17 8.5 13.2 0 8.5 0zM15 16a1 1 0 1 1 2 0 1 1 0 1 1-2 0'%3E%3C/path%3E%3C/svg%3E") center / contain no-repeat; } input { padding: 10px 30px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label&gt; &lt;input type="text" placeholder="Search"&gt; &lt;/label&gt;</code></pre> </div> </div> </p>
28,105,305
How to calculate number of users and think time for load testing
<p>I want to know how to calculate <strong>number of users</strong>, <strong>Think time</strong>, <strong>Pacing time</strong> and number of Iteration for load testing.</p> <p>Requirement is:</p> <ul> <li>I need to achieve 10000 transaction per hour.</li> <li>Need to do 1 hour execution.</li> <li>Need to specify think time and pacing time</li> </ul> <p>Note: </p> <ol> <li>My script "aircraft" contains 7 transactions.</li> <li>Overall Response time is 16 sec without think time.</li> </ol> <p>How to calculate how many users to be given so that I can achieve 10000 transaction per hour and how much think time and Pacing time and number of Iteration I need to specify?</p>
28,124,215
2
1
null
2015-01-23 07:52:02.007 UTC
9
2021-01-21 20:01:11.143 UTC
2017-08-26 22:06:23.013 UTC
null
3,885,376
null
3,978,552
null
1
8
performance-testing|load-testing
42,547
<p>If your only goal is to simulate a certain number of transactions in a certain time period, you can do that with quite few virtual users in the test.</p> <p>If your average transaction time for 7 transactions is 16 seconds it means you can do 7/16 transactions per second, using a single virtual user.</p> <p>To get 10,000 transactions in an hour you would have to use multiple concurrent virtual users.</p> <pre><code>VU = Number of virtual users time = test time in seconds TPS = transactions per second VU * time * TPS = total_transactions </code></pre> <p>In this case we know total_transactions but not VU, so we rewrite it to:</p> <pre><code>total_transactions / (time * TPS) = VU </code></pre> <p>Using the numbers we have, we get:</p> <pre><code>10000 / (3600 * 7/16) = 6.3 </code></pre> <p>I.e. you need more than 6 VUs to get 10k transactions in one hour. Maybe go for 10 VUs and insert some sleep time as necessary to hit the exact 10,000 transactions.</p> <p>How much sleep time and how many iterations would you get then?</p> <p>10 users executing at 7 transactions per 16 seconds for one hour would execute a total of 10 * 7/16 * 3600 = 15,750 transactions. We need to slow the users down a bit. We need to make sure they don't do the full 7/16 transactions per second. We can use the formula again:</p> <pre><code>VU * time * TPS = total_transactions TPS = total_transactions / (VU *time) TPS = 10000 / (10 * 3600) =&gt; TPS = 0.2777... </code></pre> <p>We need to make sure the VUs only do 0.28 TPS, rather than 7/16 (0.44) TPS.</p> <pre><code>TPS = transactions / time </code></pre> <p>Your script does 7 transactions in 16 seconds, to get 7/16 (0.44) TPS.</p> <p>To find out how much time the script needs to take, we then change it to:</p> <pre><code>time = transactions / TPS time = 7 / 0.277778 =&gt; time = 25.2 seconds </code></pre> <p>Currently, your script takes 16 seconds, but we need it to take 25 seconds, so you need to add 9 seconds of sleep time.</p> <p>So:</p> <p>10 VUs, executing 7 transactions in 25 seconds, over the course of an hour, would produce 10,000 transactions:</p> <pre><code>10 * 7/25 * 3600 = 10080 </code></pre> <p>The number of script iterations each VU would perform would be:</p> <pre><code>3600 / 25 = 144 iterations </code></pre> <p>To sum up:</p> <pre><code>Number of VUs: 10 Total sleep time during one iteration: 9 Iterations/VU: 144 </code></pre> <p>Note that this all assumes that transaction time is constant and does not increase as a result of generating the traffic. This setup will generate close to 3 transactions per second on the target system, and if you have not tested at that frequency before, you don't know if that will slow down the target system or not.</p>
1,563,473
xmlNode to objects
<p>I have been working with a 3rd party java based REST webservice, that returns an array of xmlNodes. </p> <p>The xmlNode[] respresent an object and I am trying to work out the best way to Deserialize the xmlNode[] in the object? is it to build up a xmlDocument first and the Deserialize ?</p> <p>Thanks</p>
1,564,722
3
0
null
2009-10-13 23:15:55.327 UTC
6
2021-02-16 10:53:13.937 UTC
2009-11-23 15:56:39.24 UTC
null
19,756
null
102,094
null
1
17
c#|serialization|xmlnode
42,224
<p>If you have the WCF Rest Starter Kit preview installed, there's a neat trick:</p> <ul> <li>open Visual Studio</li> <li>select your XML node contents (the XML that makes up one of your nodes) and copy it to the clipboard</li> <li>from your "Edit" menu in Visual Studio, pick "Paste XML as Types"</li> </ul> <p>This will paste your XML that's on the clipboard into your project as a C# class that is capable of deserializing that exact XML. Pretty nifty!</p> <p>See these blog posts about it:</p> <ul> <li><a href="http://www.pluralsight.com/community/blogs/aaron/archive/2009/03/16/wcf-rest-starter-kit-paste-xml-as-types.aspx" rel="noreferrer">Aaron Skonnard: WCF REST Starter Kit: Paste XML as Types</a></li> <li><a href="http://blogs.msdn.com/endpoint/archive/2009/03/16/paste-xml-as-types-in-rest-starter-kit.aspx" rel="noreferrer">"Paste XML as Types" in REST Starter Kit</a></li> </ul> <p>That should save you a lot of typing and make life a lot easier!</p> <p><strong>UPDATE:</strong><br> OK, you already have your classes generated from the XML you get back. Now you need to convert a <code>XmlNode</code> to your class.</p> <p>You'll have to do something like this:</p> <pre><code>private static T ConvertNode&lt;T&gt;(XmlNode node) where T: class { MemoryStream stm = new MemoryStream(); StreamWriter stw = new StreamWriter(stm); stw.Write(node.OuterXml); stw.Flush(); stm.Position = 0; XmlSerializer ser = new XmlSerializer(typeof(T)); T result = (ser.Deserialize(stm) as T); return result; } </code></pre> <p>You need to write the XML representation (property <code>.OuterXml</code>) of the <code>XmlNode</code> to a stream (here a <code>MemoryStream</code>) and then use the <code>XmlSerializer</code> to serialize back the object from that stream.</p> <p>You can do it with the generic method and call </p> <pre><code> Customer myCustomer = ConvertNode&lt;Customer&gt;(xmlNode); </code></pre> <p>or you could even turn that code into either an extension method on the <code>XmlNode</code> class so you could write:</p> <pre><code> Customer myCustomer = xmlNode.ConvertNode&lt;Customer&gt;(); </code></pre> <p>Marc</p>
2,304,663
Apache HttpClient making multipart form post
<p>I'm pretty green to HttpClient and I'm finding the lack of (and or blatantly incorrect) documentation extremely frustrating. I'm trying to implement the following post (listed below) with Apache Http Client, but have no idea how to actually do it. I'm going to bury myself in documentation for the next week, but perhaps more experienced HttpClient coders could get me an answer sooner.</p> <p>Post:</p> <pre><code>Content-Type: multipart/form-data; boundary=---------------------------1294919323195 Content-Length: 502 -----------------------------1294919323195 Content-Disposition: form-data; name="number" 5555555555 -----------------------------1294919323195 Content-Disposition: form-data; name="clip" rickroll -----------------------------1294919323195 Content-Disposition: form-data; name="upload_file"; filename="" Content-Type: application/octet-stream -----------------------------1294919323195 Content-Disposition: form-data; name="tos" agree -----------------------------1294919323195-- </code></pre>
2,981,395
3
1
null
2010-02-21 03:35:39.223 UTC
28
2021-10-04 08:33:45.433 UTC
2012-05-18 18:09:46.277 UTC
null
21,234
null
81,409
null
1
82
java|multipartform-data|apache-httpclient-4.x
101,383
<p>Use MultipartEntityBuilder from the <a href="https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime/4.5.3" rel="noreferrer">HttpMime library</a> to perform the request you want.</p> <p>In my project I do that this way:</p> <pre><code>HttpEntity entity = MultipartEntityBuilder .create() .addTextBody(&quot;number&quot;, &quot;5555555555&quot;) .addTextBody(&quot;clip&quot;, &quot;rickroll&quot;) .addBinaryBody(&quot;upload_file&quot;, new File(filePath), ContentType.APPLICATION_OCTET_STREAM, &quot;filename&quot;) .addTextBody(&quot;tos&quot;, &quot;agree&quot;) .build(); HttpPost httpPost = new HttpPost(&quot;http://some-web-site&quot;); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); </code></pre> <p>Hope this will help.</p> <p>(Updated this post to use MultipartEntityBuilder instead of deprecated MultipartEntity, using @mtomy code as the example)</p>
8,826,884
"StandardIn has not been redirected" error in .NET (C#)
<p>I want to do a simple app using stdin. I want to create a list in one program and print it in another. I came up with the below.</p> <p>I have no idea if app2 works however in app1 I get the exception "StandardIn has not been redirected." on writeline (inside the foreach statement). How do I do what I intend?</p> <p>NOTE: I tried setting UseShellExecute to both true and false. Both cause this exception.</p> <pre><code> //app1 { var p = new Process(); p.StartInfo.RedirectStandardInput = true; p.StartInfo.FileName = @"path\bin\Debug\print_out_test.exe"; foreach(var v in lsStatic){ p.StandardInput.WriteLine(v); } p.StandardInput.Close(); } //app 2 static void Main(string[] args) { var r = new StreamReader(Console.OpenStandardInput()); var sz = r.ReadToEnd(); Console.WriteLine(sz); } </code></pre>
8,826,956
4
1
null
2012-01-11 21:26:49.713 UTC
1
2017-11-29 00:27:19.603 UTC
2012-01-11 21:31:24.53 UTC
null
30,018
user34537
null
null
1
28
c#|.net|stdin
29,600
<p>You never Start() the new process.</p>
26,987,503
Replace toolbar layout according to the displayed fragment
<p>I have an activity with navigation drawer which replace the main_fragment_container on the activity. When one of the fragments is displayed I want to change the layout of the toolbar and add a spinner to it (and remove it when the fragment is hidden).</p> <p>My layout looks like that:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:sothree="http://schemas.android.com/apk/res-auto" android:id="@+id/main_parent_view" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" sothree:theme="@style/AppTheme.ActionBar" /&gt; &lt;android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;!-- Main layout --&gt; &lt;FrameLayout android:id="@+id/main_fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;!-- Nav drawer --&gt; &lt;fragment android:id="@+id/fragment_drawer" android:name="com.idob.mysoccer.ui.DrawerFragment" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="left|start" /&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p></p>
26,989,510
2
2
null
2014-11-18 05:48:26.61 UTC
12
2021-05-08 02:53:22.747 UTC
2014-11-18 10:39:22.17 UTC
null
2,666,976
null
2,666,976
null
1
21
android|navigation-drawer|material-design|android-toolbar
26,735
<p>Not sure what you are trying to accomplish but I think, if possible, you should approach this by letting the fragments customize your toolbar rather than replacing it. Your can let your fragments hide/show views on the toolbar depending on your needs.</p> <p>Add <code>setHasOptionsMenu(true);</code> in the fragments <code>OnCreateView()</code> and then override <code>onOptionsMenuCreated()</code></p> <p>Like this:</p> <pre><code>@Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); return inflater.inflate(R.layout.result_list, container, false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.this_frag_menu, menu); super.onCreateOptionsMenu(menu, inflater); } </code></pre> <p>If you need to do more specific things with the toolbar you can get the instance using </p> <p><code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);</code></p>
19,632,075
How to read file with space separated values in pandas
<p>I try to read the file into pandas. The file has values separated by space, but with different number of spaces I tried:</p> <pre><code>pd.read_csv('file.csv', delimiter=' ') </code></pre> <p>but it doesn't work</p>
19,633,103
3
1
null
2013-10-28 10:14:45.09 UTC
25
2022-03-10 08:44:00.043 UTC
2018-11-28 01:15:40.66 UTC
null
202,229
null
2,006,977
null
1
121
python|pandas|csv
160,131
<p>add <code>delim_whitespace=True</code> argument, it's faster than regex.</p>
19,594,152
Compress camera image before upload
<p>I am using this code (from <a href="http://www.internetria.com/blog/2013/04/12/android-enviar-imagenes-por-webservice/" rel="noreferrer" title="www.internetria.com">www.internetria.com</a>) to take a photo and upload to a server:</p> <p>onCreate:</p> <pre><code>Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri output = Uri.fromFile(new File(foto)); intent.putExtra(MediaStore.EXTRA_OUTPUT, output); startActivityForResult(intent, TAKE_PICTURE); </code></pre> <p>onActivityResult:</p> <pre><code>ImageView iv = (ImageView) findViewById(R.id.imageView1); iv.setImageBitmap(BitmapFactory.decodeFile(foto)); File file = new File(foto); if (file.exists()) { UploaderFoto nuevaTarea = new UploaderFoto(); nuevaTarea.execute(foto); } else Toast.makeText(getApplicationContext(), "No se ha realizado la foto", Toast.LENGTH_SHORT).show(); </code></pre> <p>UploaderFoto:</p> <pre><code>ProgressDialog pDialog; String miFoto = ""; @Override protected Void doInBackground(String... params) { miFoto = params[0]; try { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost("http://servidor.com/up.php"); File file = new File(miFoto); MultipartEntity mpEntity = new MultipartEntity(); ContentBody foto = new FileBody(file, "image/jpeg"); mpEntity.addPart("fotoUp", foto); httppost.setEntity(mpEntity); httpclient.execute(httppost); httpclient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } return null; } </code></pre> <p>And I want to compress the image, because the size is too big.</p> <p>I don't know how to add <code>bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);</code> to my app</p>
19,596,231
4
1
null
2013-10-25 15:41:41.91 UTC
20
2016-02-23 08:21:00.75 UTC
null
null
null
null
2,907,923
null
1
30
android|image|upload|camera|compression
70,622
<p>Take a look over here: <a href="https://stackoverflow.com/questions/7832598/bytearrayoutputstream-to-a-filebody">ByteArrayOutputStream to a FileBody</a></p> <p>Something along these lines should work:</p> <p>replace</p> <pre><code>File file = new File(miFoto); ContentBody foto = new FileBody(file, "image/jpeg"); </code></pre> <p>with</p> <pre><code>Bitmap bmp = BitmapFactory.decodeFile(miFoto) ByteArrayOutputStream bos = new ByteArrayOutputStream(); bmp.compress(CompressFormat.JPEG, 70, bos); InputStream in = new ByteArrayInputStream(bos.toByteArray()); ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename"); </code></pre> <p>If file size is still an issue you may want to scale the picture in addition to compressing it.</p>
471,103
What is the best way to get RSS Feeds into a MySQL Database
<p>I am trying to take several RSS feeds, and put the content of them into a MySQL Database using PHP. After I store this content, I will display on my own page, and also combine the content into one single RSS Feed. (Probably after filtering)</p> <p>I haven't dealt with RSS Feeds before, so I am wondering the best Framework/Method of doing this is. I have read about DOM based parsing, but have heard that it takes a lot of memory, any suggestions?</p>
471,113
4
0
null
2009-01-22 22:29:24.76 UTC
9
2016-10-05 04:37:48.727 UTC
null
null
null
Chacha102
58,088
null
1
9
php|mysql|rss
24,450
<p><a href="http://magpierss.sourceforge.net/" rel="noreferrer">Magpie</a> is a reasonable RSS parser for PHP. Easy to use:</p> <pre><code>require('rss_fetch.inc'); $rss = fetch_rss($url); </code></pre> <p>An item like this for example:</p> <pre><code>&lt;item rdf:about="http://protest.net/NorthEast/calendrome.cgi?span=event&amp;ID=210257"&gt; &lt;title&gt;Weekly Peace Vigil&lt;/title&gt; &lt;link&gt;http://protest.net/NorthEast/calendrome.cgi?span=event&amp;ID=210257&lt;/link&gt; &lt;description&gt;Wear a white ribbon&lt;/description&gt; &lt;dc:subject&gt;Peace&lt;/dc:subject&gt; &lt;ev:startdate&gt;2002-06-01T11:00:00&lt;/ev:startdate&gt; &lt;ev:location&gt;Northampton, MA&lt;/ev:location&gt; &lt;ev:enddate&gt;2002-06-01T12:00:00&lt;/ev:enddate&gt; &lt;ev:type&gt;Protest&lt;/ev:type&gt; &lt;/item&gt; </code></pre> <p>Would be turned into an array like this:</p> <pre><code>array( title =&gt; 'Weekly Peace Vigil', link =&gt; 'http://protest.net/NorthEast/calendrome.cgi?span=event&amp;ID=210257', description =&gt; 'Wear a white ribbon', dc =&gt; array ( subject =&gt; 'Peace' ), ev =&gt; array ( startdate =&gt; '2002-06-01T11:00:00', enddate =&gt; '2002-06-01T12:00:00', type =&gt; 'Protest', location =&gt; 'Northampton, MA' ) ); </code></pre> <p>Then you can just pick out the bits you want to save in the DB and away you go!</p>
692,528
Mac OS X terminal killall won't kill running process
<p>I have an instance of lighttpd running. When I do "ps -axc" the process is listed as</p> <pre><code>"614 ?? 0:00.15 lighttpd" </code></pre> <p>But when I do "killall lighttpd" I get</p> <pre><code>No matching processes belonging to you were found </code></pre> <p>I'm on Mac OS X 10.5.6. Is there something I'm missing?</p>
692,537
4
0
null
2009-03-28 09:56:15.067 UTC
7
2021-11-07 19:56:16.243 UTC
2009-03-28 11:16:07.54 UTC
Im safe against SQL injection
30,453
null
68,788
null
1
12
macos|terminal
38,381
<p>As per the other response, if it's not your process, prepend <code>sudo</code> if you're an administrator. If not, you may be out of luck.</p> <p>Also, try <code>sudo killall -9 lighttpd</code> which sends the specific signal KILL instead of TERM.</p> <p>Just to be sure you can also try <code>sudo kill -9 614</code> using the PID.</p>
512,922
How do you handle Membership/Roles when using NHibernate?
<p>I'm about to kick off a new project using NHibernate and ASP.Net MVC and have come upon the question of membership. I'm wondering if I should use a 3rd party NHibernate Membership/Role provider, create my own, or just skip the providers all together.</p> <p>So far I've looked at:<br> <a href="http://www.manuelabadia.com/blog/PermaLink,guid,3b6ccb3f-2f2a-4dcb-a414-605371a00618.aspx" rel="nofollow noreferrer">Manuel Abadia's NHCustomProviders</a> - It seems like a lot of configuraton, not sure if I want to put all that in my web.config.<br> <a href="http://www.codeplex.com/nhibernateprovider" rel="nofollow noreferrer">Leo Vildosola's NHibernateProvider</a> - Which doesn't appear to be supported by the project owner anymore since he doesn't use NHibernate anymore.<br> <a href="http://devage.com/Wiki/ViewArticle.aspx?name=eucalypto&amp;version=0" rel="nofollow noreferrer">Eucalypto</a> - I like the table structure, but am a bit warry of all the extra CMS stuff it comes with.<br> * Each of these projects looks like it hasn't been touched in a while, which could mean extra work just getting them updated to use the newest version of NHibernate.</p> <p>This is one of those problems that's been solved many times and I would like to spend my time solving new problems, and hopefully adding some business value.</p>
512,981
1
2
null
2009-02-04 19:29:21.357 UTC
11
2013-03-15 05:11:01.303 UTC
2013-03-15 05:11:01.303 UTC
RKitson
727,208
RKitson
16,947
null
1
12
asp.net-mvc|nhibernate|asp.net-membership|membership-provider
2,915
<p>I rolled my own. It's actually a lot easier than most people think (I was surprised too) - once you actually get rolling, everything comes together pretty quickly. It's one thing to spend days or more solving a solved problem, but this took me all of a few hours including planning.</p>
19,734,154
Followers/following database structure
<p>My website has a followers/following system (like Twitter's). My dilemma is creating the database structure to handle who's following who.</p> <p>What I came up with was creating a table like this:</p> <pre><code> id | user_id | followers | following 1 | 20 | 23,58,84 | 11,156,27 2 | 21 | 72,35,14 | 6,98,44,12 ... | ... | ... | ... </code></pre> <p>Basically, I was thinking that each user would have a row with columns for their followers and the users they're following. The followers and people they're following would have their user id's separated by commas.</p> <p>Is this an effective way of handling it? If not, what's the best alternative?</p>
19,734,232
4
0
null
2013-11-01 19:37:07.667 UTC
18
2018-09-27 23:25:41.14 UTC
2018-08-26 11:31:13.147 UTC
null
759,866
null
2,762,057
null
1
22
php|mysql|database|database-design
25,620
<p>That's the worst way to do it. It's against normalization. Have 2 seperate tables. Users and User_Followers. Users will store user information. User_Followers will be like this:</p> <pre><code>id | user_id | follower_id 1 | 20 | 45 2 | 20 | 53 3 | 32 | 20 </code></pre> <p>User_Id and Follower_Id's will be foreign keys referring the Id column in the Users table.</p>
19,790,570
Using a global variable with a thread
<p>How do I share a global variable with thread?</p> <p>My Python code example is:</p> <pre><code>from threading import Thread import time a = 0 #global variable def thread1(threadname): #read variable "a" modify by thread 2 def thread2(threadname): while 1: a += 1 time.sleep(1) thread1 = Thread( target=thread1, args=("Thread-1", ) ) thread2 = Thread( target=thread2, args=("Thread-2", ) ) thread1.join() thread2.join() </code></pre> <p>I don't know how to get the two threads to share one variable.</p>
19,790,803
5
0
null
2013-11-05 13:50:46.17 UTC
19
2019-02-22 04:14:49.263 UTC
2018-10-27 22:32:13.753 UTC
null
6,862,601
null
2,859,310
null
1
111
python|multithreading|global-variables
244,322
<p>You just need to declare <code>a</code> as a global in <code>thread2</code>, so that you aren't modifying an <code>a</code> that is local to that function.</p> <pre><code>def thread2(threadname): global a while True: a += 1 time.sleep(1) </code></pre> <p>In <code>thread1</code>, you don't need to do anything special, as long as you don't try to modify the value of <code>a</code> (which would create a local variable that shadows the global one; use <code>global a</code> if you need to)></p> <pre><code>def thread1(threadname): #global a # Optional if you treat a as read-only while a &lt; 10: print a </code></pre>
2,338,439
Select element based on EXACT text contents
<p>I have a list of divs that all contain a <code>p</code> tag classed as <code>index</code>. The textual content of these <code>p</code> tags is a number from 1 to <em>n</em> (although probably no more than maybe 30-40). I had the following selector, which worked fine in preliminary testing:</p> <pre><code>var ad = $('.existing_ad .index:contains('+index+')').parents('.existing_ad'); </code></pre> <p>Where <code>index</code> is the numeric index I retrieved from the <code>p</code> tag and <code>.existing_ad</code> is the class of the parent <code>div</code>. As I said, this worked fine... until I went with higher numbers. For instance, when the index is <strong>1</strong>, it selects the <code>.existing_ad</code>s where the index HAS A <strong>1</strong> IN IT, e.g. 1, 10-19, 21, 31, etc.</p> <p><strong>How can I get ONLY index <em>n</em>?</strong></p>
2,338,452
2
1
null
2010-02-25 23:30:59.61 UTC
6
2014-11-09 14:05:56.9 UTC
null
null
null
null
7,173
null
1
41
jquery
16,915
<p>How about this:</p> <pre><code>$('.existing_ad .index').filter(function() { return $(this).text() == index; }).parents('.existing_ad'); </code></pre>
42,493,135
Is it possible to access a Github Wiki via SSH?
<p>I just created a Wiki for a Github repo, and cloned it to my desktop. There is only the option to clone using <code>https</code>, which means every time I try to push <code>git</code> asks me for my username and password.</p> <p>Is there some way to use SSH in a Github Wiki as I do with all my standard repos?</p> <p>I checked the <a href="https://help.github.com/categories/wiki/" rel="noreferrer">Wiki help</a> but couldn't find anything there.</p> <hr> <p>I' using 2FA in Github by the way.</p>
42,493,214
1
0
null
2017-02-27 18:25:58.587 UTC
3
2018-02-01 23:28:05.943 UTC
null
null
null
null
1,391,441
null
1
35
git|github|ssh
4,360
<p>You can also clone wiki via ssh : </p> <pre><code>git clone [email protected]:YOUR_USERNAME/YOUR_REPOSITORY.wiki.git </code></pre>
60,454,048
how does axios handle blob vs arraybuffer as responseType?
<p>I'm downloading a zip file with <a href="https://www.npmjs.com/package/axios" rel="noreferrer">axios</a>. For further processing, I need to get the "raw" data that has been downloaded. As far as I can see, in Javascript there are two types for this: Blobs and Arraybuffers. Both can be specified as <code>responseType</code> in the request options.</p> <p>In a next step, the zip file needs to be uncompressed. I've tried two libraries for this: js-zip and adm-zip. Both want the data to be an ArrayBuffer. So far so good, I can convert the blob to a buffer. And after this conversion adm-zip always happily extracts the zip file. However, js-zip complains about a corrupted file, unless the zip has been downloaded with <code>'arraybuffer'</code> as the axios <code>responseType</code>. js-zip does not work on a <code>buffer</code> that has been taken from a <code>blob</code>.</p> <p>This was very confusing to me. I thought both <code>ArrayBuffer</code> and <code>Blob</code> are essentially just views on the underlying memory. There might be a difference in performance between downloading something as a blob vs buffer. But the resulting data should be the same, right ?</p> <p>Well, I decided to experiment and found this:</p> <p>If you specify <code>responseType: 'blob'</code>, axios converts the <code>response.data</code> to a string. Let's say you hash this string and get hashcode A. Then you convert it to a buffer. For this conversion, you need to specify an encoding. Depending on the encoding, you will get a variety of new hashes, let's call them B1, B2, B3, ... When specifying 'utf8' as the encoding, I get back to the original hash A.</p> <p>So I guess when downloading data as a <code>'blob'</code>, axios implicitly converts it to a string encoded with utf8. This seems very reasonable.</p> <p>Now you specify <code>responseType: 'arraybuffer'</code>. Axios provides you with a buffer as <code>response.data</code>. Hash the buffer and you get a hashcode C. This code does not correspond to any code in A, B1, B2, ...</p> <p>So when downloading data as an <code>'arraybuffer'</code>, you get entirely different data?</p> <p>It now makes sense to me that the unzipping library js-zip complains if the data is downloaded as a <code>'blob'</code>. It probably actually is corrupted somehow. But then how is adm-zip able to extract it? And I checked the extracted data, it is correct. This might only be the case for this specific zip archive, but nevertheless surprises me.</p> <p>Here is the sample code I used for my experiments:</p> <pre><code>//typescript import syntax, this is executed in nodejs import axios from 'axios'; import * as crypto from 'crypto'; axios.get( "http://localhost:5000/folder.zip", //hosted with serve { responseType: 'blob' }) // replace this with 'arraybuffer' and response.data will be a buffer .then((response) =&gt; { console.log(typeof (response.data)); // first hash the response itself console.log(crypto.createHash('md5').update(response.data).digest('hex')); // then convert to a buffer and hash again // replace 'binary' with any valid encoding name let buffer = Buffer.from(response.data, 'binary'); console.log(crypto.createHash('md5').update(buffer).digest('hex')); //... </code></pre> <p>What creates the difference here, and how do I get the 'true' downloaded data?</p>
60,461,828
1
0
null
2020-02-28 14:46:56.053 UTC
11
2020-03-01 03:54:17.05 UTC
null
null
null
null
497,600
null
1
48
javascript|node.js|axios|blob|arraybuffer
104,229
<p>From <a href="https://github.com/axios/axios#request-config" rel="noreferrer">axios docs</a>:</p> <blockquote> <pre class="lang-js prettyprint-override"><code>// `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default </code></pre> </blockquote> <h3><code>'blob'</code> is a &quot;browser only&quot; option.</h3> <p>So from node.js, when you set <code>responseType: &quot;blob&quot;</code>, <code>&quot;json&quot;</code>will actually be used, which I guess fallbacks to <code>&quot;text&quot;</code> when no parse-able JSON data has been fetched.</p> <p>Fetching binary data as text is prone to generate corrupted data. Because the text returned by <a href="https://developer.mozilla.org/en-US/docs/Web/API/Body/text" rel="noreferrer">Body.text()</a> and many other APIs are <a href="https://developer.mozilla.org/en-US/docs/Web/API/USVString" rel="noreferrer">USVStrings</a> (they don't allow unpaired surrogate codepoints ) and because the response is decoded as UTF-8, some bytes from the binary file can't be mapped to characters correctly and will thus be replaced by � (U+FFDD) replacement character, with no way to get back what that data was before: your data is corrupted.</p> <p>Here is a snippet explaining this, using the header of a .png file <code>0x89 0x50 0x4E 0x47</code> as an example.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>(async () =&gt; { const url = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'; // fetch as binary const buffer = await fetch( url ).then(resp =&gt; resp.arrayBuffer()); const header = new Uint8Array( buffer ).slice( 0, 4 ); console.log( 'binary header', header ); // [ 137, 80, 78, 61 ] console.log( 'entity encoded', entityEncode( header ) ); // [ "U+0089", "U+0050", "U+004E", "U+0047" ] // You can read more about (U+0089) character here // https://www.fileformat.info/info/unicode/char/0089/index.htm // You can see in the left table how this character in UTF-8 needs two bytes (0xC2 0x89) // We thus can't map this character correctly in UTF-8 from the UTF-16 codePoint, // it will get discarded by the parser and converted to the replacement character // read as UTF-8 const utf8_str = await new Blob( [ header ] ).text(); console.log( 'read as UTF-8', utf8_str ); // "�PNG" // build back a binary array from that string const utf8_binary = [ ...utf8_str ].map( char =&gt; char.charCodeAt( 0 ) ); console.log( 'Which is binary', utf8_binary ); // [ 65533, 80, 78, 61 ] console.log( 'entity encoded', entityEncode( utf8_binary ) ); // [ "U+FFDD", "U+0050", "U+004E", "U+0047" ] // You can read more about character � (U+FFDD) here // https://www.fileformat.info/info/unicode/char/0fffd/index.htm // // P (U+0050), N (U+004E) and G (U+0047) characters are compatible between UTF-8 and UTF-16 // For these there is no encoding lost // (that's how base64 encoding makes it possible to send binary data as text) // now let's see what fetching as text holds const fetched_as_text = await fetch( url ).then( resp =&gt; resp.text() ); const header_as_text = fetched_as_text.slice( 0, 4 ); console.log( 'fetched as "text"', header_as_text ); // "�PNG" const as_text_binary = [ ...header_as_text ].map( char =&gt; char.charCodeAt( 0 ) ); console.log( 'Which is binary', as_text_binary ); // [ 65533, 80, 78, 61 ] console.log( 'entity encoded', entityEncode( as_text_binary ) ); // [ "U+FFDD", "U+0050", "U+004E", "U+0047" ] // It's been read as UTF-8, we lost the first byte. })(); function entityEncode( arr ) { return Array.from( arr ).map( val =&gt; 'U+' + toHex( val ) ); } function toHex( num ) { return num.toString( 16 ).padStart(4, '0').toUpperCase(); }</code></pre> </div> </div> </p> <hr /> <p>There is natively no Blob object in node.js, so it makes sense axios didn't monkey-patch it just so they can return a response no-one else would be able to consume anyway.</p> <p>From a browser, you'd have exactly the same responses:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function fetchAs( type ) { return axios( { method: 'get', url: 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', responseType: type } ); } function loadImage( data, type ) { // we can all pass them to the Blob constructor directly const new_blob = new Blob( [ data ], { type: 'image/jpg' } ); // with blob: URI, the browser will try to load 'data' as-is const url = URL.createObjectURL( new_blob ); img = document.getElementById( type + '_img' ); img.src = url; return new Promise( (res, rej) =&gt; { img.onload = e =&gt; res(img); img.onerror = rej; } ); } [ 'json', // will fail 'text', // will fail 'arraybuffer', 'blob' ].forEach( type =&gt; fetchAs( type ) .then( resp =&gt; loadImage( resp.data, type ) ) .then( img =&gt; console.log( type, 'loaded' ) ) .catch( err =&gt; console.error( type, 'failed' ) ) );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/axios/dist/axios.min.js"&gt;&lt;/script&gt; &lt;figure&gt; &lt;figcaption&gt;json&lt;/figcaption&gt; &lt;img id="json_img"&gt; &lt;/figure&gt; &lt;figure&gt; &lt;figcaption&gt;text&lt;/figcaption&gt; &lt;img id="text_img"&gt; &lt;/figure&gt; &lt;figure&gt; &lt;figcaption&gt;arraybuffer&lt;/figcaption&gt; &lt;img id="arraybuffer_img"&gt; &lt;/figure&gt; &lt;figure&gt; &lt;figcaption&gt;blob&lt;/figcaption&gt; &lt;img id="blob_img"&gt; &lt;/figure&gt;</code></pre> </div> </div> </p>
24,254,006
rightclick event in Qt to open a context menu
<p>I have a segment of code that calls a mousePressEvent. I have the left-click output the coordinates of the cursor, and I have rightclick do the same, but I also want to have the rightclick open a context menu. The code I have so far is:</p> <pre><code>void plotspace::mousePressEvent(QMouseEvent*event) { double trange = _timeonright - _timeonleft; int twidth = width(); double tinterval = trange/twidth; int xclicked = event-&gt;x(); _xvaluecoordinate = _timeonleft+tinterval*xclicked; double fmax = Data.plane(X,0).max(); double fmin = Data.plane(X,0).min(); double fmargin = (fmax-fmin)/40; int fheight = height(); double finterval = ((fmax-fmin)+4*fmargin)/fheight; int yclicked = event-&gt;y(); _yvaluecoordinate = (fmax+fmargin)-finterval*yclicked; cout&lt;&lt;"Time(s): "&lt;&lt;_xvaluecoordinate&lt;&lt;endl; cout&lt;&lt;"Flux: "&lt;&lt;_yvaluecoordinate&lt;&lt;endl; cout &lt;&lt; "timeonleft= " &lt;&lt; _timeonleft &lt;&lt; "\n"; returncoordinates(); emit updateCoordinates(); if (event-&gt;button()==Qt::RightButton) { contextmenu-&gt;setContextMenuPolicy(Qt::CustomContextMenu); connect(contextmenu, SIGNAL(customContextMenuRequested(const QPoint&amp;)), this, SLOT(ShowContextMenu(const QPoint&amp;))); void A::ShowContextMenu(const QPoint &amp;pos) { QMenu *menu = new QMenu; menu-&gt;addAction(tr("Remove Data Point"), this, SLOT(test_slot())); menu-&gt;exec(w-&gt;mapToGlobal(pos)); } } } </code></pre> <p>I know that my problem is very fundamental in nature, and that 'contextmenu' is not properly declared. I have pieced together this code from many sources, and do not know how to declare something in c++. Any advice would be greatly appreciated.</p>
24,255,300
1
0
null
2014-06-17 00:15:47.82 UTC
7
2014-06-17 03:33:11.33 UTC
null
null
null
null
3,739,099
null
1
31
c++|qt|events|contextmenu
53,843
<p><code>customContextMenuRequested</code> is emitted when the widget's contextMenuPolicy is <code>Qt::CustomContextMenu</code>, and the user has requested a context menu on the widget. So in the constructor of your widget you can call <code>setContextMenuPolicy</code> and connect <code>customContextMenuRequested</code> to a slot to make a custom context menu.</p> <p>In the constructor of <code>plotspace</code> :</p> <pre><code>this-&gt;setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint &amp;)), this, SLOT(ShowContextMenu(const QPoint &amp;))); </code></pre> <p><code>ShowContextMenu</code> slot should be a class member of <code>plotspace</code> like :</p> <pre><code>void plotspace::ShowContextMenu(const QPoint &amp;pos) { QMenu contextMenu(tr("Context menu"), this); QAction action1("Remove Data Point", this); connect(&amp;action1, SIGNAL(triggered()), this, SLOT(removeDataPoint())); contextMenu.addAction(&amp;action1); contextMenu.exec(mapToGlobal(pos)); } </code></pre>
26,870,698
Change ActionBar title text color using Light.DarkActionBar theme in AppCompat 21
<p>I'm using the v7 appcompat 21 library to use the new Material styles on pre-Lollipop devices. My styles.xml looks like this:</p> <pre><code>&lt;style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"&gt; &lt;item name="android:textColorPrimary"&gt;#ff0000&lt;/item&gt; &lt;item name="android:textColorPrimaryInverse"&gt;#ff0000&lt;/item&gt; &lt;/style&gt; </code></pre> <p>I am trying to change the text color on the action bar. But no matter what I put for textColorPrimary or textColorPrimaryInverse, the color is always white. If I inherit from Theme.AppCompat, I can override "textColorPrimary", and if I inherit from Theme.AppCompat.Light, I can override "textColorPrimaryInverse". But neither work when using the Light.DarkActionBar theme.</p> <p>I am definitely using the AppTheme because setting attributes like colorPrimary to change the actionbar background color works fine. I am not using any other resource qualifier style files.</p> <p>I've dug through the android styles files and can't seem to figure out what attribute to override. Any ideas? Is this an appcompat bug?</p>
26,871,541
7
0
null
2014-11-11 17:23:24.963 UTC
20
2020-08-19 09:20:10.44 UTC
null
null
null
null
14,870
null
1
57
android|android-actionbar|android-appcompat|android-actionbar-compat|material-design
64,336
<p>You can change it with <code>actionBarStyle</code> attribute of theme.</p> <pre><code>&lt;style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar"&gt; &lt;item name="actionBarStyle"&gt;@style/MyActionBar&lt;/item&gt; &lt;/style&gt; &lt;style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar.Solid"&gt; &lt;item name="titleTextStyle"&gt;@style/MyTitleTextStyle&lt;/item&gt; &lt;/style&gt; &lt;style name="MyTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"&gt; &lt;item name="android:textColor"&gt;CHANGE_COLOR_HERE&lt;/item&gt; &lt;/style&gt; </code></pre>
27,571,573
Laravel 5 new auth: Get current user and how to implement roles?
<p>I am currently experimenting with the new Laravel 5 and got the authentication to work (register/login).</p> <p>To get the authenticated user in my controller I currently inject <code>Guard</code> into the controller action:</p> <pre><code>use App\Http\Controllers\Controller; use Illuminate\Contracts\Auth\Guard; class ClientController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index(Guard $auth) { return view('client.index', ['user' =&gt; $auth-&gt;user()]); } ... </code></pre> <p><strong>First Question:</strong> Is this the recommended way?</p> <p><strong>Second Question:</strong> How would I go about implementing some kind of roles/permissions? Something like <code>client.edit</code>, <code>client.add</code>, ... Does Larval 5 offer some kind of convenience here? How would I set the necessary role/permission for a route/controller action?</p> <p>I am thinking that I might need to write my own middleware for that. Any suggestions on how to approach the problem?</p>
27,651,312
2
0
null
2014-12-19 18:09:24.227 UTC
12
2015-05-21 03:35:13.497 UTC
null
null
null
null
1,532,168
null
1
21
php|authentication|laravel|laravel-5
51,082
<p>After spending some more time on Laravel 5 I can an answer my own question:</p> <p><strong>Is injecting <code>Guard</code> the recommended way?</strong> No: If you need to access <code>Auth</code> in your view, you can do so already like this:</p> <pre><code>@if( Auth::check() ) Current user: {{ Auth::user()-&gt;name }} @endif </code></pre> <p>This uses the <code>Auth</code> facade. A list of all available facades is in <code>config/app.php</code> under <code>aliases:</code></p> <p><strong>What if I need <code>Auth</code> in my controller?</strong> Injecting an instance of <code>Guard</code> like shown in the question works, but you don't need to. You can use the <code>Auth</code> facade like we did in the template:</p> <pre><code> public function index() { if(\Auth::check() &amp;&amp; \Auth::user()-&gt;name === 'Don') { // Do something } return view('client.index'); } </code></pre> <p>Be aware that the <code>\</code> is needed before the facade name since L5 is using namespaces.</p> <p><strong>I want to have permissions/roles using the new auth mechanism in L5:</strong> I implemented a lightweight permission module using the new middleware, it is called <strong>Laraguard</strong>. Check it out on Github and let me know what you think: <a href="https://github.com/cgrossde/Laraguard">https://github.com/cgrossde/Laraguard</a> </p> <p><strong>UPDATE:</strong> For the sake of completeness I want to mention two more projects. They provide everything you need to save roles and permissions in the DB and work perfectly together with Laraguard or on their own:</p> <ul> <li><a href="https://github.com/caffeinated/shinobi">https://github.com/caffeinated/shinobi</a></li> <li><a href="https://github.com/romanbican/roles">https://github.com/romanbican/roles</a></li> </ul>
27,422,054
How to implement tab bar controller with navigation controller in right way
<p>I am using Storyboard and Xcode 6. I have next controllers and scenes in my Storyboard:</p> <p><code>UINavigationController</code> that has <code>HomeViewController</code> as a root. <code>HomeViewController</code> has a button that <code>Show (e.g. Push)</code> <code>UITabBarController</code>. <code>UITabBarController</code> has 4 <code>UIViewControllers</code>.</p> <p>But my problem that after I Show <code>UITabBarController</code> there are no Navigation Bars in 4 <code>UIViewControllers</code>. But I supposed that if I <code>Show (e.g. Push)</code> <code>UITabBarController</code> then it should has embedded navigation controller that is initial controller in storyboard. Am I right? And if so how can I setup then navigation bar in Storyboard, because there are now default bar event in pushed tab bar that I see on storyboard. I have selected UIViewController and set simulated metrics in identity inspector to Translucent Navigation bar for the Top property, but I supposed it should be automatically added to this controller and to the tab bar without additional steps.</p> <p>Or should I add new navigation controller for each tab bar items that will have their root view controllers?</p> <p>The main question why I don't see navigation bar in storyboard using show (e.g. Push). For example if I add navigation controller and then set as root - tab bar controller then Xcode automatically add top navigation bar, but if the queue has an extra step like in my case HomeViewController the top navigation bar never appear automatically.</p>
27,425,271
3
0
null
2014-12-11 11:41:50.453 UTC
30
2017-11-09 05:53:49.33 UTC
null
null
null
null
587,415
null
1
54
ios|uinavigationcontroller|uitabbarcontroller|xcode6|uistoryboard
72,145
<p>Hi you need to embed each view controller that is within the tab bar in a navigation controller of its own. So the flow is like so (HomeVC is embedded in a NavController of it's own):</p> <pre><code> / --&gt; `NavController` --&gt; `ViewController1` | --&gt; `NavController` --&gt; `ViewController2` `HomeViewController`--&gt;`TabBarController`|--&gt; `NavController` --&gt; `ViewController3` \--&gt; `NavController` --&gt; `ViewController4` </code></pre> <ol> <li>Go to <strong>Editor</strong> --> <strong>Embed In</strong> --> <strong>Tab Bar Controller</strong> (or Navigation Controller)</li> </ol> <p><a href="https://i.stack.imgur.com/hG4XQ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/hG4XQ.gif" alt="How to embed correctly"></a></p> <p>To answer your questions:</p> <blockquote> <p><em>Each tab of a tab bar controller interface is associated with a custom (different [sic]) view controller. When the user selects a specific tab, the tab bar controller displays the root view of the corresponding view controller, replacing any previous views.</em></p> </blockquote> <p>So the Root View Controller of the tab must be adjoined to a Navigation Controller; a navigation view controller must be next inline in order for the View Controller to inherit a Navigation. A Tab Bar switches views to whatever is next inline. </p> <p>This document will help outline more information about it. <a href="https://developer.apple.com/documentation/uikit/uitabbarcontroller" rel="noreferrer">https://developer.apple.com/documentation/uikit/uitabbarcontroller</a></p>
21,190,395
Python Mechanize - Login
<p>I am trying to login to a website and get data from it. I can't seem to get mechanize to work on the following site. I have provided the HTML below. Could someone please give me brief help of how I can log in and print the next page?</p> <p>I have tried using mechanize and looping through br.forms(). I can see the form in that but I am having problems getting my username and password insert in and then hitting submit.</p> <pre><code>&lt;div class="loginform" id="loginpage" style="width: 300px;"&gt; &lt;div class="loginformentries" style="overflow: hidden;"&gt; &lt;div class="clearfix"&gt; &lt;div class="loginformtitle"&gt;Sign-in to your account&lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix"&gt; &lt;div class="loginformlabel"&gt;&lt;label for="USERID"&gt;Username:&lt;/label&gt;&lt;/div&gt; &lt;div class="loginforminput"&gt;&lt;input name="USERID" id="USERID" style="width: 150px;" type="text" value=""&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix"&gt; &lt;div class="loginformlabel"&gt;&lt;label for="PASSWDTXT"&gt;Password:&lt;/label&gt;&lt;/div&gt; &lt;div class="loginforminput"&gt;&lt;input name="PASSWDTXT" id="PASSWDTXT" style="width: 150px;" type="password" value=""&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix"&gt; &lt;div class="loginformlabel"&gt;&lt;label for="usertype"&gt;Select Role:&lt;/label&gt;&lt;/div&gt; &lt;div class="loginforminput"&gt;&lt;select name="usertype" id="usertype" style="width: 150px;"&gt;&lt;option value="participant"&gt;Participant&lt;/option&gt; &lt;option value="sponsor"&gt;Sponsor&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="loginformsubmit" style="text-align: right;"&gt;&lt;span class="button"&gt;&lt;button class="buttoninsidebuttonclass" type="submit"&gt;Login&lt;/button&gt;&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="loginformdescription"&gt;Both entries are case sensitive. If you fail to login &lt;strong&gt;five&lt;/strong&gt; consecutive times your account could be disabled.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I am trying something like this...</p> <pre><code>import mechanize br = mechanize.Browser() br.open("test") br.select_form(name="loginform") br["USERID"] = 'xxxxx' br["PASSWDTXT"] = 'xxxxx' br.submit() print br.title() </code></pre> <p>But I don't know how to verify that I am on the next page</p>
21,190,761
1
0
null
2014-01-17 16:04:06.13 UTC
8
2014-01-17 16:38:49.757 UTC
2014-01-17 16:21:52.25 UTC
null
1,027,427
null
1,027,427
null
1
5
python|mechanize
17,844
<p>All those <code>div</code>s should be wrapped in a <code>form</code> element. Look for that and find the <code>name</code> tag. This is the form you'll want to log in with. Then you can use the snippet below to get the cookies you'll to use for further browsing.</p> <pre><code>import cookielib import urllib2 import mechanize # Browser br = mechanize.Browser() # Enable cookie support for urllib2 cookiejar = cookielib.LWPCookieJar() br.set_cookiejar( cookiejar ) # Broser options br.set_handle_equiv( True ) br.set_handle_gzip( True ) br.set_handle_redirect( True ) br.set_handle_referer( True ) br.set_handle_robots( False ) # ?? br.set_handle_refresh( mechanize._http.HTTPRefreshProcessor(), max_time = 1 ) br.addheaders = [ ( 'User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1' ) ] # authenticate br.open( the/page/you/want/to/login ) br.select_form( name="the name of the form from above" ) # these two come from the code you posted # where you would normally put in your username and password br[ "USERID" ] = yourLogin br[ "PASSWDTXT" ] = yourPassword res = br.submit() print "Success!\n" </code></pre> <p>After this, your login cookies will be saved in the <code>cookiejar</code>. Then you can use the same <code>br</code> object to get any page you like, as such</p> <pre><code>url = br.open( page/needed/after/login ) returnPage = url.read() </code></pre> <p>This will give you the HTML source of the page, which you can then parse any way you want.</p>
39,013,249
__metaclass__ in Python 3
<p>In Python2.7 this code can work very well, <code>__getattr__</code> in <code>MetaTable</code> will run. But in Python 3 it doesn't work.</p> <pre><code>class MetaTable(type): def __getattr__(cls, key): temp = key.split("__") name = temp[0] alias = None if len(temp) &gt; 1: alias = temp[1] return cls(name, alias) class Table(object): __metaclass__ = MetaTable def __init__(self, name, alias=None): self._name = name self._alias = alias d = Table d.student__s </code></pre> <p>But in Python 3.5 I get an attribute error instead:</p> <pre><code>Traceback (most recent call last): File "/Users/wyx/project/python3/sql/dd.py", line 31, in &lt;module&gt; d.student__s AttributeError: type object 'Table' has no attribute 'student__s' </code></pre>
39,013,295
1
0
null
2016-08-18 08:23:44.91 UTC
6
2019-10-27 12:15:35.173 UTC
2019-10-27 12:15:35.173 UTC
null
1,222,951
null
5,360,312
null
1
29
python|metaclass
16,856
<p>Python 3 <a href="https://www.python.org/dev/peps/pep-3115/" rel="noreferrer">changed how you specify a metaclass</a>, <code>__metaclass__</code> is no longer checked.</p> <p>Use <code>metaclass=...</code> in the class <em>signature</em>:</p> <pre><code>class Table(object, metaclass=MetaTable): </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; class MetaTable(type): ... def __getattr__(cls, key): ... temp = key.split("__") ... name = temp[0] ... alias = None ... if len(temp) &gt; 1: ... alias = temp[1] ... return cls(name, alias) ... &gt;&gt;&gt; class Table(object, metaclass=MetaTable): ... def __init__(self, name, alias=None): ... self._name = name ... self._alias = alias ... &gt;&gt;&gt; d = Table &gt;&gt;&gt; d.student__s &lt;__main__.Table object at 0x10d7b56a0&gt; </code></pre> <p>If you need to provide support for both Python 2 and 3 in your codebase, you can use the <a href="https://six.readthedocs.io/#six.with_metaclass" rel="noreferrer"><code>six.with_metaclass()</code> baseclass generator</a> or the <a href="https://six.readthedocs.io/#six.add_metaclass" rel="noreferrer"><code>@six.add_metaclass()</code> class decorator</a> to specify the metaclass.</p>
29,173,645
Java only get Exception name without StackTrace
<p>how can I get the exception name without getting the stack trace?</p> <p>I am using <code>exception.toString()</code> to convert the thrown exception into a string, but I only want the exception name like<code>NullPointerException</code> and not the entire stack trace. </p> <p>How can I solve this?</p>
29,173,669
1
0
null
2015-03-20 18:40:02.49 UTC
3
2016-09-13 06:09:08.267 UTC
2016-09-13 06:09:08.267 UTC
null
1,540,468
null
4,183,825
null
1
35
java|string|exception|stack-trace
28,029
<pre><code>exception.getClass().getSimpleName(); </code></pre> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getSimpleName()" rel="noreferrer">Class#getSimpleName()</a></p> <p>NOTE: this will not work in case if your exception is an anonymous class (although I have personally never seen an anonymous exception in any production code)</p>
22,319,354
How to create dynamic subdomains for each user using node express?
<p>On signup, I want to give user his profile and application at username.example.com I have already created wild-card dns at my domain provider website.</p> <p>How can I do that?</p>
24,719,669
3
1
null
2014-03-11 07:45:29.487 UTC
10
2020-05-22 17:24:23.177 UTC
2014-03-18 22:21:01.747 UTC
null
321,731
null
2,513,942
null
1
14
node.js|dynamic|subdomain
11,982
<p>If using Node.js with Express.js, then:</p> <pre><code>router.get('/', function (req, res) { var domain = req.get('host').match(/\w+/); // e.g., host: "subdomain.website.com" if (domain) var subdomain = domain[0]; // Use "subdomain" ... }); </code></pre>
42,781,292
Doc2Vec Get most similar documents
<p>I am trying to build a document retrieval model that returns most documents ordered by their relevancy with respect to a query or a search string. For this I trained a doc2vec model using the <code>Doc2Vec</code> model in gensim. My dataset is in the form of a pandas dataset which has each document stored as a string on each line. This is the code I have so far</p> <pre><code>import gensim, re import pandas as pd # TOKENIZER def tokenizer(input_string): return re.findall(r"[\w']+", input_string) # IMPORT DATA data = pd.read_csv('mp_1002_prepd.txt') data.columns = ['merged'] data.loc[:, 'tokens'] = data.merged.apply(tokenizer) sentences= [] for item_no, line in enumerate(data['tokens'].values.tolist()): sentences.append(LabeledSentence(line,[item_no])) # MODEL PARAMETERS dm = 1 # 1 for distributed memory(default); 0 for dbow cores = multiprocessing.cpu_count() size = 300 context_window = 50 seed = 42 min_count = 1 alpha = 0.5 max_iter = 200 # BUILD MODEL model = gensim.models.doc2vec.Doc2Vec(documents = sentences, dm = dm, alpha = alpha, # initial learning rate seed = seed, min_count = min_count, # ignore words with freq less than min_count max_vocab_size = None, # window = context_window, # the number of words before and after to be used as context size = size, # is the dimensionality of the feature vector sample = 1e-4, # ? negative = 5, # ? workers = cores, # number of cores iter = max_iter # number of iterations (epochs) over the corpus) # QUERY BASED DOC RANKING ?? </code></pre> <p>The part where I am struggling is in finding documents that are most similar/relevant to the query. I used the <code>infer_vector</code> but then realised that it considers the query as a document, updates the model and returns the results. I tried using the <code>most_similar</code> and <code>most_similar_cosmul</code> methods but I get words along with a similarity score(I guess) in return. What I want to do is when I enter a search string(a query), I should get the documents (ids) that are most relevant along with a similarity score(cosine etc). How do I get this part done?</p>
42,817,402
1
6
null
2017-03-14 08:43:26.263 UTC
21
2018-06-25 05:41:30.7 UTC
2018-06-25 05:41:30.7 UTC
null
2,324,298
null
2,324,298
null
1
44
python|nlp|gensim|doc2vec
36,956
<p>You need to use <code>infer_vector</code> to get a document vector of the new text - which does not alter the underlying model.</p> <p>Here is how you do it:</p> <pre><code>tokens = "a new sentence to match".split() new_vector = model.infer_vector(tokens) sims = model.docvecs.most_similar([new_vector]) #gives you top 10 document tags and their cosine similarity </code></pre> <p>Edit: </p> <p>Here is an example of how the underlying model does not change after <code>infer_vec</code> is called.</p> <pre><code>import numpy as np words = "king queen man".split() len_before = len(model.docvecs) #number of docs #word vectors for king, queen, man w_vec0 = model[words[0]] w_vec1 = model[words[1]] w_vec2 = model[words[2]] new_vec = model.infer_vector(words) len_after = len(model.docvecs) print np.array_equal(model[words[0]], w_vec0) # True print np.array_equal(model[words[1]], w_vec1) # True print np.array_equal(model[words[2]], w_vec2) # True print len_before == len_after #True </code></pre>
53,707,820
How to use Active Directory Authentication in ASP.NET Core?
<p>I am using the ASP.NET Core 2.1 React SPA Microsoft template.</p> <p>I want to use Active Directory for user authentication. Our server runs on a corporate network using Active Directory domain identities.</p> <p>How can I do it?</p>
53,714,206
1
5
null
2018-12-10 14:33:35.25 UTC
7
2019-12-26 16:11:59.327 UTC
2019-12-26 16:11:59.327 UTC
null
1,011,722
user10159225
null
null
1
15
active-directory|asp.net-core-2.1
41,999
<p>The best way is to use <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-2.2" rel="noreferrer">Windows authentication</a>. However, that will only work if the server you run this on is joined to the domain (or a trusted domain).</p> <p>If not, then you will have to use Forms Authentication, where the user enters their username and password, and you authenticate against AD in your code via LDAP. There are two ways to do this in .NET Core:</p> <ol> <li>If you will only run this on a Windows server, then you can install and use the <a href="https://www.nuget.org/packages/Microsoft.Windows.Compatibility" rel="noreferrer"><code>Microsoft.Windows.Compatibility</code></a> NuGet package.</li> <li>Use the third-party <a href="https://www.nuget.org/packages/Novell.Directory.Ldap.NETStandard/" rel="noreferrer"><code>Novell.Directory.Ldap.NETStandard</code></a>.</li> </ol> <p>There are two answers on <a href="https://stackoverflow.com/a/49742910/1202807">this question</a> that describe how to implement both solutions.</p>
20,888,592
getText() method of selenium chrome driver sometimes returns an empty string
<p>I have a curious case where the selenium chrome driver <code>getText()</code> method (java) returns an empty string for some elements, even though it returns a non-empty string for other elements with the same <code>xpath</code>. Here is a bit of the page.</p> <pre><code>&lt;div __gwt_cell="cell-gwt-uid-223" style="outline-style:none;"&gt; &lt;div&gt;Text_1&lt;/div&gt; &lt;div&gt;Text_2&lt;/div&gt; &lt;div&gt;Text_3&lt;/div&gt; &lt;div&gt;Text_4&lt;/div&gt; &lt;div&gt;Text_5&lt;/div&gt; &lt;div&gt;Text_6&lt;/div&gt; &lt;/div&gt; </code></pre> <p>for each of the inner tags, I can get valid return values for <code>getTagName()</code>, <code>getLocation()</code>, <code>isEnabled()</code>, and <code>isDisplayed()</code>. However, getText() returns an empty string for some of the divs. </p> <p>Further, I notice that if I use the mac chrome driver, it is consistently the ‘Text_5’ for which <code>getText()</code> returns an empty string. If I use the windows chrome driver, it is , it is consistently the ‘Text_2’ for which <code>getText()</code> returns an empty string. If I use the firefox driver, <code>getText()</code> returns the expected text from all the divs.</p> <p>Has anyone else had this difficulty?</p> <p>In my code, I use something like this…</p> <pre><code>ArrayList&lt;WebElement&gt; list = (ArrayList&lt;WebElement&gt;) driver.findElements(By.xpath(“my xPath here”)); for (WebElement e: list) System.out.println(e.getText()); </code></pre> <p>As suggested below, here is the actual <code>xPath</code> I am using. The page snippet above deals with the last two divs.</p> <pre><code>//*[@class='gwt-DialogBox']//tr[contains(@class,'data-grid-table-row')]//td[contains(@class,'lms-assignment-selection-wizard-cell')]/div/div </code></pre>
20,963,084
10
1
null
2014-01-02 17:43:54.537 UTC
18
2021-08-11 07:40:55.61 UTC
2017-07-28 20:32:03.357 UTC
null
4,607,317
null
2,387,776
null
1
52
java|selenium|selenium-chromedriver
72,267
<p><strong>Update:</strong> The <code>textContent</code> attribute is a better option and supported across the majority of browsers. The differences are explained in detail at this blog post: <a href="http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/" rel="noreferrer">innerText vs. textContent</a></p> <p>As an alternative, the <code>innerText</code> attribute will return the text content of an element which exists in the DOM.</p> <pre><code>element.getAttribute("innerText") </code></pre> <p>The <code>isDisplayed()</code> method can sometimes trip over when the element is not really hidden but outside the viewport; <code>getText()</code> returns an empty string for such an element.</p> <p>You can also bring the element into the viewport by scrolling to it using javascript, as follows:</p> <pre><code>((JavaScriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element); </code></pre> <p>and then <code>getText()</code> should return the correct value.</p> <p>Details on the <code>isDisplayed()</code> method can be found in this SO question:</p> <p><a href="https://stackoverflow.com/questions/18062372/selenium-webdriver-isdisplayed-method">How does Selenium WebDriver&#39;s isDisplayed() method work</a></p>
20,835,544
How to fight tons of unresolved variables warning in WebStorm?
<p>I have a function that takes data from server:</p> <pre><code>function getData(data){ console.log(data.someVar); } </code></pre> <p>WebStorm says that <code>someVar</code> is an unresolved variable. How can I get rid of such warnings?</p> <p>I see several options:</p> <ul> <li>Suppress warnings in IDE settings;</li> <li>Add a JSON source file with fields (<a href="http://devnet.jetbrains.com/message/5366907" rel="noreferrer">details</a>);</li> <li>Use array-like syntax: <code>data['some_unres_var']</code>;</li> </ul> <p>Also, WebStorm is offering me to create namespace for the &quot;data&quot; (add an annotation like <code>/** @namespace data.some_unres_var*/</code>), create such field, or rename it.</p>
25,868,457
6
1
null
2013-12-30 07:53:03.353 UTC
25
2021-12-28 17:35:21.103 UTC
2020-11-06 00:22:15.68 UTC
null
4,157,124
null
930,170
null
1
137
javascript|webstorm
76,989
<p>Use <a href="https://jsdoc.app/" rel="noreferrer">JSDoc</a>:</p> <pre><code>/** * @param {{some_unres_var:string}} data */ function getData(data){ console.log(data.some_unres_var); } </code></pre>
51,833,422
try-catch statement in React JSX
<p>According to the <a href="https://jsx.github.io/doc/statementref.html" rel="noreferrer">JSX reference</a>, this is what a try-catch statement must look like</p> <pre><code>try { statement* } [catch (varname : type) { statement* }]* [finally { statement* }] </code></pre> <p>I tried the following</p> <pre><code>try { console.log(window.device.version) } catch (e : TypeError) { console.log('Error') } </code></pre> <p>Which results in the error</p> <blockquote> <p>Module build failed: SyntaxError: Unexpected token, expected ) (11:15)</p> <pre><code>9 | try { 10 | console.log(window.device.version) 11 | } catch (e : TypeError) { | ^ 12 | console.log('Error') 13 | } 14 | return ( </code></pre> </blockquote> <p>What is the correct way to use a try-catch statement in JSX then ?</p>
51,833,449
5
1
null
2018-08-14 03:45:04.243 UTC
null
2019-11-29 14:09:26.947 UTC
null
null
null
null
10,034,557
null
1
7
reactjs|jsx
56,791
<h2>React JSX</h2> <p>It looks like a TypeScript style. Just use <code>try{ } catch(e) { console.error(e); }</code> would be fine.</p> <p>Take a look at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch" rel="noreferrer">MDN</a>, and don't forget that JSX is just a syntax sugar for <code>React.createElement</code>.</p> <h2>JSX - a faster, safer, easier JavaScript</h2> <p>The link you mentioned is <strong>not</strong> react React JSX, but a whole new thing call DeNA JSX.</p> <p>Take a look at <a href="https://github.com/jsx/JSX/issues/255" rel="noreferrer">this issue</a> in DeNA JSX, and <a href="https://github.com/jsx/JSX/pull/351" rel="noreferrer">this PR</a>.</p>
4,579,020
How do I use a GLSL shader to apply a radial blur to an entire scene?
<p>I have a radial blur shader in GLSL, which takes a texture, applies a radial blur to it and renders the result to the screen. This works very well, so far. </p> <p>The problem is, that this applies the radial blur to the first texture in the scene. But what I actually want to do, is to apply this blur to the <em>whole</em> scene. </p> <p>What is the best way to achieve this functionality? Can I do this with only shaders, or do I have to render the scene to a texture first (in OpenGL) and then pass this texture to the shader for further processing?</p> <pre><code>// Vertex shader varying vec2 uv; void main(void) { gl_Position = vec4( gl_Vertex.xy, 0.0, 1.0 ); gl_Position = sign( gl_Position ); uv = (vec2( gl_Position.x, - gl_Position.y ) + vec2(1.0) ) / vec2(2.0); } </code></pre> <p><br></p> <pre><code>// Fragment shader uniform sampler2D tex; varying vec2 uv; const float sampleDist = 1.0; const float sampleStrength = 2.2; void main(void) { float samples[10]; samples[0] = -0.08; samples[1] = -0.05; samples[2] = -0.03; samples[3] = -0.02; samples[4] = -0.01; samples[5] = 0.01; samples[6] = 0.02; samples[7] = 0.03; samples[8] = 0.05; samples[9] = 0.08; vec2 dir = 0.5 - uv; float dist = sqrt(dir.x*dir.x + dir.y*dir.y); dir = dir/dist; vec4 color = texture2D(tex,uv); vec4 sum = color; for (int i = 0; i &lt; 10; i++) sum += texture2D( tex, uv + dir * samples[i] * sampleDist ); sum *= 1.0/11.0; float t = dist * sampleStrength; t = clamp( t ,0.0,1.0); gl_FragColor = mix( color, sum, t ); } </code></pre> <p><img src="https://i.stack.imgur.com/VAsz0.png" alt="alt text"></p>
4,579,333
1
0
null
2011-01-02 15:25:28.407 UTC
15
2014-08-26 22:23:56.483 UTC
2011-01-02 18:05:39.987 UTC
null
19,679
null
192,702
null
1
20
opengl|glsl|blur
13,468
<p>This basically is called "post-processing" because you're applying an effect (here: radial blur) to the whole scene <em>after</em> it's rendered.</p> <p>So yes, you're right: the good way for post-processing is to:</p> <ul> <li>create a screen-sized NPOT texture (<code>GL_TEXTURE_RECTANGLE</code>),</li> <li>create a FBO, attach the texture to it</li> <li>set this FBO to active, render the scene</li> <li>disable the FBO, draw a full-screen quad with the FBO's texture.</li> </ul> <hr> <p>As for the "why", the reason is simple: the scene is rendered in parallel (the fragment shader is executed independently for many pixels). In order to do radial blur for pixel (x,y), you first need to know the pre-blur pixel values of the surrounding pixels. And those are not available in the first pass, because they are only being rendered in the meantime.</p> <p>Therefore, you must apply the radial blur only after the whole scene is rendered and fragment shader for fragment (x,y) is able to read any pixel from the scene. This is the reason why you need 2 rendering stages for that.</p>
4,774,172
Image manipulation and texture mapping using HTML5 Canvas?
<p>In a 3D engine I'm working on I've succesfully managed to draw a cube in 3D. The only method to fill the sides is using either a solid color or gradient as far as I'm concerned. To make things more exciting, I'd really love to implement texture mapping using a simple bitmap.</p> <p>The point is that I can hardly find any articles or code samples on the subject of image manipulation in JavaScript. Moreover, image support in HTML5 canvas seems to be restricted to cropping.</p> <p>How could I go about stretching a bitmap so that a rectangular bitmap can fill up a unregular cube face? In 2D, a projected square cube face is, due to perspective, not of a square shape, so I'll have to stretch it to make it fit in any quadrilateral.</p> <p>Hopefully this image clarifies my point. The left face is now filled up with a white/black gradient. How could I fill it with a bitmap, after it has been texture-mapped?</p> <p><img src="https://i.stack.imgur.com/M5omO.png" alt="Cube"></p> <p>Does anyone have any tips on perspective texture mapping (or image manipulation at all) using JavaScript and HTML5 Canvas?</p> <p><strong>Edit:</strong> I got it working, thanks to 6502!</p> <p>It is, however, rather CPU intensive so I'd love to hear any optimization ideas.</p> <p><a href="https://i.stack.imgur.com/Uwb86.png" rel="noreferrer">Result using 6502's technique</a> - <a href="http://farm4.static.flickr.com/3593/3491018590_866b089479_z.jpg?zz=1" rel="noreferrer">Texture image used</a></p>
4,774,298
1
3
null
2011-01-23 13:54:42.717 UTC
18
2017-12-15 00:47:09.433 UTC
2011-08-24 15:54:28.98 UTC
null
514,749
null
514,749
null
1
21
javascript|html|3d|texture-mapping|html5-canvas
24,822
<p>I think you will never get an accurate result... I spent some time investigating how to do 3d graphics using canvas 2d context and I found it viable to do texture mapping gouraud shading by computing appropriate 2d gradients and matrices:</p> <ul> <li>Solid polygons are of course easy</li> <li>Gouraud filling is possible only on one component (i.e. you cannot have a triangle where every vertex is an arbitrary RGB filled with bilinear interpolation, but you can do that filling using for example three arbitrary shades of a single color)</li> <li>Linear texture mapping can be done using clipping and image drawing</li> </ul> <p>I would implement perspective-correct texture mapping using mesh subdivision (like on PS1).</p> <p>However I found many problems... for example image drawing with a matrix transform (needed for texture mapping) is quite inaccurate on chrome and IMO it's impossible to get a pixel-accurate result; in general there is no way to turn off antialiasing when drawing on a canvas and this means you will get visible see-through lines when subdividing in triangles. I also found multipass rendering working really bad on chrome (probably because of how hw-accellerated rendering is implemented).</p> <p>In general this kind of rendering is surely a stress for web browsers and apparently these use cases (strange matrices for example) are not tested very well. I was even able to get Firefox crashing so bad that it took down the whole X susbsystem on my Ubuntu.</p> <p>You can see the results of my efforts <a href="http://raksy.dyndns.org/torus.html" rel="noreferrer">here</a> or as a video <a href="http://www.youtube.com/watch?v=XHT23NnW-EY" rel="noreferrer">here</a>... IMO is surely impressing that this can be done in a browser without using 3D extensions, but I don't think current problems will be fixed in the future.</p> <p>Anyway the basic idea used to draw an image so that the 4 corners ends up in specific pixels position is to draw two triangles, each of which will use bilinear interpolation.</p> <p>In the following code I assume you have a picture object <code>texture</code> and 4 corners each of which is an object with fields <code>x,y,u,v</code> where <code>x,y</code> are pixel coordinates on the target canvas and <code>u,v</code> are pixel coordinates on <code>texture</code>:</p> <pre><code>function textureMap(ctx, texture, pts) { var tris = [[0, 1, 2], [2, 3, 0]]; // Split in two triangles for (var t=0; t&lt;2; t++) { var pp = tris[t]; var x0 = pts[pp[0]].x, x1 = pts[pp[1]].x, x2 = pts[pp[2]].x; var y0 = pts[pp[0]].y, y1 = pts[pp[1]].y, y2 = pts[pp[2]].y; var u0 = pts[pp[0]].u, u1 = pts[pp[1]].u, u2 = pts[pp[2]].u; var v0 = pts[pp[0]].v, v1 = pts[pp[1]].v, v2 = pts[pp[2]].v; // Set clipping area so that only pixels inside the triangle will // be affected by the image drawing operation ctx.save(); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.lineTo(x2, y2); ctx.closePath(); ctx.clip(); // Compute matrix transform var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2; var delta_a = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2; var delta_b = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2; var delta_c = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2; var delta_d = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2; var delta_e = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2; var delta_f = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2; // Draw the transformed image ctx.transform(delta_a/delta, delta_d/delta, delta_b/delta, delta_e/delta, delta_c/delta, delta_f/delta); ctx.drawImage(texture, 0, 0); ctx.restore(); } } </code></pre> <p>Those ugly strange formulas for all those "delta" variables are used to solve two linear systems of three equations in three unknowns using <a href="http://en.wikipedia.org/wiki/Cramer&#39;s_rule" rel="noreferrer">Cramer's</a> method and <a href="http://en.wikipedia.org/wiki/Rule_of_Sarrus" rel="noreferrer">Sarrus</a> scheme for 3x3 determinants.</p> <p>More specifically we are looking for the values of <code>a</code>, <code>b</code>, ... <code>f</code> so that the following equations are satisfied</p> <pre><code>a*u0 + b*v0 + c = x0 a*u1 + b*v1 + c = x1 a*u2 + b*v2 + c = x2 d*u0 + e*v0 + f = y0 d*u1 + e*v1 + f = y1 d*u2 + e*v2 + f = y2 </code></pre> <p><code>delta</code> is the determinant of the matrix</p> <pre><code>u0 v0 1 u1 v1 1 u2 v2 1 </code></pre> <p>and for example <code>delta_a</code> is the determinant of the same matrix when you replace the first column with <code>x0</code>, <code>x1</code>, <code>x2</code>. With these you can compute <code>a = delta_a / delta</code>.</p>
25,065,699
Why does AngularJS with ui-router keep firing the $stateChangeStart event?
<p>I'm trying to block all ui-router state changes until I've authenticated the user:</p> <pre><code>$rootScope.$on('$stateChangeStart', function (event, next, toParams) { if (!authenticated) { event.preventDefault() //following $timeout is emulating a backend $http.get('/auth/') request $timeout(function() { authenticated = true $state.go(next,toParams) },1000) } }) </code></pre> <p>I reject all state changes until the user has been authenticated, but if I go to an invalid URL that uses the <code>otherwise()</code> configuration, I get an infinite loop with a message:</p> <pre><code>Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [["fn: $locationWatch; newVal: 7; oldVal: 6"],["fn: $locationWatch; newVal: 8; oldVal: 7"],["fn: $locationWatch; newVal: 9; oldVal: 8"],["fn: $locationWatch; newVal: 10; oldVal: 9"],["fn: $locationWatch; newVal: 11; oldVal: 10"]] </code></pre> <p>Below is my <a href="http://sscce.org/" rel="noreferrer">SSCCE</a>. Serve it up with <code>python -m SimpleHTTPServer 7070</code> and go to <code>localhost:7070/test.html#/bar</code> to see it explode in your face. Whereas directly navigating to the only valid angularjs location does not blow up <code>localhost:7070/test.html#/foo</code>:</p> <pre><code>&lt;!doctype html&gt; &lt;head&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="clientApp"&gt; &lt;div ui-view="" &gt;&lt;/div&gt; &lt;script&gt; var app = angular.module('clientApp', ['ui.router']) var myRouteProvider = [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/foo'); $stateProvider.state('/foo', { url: '/foo', template: '&lt;div&gt;In Foo now&lt;/div&gt;', reloadOnSearch: false }) }] app.config(myRouteProvider) var authenticated = false app.run([ '$rootScope', '$log','$state','$timeout', function ($rootScope, $log, $state, $timeout) { $rootScope.$on('$stateChangeStart', function (event, next, toParams) { if (!authenticated) { event.preventDefault() //following $timeout is emulating a backend $http.get('/auth/') request $timeout(function() { authenticated = true $state.go(next,toParams) },1000) } }) } ]) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Is there an alternative method I should use to accomplish this authentication blocking? I do realize this authentication blocking is client side only. I'm not showing the server side of things in this example.</p>
25,066,731
6
2
null
2014-07-31 17:49:23.52 UTC
14
2015-10-22 13:09:39.57 UTC
2015-07-02 14:10:08.57 UTC
null
20,712
null
20,712
null
1
24
angularjs|angular-ui-router
13,301
<p>Fakeout. This is an interaction issue between <code>$urlRouterProvider</code> and <code>$stateProvider</code>. I shouldn't be using <code>$urlRouterProvider</code> for my <code>otherwise</code>. I should be using something like:</p> <pre><code>$stateProvider.state("otherwise", { url: "*path", template: "Invalid Location", controller: [ '$timeout','$state', function($timeout, $state ) { $timeout(function() { $state.go('/foo') },2000) }] }); </code></pre> <p>Or even a transparent'ish redirect:</p> <pre><code>$stateProvider.state("otherwise", { url: "*path", template: "", controller: [ '$state', function($state) { $state.go('/foo') }] }); </code></pre> <p>Altogether now:</p> <pre><code>&lt;!doctype html&gt; &lt;head&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="clientApp"&gt; &lt;div ui-view="" &gt;&lt;/div&gt; &lt;script&gt; var app = angular.module('clientApp', ['ui.router']) var myRouteProvider = [ '$stateProvider', function($stateProvider) { $stateProvider.state('/foo', { url: '/foo', template: '&lt;div&gt;In Foo now&lt;/div&gt;', reloadOnSearch: false }) $stateProvider.state("otherwise", { url: "*path", template: "", controller: [ '$state', function($state) { $state.go('/foo') }] }); }] app.config(myRouteProvider) var authenticated = false app.run([ '$rootScope', '$log','$state','$timeout', function ($rootScope, $log, $state, $timeout) { $rootScope.$on('$stateChangeStart', function (event, next, toParams) { if (!authenticated) { event.preventDefault() //following $timeout is emulating a backend $http.get('/auth/') request $timeout(function() { authenticated = true $state.go(next,toParams) },1000) } }) } ]) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
31,657,422
How to 'call' Matlab functions from another script
<p>My Matlab script .m file is getting too big. I want to move functionality to multiple .m files my moving functions from the primary file to a several other .m files, each based on category of functionality.</p> <p>How can the primary .m file 'call' functions in these other new .m files?</p>
31,662,210
1
7
null
2015-07-27 15:40:30.737 UTC
2
2015-08-13 16:18:38.847 UTC
2015-08-13 16:18:38.847 UTC
null
746,100
null
746,100
null
1
9
matlab
41,049
<p>All the information provided in my answer can be found in <a href="http://www.mathworks.com/help/matlab/function-basics.html" rel="noreferrer">Function Basics</a> at <strong>MATHWORKS</strong>.</p> <p>How to make a function in MATLAB? You use the following template. In addition the name of the function and the name of the file should be similar.</p> <pre><code>% ------------------- newFunc.m-------------------- function [out1,out2] = newFunc(in1,in2) out1 = in1 + in2; out2 = in1 - in2; end %-------------------------------------------------- </code></pre> <p>For using multiple functions you can apply them either in separate <code>m-file</code>s or using <code>nested/local</code> structures:</p> <p><strong>Separate m-files:</strong></p> <p>In this structure you put each function in a separate file and then you call them in the main file by their names:</p> <pre><code>%--------- main.m ---------------- % considering that you have written two functions calling `func1.m` and `func2.m` [y1] = func1(x1,x2); [y2] = func2(x1,y1); % ------------------------------- </code></pre> <p><strong>local functions:</strong></p> <p>In this structure you have a single m-file and inside this file you can define multiple functions, such as:</p> <pre><code>% ------ main.m---------------- function [y]=main(x) disp('call the local function'); y=local1(x) end function [y1]=local1(x1) y1=x1*2; end %--------------------------------------- </code></pre> <p><strong>Nested functions:</strong></p> <p>In this structure functions can be contained in another function, such as:</p> <pre><code>%------------------ parent.m ------------------- function parent disp('This is the parent function') nestedfx function nestedfx disp('This is the nested function') end end % ------------------------------------------- </code></pre> <p>You cannot call nested function from outside of the m-files. To do so you have to use either separate m-files for each function, or using class structure.</p>
48,488,701
Type 'null' is not assignable to type 'HTMLInputElement' ReactJs
<p>I am trying to reference data into reactJS along with typescript. While doing this I am getting below error</p> <pre><code>Type 'null' is not assignable to type 'HTMLInputElement' </code></pre> <p>Please let me know what exactly incorrect here, I used documentaiton from React <a href="https://reactjs.org/docs/refs-and-the-dom.html" rel="noreferrer">https://reactjs.org/docs/refs-and-the-dom.html</a> but I think I am doing something wrong here. Below is the scope snippet</p> <pre><code> class Results extends React.Component&lt;{}, any&gt; { private textInput: HTMLInputElement; ....... constructor(props: any) { super(props); this.state = { topics: [], isLoading: false }; this.handleLogin = this.handleLogin.bind(this); } componentDidMount() {.....} handleLogin() { this.textInput.focus(); var encodedValue = encodeURIComponent(this.textInput.value); ....... } render() { const {topics, isLoading} = this.state; if (isLoading) { return &lt;p&gt;Loading...&lt;/p&gt;; } return ( &lt;div&gt; &lt;input ref={(thisInput) =&gt; {this.textInput = thisInput}} type="text" className="form-control" placeholder="Search"/&gt; &lt;div className="input-group-btn"&gt; &lt;button className="btn btn-primary" type="button" onClick={this.handleLogin}&gt; ............... </code></pre> <p>Any idea what I may be missing here?</p>
48,488,884
4
3
null
2018-01-28 16:40:44.037 UTC
3
2022-01-18 05:07:04.327 UTC
null
null
null
null
3,516,787
null
1
22
reactjs|typescript|reference
46,957
<p>The error is produced becase the types definitions says input can be <code>null</code> or a <code>HTMLInputElement</code></p> <p>You can set <code>"strict": false</code> in your <code>tsconfig.json</code> </p> <p>Or you can force the input to be <code>HTMLInputElement</code> type</p> <pre><code>&lt;input ref={thisInput =&gt; (this.textInput = thisInput as HTMLInputElement)} type="text" className="form-control" placeholder="Search" /&gt; </code></pre> <p>This way is also valid (<a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions" rel="noreferrer">using definite assignment assertions (typescript >= 2.7)</a>)</p> <pre><code>&lt;input ref={thisInput =&gt; (this.textInput = thisInput!)} type="text" className="form-control" placeholder="Search" /&gt; </code></pre>
48,844,804
Flutter - setState not updating inner Stateful Widget
<p>Basically I am trying to make an app whose content will be updated with an async function that takes information from a website, but when I do try to set the new state, it doesn't reload the new content. If I debug the app, it shows that the current content is the new one, but after "rebuilding" the whole widget, it doesn't show the new info.</p> <p>Edit: loadData ( ) method, basically read a URL with http package, the URL contains a JSON file whose content changes every 5 minutes with new news. For example a .json file with sports real-time scoreboards whose scores are always changing, so the content should always change with new results.</p> <pre><code>class mainWidget extends StatefulWidget { State&lt;StatefulWidget&gt; createState() =&gt; new mainWidgetState(); } class mainWidgetState extends State&lt;mainWidget&gt; { List&lt;Widget&gt; _data; Timer timer; Widget build(BuildContext context) { return new ListView( children: _data); } @override void initState() { super.initState(); timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async { String s = await loadData(); this.setState(() { _data = &lt;Widget&gt; [new childWidget(s)]; }); }); } } class childWidget extends StatefulWidget { childWidget(String s){ _title = s; } Widget _title; createState() =&gt; new childState(); } class childState extends State&lt;gameCardS&gt; { Widget _title; @override Widget build(BuildContext context) { return new GestureDetector(onTap: foo(), child: new Card(child: new Text(_title)); } initState() { super.initState(); _title = widget._title; } } </code></pre>
48,846,640
9
5
null
2018-02-17 18:53:37.173 UTC
15
2022-02-08 18:46:29.563 UTC
2018-02-17 22:13:59.797 UTC
null
9,374,487
null
9,374,487
null
1
54
android|dart|flutter|dart-async
105,690
<p>This should sort your problem out. Basically you always want your Widgets created in your <code>build</code> method hierarchy.</p> <pre><code>import 'dart:async'; import 'package:flutter/material.dart'; void main() =&gt; runApp(new MaterialApp(home: new Scaffold(body: new MainWidget()))); class MainWidget extends StatefulWidget { @override State createState() =&gt; new MainWidgetState(); } class MainWidgetState extends State&lt;MainWidget&gt; { List&lt;ItemData&gt; _data = new List(); Timer timer; Widget build(BuildContext context) { return new ListView(children: _data.map((item) =&gt; new ChildWidget(item)).toList()); } @override void initState() { super.initState(); timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async { ItemData data = await loadData(); this.setState(() { _data = &lt;ItemData&gt;[data]; }); }); } @override void dispose() { super.dispose(); timer.cancel(); } static int testCount = 0; Future&lt;ItemData&gt; loadData() async { testCount++; return new ItemData("Testing #$testCount"); } } class ChildWidget extends StatefulWidget { ItemData _data; ChildWidget(ItemData data) { _data = data; } @override State&lt;ChildWidget&gt; createState() =&gt; new ChildState(); } class ChildState extends State&lt;ChildWidget&gt; { @override Widget build(BuildContext context) { return new GestureDetector(onTap: () =&gt; foo(), child: new Padding( padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), child: new Card( child: new Container( padding: const EdgeInsets.all(8.0), child: new Text(widget._data.title), ), ), ) ); } foo() { print("Card Tapped: " + widget._data.toString()); } } class ItemData { final String title; ItemData(this.title); @override String toString() { return 'ItemData{title: $title}'; } } </code></pre>
39,336,556
How can I slice an object in Javascript?
<p>I was trying to slice an object using Array.prototype, but it returns an empty array, is there any method to slice objects besides passing arguments or is just my code that has something wrong? Thx!!</p> <pre><code>var my_object = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four' }; var sliced = Array.prototype.slice.call(my_object, 4); console.log(sliced); </code></pre>
39,336,877
11
4
null
2016-09-05 19:23:42.453 UTC
9
2021-12-26 20:09:10.907 UTC
2016-09-05 19:47:25 UTC
null
1,280,289
null
6,797,538
null
1
42
javascript|arrays|object|arguments|slice
86,458
<blockquote> <p>I was trying to slice an object using <code>Array.prototype</code>, but it returns an empty array</p> </blockquote> <p>That's because it doesn't have a <code>.length</code> property. It will try to access it, get <code>undefined</code>, cast it to a number, get <code>0</code>, and slice at most that many properties out of the object. To achieve the desired result, you therefore have to assign it a <code>length</code>, or iterator through the object manually:</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>var my_object = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four'}; my_object.length = 5; console.log(Array.prototype.slice.call(my_object, 4)); var sliced = []; for (var i=0; i&lt;4; i++) sliced[i] = my_object[i]; console.log(sliced);</code></pre> </div> </div> </p>
39,169,701
How to extract a list from appsettings.json in .net core
<p>I have an appsettings.json file which looks like this:</p> <pre><code>{ "someSetting": { "subSettings": [ "one", "two", "three" ] } } </code></pre> <p>When I build my configuration root, and do something like <code>config["someSetting:subSettings"]</code> it returns null and the actual settings available are something like this:</p> <p><code>config["someSettings:subSettings:0"]</code></p> <p>Is there a better way of retrieving the contents of <code>someSettings:subSettings</code> as a list?</p>
39,171,558
6
5
null
2016-08-26 15:24:36.357 UTC
19
2021-07-23 01:13:40.027 UTC
2018-08-08 09:21:46.65 UTC
null
615,306
null
206,463
null
1
120
c#|asp.net-core|.net-core
90,490
<p>You can use the Configuration binder to get a strong type representation of the configuration sources.</p> <p>This is an example from a test that I wrote before, hope it helps:</p> <pre><code> [Fact] public void BindList() { var input = new Dictionary&lt;string, string&gt; { {"StringList:0", "val0"}, {"StringList:1", "val1"}, {"StringList:2", "val2"}, {"StringList:x", "valx"} }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddInMemoryCollection(input); var config = configurationBuilder.Build(); var list = new List&lt;string&gt;(); config.GetSection("StringList").Bind(list); Assert.Equal(4, list.Count); Assert.Equal("val0", list[0]); Assert.Equal("val1", list[1]); Assert.Equal("val2", list[2]); Assert.Equal("valx", list[3]); } </code></pre> <p>The important part is the call to <code>Bind</code>.</p> <p>The test and more examples are on <a href="https://github.com/aspnet/Configuration/blob/6cc477ed493e5b0da3c8f609488d667dc65a5576/test/Config.Binder.Test/ConfigurationCollectionBindingTests.cs" rel="noreferrer">GitHub</a></p>
20,360,151
Using 'if' within a 'while' loop in Bash
<p>I have these diff results saved to a file:</p> <pre><code>bash-3.00$ cat /tmp/voo 18633a18634 &gt; sashabrokerSTP 18634a18636 &gt; sashatraderSTP 21545a21548 &gt; yheemustr </code></pre> <p>I just really need the logins:</p> <pre><code>bash-3.00$ cat /tmp/voo | egrep "&gt;|&lt;" &gt; sashaSTP &gt; sasha &gt; yhee bash-3.00$ </code></pre> <p>But when I try to iterate through them and just print the names I get errors. I just do not understand the fundamentals of using "if" with "while loops". Ultimately, I want to use the <code>while</code> loop because I want to do something to the lines - and apparently <code>while</code> only loads one line into memory at a time, as opposed to the whole file at once.</p> <pre><code>bash-3.00$ while read line; do if [[ $line =~ "&lt;" ]] ; then echo $line ; fi ; done &lt; /tmp/voo bash-3.00$ bash-3.00$ bash-3.00$ while read line; do if [[ egrep "&lt;" $line ]] ; then echo $line ; fi ; done &lt; /tmp/voo bash: conditional binary operator expected bash: syntax error near `"&lt;"' bash-3.00$ bash-3.00$ while read line; do if [[ egrep "&gt;|&lt;" $line ]] ; then echo $line ; fi ; done &lt; /tmp/voo bash: conditional binary operator expected bash: syntax error near `|&lt;"' bash-3.00$ </code></pre> <p>There has to be a way to loop through the file and then do something to each line. Like this:</p> <pre><code>bash-3.00$ while read line; do if [[ $line =~ "&gt;" ]]; then echo $line | tr "&gt;" "+" ; if [[ $line =~ "&lt;" ]]; then echo $line | tr "&lt;" "-" ; fi ; fi ; done &lt; /tmp/voo + sashab + sashat + yhee bash-3.00$ </code></pre>
20,360,208
3
1
null
2013-12-03 19:42:24.303 UTC
null
2019-08-09 15:19:10.723 UTC
2019-08-09 15:19:10.723 UTC
null
9,223,868
null
824,282
null
1
9
bash|loops|if-statement|while-loop
60,741
<p>You should be checking for <code>&gt;</code>, not <code>&lt;</code>, no?</p> <pre><code>while read line; do if [[ $line =~ "&gt;" ]]; then echo $line fi done &lt; /tmp/voo </code></pre>
6,441,158
How Can I Access an SSL Connection Through Android?
<p>I started following a tutorial that wasn't cased around Android and got this:</p> <pre><code> System.setProperty("javax.net.ssl.trustStore", "truststore"); System.setProperty("javax.net.ssl.trustStorePassword", "password"); SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); try { Socket s = ssf.createSocket("192.168.2.11", 6543); PrintWriter out = new PrintWriter(s.getOutputStream()); while (true){ out.println("SSL TEST"); Log.d("DATA", "DATA SENT"); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } </code></pre> <p>I guess this boils down to a few questions: </p> <ol> <li><p>I do not have my own trust store created, but searching through tutorials and things online, I am not sure how to create one. Is there a way I can create or modify a trust store to have the certificates I need in it? (I am using a self-signed certificate if that makes any difference)</p></li> <li><p>How do I make things with the SSL handshake run smoothly? Right now, the error I am getting is:</p> <pre> javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. </pre> <p>Honestly, I don't really understand what that means.</p></li> <li><p>What settings or files do I need to modify on my Android device to make sure this connection can happen?</p></li> </ol>
6,441,356
2
4
null
2011-06-22 14:01:17.637 UTC
13
2011-06-23 01:03:24.39 UTC
2011-06-22 14:26:41.963 UTC
null
40,342
null
1,953,819
null
1
12
java|android|sockets|ssl|ssl-certificate
32,953
<p>1) It depends. Do you have a self signed cert on the server side and you are trying to validate your identity to the android device? Or are you on the android side trying to validate your idendity to the server? If it is the former , then please see this link: <a href="http://www.codeproject.com/KB/android/SSLVerification_Android.aspx?display=Mobile">http://www.codeproject.com/KB/android/SSLVerification_Android.aspx?display=Mobile</a></p> <p>You want to pay particular attention to where it makes the KeyStore file. </p> <p>2) The reason you're getting that error is because it doesn't trust the server you are connecting either because you did not create the truststore correctly or you are connecting to a server whose certificate has not been added to the truststore. What exactly are you trying to connect to? </p> <p>3) Make sure you have the <code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt;</code> in the manifest.xml.</p> <p><strong>Edit</strong> My apologies, please see the changes I made to the first paragraph.</p> <p>Here is the part to initialize your keystore and truststore</p> <pre><code>SSLcontext sslContext = SSLContext.getDefault(); KeyStore trustSt = KeyStore.getInstance("BKS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); InputStream trustStoreStream = this.getResources().openRawResource(R.raw.truststore); trustSt.load(trustStoreStream, "&lt;yourpassword&gt;".toCharArray()); trustManagerFactory.init(trustStre); KeyStore keyStore = KeyStore.getInstance("BKS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); InputStream keyStoreStream = this.getResources().openRawResource(R.raw.keystore); keyStore.load(keyStoreStream, "&lt;yourpassword&gt;".toCharArray()); keyManagerFactory.init(keyStore, "&lt;yourpassword&gt;".toCharArray()); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); </code></pre>
14,871,935
If cell contains certain text put this text in a cell
<p>I have a dataset like this:</p> <pre><code> A B C 1 A A is this 2 B Z is this 3 C D is this 4 D A is this 5 E K is this </code></pre> <p>If cell B1 contains A, B, C, D or E (so a value of column A) than I want to put A,B,C,D,or E in cell C1</p> <p>I've tried to do this with the following formula for C1:</p> <pre><code>=IF(FIND("A";B1;1);"A";IF(FIND("B";B1;1");"B";IF(FIND("C";B1;1) ... </code></pre> <p>But since my column A contains 24 possible values it becomes a very long formula.</p> <p>Can someone help me to simplify this? </p>
14,872,024
2
0
null
2013-02-14 09:48:36.443 UTC
null
2018-01-14 03:21:39.723 UTC
null
null
null
null
1,987,607
null
1
1
excel
62,039
<p>Place the following formula in column C:</p> <pre> =INDEX(A:A,MATCH(FALSE,ISERROR(FIND(A:A,B1)),0)) </pre> <p>Enter it as an array formula, i.e. press <kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>Enter</kbd>.</p>
55,487,695
React native text component using number of lines
<p>Is there a way to determine when the text will be truncated when using number of lines ? Have been searching everywhere and no clear answer. Thank you!</p>
55,488,478
4
1
null
2019-04-03 05:32:41.167 UTC
null
2022-08-19 11:01:14.81 UTC
null
null
null
null
8,863,633
null
1
31
reactjs|react-native
63,478
<p>You can use <a href="https://facebook.github.io/react-native/docs/text#numberoflines" rel="noreferrer"><code>numberOfLines</code></a> as a props for <code>&lt;Text /&gt;</code> component. Its depend on the width of your component then calculate the length of the text. This prop is commonly used with <a href="https://facebook.github.io/react-native/docs/text#ellipsizemode" rel="noreferrer"><code>ellipsizeMode</code></a>. Example:</p> <pre><code>&lt;Text numberOfLines={2} ellipsizeMode='tail'&gt; Lorem Ipsum is simply dummy text of the printing and typesetting industry. &lt;/Text&gt; </code></pre>
7,243,381
Google Chrome input type="date"
<p>I have almost no knowledge of web programming, but I have been tasked to solve something on my company's website. Apparently, I have an issue with browsers using HTML5 on a legacy site using type="date" and I need to find a way around it. </p> <p>My site has a lot of date fields that the user must input like such:</p> <pre><code> &lt;input type="date" name="DateStart" size="15" value="8/30/2011"&gt; </code></pre> <p>In every browser we currently use except Chrome, this works just fine. Chrome is the only browser that supplies rolling buttons to scroll through the date. What I see on the back end of this is an attempt to do this:</p> <pre><code>FormatDateTime(DateStart, 2) </code></pre> <p>I get an invalid date error which means that we cannot use Chrome to fill out this form. Is there a way around this problem?</p>
7,243,434
4
0
null
2011-08-30 12:48:50.443 UTC
2
2019-11-22 21:22:33.74 UTC
2015-07-08 11:14:03.26 UTC
null
432,681
null
502,486
null
1
11
html|google-chrome
40,740
<p>Chrome does not have issues with date-inputs, <a href="https://www.w3.org/TR/html/infrastructure.html#global-dates-and-times" rel="nofollow noreferrer">you are using the wrong date-format</a>, sir. Chrome isn't the only browser until today which has support for the new HTML5 inputs. Opera for example displays a dropdown with a calendar on inputs with <code>type="date"</code>.</p> <p>Also the size-attribute does not exist on HTML5-date-inputs.</p>
7,121,574
What is a PayPal payer id?
<p>Instant Payment Notification script receives among other parameters the following one:</p> <pre><code>payer_id = LPLWNMTBWMFAY </code></pre> <p>What is the meaning of that string?</p>
7,127,444
4
1
null
2011-08-19 12:30:31.653 UTC
4
2020-08-24 21:35:26.15 UTC
null
null
null
null
203,204
null
1
25
paypal|paypal-ipn
39,015
<p>It's an external unique identifier of a particular PayPal account. Since email addresses change over time. A PayerID is static.</p>
24,302,754
Python submodule imports using __init__.py
<p>I'm learning Python, and I can't figure out how imports in <code>__init__.py</code> work.</p> <p>I understand from <a href="https://docs.python.org/3/tutorial/modules.html" rel="noreferrer">the Python tutorial</a> that the <code>__init__.py</code> file initializes a package, and that I can import subpackages here.</p> <p>I'm doing something wrong, though. Could you explain for me (and for future Python-learners) what I'm doing wrong?</p> <p>Here's a simplified example of what I'm trying to do.</p> <p>This is my file structure:</p> <pre><code>package __init__.py test.py subpackage __init__.py hello_world.py </code></pre> <p>The contents of <code>hello_world.py</code>:</p> <pre><code>def do_something(): print "Hello, world!" </code></pre> <p><code>subpackage/__init__.py</code> is empty.</p> <p><code>package/__init__.py</code> contains:</p> <pre><code>import test.submodule.do_something </code></pre> <p>And finally, <code>test.py</code> contains:</p> <pre><code>do_something() </code></pre> <p>This is how I attempt to run hello_world.py using OSX terminal and Python 3:</p> <pre><code>python test.py </code></pre> <p>Python then throws the following error:</p> <pre><code>NameError: name 'do_something' is not defined </code></pre>
24,303,380
3
1
null
2014-06-19 09:04:07.523 UTC
5
2022-02-25 10:03:06.5 UTC
2014-06-19 09:11:24.003 UTC
null
1,676,127
null
2,687,446
null
1
38
python
39,914
<p>You probably already understand that when you import a <em>module</em>, the interpreter creates a new namespace and executes the code of that module with the new namespace as both the local and global namespace. When the code completes execution, the module name (or the name given in any <code>as</code> clause) is bound to the module object just created within the importing namespace and recorded against its <code>__name__</code> in <code>sys.modules</code>.</p> <p>When a qualified name such as <code>package.subpackage.module</code> is imported the first name (<code>package</code>) is imported into the local namespace, then <code>subpackage</code> is imported into <code>package</code>'s namespace and finally <code>module</code> is imported into <code>package.subpackage</code>'s namespace. Imports using <code>from ... import ... as ...</code> perform the same sequence of operations, but the imported objects are bound directly to names in the importing module's namespace. The fact that the package name isn't bound in your local namespace does not mean it hasn't been imported (as inspection of <code>sys.modules</code> will show).</p> <p>The <code>__init__.py</code> in a package serves much the same function as a module's <code>.py</code> file. A <em>package</em>, having structure, is written as a directory which can also contain modules (regular <code>.py</code> files) and subdirectories (also containing an <code>__init__.py</code> file) for any sub_packages. When the package is imported a new namespace is created and the package's <code>__init__.py</code> is executed with that namespace as the local and global namespaces. So to answer your problem we can strip your filestore down by omitting the top-level package, which will never be considered by the interpreter when <code>test.py</code> is run as a program. It would then look like this:</p> <pre><code>test.py subpackage/ __init__.py hello_world.py </code></pre> <p>Now, <code>subpackage</code> is no longer a sub-package, as we have removed the containing package as irrelevant. Focusing on why the <code>do_something</code> name is undefined might help. <code>test.py</code> does not contain any import, and so it's unclear how you are expecting <code>do_something</code> to acquire meaning. You could make it work by using an empty <code>subpackage/__init__.py</code> and then you would write <code>test.py</code> as</p> <pre><code>from subpackage.hello_world import do_something do_something() </code></pre> <p>Alternatively you could use a <code>subpackage/__init__.py</code> that reads</p> <pre><code>from hello_world import do_something </code></pre> <p>which establishes the <code>do_something</code> function inside the <code>subpackage</code> namespace when the package is imported. Then use a <code>test.py</code> that imports the function from the package, like this:</p> <pre><code>from subpackage import do_something do_something() </code></pre> <p>A final alternative with the same <code>__init__.py</code> is to use a <code>test.py</code> that simply imports the (sub)package and then use relative naming to access the required function:</p> <pre><code>import subpackage subpackage.do_something() </code></pre> <p>to gain access to it in your local namespace.</p> <p>With the empty <code>__init__.py</code> this could also be achieved with a <code>test.py</code> reading</p> <pre><code>import subpackage.hello_world subpackage.hello_world.do_something() </code></pre> <p>or even</p> <pre><code>from subpackage.hello_world import do_something do_something() </code></pre> <p>An empty <code>__init__.py</code> will mean that the top-level package namespace will contain only the names of any subpackages the program imports, which allows you to import only the subpackages you require. This gives you control over the namespace of the top-level package.</p> <p>While it's perfectly possible to define classes and functions in the <code>__init__.py</code> , a more normal approach is to import things into that namespace from submodules so that importers can just import the top-level package to gain access to its contents with a single-level attribute reference, or even use <code>from</code> to import only the names you specifically want.</p> <p>Ultimately the best tool to keep you straight is a clear understanding of how import works and what effect its various forms have on the importing namespace.</p>