INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to obtain the mean for a normal distribution given its quartiles?
Assuming we have a normal distribution for which the mean and standard deviation are unknown, how are first and third quartiles related to the mean?
|
With two quartiles (or any other two percentiles) of a normal distribution you can always compute mean and standard deviation. We start with the formulas to compute quartiles from distribution parameters:
$$Q_1=\mu+CDF^{-1}(0.25)·\sigma=\mu-0.67449·\sigma$$ $$Q_3=\mu+CDF^{-1}(0.75)·\sigma=\mu+0.67449·\sigma$$
Where $CDF^{-1}$ stands for inverse of cumulative distribution function of standard normal distribution, $\mu$ stands for mean and $\sigma$ stands for standard deviation.
Solving the equations for $\mu$ and $\sigma$:
$$\mu=\frac{Q_1+Q_3}{2}$$ $$\sigma=\frac{Q_3-Q_1}{CDF^{-1}(0.75)-CDF^{-1}(0.25)}=\frac{Q_3-Q_1}{2·CDF^{-1}(0.75)}=\frac{Q_3-Q_1}{1.34898}$$
|
stackexchange-stats
|
{
"answer_score": 5,
"question_score": 4,
"tags": "distributions, normal distribution, mean, descriptive statistics, quantiles"
}
|
How to save the webform data to custom table?
I designed a student registration form using webforms module. My requirement is to save data from the form to table student. How can i achieve this? Is there anyway to mention this in configuration file?
|
You can add custom submit handler to your Webform through `hook_form_alter` for inserting it's data into your custom table.
To achieve it check the below example.
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
if($form['#form_id'] == "YOUR_WEBFORM"){
$form['actions']['submit']['#submit'][] = 'YOUR_CUSTOM_FUNCTION';
}
}
function YOUR_CUSTOM_FUNCTION(&$form, $form_state){
$query = Database::getConnection();
$query->insert('YOUR_CUSTOM_TABLE_NAME')->fields(
array(
'FIELD_NAME_IN_TABLE' => $form_state->getValue('FIELD_NAME_IN_FORM'),
)
)->execute();
}
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "8, forms, database, webforms"
}
|
Run Method On Multiple Devices at the Same Time - Android
I currently have an application where I push a button on the main activity and it does data collection. I need to do this on multiple devices at the same time. At the moment, i'm simply trying to do this manually by timing the button press (pushing my fingers down on each device at the same time). Obviously this doesn't work practically with more than 2 devices.
I'm wondering if there is a way for me to run the method (that is called when the button is pressed) on the devices at the same time from my PC?
I've seen a lot of answers use Appium for this kind of implementation, however, this seems a little too much for what i need. Is there not a way to run this via the command line (adp)? Or even just set up a small server that the devices connect to where the method is called?
Thank you.
|
I added code to run the required method when a key was pressed. In the example code below i used F12.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// KEYCODE_F12 = 142
if (keyCode == KeyEvent.KEYCODE_F12) {
findViewById(R.id.button).performClick();
}
return super.onKeyDown(keyCode, event);
}
The keycode number for F12 is 142.
`adb devices` is used to get the device ids that are connected. I could then use adb to input the key event into the devices:
start adb -s device_id1 shell input keyevent 142
start adb -s device_id2 shell input keyevent 142
The 'start' command is used to try and run the adb commands in parallel as much as possible to reduce the input lag to the devices.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, android"
}
|
User permissions for TFS Build server
I am creating a build using the new TFS 2015 Build definitions. I have msbuild tasks as well as npm/gulp tasks. I am looking at using variables to allow me to build and deploy to each environment, with DEV being the only one that runs on check-in. However, I don't want anyone to be able to start a deploy for production. How would I go about limiting the users that can start a deploy to production? I'd prefer to only have one build definition, for maintenance.
|
Use the Release hub capabilities for deployments and create an approval workflow for your environment pipeline.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "tfs, msbuild, tfsbuild"
}
|
Knowing when KML file has loaded and features added (OpenLayers3)?
I see that ol.source.KML (untick "Stable only") fires the events `addfeature`, `change` and `removefeature`. However, I just need to know when the KML was retrieved over the network and all its features added. Is there an event like "loaded" or similar in OpenLayers 3?
I need to execute some code when the KML has been added. Waiting for `document.ready` is not enough as the KML file is loaded (over network) afterwards.
|
Listen to `change` event, check if the source state is `ready`, then do what you want, not forgetting to deregister your listener.
`var key = source.on('change', function() { if (source.getState() == 'ready') { source.unByKey(key); // do something with the source } }); `
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "openlayers 3"
}
|
Does node's readFile() use a single Buffer with all the file size allocated?
I'm quite new to Node and filesystem streams concerns. I wanted to now if the readFile function maybe reads the file stats, get the size and create a single Buffer with all the file size allocated. Or in other words: I know it loads the entire file, ok. But does it do it by internally splitting the file in more buffers or does it use only a single big Buffer? Depending on the method used, it has different memory usage/leaks implications.
|
Found the answer here on chapter 9.3:
<
As expected, readFile uses 1 full Buffer. From the link above, this is the execution of readFile:
// Fully buffered access [100 Mb file] -> 1. [allocate 100 Mb buffer] -> 2. [read and return 100 Mb buffer]
So if you use readFile() your app wiil need exactly the memory for all the file size at once.
To break that memory into chunks, use read() or createReadStream()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "node.js, file io, stream, filesystems, buffer"
}
|
Is FreeResource required on 64-bit?
According to afxv_w32.h, FreeResource and UnlockResource are not required on Win32 platforms (see last line of this file). What about Win64 platforms? I guess this remark also applies on these platforms. Can anyone confirm this? Thanks.
|
FreeResource on MSDN says no. The function was used in 16bit windows, and is no longer required afterwards, which includes 64bit.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows, 64 bit"
}
|
Batch copy file with current date in file name
How to copy files from one directory to another, whose names contain current date, and so the names change daily.
Example:
File name: Test_14042021.txt
Date today: 14/04/2021 // DDMMYYYY
I tried this, but it didn't work:
copy Test_%date:~12,10%%date:~4,2%%date:~7,2%.txt D:\
|
Try `copy Test_%date:~8,2%%date:~5,2%%date:~0,4%.txt D:\`
You can use `echo Test_%date:~8,2%%date:~5,2%%date:~0,4%.txt` to see what exactly you pass to `copy`. Fine-tune it until you see your actual file name.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "windows, batch, date, filenames, copy"
}
|
Can the document desktop stacks be split for a specific file extension?
I have documents I would like to have stacked on my desktop.
Specifically, to group all files with a particular extension all together using Mojave's new Stacks feature.
Is there a way to register a new stacks kind?
|
No - Apple designed the default configuration but does allow you to stack on tags, which are user definable.
You could also make a smart folder to locate all the specific files you want, and then curate the tags easily, but not automatically out of the box.
Source:
Here's how to use tags for custom desktop Finder stacks.
In the image below, you can see the option under `Group Stacks by -> Tags`.
Each of the files you want to put in this Stack must have the same Tag. When you do this, macOS will create a custom Stack for you for all files that contain that Tag.
This is the only way that I'm aware to create a custom Stack.

Adobe Reader XI has commenting and highlighting:
> Can I use Reader XI to add comments and highlights to a PDF file?
>
> Reader XI is the first version of Reader that enables users to annotate PDF documents using a full set of commenting and markup tools, including sticky notes, a freehand drawing tool, and typewriter, highlight, underline, and strikethrough tools. You can also use Reader XI to participate in shared document reviews, with team members seeing and building on each other’s comments to speed up review cycles.
Source: <
Check this post for pdf commenting.
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 1,
"tags": "adobe reader"
}
|
C - Initializing a global array in a function
I have an array that i want to make global, and i want to initialize in a function call. I want to first declare it without knowing it's size:
char str[];
and later initialize it:
str = char[size];
How can i do this? I'm very new to c and perhaps I'm going completely the wrong way here, any help would be greatly appreciated.
|
The way to do it is with `malloc`. First declare just a pointer:
char *str;
Then in the init function you `malloc` it:
str = malloc(sizeof(*str) * size_of_array);
This allocates `size_of_array` elements of the size that `str` points to (`char` in this case).
You should check if the allocation failed:
if (str == NULL) {
// allocation failed
// handle the error
}
Normally you have to make sure you `free` this allocated memory when you're done with it. However, in this case `str` is global, so it never goes out of scope, and the memory will be `free`d when the program ends.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 8,
"tags": "c, arrays, initialization"
}
|
How to refer to the file currently being loaded in Emacs Lisp?
I am looking to include a reference to a non-elisp file (a small Python program), and would like to be able to say "it is in the same directory as the current file, but with a different file name." In many scripting languages, there are things like `__FILE__` (in PHP) for getting an absolute path to the current file.
If the file to be included is in the `load-path`, then I can find it with `(locate-library "file.py" t)`, but I'm kind of stuck if the file is not in the load path.
So is there a way for an Emacs Lisp file to find out its own absolute path (when being loaded, not visited)?
|
`M-x describe-variable load-file-name`
load-file-name is a variable defined in `C source code'.
Documentation:
Full name of file being loaded by `load'.
You might also be interested in the `symbol-file` function, which will tell you the absolute filename in which a specified function or variable was defined.
If you want to get fancy, you can check the `load-in-progress` variable. If that's `nil`, then no load is in progress (and you're presumably being `eval`'d in a buffer). In that case, you could try `(buffer-file-name)` to get the filename.
|
stackexchange-stackoverflow
|
{
"answer_score": 31,
"question_score": 22,
"tags": "emacs, elisp"
}
|
Regex - Match string and certain suffix
I have looked at some example but I can't get my regex to work correctly. I would like to match when there is no suffix or the suffix is in a list.
Sample Data
Tom
Tom (2)
Tom (3)
Tom (4)
I would like to match everything but the Tom (4) row. Each entry is on it's own line. Can you point me in the right direction? I can't seem to get my head around regex stuff.
|
Is this what you mean?
`Tom($| \((2|3)\))`
This would match `Tom` only, or `Tom` followed by parens with a `2` or `3`.
The `$` is an anchor to match the end of the line. The `(2|3)` matches either a `2` or `3`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "regex"
}
|
C#:Regex How to Match specific div close tag but the last close tag?
For examle:
<div id="outer">
<div id="a">
<div class="b"> 11111111111</div>
<div class="b"> 22222222222222</div>
</div>
</div>
Now I want to match the elements of id is `a`, and replace it to empty, but I found I can't, because `id="a"` is not the outer div. This is my c# code ,it will match the last ****Tag.
Regex regex = new Regex(@"<div id=""a([\s\S]*) (<\/[div]>+)");
|
Try this:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var divs = doc.DocumentNode.Descendants().Where(x => x.Name == "div" && x.Id == "a");
foreach (var div in divs.ToArray())
{
div.InnerHtml = "";
}
var result = doc.DocumentNode.OuterHtml;
The `result` I get is:
<div id="outer">
<div id="a"></div>
</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, regex"
}
|
How to change a HTML element by id?
This is a beginner question, I am following a javascript course, and it should work but it does not.
In my HTML page I have the following elements (done that way so the "x1=" and the number are on the same line):
<section id="results">
Solutions
<p></p>
x1=<label id="x1">0</label>
<p></p>
x2=<label id="x2">0</label>
</section>
and in the javascript part I try to change these elements with the following code
document.getElementById("x1").value = x1;
document.getElementById("x2").value = x2;
but they do not change. I also do not see an error in the console.
What am I doing wrong?
|
The issue is `<label>` does not have a `value` property. You have to either use `textContent` or `innerHTML` like:
document.getElementById("x1").textContent = x1;
document.getElementById("x2").textContent = x2;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, html"
}
|
Forcing RTL order in a JTextArea
I am trying to force a JTextArea (and other text components through my application) to allow users to type RTL. This works correctly for input such as Arabic, but I must also be able to set it to apply this to standard text. Therefore, if I type "hello!" it will show up as "!olleh".
I have tried using the applyOrientation() method and setting the text area to have RTL like so:
jTextPane1.getDocument().putProperty(
TextAttribute.RUN_DIRECTION,
TextAttribute.RUN_DIRECTION_RTL);
I have had no success thus far. It has been suggested that I try the Bidi libraries, but these seem focused on interpretation of text which is already bidirectional. When I apply the above, I get right justified text, but it remains LTR in terms of the character order. Is there anything that I'm missing here? Is there a way to set the value that Java itself checks when looking for which direction text entry should move the carat?
|
My problem was solved by the \u202e and the \u202c characters pointed out by RealSkeptic. One will force all characters following it into RTL form, the other forces all characters following it into LTR form. This is a quick and dirty fix, but for my problem, it offered the solution I needed.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, text, bidirectional"
}
|
How to add an extra line that also have a pattern in file containing a pattern in previous line?
I have a file -
something
\title{\hypertarget{A64L}{A64L(3)}}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}
The word in `{}` may be anything, but same in consecutive `{}`.
I want to get
something
\title{\hypertarget{A64L}{A64L(3)}}
\addcontentsline{A64L}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
\addcontentsline{MALLOC}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}
\addcontentsline{STRCMP}
I tried following, but failed.
sed -e /\\\\title\{\\\\hypertarget\{.*\}\{.*\(3\)\}\}/a\\\\\\addcontentsline\{\&\} filename
This is an extension of <
|
I'm not sure exactly what you're trying to capture, but
$ sed 's/\\title{\\hypertarget\({[^}]*}\).*/&\n\\addcontentsline\1/' file
something
\title{\hypertarget{A64L}{A64L(3)}}
\addcontentsline{A64L}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
\addcontentsline{MALLOC}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}
\addcontentsline{STRCMP}
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "shell script, awk, sed, grep, perl"
}
|
What do you use for profiling in Eclipse, now that TPTP is going to be archived?
Have you found a good alternative to TPTP, which is being archived, to profile Java applications in Eclipse?
I understand this is not exactly a programming question, so please just drop me a message if this is not appropriate for Stack Overflow.
EDIT: There's also a relevant question, from 2008 here but I was looking for something a little more updated.
|
VisualVm, that comes with the JDK itself is good for some CPU and memory profiling, though, it doesn't integrate well with eclipse.
YourKit is a great profiling tool that integrates quite well with eclipse but its not free. You will need to buy a license for it.
Eclipse Memory Analyzer (MAT) is another great tool that helps a lot in analyzing java heap dumps. It is perfect for pointing out any un-intentional memory leaks in a java application.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 13,
"tags": "eclipse, profiler, eclipse tptp"
}
|
reg ex for searching filenames
I want to select the files, whose names ends with `_90.jpeg|_180.jpeg|_270.jpeg|_90.jpg|_180.jpg|_270.jpg`.
currently I am using the following approach
pattern = re.compile('_90.jpeg|_180.jpeg|_270.jpeg|_90.jpg|_180.jpg|_270.jpg')
pattern.search(filename)
Is there any cleaner way to represent the _xxx.yyyy in regular expression.
|
You can use: `pattern = re.compile('(_9|_18|_27)0\.jpe?g$')`
If any digits are fine: `pattern = re.compile('_\d+\.jpe?g$')`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -2,
"tags": "python, regex"
}
|
Вывод select через button
При нажатии кнопки должна появится та часть массива которая указана в select.
let selStation = document.querySelector('#select-station');
let btnStation = document.querySelector('.btn-station');
const metro = {
"red" : [
'Академгородок', 'Житомирская', 'Святошин', 'Нивки',
],
"blue" : [
'ТЧ-2 «Оболонь»', 'Героев Днепра', 'Оболонь', 'Почайна',
],
"green" : [
'Сырец', 'Дорогожичи', 'Герцена', 'Лукьяновская',
]
}
let massKey = Object.keys(metro);
for( let i = 0; i < massKey.length; i++) {
selStation.add(new Option(massKey[i]))
}
btnStation.addEventListener('click', function () {
let val = metro[this.value];
for( let i = 0; i < val.length; i++) {
document.write(val[i]);
}
})
<select id="select-station"></select>
<button class="btn-station">Send</button>
|
let selStation = document.querySelector('#select-station');
let btnStation = document.querySelector('.btn-station');
const metro = {
"red": ['Академгородок', 'Житомирская', 'Святошин', 'Нивки'],
"blue": ['ТЧ-2 «Оболонь»', 'Героев Днепра', 'Оболонь', 'Почайна'],
"green": ['Сырец', 'Дорогожичи', 'Герцена', 'Лукьяновская']
};
Object.keys(metro).forEach(i => selStation.add(new Option(i)));
btnStation.addEventListener('click', function () {
let val = metro[selStation.value];
output.innerHTML = val.join('<br/>');
});
<select id="select-station"></select>
<button class="btn-station">Send</button>
<div id='output'></div>
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript"
}
|
rewriting if statement in PHP
I have this conditional if statement:
if ( isset($_POST['x']) && empty($_POST['x']) && isset($_SESSION['x']) && $_SESSION['x'] )
$response['x'] = 1;
else
$response['x'] = 2;
I want to make it something like the opposite, for example:
if ( !isset($_POST['iQapTcha']) || !empty($_POST['iQapTcha']) || !isset($_SESSION['iQaptcha']) || !$_SESSION['iQaptcha'] )
$response['captcha'] = 2;
exit();
Is my new version correct? or this is not the best idea?
Thanks.
|
Simpliest way:
if (!(*old condition here*))
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "php, if statement"
}
|
How can I write MemoryStream to byte[]
> **Possible Duplicate:**
> Creating a byte array from a stream
I'm trying to create text file in memory and write it `byte[]`. How can I do this?
public byte[] GetBytes()
{
MemoryStream fs = new MemoryStream();
TextWriter tx = new StreamWriter(fs);
tx.WriteLine("1111");
tx.WriteLine("2222");
tx.WriteLine("3333");
tx.Flush();
fs.Flush();
byte[] bytes = new byte[fs.Length];
fs.Read(bytes,0,fs.Length);
return bytes;
}
But it does not work because of data length
|
How about:
byte[] bytes = fs.ToArray();
|
stackexchange-stackoverflow
|
{
"answer_score": 162,
"question_score": 63,
"tags": "c#, stream"
}
|
Empty nested initializer list in C++
Consider this piece of code:
struct S {
float b;
int a;
};
int main() {
S s{{{}}};
return s.a;
}
Godbolt
**Clang 6.0.0** compiles this code, but shows a warning:
> _< source> warning: too many braces around scalar initializer [-Wmany-braces-around-scalar-init]_
**GCC 8.2** doesn't compile this code and reports an error:
> _< source>: In function 'int main()': <source>:9:10: error: braces around scalar initializer for type 'float'_
Which one is correct? What does the specification say about this?
|
Both compilers are correct. Unless you violate a rule that says _no diagnostic required_ the compiler should issue you a message. Whether that message is a warning or an error is up to the implementation. Normally you'll get a warning if it is something the compiler can still proceed with and an error when there is no way the compiler can continue.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, initializer list"
}
|
how to create PIXI.text with background image
I'm using PIXI and I want to add some text objects with background images.
var text = new PIXI.Text('my custom text',
{
font : '12px Arial',
fill : 0x666666,
align : 'center',
cacheAsBitmap: true, // for better performance
height: 57,
width: 82
});
stage.addChild(text);
Is `PIXI.texture` the only way to add background image (like a baloon) to this text?
If so, using the below code:
var texture = PIXI.Texture.fromImage("balloon");
text.setTexture(texture);
I get this error:
Uncaught TypeError: Cannot set property 'x' of null
What I'm doing wrong?
|
You can not set a background image on a Text Object. But you can easily add the Text Object as a child of a Sprite.
NOTE: A Texture stores the information that represents an image, but it cannot be added to the display list directly. You should use PIXI.Sprite instead.
//Create the background Image
var sprite = PIXI.Sprite.fromImage('balloon');
sprite.position.x = 100;
sprite.position.y = 100;
stage.addChild(sprite);
//Add text as a child of the Sprite
var text = new PIXI.Text('my custom text',
{
font : '12px Arial',
fill : 0x666666,
align : 'center',
cacheAsBitmap: true, // for better performance
height: 57,
width: 82
});
sprite.addChild(text);
You can center align everything like so:
sprite.anchor.x = sprite.anchor.y = 0.5;
text.anchor.x = text.anchor.y = 0.5;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "canvas, pixi.js"
}
|
AS2 Click tag for flash banner
I have been told that this is the way that i need to set up a specific URL link
on(release){
getURL(_level0.clickTag, "_blank");}
How would i add this to my banner with a custom link? Also, how do i apply the code to the button itself which is called:
> click_btn
any help is much appreciated
thanks!
|
2 ways you can do this:
1) click on the button, and enter your code exactly as you have it into the Actions panel.
2) from the timeline, (convention is to use frame1 of the first layer), in the Actions panel:
click_btn.onRelease = function() {
getURL (_level0.clickTag, "_blank");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "actionscript 2, flash cs5"
}
|
Modifying XML file from string source - how to do it?
I have a problem, where I want to change some lines in my `XML`, but this `XML` is not in file, it is in `string`. I am using `Python 3.x` and lib `xml.etree.ElementTree` for this purpose.
I have these piece of code which I know works for files in project, but as I said, I want no files, only operations on string sources.
source_tree = ET.ElementTree(ET.fromstring(source_config))
source_tree_root = ET.fromstring(source_config)
for item in source_tree_root.iter('generation'):
item.text = item.text.replace(self.firstarg, self.secondarg)
This works, but I don't know how to save it. I tried `source_tree.write(source_config, encoding='latin-1')` but this doesn't work (treats all `XML` as a name).
|
I don't think you need both `source_tree` and `source_tree_root`. By having both, you're creating two separate things. When you write using `source_tree`, you don't get the changes made to `source_tree_root`.
Try creating an ElementTree from `source_tree_root` (which is just an Element), like this (untested since you didn't supply an mcve)...
source_tree_root = ET.fromstring(source_config)
for item in source_tree_root.iter('generation'):
item.text = item.text.replace(self.firstarg, self.secondarg)
ET.ElementTree(source_tree_root).write("output.xml")
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, xml"
}
|
I get the undefined in javascript
Can anyone expain why i get undefined?
function besked(input) {
let inputstring = String(input)
result = "";
for(i = 0; i < inputstring.length; i+=2 )
{
result += inputstring[i];
}
}
console.log(besked("HHeljw OirnFgaeCrs"))
|
the default return value in JS functions is undefined so in order to get something else from that function you should do it like so:
function besked(input) {
let inputstring = String(input)
result = "";
for(i = 0; i < inputstring.length; i+=2) {
result += inputstring[i];
}
return result;
}
console.log(besked("HHeljw OirnFgaeCrs"))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, undefined"
}
|
How to translate ts variables in angular 4?
How to translate angular variables in template or ts file itself
HTML code - someComponent.html
<button (click)="changeLang('en')">En</button>
<button (click)="changeLang('de')">de</button>
<p>{{rate}}</p>
Ts File - someComponent.ts
rate:string="productRate";
changeLang(lang){
this.translate.use(lang);
this.traslate.get(this.rate).subscribe(res=>{this.rate = res;});
}
Json file-en.json
{ "productRate": "Product Rate" }
Json file-de.json
{ "productRate": "Produktpreis" }
I know how to do it in template using pipe but unable to do it in ts.
I had referenced stack overflow but unable to get the result. Please help
|
From `Docs`
> get(key: string|Array, interpolateParams?: Object): Observable: Gets the translated value of a key (or an array of keys) or the key if the value was not found
You have to inject TranslateService as a dependency and do it as,
constructor(private translate: TranslateService) {
let foo:string = this.translate.get('productRate');
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "angular, typescript, angular translate"
}
|
String.format() is Capitalizing Arguments
I have a String format String:
String.format("CREATE TABLE %s ("
+ "%S INTEGER PRIMARY KEY AUTOINCREMENT, %s INTEGER NOT NULL, %s TEXT NOT NULL)",
SPORT_TABLE, SPORT_ID, SPORT_WSID, SPORT_TITLE);
But my second argument (`SPORT_ID`) is being capitalized. Why is this happening? What can I do to fix this?
|
It **is** a perfectly documented behavior even if not a well known one (probably because it's neither an obvious need nor something very useful).
From the javadoc :
> The following table summarizes the supported conversions. Conversions denoted by an upper-case character (i.e. 'B', 'H', 'S', 'C', 'X', 'E', 'G', 'A', and 'T') are the same as those for the corresponding lower-case conversion characters except that the result is converted to upper case according to the rules of the prevailing Locale. The result is equivalent to the following invocation of String.toUpperCase()
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 6,
"tags": "java, string formatting"
}
|
How to set css module in webpack.config file?
{ test: cssRegex, exclude: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, modules:{ localIdentName: '[name] **[local]** [hash:base64:5]' }, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, }), }
|
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true
}
}
]
}
As you can see in the config, you need to use two loaders, style-loader and css-loader. You also need to install them as NPM dependencies:
npm install --save-dev style-loader css-loader
`modules: true` that tells css-loader to enable CSS modules.
`importLoaders: 1` means that it also applies CSS modules on @imported resources.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reactjs"
}
|
Empty folder in Assets tree on Android
I'm using the AssetManager to list the contents of my assets folder on Android. Everything is working as expected except for if I have an empty subfolder. It is not included in the list. If I put a file in the folder, the folder and the file show up no problem.
Is this the expected behavior? I imagine that under normal circumstances an empty folder is pretty useless as an asset and can probably be ignored, but I am intending to copy the folder hierarchy out of the assets folder to the SD card, so including everything, even empty folders, would be best.
I haven't found any documentation that covers this particular issue.
Thanks!
|
This isn't unusual when it comes to archive files and remember Android package apk files are basically zip files.
Some archive utilities allow a switch for including empty directories but I don't know a way of doing that when building an Android apk. In general (for any archiving / packaging) I simply include an empty text file called PlaceHolder.txt which will obviously force creation of the correct tree structure as you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "android"
}
|
How do I change SQL Server 2005 to be case sensitive?
I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries?
|
How about:
ALTER DATABASE database_name COLLATE collation_name
See BOL for a list of collation options.aspx) and pick the case-sensitive one that best fits your needs (i.e. the one your client is using).
Obviously, it's probably a good idea to make a full backup of your database before you try this. I've never personally tried to use a database with a different collation than the server's default collation, so I don't know of any "gotchas". But if you have good backups and test it in your environment before deploying it to your client, I can't imagine that there's much risk involved.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 7,
"tags": "sql server"
}
|
How to build a json object
Right now in my thread controller I have the following
def thread
@thread = Thread.find(params[:id])
....
render :json => {"success" => 1}, :content_type => 'application/json'
end
What I'd like to do is build the json response to include @thread, but only some params so it's something like this:
{"success" => 1, "thread" => {"id": 1, "title": "hello world"}
Any idea how I can build this json object in the rails controller? Goal being to not include all the thread fields and to include success which is not a thread field?
Thanks
|
you should use the model's `as_json` function.
render :json => {"success" => 1, :thread => @thread.as_json(:only => [:my, :wanted, :attributes]) }
as_json includes a large number of options to help you build a hash ready for JSON encoding including `only`, and `except` which will include all attributes on the model apart from the ones listed. `methods` which will add other methods available on the object and `include` to add associations (belongs_to, has_one, has_many etc) into the hash.
For more info examples see the as_json documentation at: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ruby on rails, ruby, ruby on rails 3, json"
}
|
Dataweave 2.0 - Cannot coerce String to LocalDateTime
I get a CSV file with data that I transform to application/java.
One of the fields (Creation_Date) is a DateTime field that I get as String because the output field is a string type.
**Input field:** Creation_Date ( _String_ ) - **Example** : 2019-03-02 07:00:00.000
**Output field:** CreatedDate ( _String_ ) - **Example** : 2019-03-02 08:00:00.000
I use that code in my Dataweave 2.0 transformation because I want to add one hour more to the input datetime:
CreatedDate: payload.Creation_date as LocalDateFormat {format: "yyyy-MM-dd HH:mm:ss+01:00"}
But it returns an error:
Cannot coerce a String to a Localdatetime, caused by CreatedDate
|
To add or modify parts of the data such as adding hours you should convert to LocalDateTime and then use a Period to add a specific Period of time to the datetime. Also need to as milliseconds to format based on your expected input/output. Try this, but change pretendPayload to payload for your example:
%dw 2.0
output application/json
var pretendPayload = {Creation_date: "2019-03-02 07:00:00.000"}
type LocalDateFormat = LocalDateTime { format: "yyyy-MM-dd HH:mm:ss.SSS" }
---
{
CreatedDate: (pretendPayload.Creation_date as LocalDateFormat + |PT1H|) as String{format: "yyyy-MM-dd HH:mm:ss.SSS" }
}
Info on Period here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "mule, dataweave, string to datetime"
}
|
Where is the memory which vmware used?
I have use vmware. I define 5 gb ram for it.
When look system resources in task manager I see vmware just uses 20 mb.
But when I look in vmware (centos) it uses 2gb ram.
How can I see the real usage?
thanks in advance
, such as:
<results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this?
|
This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even need the message.
If it proves to be absolutely necessary, I think you'll need to produce your own testrunner that would (off the top of my head) read an additional attribute off the TestCase and attach it to the output.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 6,
"tags": "unit testing, nunit"
}
|
Linq Grouping Order By Date then Time
Good Evening,
I've managed to get my Linq query almost correct. There is just one more issue I'm struggling to resolve.
My query is
var o =
(from c in x
group c by x.Date.Date into cc
select new
{
Group = cc.Key.Date,
Items = cc.ToList(),
ItemCount = cc.Count()
}).OrderByDescending(p => p.Group);
Now this query works fine. It groups within a ListView by the date. x.Date is a DateTime field in my SQL Database. Therefore I'm selecting x.Date.Date to Group by the actual Date of the DateTime field, as if it was just x.Date it would Group by the date and time.
My question is, how do I group by time so the newest time is at the top of the group?
Many thanks
|
Change `Items = cc.ToList()` to `Items = cc.OrderBy(c => c.[field_you_want_to_sort_by]).ToList()`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "c#, .net, linq"
}
|
C# generlized order by
I want to create a generalized method for sorting any kind of list by any kind of variable.
E.g. I have a Student and a Class entity:
Order(studentList, s => s.Name, desc)
Order(classList, s => s.ClassName, desc)
I have tried to create a private method for doing this:
private List<T> Order<T, TKey>(List<T> listToOrder, Expression<Func<T, TKey>> sortKey, bool desc)
{
return desc ? listToOrder.OrderByDescending(sortKey) : listToOrder.OrderBy(sortKey)
}
But this obviously doesn't work. Any ideas how I can achieve this? Will edit the answer if it's not sufficient enough.
|
If your `Student` & `Class` values are collected, you can try to write an extension method
1. return type might be `IOrderedEnumerable<T>` which type from `OrderBy` & `OrderByDescending`.
2. you might not need to use `Expression` just use delegate `Func<T, TKey>` will be enough
as below
public static class MyExtesion{
public static IOrderedEnumerable<T> Order<T, TKey>(this IEnumerable<T> source,Func<T, TKey> sortKey, bool desc)
{
return desc ? source.OrderByDescending(sortKey) : source.OrderBy(sortKey);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, linq"
}
|
How to forward MPMoviePlayerController to specified time in iPhone application?
I am new to iPhone development, I need to play videos which are on some link and I have overlay of three labels(like 'jump to 1:20') on the MPMoviePlayerViewController by tapping on the label the movie controller is forwarded to that labeled time. I have tried two functions namely "setCurrentTime" and "initialPlaybackTime" but none of these didn't give result for me..
some help will be very helpful to me. thank you..
|
@property(nonatomic) NSTimeInterval currentPlaybackTime
It's part of the MPMediaPlayback protocol. <
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "iphone, mpmovieplayercontroller"
}
|
Best species of moss for a rock garden in the Midwest USA?
I live in the Midwest USA and I'm making plans for a rock garden inspired by one in Japan. I would probably need something tolerant to winter temperatures and hot summers, along with a mostly sunny lawn (I've got 2 trees packed into the corner of my backyard, one large birch, and one maple that's ~13 feet tall), just a generally hardy species that can tolerate the climate of the Midwest.
What's the best species for this garden project?
|
I suggest walking in a woods to look for a local moss suited for your location. You may be able to collect some to get started. I have a small pond surrounded by rock in E.TX, Now 25 years old. A native moss volunteered after a few years and slowly grew in cracks and seams. I did not start it , but after it started , I moved pieces around to speed spreading. In my experience garden shops do not stock moss, especially the chain stores. A friend had a small garden shop with an extra wide variety. My moss start may well have been a hitchhiker on plants I purchased.
|
stackexchange-gardening
|
{
"answer_score": 2,
"question_score": 3,
"tags": "variety selection, moss, plant hardiness"
}
|
How to display a status message in the Gnome panel?
I have a Gnome applet I've been working on. It is written in Python and it displays the progress of something in a small label.
My question is: what is the best way to display status notifications to the user? On Ubuntu, I notice that whenever I connect to a network or adjust the volume, a black box appears in the upper-right corner. Is there a way to do something like that with Python?
|
You can use pynotify, there isn't much documentation but it's usage is pretty straightforward. Example:
import pynotify
pynotify.Notification ("WiFi connection lost","","notification-network-wireless-disconnected")
See also: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ubuntu, gnome, status"
}
|
Convex vs strict convex sets
Could somebody give me an example of a strict convex set? I can't find any info on the internet more than the definition and I have a hard time getting an intuition for the difference between convex set and strict convex. So an example in $\Re$,$\Re^2$ or $\Re^3$ would be very appreciated. Thanks
|
A set $C \subseteq \mathbb{R}^n$ is _convex_ if it contains all line segments between any two of its points. It is _strictly convex_ if, furthermore, such a line segment does not intersect the boundary $\partial C$, except possibly at its endpoints.
For example, the unit $n$-ball $D^n \subseteq \mathbb{R}^n$ is strictly convex, but the unit $n$-cube $[0,1]^n \subseteq \mathbb{R}^n$ is not. (For the former, note that the line segment connecting any two vertices of the $n$-cube is contained entirely in the boundary of the $n$-cube.)
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 1,
"tags": "general topology"
}
|
Portable format for UML models
Is there a portable format for UML diagrams, such that such a diagram saved in that format can be imported and rendered by any, or nearly any, modeling tool?
< says "At the moment there are several incompatibilities between different modeling tool vendor implementations of XMI, even between interchange of abstract model data. The usage of Diagram Interchange is almost nonexistent. Unfortunately this means exchanging files between UML modeling tools using XMI is rarely possible." That would seem to suggest the answer is no, unless there is some other format that is used instead?
|
Short answer is no. Longer answer is partially. XMI is portable regarding elements, etc. Fonts, location on diagram, etc. not so much. Which is pretty much what you already knew.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "uml"
}
|
How do you restrict access to certain paths using Lighttpd?
I would like to restrict access to my `/admin` URL to internal IP addresses only. Anyone on the open Internet should not be able to login to my web site. Since I'm using Lighttpd my first thought was to use `mod_rewrite` to redirect any outside request for the `/admin` URL back to my home page, but I don't know much about Lighty and the docs don't say much about detecting a 192.168.0.0 IP range.
|
Try this:
$HTTP["remoteip"] == "192.168.0.0/16" {
/* your rules here */
}
Example from the docs:
# deny the access to www.example.org to all user which
# are not in the 10.0.0.0/8 network
$HTTP["host"] == "www.example.org" {
$HTTP["remoteip"] != "10.0.0.0/8" {
url.access-deny = ( "" )
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mod rewrite, redirect, admin, lighttpd"
}
|
Top command: How to stick to one unit (KB/KiB)
I'm using the `top` command in several distros to feed a Bash script. Currently I'm calling it with `top -b -n1`.
I'd prefer a unified output in KiB or KB. However, it will display large units in megabytes or gigabytes. Is there an option to avoid these large units?
Please consider the following example:
4911 root 20 0 274m 248m 146m S 0 12.4 0:07.19 example
Edit: To answer 123's question, I transform the columns and send them to a log monitoring appliance. If there's no alternative, I'll convert the units via awk beforehand as per this thread.
|
Consider cutting out the middleman `top` and reading directly from [`/proc/[1-9]*/statm`]( All those files consist of one line of numbers, of which the first three correspond with `top`'s `VIRT RES SHR`, respectively, in units of pages, normally 4096 B, so that by multiplying with 4 you get units of KiB.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "linux, bash"
}
|
Why did NASA use U.S customary units?
NASA was using U.S customary units (inches, feet, nautical miles, pounds, tons, US gallons etc.) during the Mercury and Apollo programmes, and beyond.
There are significant disadvantages to using U.S customary units, the most obvious being that the ratios are not uniform or round numbers (e.g. 6076.12 feet in 1 nautical mile).
Considering that much of the maths involved was done by hand, this seems like an unnecessary complication. Why not just use metric? Metric was already widely used by scientists and some engineers anyway.
|
The Apollo Guidance Computer _did_ use metric/SI units internally for its calculations. But it converted to imperial/USC units when it displayed data on the DSKY. This is probably because the Apollo astronauts (mostly trained as test pilots) had an intuitive "feel" for imperial/USC units.
> Although data was stored internally in metric units, they were displayed as United States customary units - Wikipedia
.
> The computer display readouts were in units of feet, feet per second, and nautical miles – units that the Apollo astronauts, who had mostly trained as US Air Force pilots, would have been accustomed to using. Internally, however, the computer’s software used SI units for all powered-flight navigation and guidance calculations, and values such as altitude and altitude rate were only converted to imperial units when they needed to be shown on the computer’s display. \- UK Metric Association
|
stackexchange-space
|
{
"answer_score": 82,
"question_score": 42,
"tags": "nasa, unit systems"
}
|
Optionally loading/selecting a column in linq
So lets say I have a linq query like so
var stuff = from t1 in TableOne
let t2 = t1.TableTwo
where t1.id = "someId"
select
new
{
column1 = t1.Col1,
column2 = t2.Col1
column3 = (from t3 in TableThree
where t3.id = "someId"
select new SomeObject
{
Field1 = t3.Col1,
Field2 = t3.Col2
}).ToList()
}
Now in some scenarios i want to load the data in column 3, as in when a parameter passed in to the method contains this is not null. And when the parameter is null i dont want to load it for effciencies sake. Any suggestions on how i can achieve the desired result?
|
In your subquery check if the parameter `someParameter` is not null.
column3 = (from t3 in TableThree
where
someParameter != null &&
t3.id == "someId"
select new SomeObject
{
Field1 = t3.Col1,
Field2 = t3.Col2
}).ToList()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, linq"
}
|
What's the before block without the :each or :all parameter in Rspec?
I'm familiar with the Rspec's `before` blocks.
For example,
before(:each) do
# some setup code before each test
end
and
before(:all) do
# some setup code before all the tests
end
But I have seen
before do
# some code
end
How is this `before` without any parameter different from `before(:each)` and `before(:all)`? If it's different, when is it executed?
Thank you.
|
before do
# some code
end
Is simply shorthand for
before(:each) do
# some code
end
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "ruby on rails, rspec"
}
|
HibernateException: No Hibernate Session bound to thread
I am getting this exception and after a lot of R&D i am unable to resolve it.
Basically the error comes when it uses findAll() method located in `hbnpojogen-persistence-1.4.4.jar`
public abstract interface GenericDAO<T, PK extends Serializable>
public abstract List<T> findAll();
This is the code that tried to use this method.
HibernateFactory.getDataDao().findAll();
|
You need to open a transaction before executing `findAll()`. See e.g. Spring's `HibernateTransactionManager` and `@Transactional` annotation.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, hibernate, spring"
}
|
Is there a way to display info messages for any Dr. Racket Exception?
I currently have the following lines to try and test parts of code.
(with-handlers ([exn:fail? (lambda (exn) 'Error)]) (car 17))
I was wondering it there was any way to change 'Error to a function of the caught exception in order to help print out the reason why it failed?
I've also been using check-not-exn, but that function writes too much information to the console.
|
Why not just print the exception to the console?
(with-handlers ([exn:fail? displayln]) (car 17))
=> #(struct:exn:fail:contract car: contract violation
expected: pair?
given: 17 #<continuation-mark-set>)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "unit testing, testing, racket, interpreter"
}
|
Hayek influenced by?
I am going to write an essay about Hayek's views on economic and political (individual) liberty. I am trying to find books to develop a positive discussion on the topic, but I do not know where to search. I started with J.S. Mill's "on Liberty" and Hobbes' "Leviathan", but I cannot find where Locke discuss subjects such as individualism. Also, I was thinking about reading anarchist idea on the topic as an opposing view. Is there any good reading I've missed so far?
|
Hayek's The Constitution of Liberty is in my opinion the place to start. It has a lot of references to John Stuart Mill (which whom he strongly disagrees, btw), and puts forward his argument on freedom. There is also a very recent (but rather long) analysis of Hayek's book (available online here), which dissects his influences.
|
stackexchange-economics
|
{
"answer_score": 2,
"question_score": 2,
"tags": "political economy"
}
|
Map relationship with Entity Framework
Maybe im just an idiot, but I am having serious issues mapping relationships with the new entity framework.
When using LinqToSql, you would just right click the table, add association, select the two tables, and selected the property from each table the association was based on. End of story, it worked perfectly.
Using the entity framework and the slightly different visual editor, I go about doing the same thing, but there is no option in the initial association menu to select the actual properties. So after that, you bring up the association map, and thats where the problems start... What the hell? The only thing you can edit in here is the column to which a key is mapped, but the only columns you can choose are those in the same table as the key... Im completely lost.
|
Instead of mapping the association in the designer, try setting up your foreign key constraints on your tables then update the model from the database and the associations will be setup for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "entity framework, entity relationship"
}
|
Will nanobots keep my pilot alive if I use the self destruct button?
If I have the Nano Mech in my squad (or find/buy the nanobot system) and I come into possession of a Self Destruct Button, will the nanobots heal damage for every enemy I kill when I use it, keeping my mech (and pilot) alive?
|
Yes, healing from an attack that brings your mech's health to 0 will save both the mech and the pilot.
|
stackexchange-gaming
|
{
"answer_score": 11,
"question_score": 12,
"tags": "into the breach"
}
|
SQL query to calculate a flag based on the row value
TableA is a superset that has 1000 rows and TableB is a subset that has 500rows. Structure of both tables is same with ID and Empno. Write a SQL query that should result ID, Empno, flag(Y/N) shows Y if row in Table B is already present in TableA else flag shows N
TABLE A
id emp
1 a
2 b
3 c
4 d
TABLE B
id empno
1 a
2 b
3 f
4 g
Resultset
id empno flag
1 a Y
2 b Y
3 f N
4 g N
select id, empno , ?case statement on id in table b as flag ??
from table b
|
Use an outer join and a check for NULL
select a.id, a.empno,
case when b.id is null then 'N' else 'Y' end as flag
from table_a a
left join table_b b on a.empno = b.empno;
The above will show your for each row in table_a if it exists in table_b.
If you **only** want to see rows from table_b you could use something like this:
select id, empno,
case
when (select count(*) from table_a a where a.empno = b.empno) = 1
then 'Y'
else 'N'
end
from table_b b
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "sql, oracle, oracle11g"
}
|
How to get an upload progress bar for urllib2?
I currently use the following code to **upload** one file to a remote server:
import MultipartPostHandler, urllib2, sys
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
params = {"data" : open("foo.bar") }
request=opener.open(" params)
response = request.read()
This works fine, but for larger files the upload takes some time, and it would be nice to have a callback that allows me to display the upload progress?
I already tried the kodakloader solution, but it does not has a callback for a single file.
Does anyone knows a solution?
|
I think it's impossible to know upload progress with urllib2. I'm looking into using pycurl.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python"
}
|
Please recommend a good OpenStreetMap component
I've been asked to write an internal application for our business that uses mapping functionality to place push-pins of business related data.
As this is not a public facing application and to be used by a single person within our firewall I can not use google maps as we do not have the funds for the google license.
I am investigating the use of OpenStreetMap and can either embed a component into an already existing WPF application or embed into an existing WPF application, a NetBeans platform based application or into a new web application.
Could someone please suggest a library for use in either of these environments?
|
I recently updated `JMapViewer` from r26523 to r26975 without incident. Subjectively, it seems faster.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c#, java, netbeans, openstreetmap"
}
|
How can a game have both Full and Partial Controller suport?
When looking at the game Scourge: Outbreak I noticed that it features both "Partial Controller Support" and "Full controller support".
!Both Controller
At first I thought maybe if a game has full support, it must also have partial. Goat Simulator, however, only has full support. Looking through to see if I could find another game with both, I found Mercenary Kings also features Partial and Full support.
|
It would appear that having both is an error in the entry at some point. According to the developer of Scourge:
> "The game is fully suported, even the text input in Big Picture mode" [...] "Seams like an error." source
After looking through many of the Full controller support and Partial controller support games, it seems like this is a rare case. It is likely that any game that lists both did so by accident.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 5,
"tags": "steam, controllers"
}
|
Can I accept post request only from a domain name?
I'm implementing a payment method on my application, and the bank site send back a post request with information about the payment, like the status, the payment id ...
But to be sure the request is not from someone trying to do bad stuff, can I accept only request from my bank system? I'm looking for something to check in the request for this action/controller is only from mybank.com and skip others.
|
You can constrain the route:
post 'yourpath', to: 'controller#action', constraints: { protocol: ' host: 'yourbank' }
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "ruby on rails, ruby, post, domain name"
}
|
How to kerberos authentication with nginx
How do I configure Kerberos authentication with NGINX? I want to setup configuration on NGINX similar to the Apache mod_auth_kerb. Is there any recommended way of doing this?
|
I was able to do this by using source nginx install with module pam
We can even use ldap authentication.
Ref: <
|
stackexchange-stackoverflow
|
{
"answer_score": -9,
"question_score": 9,
"tags": "nginx"
}
|
Clearing SQL server log file LDF
I understand I need to fully backup the log file before I do anything.
But, once I do that, what would happen if I followed the procedure for detaching the database and then deleting the log file and then recreating it?
|
This could be quick way of shrinking database log file because sp_attach_db will automatically create a new log file of the original size specified with the database creation.
And also detach procedure is safe as SQL Server ensure that server is cleanly detaching database files which means
1\. No incomplete transactions are in the database
2\. Memory has no dirty pages for DB
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql server 2008"
}
|
Use Canon AE-1 lenses on a Sony Alpha a6000
I have found that my father had an old Canon AE-1 film camera, and I'm about to buy a Sony Alpha a6000 camera. The old AE-1 camera has a good 80mm lens that I'd love to use on my Sony camera, even if all the focus and zooming is manual (I love manual). Is there a chance to have an adapter to use that lens on the Sony.
Cheers!
|
Your Sony Alpha a6000 uses the Sony E-mount. There are many adapters available that will allow you to use a Canon FD lens from a Canon AE-1 on your Sony Alpha a6000 camera.
FD to Sony E-mount adapters at Amazon.com
|
stackexchange-photo
|
{
"answer_score": 1,
"question_score": 0,
"tags": "canon, sony, sony alpha"
}
|
In an OpenStack cluster, must all machines be of the same processor architecture?
With OpenStack's architecture, is it possible to, for instance, have a PowerPC64 (Altivec) machine, a Intel CoreDuo machine, and a ARMv6 all on the same cluster? Or is this impossible, because of the restrictions in building buildpacks when deploying to multiple architectures?
_EDIT: Whoops, I meant OpenStack, not OpenShift ;)_
|
The answer above is correct (answer from developercorey). Although whether this suits you depends on how its managed and what your trying to achieve. Typically when you add servers with different physical attributes such as CPU, Disk, Network cards etc you group them into different host aggregates.
By default when you launch a VM it will try and find a suitable host, but you can also tag it, so for example if your VM required alot of disk IO, you might want to place it on a host that has SSD drivers. So you can put those hosts into a 'SSD' aggregate, and then when launching your VM you can make sure it goes to a host in that aggregate.
If your just trying to make the most out of the hardware you have, then I don't see any issue by mixing them.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "openstack, processor"
}
|
How to search Multiple items or Search regardless of position UISearchBar
Ive been following this example < Ive incorporated sqlite to fill the tableview, but currently the search is using substrings with .contains.
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredFood = food.filter { candy in
return candy.name.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
Ive looked up a few different ways, NSPredicates and Regex, but Im not quite sure how to incorporate them correctly, or if thats what I even need to do.
Ex.Cell is "Stackoverflow is so amazing!" If i search for Stackoverflow, the search is fine, but if I search "so is" I get no results.
|
You are looking for a more customized search method, which you would have to develop yourself.
For the example you provided, this code searches for each individual word to match:
let searchTerms = searchText.componentsSeparatedByString(" ").filter { $0 != "" }
filteredFood = food.filter { candy in
for term in searchTerms{
if !candy.name.lowercaseString.containsString(term.lowercaseString){
return false
}
}
return true
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ios, regex, swift, swift2"
}
|
How to calculate the \$\mathcal{H}_2\$ norm of a second order transfer function?
I'm having trouble to calculate the \$\mathcal{H}_2\$ norm of a second order transfer function
$$H(s) = \frac{\omega_n^2}{s^2+2\xi\omega_ns+\omega_n^2}$$ where \$\xi>0\$ and \$\omega_n>0\$. I know that the \$\mathcal{H}_2\$ norm is given by $$||H_2|| = \bigg\\{\int_{-\infty}^{\infty}|H(j\omega)|^2d\omega\bigg\\}^{1/2}$$ and that the magnitude of the frequency response is given by $$|H(j\omega)| = \frac{1}{\sqrt{\bigg(\dfrac{2\xi\omega}{\omega_n}\bigg)^2+\bigg(1-\dfrac{\omega^2}{\omega_n^2}\bigg)^2}}$$ Can someone help me with this? Is there another away to calculate it? Thanks a lot.
|
From a state-space representation, the \$H_2\$ norm can be computed as \$\sqrt{\text{Trace}\left(b q b^T\right)}\$ or \$\sqrt{\text{Trace}\left(c p c^T\right)}\$, where \$b\$ and \$c\$ are the input and output matrices, and \$q\$ and \$p\$ are the observability and controllability gramians.
I have done the calculations below using Mathematica and the result is \$\frac{1}{2}\sqrt{\frac{\omega _n}{\zeta }}\$.
.keyup(function() {
$('#titleBar').text(this.value);
});
That works super except I'd also like the ability to hide the div (I know how to make it start off hidden) when there's no text in the form input.
In otherwords when someone types into the form input a div will appear and the text which is being typed into the input appears in the div. If the user clears the input again then the div dissappears.
Sorry I'm new to JS :)
|
Do a test to see if the text box value's length is greater than 0:
$('#CampaignTitle').keyup(function() {
if($(this).val().length > 0)
{
$('#titleBar').text($(this).val()).show();
}
else
{
$('#titleBar').hide();
}
});
The key line here being `if($(this).val().length > 0)`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, css"
}
|
SQL swap field values
I have a SQL table (MYSQL 4.0 to be precise) composed of the following :
int no (primary)
int field1
int field2
I would like to swap the values of field1 with the values of field2 and vice-versa.
Ex.: 1;2.5;3.76 becomes 1;3.76;2.5
I need a swapping temporary variable of some sort. But I don't think I can use something like
Set @var1 = field1
inside my update statement. And I don't think altering the table to add a temporary column is my best bet either.
|
I found this
UPDATE swap_test
SET x=(@temp:=x),
x = y,
y = @temp
WHERE ...
here as solution with session variables (there are other solutions in the provided link and also a link back to another so question)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "sql, mysql"
}
|
reverse timer in jquery / javascript?
I want the jquery or javascript reverse timer where as i need to give only the int as minute to run it : let say i gave 2 mins as input then it should reduce by second per each second but display must be:
01:59 -> tick -> 01:58...and so on. how to achieve this ?
|
Try jquery.timers.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery plugins, timer"
}
|
Show data of a JSON array with a alert
> **Possible Duplicate:**
> I have a nested data structure / JSON, how can I access a specific value?
I want to show data of a JSON array, I tried this but it doesn't work :
var Content = [{
"01":[{"text":"blablablablabla","foo":"abeille :o"}],
"02":[{"text":"blobloblobloblo","fuuu":"bzzzz :)"}],
"03":[{"text":"blibliblibli","fiii":"bzzoooo ;)"}]
}];
alert(Content.01.foo);
How to do this?
|
You need quotes and array indices.
// v---index 0 of the Array
Content[0]["01"][0].foo
// ^---index 0 of the Array
// ^----^---square brackets and quotes
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 1,
"tags": "javascript, jquery, arrays, json"
}
|
Flex Rich Text Editor - Limiting the number of characters
Is there a way to restrict the number of characters in the Flex Rich Text Editor? I guess there should be, since it's possible in a textarea. So, if I could get hold of the textarea contained in the rich text editor, I would be able to do it
|
I think this would be fairly easy in actionscript, although I'm not exactly sure how one would do it in mxml. It appears that there are two children that are contained in the `RichTextEditor`, one of them being `TextArea`. According to the documentation (< you can access the subcontrols like so:
myRTE.toolBar2.setStyle("backgroundColor", 0xCC6633);
With myRTE being the instance of your text editor. So my guess would be something like this would work:
myRTE.textArea.maxChars = 125;
With 125 being the number a characters you would want restricted to.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "apache flex, rich text editor"
}
|
Will requiring express more than once incur an overhead?
What I mean by this is, I refactored my code so that I require it twice. In one file I use it for the middleware it has. In the other file I use it to actually create an app by calling it.
// index.js file ( entry point )
const express = require('express');
const app = require('./app');
// various middleware ...
// app.js file
const express = require('express');
const app = express();
app.set('port', (process.env.PORT || 3000));
module.exports = app;
I'm assuming this is O.K because require is only locating a reference to express and I only create one app.
|
It is perfectly alright to require express in multiple files, since in nodejs, when requiring a module one of the steps involved is caching of the required file. So when a module is required again it doesn't have any overload.
Refer this link for more on require
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, express"
}
|
What should be the definition of absurdity?
I several times have encountered questions, asked by myself and other people about different things, subjects, phenomena, considered to be absurd to common perception. But, sometimes through rigourous thinking, I have found some valiant insight into wisdom by answering those questions(some).
History says absurdity is often misunderstood. Before Gallileo's obsrvation of the solar system, the idea of a heliocentric solar system would have seemed absurd. Set theory's some assertions seem to be absurd to common sense. Einstein's thinking beyond Newtonian gravity seemed absurd. Sometimes 'absurd' thinking gives birth to new realm of wisdom.
So, my question, what should be the exact definition of 'absurdity?
|
Absurdity is self-contradiction. Absurdity is the situation when one set of premises, or one set of observations, requires a conclusion that must be true and must be false at the same time.
|
stackexchange-philosophy
|
{
"answer_score": 1,
"question_score": 4,
"tags": "philosophy of science, philosophy of mathematics, terminology"
}
|
Function returning pointer to itself?
Is it possible in C++ to write a function that returns a pointer to itself?
If no, suggest some other solution to make the following syntax work:
some_type f ()
{
static int cnt = 1;
std::cout << cnt++ << std::endl;
}
int main ()
{
f()()()...(); // n calls
}
This must print all the numbers from 1 to `n`.
|
struct function
{
function operator () ()
{
//do stuff;
return function();
}
};
int main()
{
function f;
f()()()()()();
}
You can choose to return a reference to function if needed and return `*this`;
_**Update:_** Of course, it is syntactically impossible for a function of type `T` to return `T*` or `T&`
_**Update2:_**
Of course, if you want one to preserve your syntax... that is
some_type f()
{
}
Then here's an Idea
struct functor;
functor f();
struct functor
{
functor operator()()
{
return f();
}
};
functor f()
{
return functor();
}
int main()
{
f()()()()();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 29,
"question_score": 27,
"tags": "c++"
}
|
I want to implement this in my web page. I have only trivial knowledge in web development
When someone loads this page, '<
I want to seperate the 'abcdef......wxyz' part from the link and display it in the page. How could i do it? Thanks in advance
|
you can try something like
$strExplode = explode('/',$_SERVER['REQUEST_URI']);
$strWanted = $strExplode[sizeOf($strExplode) -1];
echo $strWanted // will print 'abcdef......wxyz'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "php, asp.net, web, web deployment project"
}
|
Ubuntu sound not working
I am using Ubuntu 10.10 and my sound stopped working. It had happened before and I had a vague recollection that reinstalling something worked so I did:
sudo apt-get purge pulseaudio
sudo apt-get install pulseaudio
sudo apt-get purge alsa
sudo apt-get install alsa
but now even the volume control icon is gone. I also tried this later:
sudo apt-get --purge remove linux-sound-base alsa-base alsa-utils
sudo apt-get install linux-sound-base alsa-base alsa-utils
, but still the sound is not coming .
|
One possibility is is that your user account is not authorized to use audio devices.
"To resolve it, go to System → Administration → Users and Groups, select your user, click on the Advanced Settings button, enter your password, click the User Privileges tab and make sure the Use audio devices box is checked. While you're at it, do the same for the other users on your system."
**Source** : <
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 2,
"tags": "sound, troubleshooting"
}
|
Proving a differential equation is a circle
So, I have solved the differential equation, to find the general solution of:
$$\frac{y^2}{2} = 2x - \frac{x^2}{2} + c$$
I am told that is passes through the point $(4,2)$. Using this information, I found $C$ to be $2$. Then I am asked to prove that the equation forms a circle, and find the radius and centre point. So I know to try and get it into the form:
$$x^2 + y^2 = r^2$$
So I can get:
$$\frac{y^2}{2} + \frac{x^2}{2} = 2x + 2$$
Multiply both sides by $2$:
$$y^2 + x^2 = 4x + 4$$
But from here I am not sure how to group the $x$'s to leave only a constant on the RHS. Any guidance would be much appreciated.
|
You have,
$$ y^2 +x^2 = 4x+4,$$
what we need to do is group the $x$'s together and complete the square,
$$ y^2 + \left( x^2-4x \right) = 4.$$
So we need to complete the square for the expression $x^2-4x$. The idea is to write this polynomial as a perfect square plus a constant. To do this we first consider the expression $(x+a)^2 = x^2 + 2ax + a^2$. This motivates us to rewrite our polynomial as,
$$ x^2-4x = x^2-2(2)x = (x-2)^2-2^2 = (x-2)^2-4$$
we can then substitute this back into the original equation to get,
$$ y^2 + \left( x-2\right)^2 = 8.$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "ordinary differential equations, circles"
}
|
How do I label images for deep learning classification?
I have roughly 30,000 images of two categories, which are 'crops' and 'weeds.' An example of what I have can be found below:
 on each image that will be used for training? If so, is there an easier way than going through all 30,000 of my images?
I'm very new to this, so any specific details would really help a lot!
|
If each photo is intended to show a photo of weed or crops you should give one label. If your task is different where you also try to localize weed or crops in the image, then you need to label accordingly. My understanding is you are trying to do the first case, therefore, there should be one label for each image.
|
stackexchange-ai
|
{
"answer_score": 0,
"question_score": 0,
"tags": "deep learning, object detection"
}
|
unable to add dependency for com.google.android.gms.tasks.OnSuccessListener
In my android app, I am trying to add the dependency
implementation 'com.google.android.gms:play-services-tasks:16.0.1
and import
import com.google.android.gms.tasks.OnSuccessListener;
The import is not successful. Could you assist me to resolve this erroe ?

var product = Factory.createProduct().sale(function() {
console.log(product.id)
});
Заранее благодарю!
|
Приведу один из примеров.
Давайте упростим пример, чтобы было понятней:
function sale(callback) {
if (callback) {
setTimeout(callback, 100);
}
return {
id: 'some_id'
};
};
var product = sale(function() {
console.log('in callback: ' + product.id);
});
console.log('simple log: ' + product.id);
Здесь в функцию `sale` был передан объект функции, который как бы "захватил" область выполнения, которая содержит `product`. Это называется - замыкание.
В итоге - было присвоено значение `product`, а после этого выполнился по таймауту callback, который содержал в себе ссылку на `product`
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, ecmascript 6, node.js"
}
|
Iterating an ArrayList to return a value
I am having trouble seeing the error of my work: I am creating an iterator (in my class LamborghiniCarLot) which will give the number of vehicles in my (ArrayList inventory;) which are rear-wheel-drive. the Lamborghini class has a method called getIsRearWheelDrive(). But attempting to call it, I get the method not found. "inventory" is the field variable holding the arraylist. Here is my code as it stands:
public int howManyAreRearWheelDrive()
{
int numberRearWheel = 0;
Iterator<Lamborghini> it = inventory.iterator();
Lamborghini inv = null;
while(it.hasNext())
{
inv = it.next();
if(inv != null)
{
if(it.getIsRearWheelDrive() == true)
{
numberRearWheel ++;
}
}
}
return numberRearWheel;
}
|
if(it.getIsRearWheelDrive() == true)
should be
if(inv.getIsRearWheelDrive() == true)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, arraylist, iterator"
}
|
Gremlin for CosmosDB - Cannot create ValueField on non-primitive type GraphTraversal
I'm trying to execute a query but facing this error. Below query is the simplest form of what I was trying to achieve.
g.V('Users12345').as('u').
project('id', 'email', 'test').
by('id').
by('emailId').
by(where(values('id').is(eq(select('u').values('id')))))
I was trying to use select inside project. What's that I'm missing here?
|
The invalid part is `eq(select('u').values('id'))`. I guess "the query in its simplest form" means that you're aware of it being pointless. Assuming that `u` is actually not the same user that's being projected, you probably want to do something more like this:
g.V('Users12345').as('u').
project('id', 'email', 'test').
by('id').
by('emailId').
by(coalesce(where(eq('u')).by('id').constant(true), constant(false)))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "azure cosmosdb, gremlin, tinkerpop"
}
|
Why can't I run programs after closing SSH connection using setsid, nohup or disown?
I am attempting to run a program 'a.o' on a remote server. To keep it running after closing SSH connection, I tried the following:
setsid ./a.o
nohup ./a.o
./a.o &
disown -h %1
None of these options seem to work, and I cannot figure out why. Any ideas on how to fix this problem?
P.S. I am using a tunnel connection to connect to the server via a jump machine. Also, this is a program that involves CUDA code running on GPU. Do these have anything to do with the issue?
|
**The`nohup` Wikipedia Page has a reference to this issue specifically:**
> Note that nohupping backgrounded jobs is typically used to avoid terminating them when logging off from a remote SSH session. A different issue that often arises in this situation is that ssh is refusing to log off ("hangs"), since it refuses to lose any data from/to the background job(s).[6][7] This problem can also be overcome by redirecting all three I/O streams:
>
>
> $ nohup ./myprogram > foo.out 2> foo.err < /dev/null &
>
>
> Also note that a closing SSH session does not always send a HUP signal to dependent processes, such as when a pseudo-terminal has not been allocated.
As mentioned in comments, `screen` and `tmux` are perfect for this too. Personally, I prefer `tmux`.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 1,
"tags": "bash, ssh"
}
|
FSharpCore 4.4.0.0 for version fsharp 4.0 vs fsharpcore 4.1 with fsharp 4.1
I'm confused.
I'm upgrading an old project that has references to FSharp.Core 4.4 everywhere yet the latest version of fsharp.core on nuget is `4.1.*.*`
Is there a document explain what is going on with the version numbers going backwards?
|
The document is here, under "FSharp.Core version numbers"
FSharp.Core 4.4.0.0 corresponds to F# 4.0 running on .NET 4.5+.
The Nuget packages have a different versioning system where the first two digits are the F# version. Each nuget package targets one version of F#, but contains multiple FSharp.Core versions for different profiles. E.g. FSharp.Core Nuget version 4.1.12 is the latest Nuget package for F# 4.1 and contains FSharp.Core 4.4.1.0 for desktop, and various FSharp.Core portable profiles 3.N.4.1.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "f#"
}
|
Bootstrap 3 responsive not working on mobile of android internet explorer
i am using bootstrap 3.I am testing out Bootstrap 3 responsiveness navbar and I have a website link . When I resize the browser on a desktop, it all works fine including the nav bar which become collapsible menu with a small icon on the top which I can click to see more menu buttons and converted it in to 12 grids as per code.
But when I tried it from my mobile browser (I tried it on internet browser on an Android), I didn't see the responsive design. I could only see very small version of desktop like website.
I have already added this code in head section.
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
but still its not working.(you can check from your mobile for proof). Could anyone point out what I am doing wrong?
|
hello friends, As waki pointed out my problem that i put meta tag for the viewport is not correct although i have updated here correctly but in my original site i have written like as waki mentioned above. thanks waki for your valuable comment.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "android, jquery, html, css, twitter bootstrap"
}
|
Android How GridView add static content
 is
paramName varchar2(30);
begin
paramName = 'myParam';
end
end procedure sp_example;
Is there a way to get the name of `myParam` using reflection, instead of hard coding it?
|
Try:
select argument_name from all_arguments where object_name = 'SP_EXAMPLE';
This view can also show you the data types, positions, etc., and you can use it in SQL or PL/SQL. Plenty of info in the various metadata views.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 5,
"tags": "reflection, plsql"
}
|
Split/separate in array string by some rules
I need to separate string like
1FS-2y 4f 5f
And get array like
1,FS,-,2,y, ,4,f, ,5,f
Whether there is a easy way to do it?
|
Use `string.match` instead of `string.split`
var s = "1FS-2y 4f 5f";
alert(s.match(/[A-Za-z]+|\W+|\d+/g))
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "javascript, arrays, string, split"
}
|
Merge data from two tables into single column of another table
How to merge data from multiple tables into single column of another table.
Example:
**Table A**
Col1 | Col2 | Col3
10
20
**Table B**
Col1 | Col2 | Col3
13
99
I want my **o/p** in **Table C in Col1** as
Col1
10
20
13
99
I did (part of query)
Select Col1 from A
Union
Select Col1 from B
but it is not giving me this desired result
|
The `SELECT` appears correct (you may want to use `UNION ALL` instead of `UNION` to avoid elimination of duplicates).
If you want the results to be in the third table `C`, you need to make an `INSERT` from your `SELECT`, like this:
INSERT INTO C (Col1)
(
SELECT Col1 from A
UNION ALL
SELECT Col1 from B
)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "sql, oracle, plsql"
}
|
When I call the clear method for a ListView object, the column headers disappear - VB.Net
Good day, I've just started teaching myself VB.net. I'm trying to create a simple note keeping program.
I've come across a problem, where by I call the Clear method of the ListView object, and its column headers disappear.
screen shot of what happens
The code for button 2 is:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
lstNotes.Clear()
End Sub
Any help will be appreciated, thanks!
|
The `Clear` method on a listview does exactly that. Just as advertised.
Use `lstNotes.Items.Clear()` instead.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 0,
"tags": "vb.net, listview"
}
|
Cleaning up alternating code
I have this function that about the following
bool flag = true;
while(true){
if(flag){
function1();
}else{
function2();
}
flag = !flag;
}
I'm looking at it and it doesn't really seem that clean. I just want to alternate between those 2 functions. Is there a way to make this a bit more cleaner and more readable or would you just keep it this way? Because now I'm having like 5 rows of code that seems a bit messy.
PS: _The`while(true)` isn't actually part of the code, just a demonstration that it's going on for some time._
|
IMHO, it is ok. It's clear what is meant.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#"
}
|
Is there any way to stream music in the background with Ionic framework?
I'm developing an Android app using Ionic for music streaming, like a personal Spotify. I can easily play an audio file using Streaming Media plugin, but it seems that this plugin was made for video purposes, because it always brings the player to the front in fullscreen, so you can't navigate through the app while the music is playing, you also can't lock your screen or the playback is stopped.
Is there any way to stream music in the background? Like when I tap the song I want to play, it just starts playing without bringing in another screen? (like you can easily do in AndroidStudio with MediaPlayer). I've search it anywhere for the past week and I just can't find any solution.
|
I realized Background-Audio in my ionic2/3 Project with
cordova-plugin-media 3.0.1 "Media"
cordova-plugin-music-controls 2.1.4 "MusicControls"
and to workaround some issues on ios I need to add this plugin also
nl.kingsquare.cordova.background-audio 1.0.1 "background-audio"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angularjs, ionic framework"
}
|
Area under the curve uing 4 rectangles evaluated at the right hand endpoint
Approximate the area under the curve $f(x)=3x^2+1$ over the interval $[1,3]$ using 4 rectangles evaluated at the right hand endpoints. Would I do $(3-1)/4=.5$? If so what do I do after that step?
|
$\sum_{n=1}^{n=2.5}(f(n)*h)$
where $h=0.5$
see the illustration :
!enter image description here
As seen in the graph, the area under the curve is approximated using the sum of areas of the 4 rectangles, where the $length = h$ and $height = f(x)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus, area"
}
|
Is $x^TAy = y^TAx$ for any matrix $A$?
I know that $x^TAy = y^TAx$ is true for symmetric quadratic matrices, but, it is true for non symmetric quadratic matrices?
|
No. Let $e_i$ denotes the vector with a $1$ at the $i$-th position and zeros elsewhere. If $A$ is not symmetric, then $a_{ij}\ne a_{ji}$ for some $i\ne j$, but then $e_i^TAe_j=a_{ij}\ne a_{ji}=e_j^TAe_i$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, matrices"
}
|
How can I find the length of a number?
I'm looking to get the length of a number in JavaScript or jQuery?
I've tried `value.length` without any success, do I need to convert this to a string first?
|
var x = 1234567;
x.toString().length;
This process will also work for`Float Number` and for `Exponential number` also.
|
stackexchange-stackoverflow
|
{
"answer_score": 420,
"question_score": 228,
"tags": "javascript, jquery"
}
|
Nexus 6 vibrates 3 times quickly
Sometimes my Nexus 6 vibrates 3 times quickly, but there is no indication why in the Notification bar. Does anyone know why? I'm using Project Fi, so it could be related to that.
|
I believe I've come up with an answer to my own question. Project Fi devices vibrate quickly 3 times every time the cellular radio connects to a wireless carrier.
|
stackexchange-android
|
{
"answer_score": 1,
"question_score": 1,
"tags": "nexus 6"
}
|
Flatten Dataframe in Pandas

|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "python, pandas, dataframe"
}
|
Generate non-overlapping permutations
Let `l` be a list
l = Flatten[Range[7] & /@ Range[12]]; (* 1,2,3,4,5,6,7,1,2,3,4,5,6,7,... *)
The question is to efficiently generate three random permutations from this list, like
p1 = RandomSample[l];
p2 = RandomSample[l];
p3 = RandomSample[l];
but with a very special property. The three lists may not have an equal value on the same position. In other words: every element of `Transpose[{p1,p2,p3}]` must have three unique values.
|
p = Table[, {3}]; (* 3 is the number of 'special' permutations. Note that this number cannot be greater than the number of unique elements of l *)
p[[1]] = RandomSample[l];
For[i = 2, i <= Length[p], i++,
p[[i]] = p[[1]];
Do[
p[[i, j]] = RandomChoice[Complement[l, Table[p[[k, j]], {k, i - 1}]]],
{j, Length[l]}]
]
This seems to be a method without trial and error. One could speed it up by storing the result of the complement for each i as it only changes a little for each next i.
|
stackexchange-mathematica
|
{
"answer_score": 1,
"question_score": 4,
"tags": "random"
}
|
Setting TypeFace NullpointerException
I want to add a `TypeFace` to my `TextView`. here's my Java code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
setContentView(R.layout.activity_help);
}
but when i run the app, i get a log cat error
Caused by: java.lang.NullPointerException
at com.example.enxin.crystallise.Help.onCreate(Help.java:15)
There are many kinds of NullPointerException so I'm not sure how to solve this
|
The problem is you're calling `findViewById()` before setting the content view.
`findViewById()` implicitly calls `getWindow()` which is still `null` at that time.
Call `setContentView()` **before** initializing your `View`:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, typeface"
}
|
Is there an simple way or a function that can get the difference, product or quotient of all numbers in an array
So I just want to know if there's a simpler way to get all the numbers in an array and subtract, add, multiply, and divide them better than what I have done here: (the code here is to subtract all the numbers in an array)
double diff = numArray[0];
for (int i=1; i!=numArray.length; i++) {
diff -= numArray[i];
}
or is there a function that can make my life easier, because I know there is a function to add all the numbers in an array but wasn't able to find anything else.
|
Cleaner? Your code is pretty clean I think.
However, an alternative may be using streams:
double[] numArray = { 17.0, 13.0, 36.5, 7.5, 3.2 };
double result = DoubleStream.of(numArray)
.skip(1)
.reduce(numArray[0], (a, b) -> a - b);
System.out.println(result);
What happens here? We use the Stream specialization for primitive `double`s, `DoubleStream`, in order to walk over the elements of the `double` array. We skip the first element, because all subsequent elements should be subtracted from the first element. Then we perform a _reduction operation_, with as initial value the first element of the array, and we subtract the subsequent element from the previous result.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, arrays"
}
|
Missing value imputation in (almost) balanced data set
Suppose we have a categorical field in our data set with two classes. The field contains 5% missing values. Of the remaining 95% values, 47.4% belong to class A and 47.6% belong to class B. Normally, we use mode to impute the missing value with the class having the highest frequency. But in this case, since the two classes have almost the same frequency, would it make sense to impute 5% of the values with class B? What would be the best approach to handle such a situation?
|
In my personal opinion, imputation very often crosses the boundary into "simulating knowledge we _do not have_ " territory. This sounds like it may well be such a case.
My first impulse would be to use _three_ possible values in your categorical field: the two you have and "missing". Then re-train your model. An advantage is that then you can also apply your model to cases where this field is missing "in production".
Whatever way forward you decide on: do a sensitivity analysis. Fill all missings with one category, then with the other. How much do the predictions change? If your method of addressing the missingness (which could be imputation or something else, per above) has a _major_ impact on your evaluation metric, then this a point where you may want to invest more resources - either in collecting the missing data, or in finding some workaround.
|
stackexchange-stats
|
{
"answer_score": 1,
"question_score": 1,
"tags": "categorical data, missing data, data imputation"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.