INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Why should I make an instance of the View class?
This code sums 2 numbers.
My question is: why should I make an instance `v` of the class `View`, if I will never use it in my code?
If I try without the instance `v` of the class `View`, the app crashes.
public void onButtonClick(View v) {
EditText r1 = (EditText)findViewById(R.id.editText3);
EditText r2 = (EditText)findViewById(R.id.editText4);
TextView t = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(r1.getText().toString());
int num2 = Integer.parseInt(r2.getText().toString());
int sum = num1+num2;
t.setText(Integer.toString(sum));
}
|
Because it's the required method signature for when you add an `onClick` listener in an xml layout.
The object variable `v` is used in case you have multiple Views firing to the same method when clicked.
You can then use `v.getId()` to determine **which** View fired the method (normally, by using a `switch ... case`) and act consequently.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "java, android, android layout, onclick"
}
|
How to convert Bitmapdata to Base64 format?
Is there any example which helps in generating Base64 based image from Bitmapdata? I know I have to use encode in bitmapdata, but I am not sure how to use it?
It takes (rect : flash.geom.Rectangle, compressor : flash.utils.Object, ?byteArray : flash.utils.ByteArray) : flash.utils.ByteArray;
How to fill compressor incase I want to compress using jpeg?
Also, what's the input of byteArray ? Any help?
|
There is an example in the AS3 doc of BitmapData.html#encode():
// Compress a BitmapData object as a JPEG file.
var bitmapData:BitmapData = new BitmapData(640,480,false,0x00FF00);
var byteArray:ByteArray = new ByteArray();
bitmapData.encode(new Rectangle(0,0,640,480), new flash.display.JPEGEncoderOptions(), byteArray);
To generate a Base64 String, you can use `haxe.crypto.Base64` (added after 3.0.1). In OpenFL, `ByteArray` extends `Bytes`. So you may simply feed it to `Base64.encode`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "haxe, openfl"
}
|
Is there a win32 command line tabifier that supports ... `read details` (revised)?
I use an editor that allows me to type in a command to run. In order to see the output without having to redirect it to a file, I precede the command with "cmd /k," which leaves an open cmd.exe window. So I'd like to find a way to catch the call to cmd.exe and pass it onto an application that tabifies cmd.exe, a terminal emulator as it's called. The desired result would be similar to what happens in a tabbed editor, when that editor is to open some file, it does so in another tab, and not in another window. While in a given situation it may be easier to modify the command to redirect output to display in the editor itself, in general it would be more helpful if I could find a way to catch all such calls into one window.
|
When a program that attains the above criteria is found, this post may be edited to link to it.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "command line, tabs"
}
|
Autoloading a particular driver, based on a detected specific kernel
I need to write a _script_ and determining its _placement_ within Debian 7.9 filesystem. The script needs to be executed automatically on startup and, after checking what kernel is currently loaded (2.6.x vs. 3.2.x), unload the incorrect network driver, if loaded, and load the correct one. This question is the follow-up for my prior question and represents the only missing piece of that puzzle, as I've already figured out cross-kernel compiling of network driver by myself.
In terms of the location, I think that the script should be placed into "/etc/rcX.d" directories.
|
The location you guessed is nearly correct. But `/etc/rcX.d` directories usually contain only links to scripts in `/etc/init.d/`, so that a script only has to exist once but can be called at different runlevels.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "debian, shell script, linux kernel, kernel modules, startup"
}
|
Visual Studio Build Error: "Being in the internet or restricted zone"
I wanted to build my solution of my app, however this error popped out:
Couldn't process file Form1.resx due to its being in the Internet or Restricted zone or having the mark of the web on the file. Remove the mark of the web if you want to process these files.
Please help!
|
Did you download the project, or part of it, from the internet?
If so, you might have to unblock the file(s) first. Select the file(s) in windows explorer, right click, select properties, and on the "General" tab you will see this.
 {
// Pick up the tree 30 times
pickWalk -d up ;
$i++ ;
}
// List all selected objects
string $rootNode[] = `ls -sl` ;
// Clear selection
select -cl ;
string $myroot = $rootNode[0] ;
|
to get the root, just string-split the long name:
global proc string get_root(string $node)
{
string $longname[] = ls("-l", $node);
string $tokens[];
tokenize($longname[0], "|", $tokens);
return $tokens[0];
}
Of course it's much more elegant in Python:
root = cmds.ls(node, l=True)[0].split("|")[0]
You could also re-write the orignal function by calling `listRelatives -p` until it returns nothing; but the string method is easier
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "while loop, maya, mel"
}
|
why the code seems haven't executed when there is no output related?
consider this Fortran program:
program main
implicit none
double complex :: a(51,51),b(51,51)
Integer::i,j
real(8)::ht=0.01
real(8) T1,T2
do i=1,51
do j=1,51
a(i,j)=cmplx(Sin(0.01*i),Cos(0.01*j))
end do
end do
call cpu_time(T1)
do i=1,23497
b(:,:)=(0.,1.)*ht/2.*a(:,:)
end do
call cpu_time(T2)
write(*,*) sum(b)
print '("Time = ",f12.9," seconds.")', T2-T1
end program main
the output is
(-12.4321907340245,3.30723047182099)
Time = 0.052991000 seconds.
If we comment out the `write(*,*) sum(b)`, the output is
Time = 0.000000000 seconds.
it seems the loop is not executed, why this happens?
|
When you remove the `write` statement, the compiler can see that the variable `b` is never used, so it removes the code that assigns `b`.
Once it has done that, it can then tell that the variable `a` is never used, either, so it removes the code that assigns that variable.
Then there's nothing left except the calls to `cpu_time()`.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 3,
"tags": "performance, fortran"
}
|
Datapie: gaps between slices
I need to remove the gap between the green and cyan slices as shown below: 
x1 = tf.keras.layers.Dense(..)(inp)
x2 = tf.keras.layers.Dense(...)(x1)
model = tf.keras.Model(inp, [x1, x2])
model.compile(loss=['loss_for_x1', 'loss_for_x2'],
optimizer='rmsprop',
loss_weights=[1., 1.]) # How many the loss function influences
You can thing of this as applying a loss directly to first layer.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "keras, scikit learn, neural network, autoencoder, loss function"
}
|
What's the difference between "uintN" and "varuintN" in WebAssembly?
What's the difference between "uintN" and "varuintN"? Why did not we directly use "varuintN" to replace "uintN" in WebAssembly?
BTW, there are only a few fields that are using "uintN" type which include "magic number" and "version".
|
varuint uses LEB128 encoding, which is a variable length encoding, and therefore size efficient. I think the instances where non variable length encoding are used is places where encoding size is not a priority, e.g. storage of numeric values in linear memory
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "webassembly"
}
|
printing lines where certain columns do not match, with awk
I have a tab separated file like this:
1 10502 C T
1 10506 C T
1 10567 G A
...
And I'm trying to print out all lines where `column 3 != column 4`, **excluding** the cases where `column 3 = C and column 4 = T`.
I tried
awk '{
if (($3 == $4) || ($3 == C && $4 == T) )
next ;
else
print $0; }'
but I'm not sure what's going wrong...
|
just fix your codes:
awk '($3 != $4) && !($3=="C" && $4=="T")' file
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 7,
"tags": "awk, matching"
}
|
overriding a method on a global module in webpack
I have something like this in my webpack config:
plugins:[
new webpack.ProvidePlugin({ THREE: 'three' }),
...
which makes THREE available globally (or at least wherever its used?)
I would like to override a method from this library, for example in the entry point:
THREE.Something = mySomething;
I'm not succeding, how is this done?
Alternatively i tried something like.
require(expose?THREE!./myCustomThree.js);
But that didnt work either, i only got it in the scope where i made the require call. I was able to override the method though, but can't make it global.
|
ProvidePlugin just replaces globally the string provided with the instance of the module defined.
new webpack.ProvidePlugin({
'$': 'jquery',
'$.each': 'moment'
})
The above plugin now replaces all instances of `$` in your code with the instance of jquery. And in the second case, it replaces `$.moment` with the instance of moment.
You have to understand that ProvidePlugin simply renames the module to the string you provide and I guess that is kind of an override.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, requirejs, webpack"
}
|
What is this white fungus like growth on my mango tree roots?
It has rained constantly for the past week and suddenly today I noticed this very aggressively growing white thing. Can you guys please tell me if this is dangerous for the tree? I have seen mushrooms come out in my garden after rainfalls but they soon wither away adding nutrition to my soil, so I am wondering if this will be a helpful ingredient as well.
 in the vicinity, because that might be honey fungus, but you haven't reported any symptoms or problems with the mango tree in your question, so it doesn't seem like it's that.
Ensure that pot isn't actually standing on any of the exposed roots, keep it clear, well away so that water from the pot is not constantly passing over the root.
|
stackexchange-gardening
|
{
"answer_score": 1,
"question_score": 2,
"tags": "roots, fungus"
}
|
luminance ratio for shadow removal
In this paper: Human Body Tracking by Adaptive Background Models and Mean-Shift Analysis Section 3, the authors mention about luminance ratio thresholds for brightness and darkness (r1, r2). Can anyone suggest what should the values be?
|
You have them explained in **this paper**, sections 4.2 and 4.3.
I usually prefer to post self-contained answers, but this topic is not easy to understand without reading the whole paper.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "image processing, computer vision"
}
|
Display date difference in MS Word field
I have an CV and would like to automatically update my age when opening. So, what formula should I insert in a MS Word field?
Something like:
**{= {DATE} - {"01/01/1983"} }**
|
This is one of the better sites for working with Word field codes - < \- and there are examples there on how to create +/- dates.
Here's how you would calculate based of a birth month of January and birth year of 1983.
`{IF{DATE\@"MM"} >= 01 { = {DATE\@"YYYY"} – 1983 \#"00"} { = {DATE\@"YYYY"} – 1984 \#"00"}}`
Note that in the case of the month of January, this IF statement will always be true and give you =YEAR-1983. You can use another nested IF statement to check on the day to further get more accurate.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 8,
"tags": "ms word, word field, fieldcodes"
}
|
PHP Array Operator
I’m now learning PHP array but I have a question about the array operator. I saw an example when creating an array like this:
<?php
$array = array();
$array["a"] = "apple";
$array["b"] = "banana";
?>
Do I really need to declare the variable as `array` first?
Or can I just ignore the first line: `$array = array();`?
|
Better yet, just initialize your array _and_ assign values to it at the same time:
<?php
$array = array(
"a" => "apple",
"b" => "banana"
);
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, arrays"
}
|
How to share pixel data between Bitmap and Bitmapsource without a reallocation?
Is it possible to create a `System.Windows.Media.Imaging.Bitmapsource` from a `System.Drawing.Bitmap` without a reallocation? Unfortunately all methods described in other post included a copy of the `pixel data` which is not always needed and very expensive...
|
I found this solution and it worked perfectly for me!
WpfImage.Source = new SharedBitmapSource(DrawingBitmap);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c#, .net, image, bitmap, bitmapsource"
}
|
Find least frequent value in whole dataframe
my dataframe is something like this
> 93 40 73 41 115 74 59 98 76 109 43 44
105 119 56 62 69 51 50 104 91 78 77 75
119 61 106 105 102 75 43 51 60 114 91 83
It has 8000 rows and 12 columns
I wanted to find the least frequent value in this whole dataframe (not only in columns).
I tried converting this dataframe into numpy array and use `for` loop to count the numbers and then return the least count number but it it not very optimal. I searched if there are any other methods but could not find it.
I only found scipy.stats.mode which returns the most frequent number.
is there any other way to do it?
|
You could `stack` and take the `value_counts`:
df.stack().value_counts().index[-1]
# 69
`value_counts` orders by frequency, so you can just take the last, though in this example many appear just once. `69` happens to be the last.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "python, pandas, numpy, scipy"
}
|
print the number in second col the number of times in a new line always as specified in col 1
how do I print the value in col 2 as many times as it is specified in col 1.
10 -11
9 -10
7 -9
7 -8
7 -7
12 -6
362 -1
271 1
94 2
41 3
17 4
13 5
16 6
5 7
expected output:
-11
-11
-11
-11
-11
-11
-11
-11
-11
-11.....so on and so forth...
|
This perl one-liner does the job:
perl -ane '($x,$y)=split;print"$y\n"x$x' file
**Outoout:**
-11
-11
-11
-11
-11
-11
-11
-11
-11
-11
-10
-10
-10
-10
-10
-10
-10
-10
-10
...
**Explanation:**
($x,$y)=split; # split the values from each line ($x=first value, $y=second value)
print"$y\n"x$x # print $x times the value $y followed by line break
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "awk, perl"
}
|
1:3 Resonance on a playground swing and KAM theory
Not sure if this question belongs in physics or mathematics.
Recently I have been making some computer simulations of somebody swinging on a playground swing at varying frequencies. Specifically I was interested if it is possible to cause a 1:3 resonance by moving the swinging person's centre of mass three times as fast as the frequency of the swing. By KAM theory I would expect that this should be the case.
However, when I did the computation swinging at 1:3 (or at any other rational multiple except 1:2) did not cause any resonances.
Typically KAM theory only tells you something about the stable solutions and not the resonant ones. So it is not really a contradiction. However I still would except that you can cause resonance at 1:3. Or would this resonance only be visible at very large time scales?
|
Ah so I think the answer lies in numerical mathematics. It appears that the 1:3 resonance is very difficult to find since the resonant domain is really small.
You will see this if you look at the bifurcation diagrams indicating the resonant domains. < Then you observe that the resonant domains for all frequencies except the 1:2 resonance is small if the epsilon is small (very informally the size of epsilon would correspond in the swing to the magnitude of your initial velocity), hence numerically these are probably very hard to find. However if I increase this epsilon then the resonance domains will increase their size and indeed you can verify this very easy numerically.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "dynamical systems"
}
|
PHP-destroy-session-on-close-of-main-window
How to destroy the session on closing the browser When browser window is closed, session should be terminated. Right now, if I close the window and type the application url, it is allowing me to access application.
|
Fixed.
With below settings "application" session expires during browser close.
Firefox Browser->Tools->Options->General Tab StartUp: When Firefox starts: Show a blank page
Firefox Browser->Tools->Options->Privacy Tab History: Firefox will Use custom settings for history / Never remember history Cookie: Keep Until : I close firefox
|
stackexchange-stackoverflow
|
{
"answer_score": -3,
"question_score": 2,
"tags": "php, session"
}
|
Site.com error when attempting to add domain name
We are trying to migrate an existing domain to Site.com. We've followed the instructions outlined here:
<
However, when attempting to add the domain to Site.com we get the error: "Error: The domain and path combination is already in use. Enter a different domain name or path and try again"
Now, the DNS is not set up with an DNS A record as far as I know, just a CNAME record. What would be the migration process for such a set up? And could it be causing such an error.
|
Thank you crmprogdev for your help.
I did eventually open a case with Salesforce support regarding this issue. The problem is that the domain that we are attempting to migrate to Site.com is already associated with a Force.com site. I failed to mention that in my original question because I did not know that. Or rather, I did know it but had forgotten about it.
So, we have to first deactivate the Force.com site, then change the DNS CNAME record to point to the Site.com URL, and then we should be able to add the domain to Site.com.
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 5,
"tags": "site.com"
}
|
MySQL NOT IN Syntax convertible to JOINs?
I have the following query:
select full_name, email, users.uid
from
cloudsponge
inner join
`users` on users.uid = cloudsponge.importer_uid
where cloudsponge.email not in (select mail from users)
It works as expected but I'm wondering, can I convert the last line to a join (rather than a subquery). This would be helpful as I can use my frameworks ORM rather than hardcode SQL into the application.
Thanks!
|
You can write:
SELECT full_name, email, users.uid
FROM cloudsponge
INNER
JOIN users
ON users.uid = cloudsponge.importer_uid
LEFT
JOIN users AS users2
ON cloudsponge.email = users2.mail
WHERE users2.mail IS NULL
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "mysql, sql"
}
|
c# - check for null in a collection initializer
I am parsing a `Json` document using Json.NET and creating an `ArrayList` using a `Collection Initializer` as follows
var array = new ArrayList
{
inputJson["abc"].ToString(),
inputJson["def"].Value<float>(),
inputJson["ghi"].Value<float>()
};
Now I would like to add a null check so it doesn't throw an exception if one of the properties is missing in the Json document.
Thanks
|
Something like this would do the trick
var array = new ArrayList
{
inputJson["abc"] != null ? inputJson["abc"].ToString() : "",
inputJson["def"] != null ? inputJson["def"].Value<float>() : 0.0F,
inputJson["ghi"] != null ? inputJson["ghi"].Value<float>() : 0.0F
};
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, json.net"
}
|
How to use same path in loadChildren for Nativescript and Angular?
I have a project using Angular and Nativescript, and we'd like to use the same routes.
Here's how my routes look like:
{
path: '',
component: BaseComponent
},
{
path: 'details',
//loadChildren: '~/app/Routes/base/details/details.module#DetailsModule',
loadChildren: './details/details.module#DetailsModule',
}
The commented one works on Nativescript, but not on Angular. The other one works on Angular but not on Nativescript.
How can I use the same path to lazy load my module in Nativescript AND Angular, without having 2 files?
Thanks in advance! Have a great day :)
|
In case someone's having this problem, you can do this:
{
path: '',
component: BaseComponent
},
{
path: 'details',
loadChildren: () => DetailsModule,
}
The import is a relative path and work wit both of the platform
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "angular, routes, nativescript"
}
|
How to debug firebase web app locally
I need to build a Cloud Function, so i am trying to set up a developer environment where i can test and debug a firebase function.
From the examples i saw, it all ends up setting up a nodejs node. Because i can't run the node directly, i need to use firebase CLI to start it, so i can't use any local debug.
The best thing i can come with is to put the code in html page and use the browser native debug, which is ok, but database handlers do not work.
Debugging on the server, looks to complicated for short cycles.
Is there a better way to debug it locally?
Update: database handlers work, but only while code is running. Can be triggered if the target object is changed during the same execution.
|
You seem to be confusing two pieces of your app:
1. the web app, which is served from Firebase Hosting's servers, but runs in your user's browsers
2. the functions, which run on Google Cloud's servers
To debug your web app locally, you can use `firebase serve` (similar to how you use `firebase deploy` to deploy it). Then open the site in your browser (it defaults to ` and debug it using your browser's developer tools.
To debug your Cloud Functions for Firebase locally, there is an emulator. See the documentation for more info and the answer here: how to test Cloud Functions for Firebase locally on pc.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "node.js, debugging, firebase"
}
|
Creating JDBC Application
I have this piece of code:
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8","root","Icdjoil100");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from t_user");
while(rs.next())
//System.out.println(rs.getInt(0)+" "+rs.getString(1));
con.close();
}catch(Exception e){
e.printStackTrace();
}
but I have this error:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.ResultSet.checkClosed(ResultSet.java:666)
at com.mysql.jdbc.ResultSet.next(ResultSet.java:7274)
at Test.main(Test.java:19)
|
Since you commented out your print statement, your loop is now closing the connection (and all of its dependent resources). Your code, without the commented out line:
while(rs.next())
con.close();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, mysql, sql, database, jdbc"
}
|
Cloud mapping experiment. Contact [email protected] in the access logs
54.204.131.75 - - [09/Jul/2014:17:53:43 +0100] "HEAD / HTTP/1.1" 200 283 "-" "Cloud mapping experiment. Contact [email protected]"
A new line in my access log the other day. As far as i can tell this is most likely a phishing scam. Does anyone know if I might be wrong.
I can see little more trace on my machine of any damage. The log was recorded 3 time over the course of an hour or so.
|
It looks like somebody's robot accessing the HTTP server on your machine. My gut says it's probably harmless. Searching Google for those keyword returns other people who are seeing it in their logs, too.
It's good to be vigilant and it's good to hear that you're watching your logs so closely. In this case, I suspect you're alright.
|
stackexchange-serverfault
|
{
"answer_score": 9,
"question_score": 7,
"tags": "log files"
}
|
Isabelle2016 and command line
I am new to Isabelle and now trying to do a proof using the command line of Cygwin to measure the time needed to prove a lemma.
What would be the best and easiest way to do that?
I would expect there is a command like: "isabelle theory_file.thy", but having run through The Isabelle System Manual I got a feeling that everything is much more complex than that and got lost eventually.
So I have a theory file and am looking for a way to start a prove process with the Cygwin terminal included to the Isabelle2016 distribution for Windows.
Every piece of advice or direction I need to look to is highly appreciated. Thanks in advance.
|
If you just use the normal Prove IDE (Isabelle/jEdit), you can get timing information for individual commands as follows:
* CONTROL-hover over the command keyword: timing is displayed for commands that take measurable time (more than 1 millisecond).
* The Isabelle/jEdit menu item "Plugins / Isabelle / Timing" provides a separate Timing panel for theories and commands, see also the Isabelle Documentation with the label **jedit**.
If you really need batch-mode timing of while sessions (with all theories therein), the easiest way is via `isabelle build -v`. See the **system** manual about that (in section "Isabelle sessions and build management").
Note that everything runs in parallel by default, so timing results always need sensible interpretation.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "cygwin, isabelle"
}
|
Keep a local folder in sync with a remote FTP folder
I'm looking to build a client node app to keep a folder on the clients machine in sync with any changes that happen with a folder it's cloned from on a remote FTP server.
I could connect to the server and download all the files initially, but I'm not sure how to keep track of file changes.
I could keep a file with filenames/checksums for all files and folders somewhere on that remote server so I can tell when files need re-downloading. However I'm not sure how I'd handle file deletions, maybe if the file name is no longer in the server side hash file I know to delete it.
I guess I'm asking is there any better ways of keeping a local and remote folder in sync with Nodejs?
|
I solved this by generating an "index" json file on the server that lists the path to every file and it's size and md5 hash. I then download this file and perform checks against everything in the list, anything missing I download. I then save a local copy of that index file then next time I check for updates anything that exists in my local index file but not the remote one indicates deletions are needed. Hashing lots of files (10GB~) on the client side was pretty slow so after the first sync I store hash's of folders in the index files, then I can just compare folder hash values in local/remote index and if there are differences I can then do the expensive hashing on individual files in those folders.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "node.js, ftp, synchronization, rsync"
}
|
If the index is greater than arr length it should go back round again
function getAnyItem(arr, position) {
if (position > arr.length) {
return position = arr[0] ;
}
let index = arr[position];
return index;
}
I am really struggling on finding a way to go back round an array without using loops.Above is what I have written so far, all I get it undefined. Any help would be much appreciated as I am new to coding.
getItem(['a','b','c'], 10) should return 'b'
|
You could take the remainder operator `%` with the length of the array
function getItem(arr, position) {
return arr[position % arr.length];
}
console.log(getItem(['a','b','c'], 10)); // 'b'
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "javascript, arrays"
}
|
2nd Law of Thermodynamics
I understand that the 2nd law of thermodynamics roughly states that, if you have a body (or a gas in a chamber) that is hot at one end and cold on the other, the heat will always flow from the hot to the cold part and to get the opposite effect, one has to put energy in from the outside (through a machine or something).
Now, I don't understand why this fact cannot be explained just through probabilities (of the velocities of the gas molecules, say).
It would seem to me that it is simply very, very, very unlikely that faster moving molecules all end up in (approximately) one spot at any time.
But from all the fuzz about the 2nd law, I'm led to believe that there has to be more behind it than probability. So where am I wrong? Why is the second law beyond probability? How is the 2nd law tested? (so that one can rule out simple probability?)
ps.: I haven't yet had a course on probability theory. So my understanding of it is limited.
|
I assure you, it is all probability AND statistics.
Well you see when you say "a gas is at 300 Kelvin", then it does not mean all the molecules in the gas are "at 300 Kelvin", it rather states an average. It represents the total behavior of the gas compared to anything at any other temperature. So there are actually molecules with more kinetic energy, and those with less kinetic energy, interacting with each other and the environment they are in, however due to the massive number of collisions and interactions, the result with highest probability(i.e. same temperature box&gas stays at the same temperature) is the macroscopic outcome.
Probability, combined with statistics is a very powerful tool to represent macroscopic nature, and I suggest you to take probabilistic maths and statistical thermodynamics courses to further investigate such issues.
|
stackexchange-physics
|
{
"answer_score": 10,
"question_score": 5,
"tags": "thermodynamics"
}
|
How to find best selling products?
I want to find the best selling products according to this criteria.
Minimum order = 5
* Product A = 100 orders -last order = 29 Dec 2021
* Product B = 6 orders - last order = 1 Jan 2022
* Product C = 3 Orders - last order = 3 Jan 2022
Product B must show first.
Product C will not show because it has less than 5 orders.
Here is my database structure and what I tried
<
|
Here's the query for getting all products with minimum order count of 5, sorted in descending order.
SELECT p_name,
tmp.total_orders,
tmp.last_purchased
FROM products P
INNER JOIN (
SELECT product_id,
COUNT(*) AS total_orders,
MAX(created_at) AS last_purchased
FROM order_items
GROUP BY product_id
HAVING total_orders >= 5
) AS tmp ON tmp.product_id = P.id
ORDER BY last_purchased DESC
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql"
}
|
Understanding "update_option_(option_name)" Wordpress hook
I am creating a plugin for Wordpress and haven't really worked with Wordpress very long and i want to have a function run once a specific option is updated for a blog. I think that update_option_(option_name) is the hook i want but i can't understand or find how to use it and was wondering if anyone had an example or a link to show me how this hook works? THANKS!!!!
|
If you run over a specific wordpress function or hook name, just go to google and enter:
codex *function or hookname*
like
codex update_option_(option_name)
for your question.
Normally the first result directs you to the wordpress documentation page (codex) that normally answers most questions. If not, there are more search results that are most often helpful.
Additionally, all hooks are documented inside the wordpress codebase. You only need to read the code where the hook get's invoked to understand what the input values (and if a filter, the output values as well) mean. In your case that hook is located here: <
Hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, wordpress"
}
|
Simple way to have a hybrid JTextField / JPasswordField?
I am developing a simple applet that has a simpe sign-in interface.
And to be concise in space, I have two JTextFields for username and password, which I also use as labels. i.e. to start with, the username JTextField will be pre-filled with grey text saying "username" and the password JTextField pre-filled with "simple password".
Then as soon as the JTextField gets focus, i clear the prefill text and set the text color to black. Similar to stackoverflow's search box, but in swing.
Now for security, I would like to mask the password field when the password JTextField gets focus (but of course still have the pre-filled text legible to start with). JPasswordField doesn't allow the toggling of mask/unmask.
Any ideas for a simple way to obtain this functionality in my simple applet?
|
You can disable the masking echo character with setEchoChar((char)0); as stated in the JavaDoc.
An example
final JPasswordField pass = new JPasswordField("Password");
Font passFont = user.getFont();
pass.setFont(passFont.deriveFont(Font.ITALIC));
pass.setForeground(Color.GRAY);
pass.setPreferredSize(new Dimension(150, 20));
pass.setEchoChar((char)0);
pass.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
pass.setEchoChar('*');
if (pass.getText().equals("Password")) {
pass.setText("");
}
}
public void focusLost(FocusEvent e) {
if ("".equalsIgnoreCase(pass.getText().trim())) {
pass.setEchoChar((char)0);
pass.setText("Password");
}
}});
Greetz, GHad
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "java, swing, applet"
}
|
How do I print something after n seconds?
Sorry if this is a basic question but I'm just trying to print a string after a certain number of seconds and I'm not sure how to do it. I can put an input beforehand so that there is a reference for when the start of the 6 seconds.
something like this:
x = input()
after 6 seconds:
print('Hello World!')
|
use `import time`
import time
x = input()
time.sleep(6)
print('Hello World!')
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, python 3.x"
}
|
How do I add a header to a Django RequestFactory request?
To manually send a GET request with a header, I do this with `curl`:
curl -H "Key: Value"
I want to write a unit test that makes a request (using `django.test.RequestFactory`) containing a header. How can I add a header to the request?
For clarity, below is an example of what I'd _like_ to be able to do, though what I have written below is _not_ valid code because `RequestFactory.get()` does not have a `headers` parameter:
from django.test import TestCase, RequestFactory
class TestClassForMyDjangoApp(TestCase):
def test_for_my_app(self):
factory = RequestFactory()
my_header = dict(key=value, another_key=another_value)
factory.get('/endpoint/', headers=my_header)
|
You need to pass _**`HTTP_*`**_ kwargs to the `get(...)` ( or any valid http methods) to pass a custom HTTP header in the request.
class TestClassForMyDjangoApp(TestCase):
def test_for_my_app(self):
factory = RequestFactory()
**my_header = {"HTTP_CUSTOM_KEY": "VALUE"}**
request = factory.get("/some/url/", ****my_header** )
print(request.headers) # {'Custom-Key': 'VALUE'}
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 7,
"tags": "django, unit testing, http headers"
}
|
Создание аудиофайла из сэмплов (аудиофайлов)
Есть в наличии 12 сэмплов (ogg файлов, но думаю формат не важен, можно и wav) которые нужно сохранить в виде мелодии (между кусочками одинаковая пауза, до 12 кусочков одновременно играть может). Может есть какая библиотека для этого. Интересует решение для Java.
|
Под vanilla Java есть такое решение по конкатенации 2-х аудио файлов:
AudioInputStream myClip1 = AudioSystem.getAudioInputStream(new File(clipFile1));
AudioInputStream myClip2 = AudioSystem.getAudioInputStream(new File(clipFile2));
AudioInputStream appendedFiles = new AudioInputStream(
new SequenceInputStream(myClip1, myClip2),
myClip1.getFormat(),
myClip1.getFrameLength() + myClip2.getFrameLength());
AudioSystem.write(appendedFiles, AudioFileFormat.Type.WAVE,
new File("AppendedClip.wav"));
Под Android сейчас не работает - где в районе API 9-10 поддержка пакета **javax.sound.sampled** была убрана по неизвестным причинам
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, java"
}
|
Is there evidence of people moving east to Europe?
We know that the Inuits moved from present-day Alaska to Greenland, but did they move any farther east? At least to Iceland or the other Nordic countries?
They would have to cross the Atlantic which wouldn't be the easiest, but the fact that they moved so quickly from Alaska to Greenland, makes me wonder whether they expanded any further.
|
No, they didn't. There is no evidence of human occupation in Iceland before Irish monks and later the Vikings settled there. Eskimo technology wasn't bad at all, kayaks are pretty nifty boats. But not suitable for migration.
|
stackexchange-history
|
{
"answer_score": 5,
"question_score": 1,
"tags": "europe, immigration, migration, arctic"
}
|
If $Y_i = 1 - X_i$, why is $Y_{(1)} = X_{(n)}$ if $X \sim U(0, 1)$?
I saw in my notes that if $Y_i = 1 - X_i$, then $Y_{(1)} = X_{(n)}$ if $X_i \sim U(0, 1)$?
Note that $X_{(i)}$ is the i-th order statistic so $X_{(n)} = \max\\{X_1, \ldots, X_n\\}$.
Isn't $Y_{(1)} = \min\\{1 - X_1, \ldots, 1 - X_n\\}$? If so, wouldn't $Y_{(1)} = X_{(1)}$?
It's possible something may have gotten lost in translation in my notes, but I wanted to make sure I'm not misunderstanding something here.
|
* Multiplying the $X_i$ by $-1$ reverses the order: $a <b \iff -a > -b$
* Adding $1$ does not change the order: $-a > -b \iff 1-a > 1-b$
* So the highest $X_i$ corresponds to the lowest $-X_i$ and the lowest $Y_i=1-X_i$
* So $$Y_{(1)} =\min\\{Y_1, Y_2, \ldots, Y_n\\} \\\ = \min\\{1-X_1, 1-X_2, \ldots , 1-X_n\\}\\\ = 1+\min\\{-X_1, -X_2, \ldots, -X_n\\} \\\ = 1-\max\\{X_1, X_2, \ldots ,X_n\\} \\\ =1 -X_{(n)}$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "probability, random variables, uniform distribution, order statistics"
}
|
match multiple slashes in url, but not in protocol
i try to catch multiple slashes at the ende or inside of url, but not those slashes (which could be two or more), which are placed after protocol ( ftp:// file:///)
i tried many findings in similar SO-threads, like `^(.*)//+(.*)$` or `^:`, or `^(.*?)(/{2,})(.*)$` in < < and < But nothing worked clear for me.
Its pretty weird, that i can't find a working example - this goal isn't such rar. Could somebody share a working regex?
|
Here is a rule that you can use in your site root .htaccess to strip out multiple slashes anywhere from input URLs:
RewriteEngine On
RewriteCond %{THE_REQUEST} //
RewriteRule ^.*$ /$0 [R=301,L,NE]
`THE_REQUEST` variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules. Example value of this variable is `GET /index.php?id=123 HTTP/1.1`.
Pattern inside `RewriteRule` automatically converts multiple slashes into single one.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "regex, .htaccess"
}
|
Definition of exterior product
From $r$ linear functionals $f_1,\cdots, f_r\in E^*$, we obtain the $r$-linear alternating form $f_1 \wedge \cdots \wedge f_r: E\times \cdots \times E \to \mathbb{R}$, defined by
$$(f_1 \wedge \cdots \wedge f_r)(v_1, \cdots, v_r) = \det(f_i(v_j)))$$
It is defined as a determinant. However, I have an exercise that asks me to calculate things like $e_1 \wedge e_2$. But where do I apply $e_1$ and $e_2$? In the definition the functionals $f_i$ are applied onto vectors $v_j$, but the exercise asks me to just take the product $e_1 \wedge e_2$.
$(e_1 \wedge e_2)(v_1, \cdots v_2)$?
|
$$ (e_1 \wedge e_2)(v_1, v_2) = e_1(v_1) e_2(v_2) - e_1(v_2) e_2(v_1) = \left| \begin{matrix} e_1(v_1) & e_1(v_2) \\\ e_2(v_1) & e_2(v_2) \end{matrix} \right| $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, linear algebra, abstract algebra"
}
|
Are Tasks created as background threads?
I'm just wondering whether the new Task class in dot.net 4 is creating a background or foreground thread ?
Normally I'd set "IsBackground" on a Thread, but there's no such attribute on a Task.
I've not been able to find any documentation of this on MSDN :-(
|
Shouldn't be tough to verify:
class Program
{
static void Main()
{
Task
.Factory
.StartNew(() => Console.WriteLine(Thread.CurrentThread.IsBackground))
.Wait();
}
}
And the answer is ...
ǝnɹʇ
|
stackexchange-stackoverflow
|
{
"answer_score": 130,
"question_score": 93,
"tags": "c# 4.0"
}
|
How to find if a list/set is contained within another list
I have a list of product IDs and I want to find out which orders contain all those products. Orders table is structured like this:
order_id | product_id
----------------------
1 | 222
1 | 555
2 | 333
Obviously I can do it with some looping in PHP but I was wondering if there is an elegant way to do it purely in mysql. My ideal fantasy query would be something like:
SELECT order_id
FROM orders
WHERE (222,555) IN GROUP_CONCAT(product_id)
GROUP BY order_id
Is there any hope or should I go read Tolkien? :) Also, out of curiosity, if not possible in mysql, is there any other database that has this functionality?
|
You were close
SELECT order_id
FROM orders
WHERE product_id in (222,555)
GROUP BY order_id
HAVING COUNT(DISTINCT product_id) = 2
Regarding your "out of curiosity" question in relational algebra this is achieved simply with division. AFAIK no RDBMS has implemented any extension that makes this as simple in SQL.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "mysql, sql, relational division"
}
|
Is it possible to create an Android database without external tools?
I have been searching for this for the past few days and every tutorial I see needs for me to use an external package. Is there anything built into the Android SDK that would allow me to create a database? I thought I saw something on it a long time ago, but I can't find anything to back that foggy memory up.
|
Do you mean creating SQLite database? The `SQLiteDatabase::openOrCreateDatabase()` will create sqlite database and it's part of the android SDK:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, database, sdk, package"
}
|
Valuation over the algebraically closed field of rational number
How do we define the valuation over the algebraically closed field of rational numbers say $\bar{\mathbb Q}$ as an extension of the valuation of $\mathbb Q$ ?
|
For any finite Galois extension $K/\mathbb{Q}_p$, there is a unique extension of the norm that respects the $p$-adic norm on $\mathbb{Q}_p$, and this is Galois-invariant. Therefore, it must be given by $|x|_K = |Norm(x)|_p^{1/[K:\mathbb{Q}_p]}$. By uniqueness, if we have a tower of field extensions $L/K/\mathbb{Q}_p$, then restricting the norm on $|\cdot |_L$ to $K$ gives $|\cdot |_K$. Since any element of $\overline{Q}$ lives in a finite Galois extension of $\mathbb{Q}_p$, this gives a way to extend the norm to all of $\overline{Q}$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "commutative algebra, valuation theory"
}
|
ionic http request not fired
i am using ionic v2 , the problem is when i send http request it is not shown on chrome
export class Auth {
constructor(public http: Http) {
console.log('Hello Auth Provider');
}
login(){
console.log('Hello');
this.http.post('localhost:8100/api/User/getAll/' , '' , {});
}
}
i fire login method , it console out 'Hello' but not fire the http
that means ionic not firing the http call , i have installed white list plugin , edit xml file and install chrome extension but there is nothing of those solved the issue
|
You have to `map()` the response then use the `subscribe()` method because the angular Http use `Observables`. check this
this.http.post('localhost:8100/api/User/getAll/' , '' {})
.map(res => res.json())
.subscribe(
response => {
console.log(response);
},
error => {console.log(error)
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cordova, google chrome, http, ionic framework"
}
|
How can I know redux-form resetForm() is completed?
I use `redux-form` \+ `react` in my project:
//My components
<button type="submit" className="btn btn-primary" onClick={this.getBuildingList.bind(this)}>Search</button>
<button type="button" onClick={this.resetBuildForm.bind(this)}>Reset</button>
//resetBuildingForm function
resetBuildingForm(){
let { dispatch, resetForm, list } = this.props;
resetForm();
//when I resetForm, I want to search again
this.getBuildingList();
}
when I resetForm, I want to search again, but when I get state in redux-form, I get the state is old but not new, How can I know when the resetForm event is complete and the state is updated?
|
You could listen for when your form goes from `dirty` to `pristine`.
componentDidUpdate(prevProps) {
if(this.props.pristine && !prevProps.pristine) {
// we just reset
this.getBuildingList()
}
}
Then you can just call `this.props.resetForm()` to initiate the reset.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "reactjs, redux form"
}
|
Get the ASP.NET form name
I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript.
The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names.
Thanks.
|
I'm not totally sure that this will address what you're asking for, so please comment on it:
In your script, when the User Control renders, you could have this placed in there. So long as script doesn't have a "runat" attribute, you should be good.
<script type="text/javascript">
var formname = '<%=this.Page.Form.Name %>';
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "asp.net, javascript, forms"
}
|
Jar file escapes "--" from substituted variable - Bash
Code:
#!/bin/bash
MyVariable="--option arg1,arg2"
echo Variable output : $MyVariable
java -jar HelloInternet.jar "$MyVariable"
Expected results:
The jar file should recognize and use the value stored in variable.
Actual results:
The jar file escapes "\--" from "\--option arg1,arg2" , and interprets the variable without the "\--" .
Include any error messages:
Exception in thread "main" joptsimple.UnrecognizedOptionException: option arg1,arg2 is not a recognized option
Describe what you have tried:
I tried using `' '` instead of `" "` and vice versa without success.
|
Use an array when you need an array:
MyVariable=(--option arg1,arg2)
java -jar HelloInternet.jar "${MyVariable[@]}"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, bash, jar"
}
|
Why are these two complex exponentials equal?
Why is $$e^{i(\theta+\pi)} = -e^{i\theta}$$ I saw this but I'm not sure why it works. If someone could show me the steps I would really appreciate it.
|
To show : $$e^{i(\theta+\pi)}=-e^{i\theta}$$
Now $$e^{i \theta} = \cos \theta + i \sin \theta \cdots (1)$$
so $$e^{i(\theta+\pi)}=\cos (\theta+\pi) + i \sin (\theta+\pi) \cdots (2)$$
Also , recall that $$\cos (\pi+\theta) = -\cos \theta $$ and $$\sin (\pi+\theta) = -\sin \theta $$
From the above results $(2)$ modifies to $$e^{i (\theta+\pi)} = -(\cos \theta + i \sin \theta)$$
Therefore from $(1)$ $$e^{i(\theta+\pi)}=-e^{i\theta}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex numbers"
}
|
matplotlib: left yaxis and right yaxis to have different units
I'm plotting curves in Kelvin. I would like to have the left yaxis to show units in Kelvin and the right yaxis to show them in Celsius, and both rounded to the closest integer (so the ticks are not aligned, as TempK=TempC+273.15)
fig=plt.figure
figure=fig.add_subplot(111)
figure.plot(xpos, tos, color='blue')
I should not use `twinx()` as it allows superimposing curves with two different scales, which is not my case (only the right axis has to be changed, not the curves).
|
!enter image description hereI found the following solution:
fig=plt.figure
figure=fig.add_subplot(111)
figure.plot(xpos, tos, color='blue')
... plot other curves if necessary
... and once all data are plot, one can create a new axis
y1, y2=figure.get_ylim()
x1, x2=figure.get_xlim()
ax2=figure.twinx()
ax2.set_ylim(y1-273.15, y2-273.15)
ax2.set_yticks( range(int(y1-273.15), int(y2-273.15), 2) )
ax2.set_ylabel('Celsius')
ax2.set_xlim(x1, x2)
figure.set_ylabel('Surface Temperature (K)')
Do not forget to set the twinx axis xaxis!
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 7,
"tags": "matplotlib, axis"
}
|
No funciona Método de insercion Directa | Visual Basic
no funciona este código, se queda trabado cada vez que quieres dar al botón de "ordenar" , los siguientes variables están declaradas como, i, j, Auxiliar, n como de valor entero. El código es el siguiente:
If rbdirecto.Checked = True Then
n = lstnumeros.Items.Count
For i = 1 To n
Auxiliar = lstnumeros.Items(i)
j = i - 1
While (j >= 0) And (Auxiliar < lstnumeros.Items(j))
lstnumeros.Items(j + 1) = lstnumeros.Items(j)
j = j - 1
End While
lstnumeros.Items(j + 1) = Auxiliar
Next
End If
Sería de mucha ayuda que me digan en donde esta el error del codigo.
|
Encontré dos cosas en tu código: un es que el For debería ir de cero a N-1, ya que no es un vector, sino una lista que comienza de cero. Lo segundo es que el While en lugar de tener un And debería tener un AndAlso, para que en caso de que j sea menor a cero no de error la segunda validación del while. Te paso el código:
If rbdirecto.Checked = True Then
n = lstnumeros.Items.Count
For i = 0 To n - 1
Auxiliar = lstnumeros.Items(i)
j = i - 1
While (j >= 0) AndAlso (Auxiliar < lstnumeros.Items(j))
lstnumeros.Items(j + 1) = lstnumeros.Items(j)
j = j - 1
End While
lstnumeros.Items(j + 1) = Auxiliar
Next
End If
Espero te sirva. ¡Suerte!
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vba"
}
|
How to pass inline style with props in react js?
I want to pass inline styles with props like this :
<P style={{marginTop : '20px'}}>{price}</P>
import React from 'react';
function P(props) {
return <p style={{ width: '100%', textAlign: 'right', fontSize: '1.3em' ,{props.style} }}>{props.children}</p>;
}
export default P;
But it throws an error in terminal saying :
Unexpected token, expected , (4:74)
2 |
3 | function P(props) {
> 4 | return <p style={{ width: '100%', textAlign: 'right', fontSize: '1.3em' {props.style} }}>{props.children}</p>;
| ^
5 | }
6 |
7 | export default P;
How can I pass inline styles with props to another component in react js ?
|
What you should do is, send the exact value of margin-top, rather than the css code, like so
<P marginT='20px'>{price}</P>
and using it like:
<p style={{ marginTop: this.props.marginT }}>{props.children}</p>;
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, css, reactjs"
}
|
Can I extract the GPG public key if I have an encrypted file, the private key pgp file, and the pass phrase?
I am working on a project where I have been provided with a GPG private key in armor text format, the pass phrase, and a file that was encrypted with the public key. The public key is not available however. I have verified the parts I have by importing the private key and decrypting the sample file, so I know the 3 bits I have are working.
Is there any option to recreate the public key from these 3 parts that I have access to?
|
If you have already imported the private key with `gpg --import private.asc` you can export the public key with `gpg --export <id>`. By default, it only exports the public key.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 0,
"tags": "gpg"
}
|
Mercurial API: hg.repository with https
I'm trying to write a simple script that clones an existing Mercurial kiln repository that uses https authentications. I have this snippet:
from mercurial import hg, ui
repo = hg.repository(ui.ui(), "
Normally, whenever I would clone this repo or something, Mercurial would ask me to authenticate myself with a username and password. Instead, the above snippet just isn't getting authorized and gives me this error:
[a bunch of tracebacks...]
File "C:\Python26\lib\site-packages\mercurial\url.py", line 131, in find_user_password
raise util.Abort(_('http authorization required'))
mercurial.error.Abort: http authorization required
How can I pass my username and password to the `hg.repository` function? I've looked at both the source to hg.py and ui.py, but neither were helpful.
|
You could try setting those directly to the url.
> <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "python, api, mercurial, https"
}
|
Is it possible to delete one of my accounts after they were merged?
My two different accounts were merged into a single one. So, I would like to delete one of the accounts. Is this possible? If yes, then how can I do this and is there any consequence to this on deleting one of the accounts that was merged?
|
If one account is merged with another, the merging account (not the target) will be deleted as part of the process.
|
stackexchange-meta
|
{
"answer_score": 1,
"question_score": 2,
"tags": "support, deleted accounts, merge accounts"
}
|
Seeking FOSS user admin code
It must be a fairly standard wheel, so I'd rather not reinvent it.
Create/modify/delete users. Ditto their passwords & maybe enforce password change every X days. Also, create groups, like "sales", "support", etc and add/remove users.
The only unique part should be what they have permission to do (visit certain parts of the site after login, etc)
And I'd like to store admin data in an ODBC compliant database (MySql to start with, but I may move on).
Is this a new wheel?
* * *
There doesn't seem to be much of anything on SourceForge, but if I could find something established and trusted I wouldn't even mind paying a few $100 as a trade of for the time needed to develop & test it.
|
It's been done before, but the risk of obtaining it from an external source is to get and use something you don't truly understand, and possibly misuse it. That said, I did a search for just this sort of thing recently, and didn't find much of anything I particularly liked; I rolled my own, and now am happy because I _do_ have full knowledge of exactly what the authentication is doing.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php"
}
|
PHP - Obter valores de variáveis em string
Sou novo em Wordpress e PHP e estou com um probleminha rsrs
Tenho uma string bem grande que obtenho dinamicamente. Essa string é, na verdade, um array com vários valores e variáveis. Gostaria de pegar todos os valores contidos na variável videoID que se repete N vezes dentro desse array (que na verdade é uma string).
Ou, em outras palavras, estou tentando usar a API do YouTube para mostrar o conteúdo de uma playlist no meu site. Consegui apenas obter uma string GIGANTE usando _file_get_contents_ na url _ . Se alguém puder me ajudar a fazer isso :)
Obrigado!
|
Criei uma API_KEY pra responder sua pergunta. :)
O objeto json que a API do Youtube envia é grandinho e tem um monte de detalhes, se quiser montar um array só com os ids dos vídeos, pode fazer o seguinte:
<?php
$playlist = "SUA_ID_DA_PLAYLIST";
$api_key = "SUA_API_KEY";
// URL com ID da API e da lista de reprodução
$url_do_youtube = "
$json = file_get_contents($url_do_youtube);
$obj_videos = json_decode($json);
//var_dump($obj_videos);
$lista_videos = $obj_videos->items;
$lista_id_videos = array();
foreach($lista_videos as $obj_video)
{
$lista_id_videos[] = $obj_video->contentDetails->videoId;
}
var_dump($lista_id_videos);
Espero que ajude, se tiver alguma dúvida pergunte aqui mesmo. Se a resposta tiver sido útil, dê uma moral e aceite como resposta e clique na setinha pra cima pra me dar pontos de reputação. Falow, valew. :)
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, wordpress, string, youtube api"
}
|
wordpress query - next two events by metadata date
I have posts in the "events" category that have a meta-data called "start_date".
Is there a way that I can query the next two events in the system (after today's date)?
I know that I can easily get the last two events in the system, but my wordpress nor my sql is strong enough to figure out how to query the next two events.
|
Just to give you an idea, try the following, not tested.
<?php
$args=array(
'meta_key'=>'start_date',
'meta_value'=> now(),
'meta_compare' => '>',
'order' => 'DESC',
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo 'List of Posts';
$i=0;
while ($my_query->have_posts()) : $my_query->the_post();
the_title();
$i<2 ? $i++ : break;
endwhile;
}
wp_reset_query();
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "mysql, wordpress"
}
|
What is the dict.cc entry : etw. hätte gemacht worden sein müssen?
 Das hätte gemacht werden müssen – That would have had to have been done (but it wasn’t)
or
2) Das müsste gemacht worden sein – That would have had to have been done, was bound to have been done before xyz time, in order for something to be the case.
so what is dict.cc's 3) "etw hätte gemacht worden sein müssen"... Is this correct? is this another tense?
I think maybe it is wrong.
Unless this is correct and the difference between 1) and 3) would be perhaps:
1) That would have had to have been in the process of being done
3) That would have had to have already been done, before xyz happens
So whats the difference in the german phrases: "das hätte gemacht werden müssen" and "das hätte gemacht worden sein müssen"
|
Nice tricky question.
> Das hätte gemacht werden müssen
That should have been in the process of being done by the time we're referring to. No statement is made whether the deadline for finishing the work is in the past or future. Most probably it hasn't been started yet, though.
> Das müsste gemacht worden sein
The process of "making" should have been finished by the time we're referring to. And the reference is from today. We don't know whether it's been done or not. Deadline for finishing can be in the past or future.
> Hätte gemacht worden sein müssen
The process of "making" should have been finished by the time we're referring to. And the reference is from yesterday - We know it hasn't been done. Deadline for finishing thus was in the past.
IMHO, the entry is OK.
|
stackexchange-german
|
{
"answer_score": 4,
"question_score": 4,
"tags": "verb, tense"
}
|
Выборка данных самой последней даты
Есть две таблицы `room`, `journal`
room
-----------------
id int,
name varchar(20)
journal
-----------------
id int,
date timestamp,
degree char(3),
room_id int
Как выбрать данные как `room.name`, `journal.date`, `journal.degree` из таблиц, при условии что данные должны быть самого последнего дня `max(journal.date)`, для каждого `room.name`
|
В версии PostgreSQL 9.3 можно воспользоваться оконными функциями:
select distinct
room.name
,first_value(journal.date) OVER (partition by room.id order by journal.date desc, journal.id desc)
,first_value(journal.degree) OVER (partition by room.id order by journal.date desc, journal.id desc)
from room
inner join journal ON room.id = journal.room_id
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, postgresql"
}
|
Drupal 7 subfolder multisite
I'm trying to setup a drupal 7 multisite using subfolders for example:
example.com/site1
example.com/site2
In my drupal sites folder I have sites1 and sites2 according to sites.php I should be able to set it up as the following:
$sites['example.com/site1'] = 'site1';
$sites['example.com/site2'] = 'site2';
However this doesn't work, I can definitely see a site at example.com but am unable to see any of the sites in the sub folder.
|
If you want to do it this way then you have to symlink the folder to the root of the drupal install:
cd /var/www/drupal
ln -s . site1
Then within sites.php use the following:
$sites = array(
"example.com.site1" => "site1",
);
|
stackexchange-drupal
|
{
"answer_score": 6,
"question_score": 7,
"tags": "7, multi sites"
}
|
Битрикс оплата счета частями
Как реализовать оплату заказа частями, использую обработчик счет? Например, сумма заказа 10 000 руб, заказчик может оплатить любую сумму, например 3623 руб.
Как сформировать счет на эту сумму?
|
Создаете свою форму оплаты. Смотрите если введенная сумма меньше той, что человек должен заплатить при помощи АПИ удаляете неоплаченную запись оплаты. И вместо нее формируете две новых. На оплачиваемую сумму и на остаток. Далее запускаете стандартный ход оплаты. Возможно проще (с точки зрения разработки) сделать двухшаговую оплату: задаем сумму и переходим к оплате.
АПИ работы с заказом достаточно хорошо расписано здесь
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "php, битрикс"
}
|
Webpack output file purpose here?
I'm doing the React tutorial (< and I'm confused as to what webpack entry and output filename do exactly?
In the example they have created a file index.html and App.jsx. However, in the HTML they have "". But no index.js file has been created. Although, the output filename in the webpack.config file is index.js
What I believe is happening, is the entry point is where the server tells client to start out at and the output filename (index.js) is where the server is writing out all of the necessary data that will be sent to the the client... is this right?
|
Yes that is basically correct you have an entry file where webpack starts to require and compile all other files from and it will export the output/ bundled file to where every you want it to go. Most of the time this compiled and minified depending on which loaders you are using.
entry: 'index.js',
output: {
filename: 'bundle.js',
path: './app/assets'
},
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, reactjs, webpack"
}
|
Auto-increment field of six digits
I have a table with an "identifier" attribute. I need this attribute to be unique and auto-incremented by one (length of the attribute must be six digits).
For example the first time I persist an entity, the identifier should be 000001 and the second one 000002 and so on.
Could you please tell me how to implement this requirement?
Thanks in advance.
|
You will have to convert your number as a String. To do so, you can use String.format.
String.format("%06d", num)
'0' The gaps are filled with 0.
'6' The result has a size of 6.
'd' The result is formatted as a decimal integer.
For example:
int num = 8;
String var = String.format("%06d", num);
will return:
var = "000008"
**EDIT: The syntax of String.format can be found here:<
If you want to retrieve an ID from your base, just parse the String as a Number:
String identifier = "000008"; // Returned ID from database
Number num = Integer.parseInt(identifier); // num = 8
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, db2"
}
|
Should I upgrade to PHP 5.3?
PHP version 5.3 has been released, and although it looks great, all my code already works fine. I don't see what this new version offers to justify upgrading and working through possible issues after the upgrade.
Should I upgrade anyway just for good practice, or is an upgrade not needed unless I am actually using the new features?
|
You might consider upgrading just for the "Improved PHP runtime speed and memory usage" and bug fixes. Source. I would also say that if you are using create_function anywhere, you should upgrade and replace that ugly, nasty mess, with the much cleaner lambda. Here is the migration guide from 5.2.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 4,
"tags": "php, php 5.3, porting"
}
|
Amazon DynamoDB: Copy Data Model from one account to the other account
What is the best/easy way of copying schema(data model) from one AWS account to the other AWS account. Spent some time looking in NoSQL-Workbench but do not find anything relevant. I am not interested in data transfer, I am more interested in transferring the data model (tables, sort keys, partition keys and other configuration)
|
You can use the awscli to describe a table, as follows:
> aws dynamodb describe-table --table-name mytable
This will output a JSON description of the table, including the key schema and indexes.
You can use the relevant parts of this JSON output to create a new table and indexes using:
> aws dynamodb create-table
Run any awscli command with an additional `help` option for more help. Use `--region us-west-2` (or other region as appropriate) to target a specific AWS region.
If you have typical DevOps automation then you may already have these things encoded in a template (CloudFormation or other) and you can use that.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "amazon web services, amazon dynamodb"
}
|
How make transparent AppCompat style?
My activity style must be from AppCompat theme.
So I make custom style and set activity style in manifest.
But black background is shown.
Below is custom theme
<style name="TransparentTheme" parent="@style/Theme.AppCompat">
<item name="android:background">@null</item>
<item name="background">@null</item>
<item name="android:windowBackground">@null</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@null</item>
</style>
|
**use @android:color/transparent instead of @null**
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 9,
"tags": "android, android theme, android styles, android appcompat"
}
|
AWK command in bash program
here is my program:
for ((i=1;i<=300;i++)); do
awk 'NR==$i{print}' file.dat > fileB.dat
done
the `file.dat` contains 300 lines that I want to save in different files, but the `NR==$i` doesn't work, nothing is printed.
I don't see what is wrong. Thank you
|
Try:
for i in {1..300}; do
awk "NR==$i{print}" file.dat > fileB.dat
done
The single quote ', prevents the shell from expanding variables, in this case `i`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "bash, awk"
}
|
Linear address and physical address
What is linear address? How is it different from physical address?
|
Linear address is generated ~~after~~ **before** page table mapping. Physical addres is generated ~~before~~ **after** page table mapping(ie paging).
Linear Adress,created by adding logical address to the base of segment, CS,DS,ES,SS,FSor GS.
When Paging is enabled, the page tables are used to translate linear address to physical address.
On the Other Hand, Physical Address is nothing but, the address value that appears on pins of processor during a memory read/memory write operations.
InShort, we can say if paging is disabled linear address = physical address
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 14,
"tags": "memory management, x86, memory address, memory segmentation, address space"
}
|
Execute a code when returning form safari (iOS)
I use the facebook sdk in my app. The facebook sdk takes the user to a safari facebook login. Once the facebook login is done the user is taken back to the app and i want to write a set of code to get the access token and proceed with the operation. But where should this code to be written?
|
If you have correctly set up the callback URL of your app (something like `fb19374518456`, where the long number is the Facebook app ID), then Facebook will redirect you from Safari back to the app. In this case, you can implement the
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sApp annotation:(id)ann
method and pass the URL you get to the facebook SDK - it will then parse the URL and obtain the access token and expiration date from it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "ios, facebook, sdk"
}
|
Hide Drupal nodes from search
I made a private section on a drupal site by writing a module that checks the RERQUEST_URI for the section as well as user role. The issue I am running into now is how to prevent those nodes/views from appearing in the search.
The content types used in the private section are used in other places in the site.
What's the best way to get Druapl search to ignore the content/not index/not display it in search results?
|
There is a wonderful article that explains just this on the lullabot site.
It's worth reading the comments to the post too, because people there suggested alternate ways of doing that, also by mean of contrib modules (rather than implementing some hooks in your own code). Code for D6 is in the comment as well.
HTH!
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "php, search, drupal, drupal 6, acl"
}
|
Retrieve value from input object plain js
I have the following field,
<input id="department" value="finance"/>
I'm trying to create an object variable containing the field in plain old javascript like so.
var $field = $(document.getElementById("department"));
I'm then trying to pull the value from the field variable, however it's failing.
$field.value;
Does anybody know what I'm doing wrong?
|
That looks like a jQuery object, which is a collection of DOM elements, and the `value` property is attached to the DOM elements.
You should have:
var field = document.getElementById("department");
// now you can access field.value
jQuery objects have a `val()` method that gets you the value of that property:
var field = $('#department');
// here you can call field.val();
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": -1,
"tags": "javascript"
}
|
Enable bitcode vs include bitcode before submitting app
What's the difference between the **"Enable Bitcode"** setting in the app's target & project and the **"Include Bitcode"** checkbox that is present before submitting to App Store?
If I have "Enable Bitcode" FALSE and have "Include Bitcode" checked, what happens? If I have "Enable Bitcode" TRUE and have "Include Bitcode" unchecked, what happens?
I saw other questions asking only what "Enable Bitcode" does, but mine ask the difference with this setting and the "Include Bitcode" setting just before submitting the app to the App Store.
Thanks
|
As you might imagine, you need both enabled in order to have your app support Bitcode recompilation in iTunes Connect. Just enabling it in Xcode simply means the Bitcode "architecture" is compiled, it doesn't necessarily mean that's sent to Apple.
Advance warning: I've done some tests on app submission with and without Bitcode, and for whatever reason submitting _with_ Bitcode substantially slows down the time it takes for your binary to be processed so that it's ready for submission. Without Bitcode it can appear in a few minutes or up to maybe three hours; with Bitcode I've frequently had delays of 24 hours or more.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 15,
"tags": "ios, xcode, bitcode"
}
|
How can I add embed animated gif to a github repository README.md?
The animated gif I have is 2.5MB size Converted it from mp4 video.
|
You can see an animated gif in this `kellim/farmers-market-finder` README file.
The source code shows that gif embedded as any other picture:
!Farmers Market Finder - Animated gif demo
You have the same method used in "How to add GIFs to your GitHub README" from Joe Cardillo.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "github, repository, animated gif"
}
|
Sql query for pattern matching on a keyword list with 2 character word
I have a predefined list of keywords , which I want to attach to a text during pattern matching.
For e.g :
Suppose the list of my keywords is : ['DZ' , 'BL' , 'TS' , 'FZ']
The characters that I will be attaching one of these keywords is 'SN'
The text I am doing string matching in is : 'RMK A02 SLP 29861 FZSNB24E36'
I want to extract strings which have any one keyword from the list + 'SN'
Thanks in advance.Apologies for bad articulation. I am new to asking questions on Stack Overflow
|
You can list the allowed values in the regular expression:
select regexp_substr(col, '(DZ|BL|TS|FZ)SN'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sql, teradata"
}
|
How do I turn on SQL debug logging for ActiveRecord in RSpec tests?
I have some RSpec tests for my models and I would like to turn on SQL ActiveRecord logging just like I see in the Rails server mode. How to do that?
I start my tests with
RAILS_ENV=test bundle exec rspec my/test_spec.rb
Thanks
|
By default, all your db queries will be logged already in test mode. They'll be in `log/test.log`.
|
stackexchange-stackoverflow
|
{
"answer_score": 62,
"question_score": 114,
"tags": "ruby on rails, ruby, activerecord, rspec rails"
}
|
Asp.net Error while trying to create a bundle - Only application relative URLs (~/url) are allowed
I am getting an error, when trying to include a css file in the bundle, it says that `Asp.net MVC Bundle - Only application relative URLs (~/url) are allowed`.
Here is the code:
bundles.Add(new StyleBundle("~/bundles/lib/anim_css").Include(
"~Vendor/lib/animate/animate.min.css", new CssRewriteUrlTransform()));
Where the `Vendor` folder is the source folder of that css. That folder is included in the project, being like that ...ProjectFolderName/Vendor
This did not help
|
`~Vendor/lib/animate/animate.min.css` is not a legal relative URL. It needs to be `~/Vendor/lib/animate/animate.min.css`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net, bundles"
}
|
looking for better option to print associated values from two items in python dictionary
For the python dictionary below:
fruits = {'names': ['apple', 'banana', 'mango'],
'prices': [12.99, 2.99, 9.99]
}
How to get the prices associated with each fruit?
Basically, I want pair wise printing:
apple = 12.99
banana = 2.99
mango = 9.99
I was thinking of using double for loop, for example:
for fruit in fruits['names']:
print(fruit)
for ….
print(...)
but somehow this looks no good. Any other options?
|
You can use a dictionary that maps the names to prices right from the beginning:
prices = dict(zip(fruits['names'], fruits['prices'])) # in case you need to convert
Then simply iterate over that dictionary:
for fruit, price in prices.items():
print(f'{fruit} = {price:.2f}')
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "python, dictionary"
}
|
How to get a list of all the weather stations, in a given state, using wolfram mathematica
I am currently working on making a 3D plot with Latitude on the x, Longitude on the y, and total rainfall during hurricane Harvey on the z.
The `weatherdata` function in wolfram `mathematica` requires you to pass in a name of a weather station as a parameter.
Is there a way to use the Entity or `EntityList` function to get a list off all the names of weather stations in a given state.
|
This method works, although there is probably a more direct way. To find the weather stations in Illinois, for example, find the nearest 100 from Springfield, then select the ones in Illinois.
coordinates = CityData["Springfield", "Coordinates"];
weatherstations = WeatherData[{coordinates, 100}];
entityvalues = EntityValue[
weatherstations, "PropertyAssociation"];
properties = {
#[[Key[EntityProperty[
"WeatherStation", "Name"]]]],
#[[Key[EntityProperty[
"WeatherStation", "Coordinates"]]]]} & /@
entityvalues;
states = {GeoNearest["USState", Last[#]],
First[#]} & /@ properties;
Last /@ Select[states, #[[1, 1]] == Entity[
"AdministrativeDivision",
List["Illinois", "UnitedStates"]] &]
> {KCPS, KSAR, KBLV, KALN, KPPQ, KUIN, KCIR, KMDH, KMWA, K3LF}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "wolfram mathematica, weather"
}
|
Downloading data from internet - pay attention to what?
In my application I'm downloading data from a website with a xml reader. After that I build an sqlite database with them. All works fine, but I'm afraid that something in the download process can happen (connection interrupts), by which the database is not complete.
Does anyone have something like a list with conditions as to what I need to do for a `save` download? (for example: check connection before the download starts)
|
when parsing the XML and inserting into the DB you'll do the following code:
db.beginTransaction();
try {
// here you parse and insert onto the DB.
// if any exception is reached (the XML reader connection was dropped or whatever)
// it will catch the exception and end the transaction without making it successful
// and SQLite will rollback all the actions you've done here.
db.setTransactionSuccessful();
} catch(Exception e){
Log.e("MyTag", "Transaction fail. " +
e.getClass().getSimpleName() + " - " +
e.getMessage());
}finally {
db.endTransaction();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, download, internet connection"
}
|
Error "Invalid transaction envelope type: specified type" while deploying a smart contract through MyEtherWallet
I have a written a smart contract in Remix. It was possible to deploy this contract on Ropsten through Remix Injected Web3, and also to interact with the smart contract through Remix. Now I am going to deploy the same contract (compiled in Remix, using the bytecode and ABI from Remix) through MyEtherWallet. I am getting the following error message:
Invalid transaction envelope type: specified type "0xOUT" but including maxFeePerGas and maxPriorityFeePerGas requires type: "0x2"
Other people had put the same question (same error message) on other platforms before, but were not given an answer.
|
This error is specific to MEW 6, use their older version to resolve it: <
|
stackexchange-ethereum
|
{
"answer_score": 1,
"question_score": 1,
"tags": "contract deployment"
}
|
Does Method.invoke create another thread of execution?
Does the method.invoke function create another thread of execution? Because when I used it to call a GUI application's main method, the invoke method returned immediately and the program and the GUI application were running at the same time.
|
No.
The behaviour you observe is caused by the fact that the GUI library starts an Event Dispatch Thread when initialized, and all following GUI-related work is performed by that thread.
**EDIT** Here is a simple Swing GUI application:
public class Test {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Hello, world!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
System.out.println("Main method returns");
}
}
If you run it, you will see that all these methods are non-blocking, therefore `main` method returns immediately after GUI is set up, and further work is performed by Event Dispatch Thread.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "java, reflection"
}
|
Android layout-sw340dp issue for htc evo 3d
I need to create layouts for htc evo 3D phone, i created them but its automatically gets the layout-normal and it does not fits for the phone, so then i created new layout as layout-sw340dp and set of images as dreawble-sw340dp its displays compatible fine in the eclips layout designer, but when i check it in the emulator, its displaying the same layout-normal layouts, can any one help me with this... Application API level is 2.3.3
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true" />
|
Android 2.3.3 emulator is only works for basic three layouts eg:- layout-large, layout-normal, layout-small, but layouts in layout-sw340dp folder works perfectly in avd instance in 4.0.1
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android"
}
|
You don't have permission to access / on this server.がでてアクセスできない
apache2.4Laravel
DocumentRoot "/root/test/laravel/public"
ServerName mailsvr-01.local:80
※Laravel3.0/root/test/
<
※
You don't have permission to access / on this server.
[14/Jan/2016:18:34:30 +0000] "GET / HTTP/1.1" 403 209
|
/rootroot/root(/var/tmp)
Apacheapachenobodyroot/root
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, laravel"
}
|
Jailcoder with SDK 6.0
I am new to `iOS`. I was installing latest `XCode` with `SDK 6.0` in it. I have been successfully testing my app developed using `SDK 6.0` on simulator. Now i want to test it on real device without developer program account. To do that, i use `Jailcoder`. I have an `iPhone 3GS`, with `AppSync 5.0+` installed. I have tried `"Quick XCode Patch"` and `"Patch My Project"`. However i still get signing error. It said,
> CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 6.0'
Seems it due to `iOS 6.0 SDK` that has not been supporting `jailbroken` devices. I need some hints and workarounds to deal with this error.
|
By default, Xcode requires iOS apps to be signed. However, there is a `plist` file that Xcode uses, where you can change this. You can tell Xcode that code signing is **not** required.
Check this file:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/SDKSettings.plist
You can edit it on your Mac with the **Property List Editor** application.
Make sure that in that file, `CODE_SIGNING_REQUIRED` is set to `NO`. You'll probably need to do this each time you install a new iOS SDK (e.g. 5.0, 5.1, 6.0, etc.)
You can find out more about this on the BigBoss website here. BigBoss is one of the popular Cydia repositories for distributing jailbreak apps and tweaks.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ios, jailbreak, ios6"
}
|
Android : Facebook app id showing error in values-ta/strings.xml and can't able to generate signed apk
I'm using facebook login in my app. I've created facebook app id. If I use facebook app id in values/strings.xml it works fine and I'm able to generate signed apk in android studio. If I use that facebook app id in values-ta/strings.xml and values-de/strings.xml it shows an error and I'm not able to generate apk.
> **Error:** Resources referenced from the manifest cannot vary by configuration (except for version qualifiers, e.g. -v21.) Found variation in ta.
>
> Elements in the manifest can reference resources, but those resources cannot vary across configurations (except as a special case, by version, and except for a few specific package attributes such as the application title and icon.)
Can anyone help me to solve this issue.
Thanks.
|
The solution is we need to add attribute `translatable="false"` in that particular string resource.
|
stackexchange-stackoverflow
|
{
"answer_score": 19,
"question_score": 12,
"tags": "android, facebook"
}
|
Load a javascript object with its functions from file
In a website I would like to use a javascript function to load an object from a file. I initially tried using JSON but my javascript object is complex and has functions for some parameters. Is there a way I can load the object from a file?
### myObject.js (not valid JSON as it has a function)
{
"value1": "some value",
"functionValue": function() {
return "function value";
}
}
### function to load object from file
function getFileObject(fileURL) {
var myObject;
$.ajax({
url: fileURL,
type: "GET",
datatype: 'json',
async: false,
success: function (result) {
myObject = result;
}
});
return myObject;
}
|
If you **really** have to pass a function implementation, simply don't use JSON and eval your text.
function fetchFileObject(callback) {
$.ajax({
url: value,
type: "GET",
datatype: 'text',
success: function (result) {
var myObject = eval('('+result+')');
callback(myObject); // do something with myObject
}
});
}
But... that's not something I'd consider myself.
Beware that you really shouldn't use `async: false`. It's now deprecated and there never was any good reason to use it. That's the reason why I refactored your code to accept a callback.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, ajax, json"
}
|
Retrieving Table cells value in Javascript - Firefox vs IE
I am using the following code to retrieve the content of a cell in the table. This works fine in Mozilla Firefox. But, its not working in IE. Any suggestions??
var langName = tblCells[1].textContent.trim();
The error message is:
1.textContent is null or not an object
|
function text ( el ) {
return el.textContent? el.textContent : el.innerText;
}
Use however you like. IE uses innerText.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, internet explorer, firefox"
}
|
Alignment of different-sized objects in Row
I would like to Align several distinct boxes so that the top of each one is at the same level. For example:
framed1 := Framed["", ImageSize -> {100, 100}]
framed2 := Framed["", ImageSize -> {250, 75}]
framed3 := Framed["", ImageSize -> {50, 50}]
Row[{framed1, framed2, framed3}, " "]

|
Somehow a precompiled.config file had made it to production. Don't know how but deleting that file resolved the App_Code directory error and the Application_Start method not being called.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 4,
"tags": "asp.net, iis, iis 7.5"
}
|
select all from both tables with different aliases for id columns
Two tables: `users` and `story`
Want to select all from both tables, but need a different alias for `users.id` vs `story.id`
$sql = "select id as userid, name, status from users as t1, id as msgid, data, msg, xdir from story as t2 where...
Getting syntax error.
Any help?
|
You need to write a join. And you need to use table prefixes when referring to the column names that appear in both tables to distinguish them.
The entire `SELECT` list comes before the `FROM` and `JOIN` clauses.
SELECT u.id AS userid, name, status, s.id AS msgid, msg, xdir
FROM users AS u
JOIN story AS s ON s.authorid = u.id
WHERE ...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "php, mysql"
}
|
neo4jclient Expression type Add is not supported
I have two Nodes - Phone and Users. 10000 Phones and 10000 users. I want connect it with relation.Its show me error **neo4jclient Expression type Add is not supported**
for (int k=1;k<10000;k++)
{
client.Cypher
.Match("(user1:User)", "(user2:Phone)")
.Where((Users user1) => user1.Fio == "Radzhab"+k)
.AndWhere((Phone user2) => user2.Name == "33-333"+k)
.Create("user1-[:HAVE_PHONE]->user2")
.ExecuteWithoutResults();
}
`MATCH (user1:User), (user2:Phone) WHERE user1.Fio = "Radzhab1" AND user2.Name = "33-3331" CREATE user1-[:HAVE_PHONE]->user2;` **its work correct in console**
|
This looks like a bug in Neo4jClient.
As a workaround, try this:
for (var k = 1; k < 10000; k++)
{
var fio = "Radzhab"+k;
var name = "33-333"+k;
client.Cypher
.Match("(user1:User)", "(user2:Phone)")
.Where((Users user1) => user1.Fio == fio)
.AndWhere((Phone user2) => user2.Name == name)
.Create("user1-[:HAVE_PHONE]->user2")
.ExecuteWithoutResults();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, neo4j, neo4jclient"
}
|
How to set router link in vue.js to use alias as a slug?
I have problem generating links via vue-router. I set my route in vue-router like so:
const routes = [
...
{
path: '/:version/terms-and-conditions',
name: 'Terms',
component: Terms,
alias: ['/:version/privacy-policy']
},
...
]
I can use router-link with parameters:
<router-link :to="{name: 'Terms', params: { version: 'v1' }}">Link</router-link>
however it generates link to the main path:
What I'm trying to achieve is to use vue-router to get link to:
I know that I could possibly add a separate path for the same Terms Component, but I'd love to use alias if possible to make things cleaner. Any idea how to do it (using path from alias array)?
|
I believe you could just specify the route in your router-link like so:
<router-link to="/v1/privacy-policy">Link</router-link>
The router will then resolve the link using the alias you've defined.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vue.js, vue router, vuejs3"
}
|
Разработка метода jQuery
В плагине TwitterBoostrap bootstrap-button.js есть такая строчка:
$.fn.button.Constructor = Button
Button это объект типа класса.
Что означает эта строка? Есть в javascript конструктор, но он пишется с маленькой буквы, почему здесь большая? Если это конструктор, то когда он вызывается?
Полностью код плагина тут: <
|
Ответ, надеюсь, сами переведете?
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery"
}
|
Is there any way to replace a ripped ball joint boot?
I installed new ball joints tonight. One side went in great. But one of the ball joints, when I was putting it in with the press, the rubber grease boot got pinched and ripped a tiny bit. And some grease came out.
Is there anything I can do or do I have to pop it out and put a new one in?
I'm really bummed about this.
Just for kicks, here is what the new one looks like compared to the old one:
!enter image description here
UPDATE: I ended up taking out the ball joint and installing a new one. Put me back an extra $50, but in the end I'd rather do that then do this over again in 6 months. Also for the record, this is a 2000 Ford Taurus. Thanks for all the help!
|
Sadly, once the boot is torn, you can't really patch or repair them, as whatever repair you make will be weak and tear again quite rapidly.
Your only option is going to be to get a new boot.
|
stackexchange-mechanics
|
{
"answer_score": 3,
"question_score": 4,
"tags": "ball joint"
}
|
Do repeated sentences impact Word2Vec?
I'm working with domain-oriented documents in order to obtain synonyms using Word2Vec. These documents are usually templates, so sentences are repeated a lot.
1k of the unique sentences represent 83% of the text corpus; while 41k of the unique sentences represent the remaining 17% of the corpus.
Can this unbalance in sentence frequency impact my results? Should I sub-sample the most frequent sentences?
|
Are the sentences exactly the same, word to word? If that is the case I would suggest removing the repeated sentences because that might create a bias for the word2vec model, ie. repeating the same sentence would overweigh those examples single would end with higher frequency of these words in the model. But it might be the case that this works in your favor for find synonyms. Subsample all the unique sentences, not just the most frequent ones to have a balanced model.
I would also suggest looking at the FastText model which is built on top of the word2vec model, builds n grams at a character level. It is easy to train using gensim and has some prebuilt functions like `model.most_similar(positive=[word],topn=number of matching words)` to find the nearest neighbors based on the word embeddings, you can also use `model.similarity(word1, word2)` to easily get a similarity score between 0 and 1. These functions might be helpful to find synonyms.
|
stackexchange-datascience
|
{
"answer_score": 1,
"question_score": 1,
"tags": "machine learning, nlp, word2vec, word embeddings"
}
|
LOGIC LAWS - Logical Problem - Who is older?
question in this picture
I'm having a hard time determining who is older since this was the only statement given. Both answer satisfies the statement.
1. Bill - Sally - Tom
2. Sally - Bill - Tom
I'm not also sure what logical laws I need to use, in order to get the answer.
|
You are correct. You _cannot_ solve this with just that information.
Only knowing that Tom is younger than both Bill and Sally is insufficient to tell whom is the oldest.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "discrete mathematics, logic"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.