INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
List comprehension based on a dictionary in Javascript
I use list comprehension often in Python specifically to create a list from a dictionary of key values, in a sorted manner, I define the sorted keys in a list and use comprehension to get a sorted list, I have been looking around but could not find a similar method of doing the following in Javascript other than using a map:
Is there a better way to do this in Javascript?
In Python:
d = {'k2':'v2','k4':'v4','k3':'v3','k6':'v6','k5':'v5'}
list_keys=['k1','k2','k3','k4','k5','k6']
list_wanted_values = [d[c] for c in list_keys]
#list_wanted_values=['v1','v2','v3','v4','v5','v6']
In Javascript:
var js_list_wanted_values = list_keys.map(function(k){
js_list_wanted_values[k] = d[k]
)} | maybe this
var js_list_wanted_values = list_keys.map(k => d[k]) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, python, list, dictionary, list comprehension"
} |
how to access class of this?
basically i have
$("msgbox .content").html("FOO");
but i have made a plugin and need to replace msgbox with $(this), so how to i select a class of $(this)? | If I understood you correctly:
$(".content", this).html(...);
$(this).find(".content").html(...);
Both are the same thing. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "jquery, jquery plugins"
} |
Create varchar from SELECT result
DECLARE @result varchar(MAX)
SELECT
NAME
FROM
Table
WHERE
ID = @Id
I need to fill `@result` with result Names, separated by ','.
For example, if `SELECT` returns 'A','B' and 'C', the `@result` should be 'A, B, C'.
It is Microsoft SQL Server 2008. | DECLARE @result varchar(MAX)
SET @result = '';
SELECT
@result = @result + NAME + ','
FROM
Table
WHERE
ID = @Id
SET @result = SUBSTRING(@result, 1, LEN(@result) - 1)
SELECT @result
Enjoy :D | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 4,
"tags": "sql, sql server, tsql, sql server 2008"
} |
sql server left join with filter - sql server 2012
I have 2 tables . One of employees and other breaks. I want to show all records from the Employees table ( LEFT JOIN) and see if any employee rests next Sunday (if have a record in the other table - breaks
SELECT T1.idEmp
, T1.fname
, T1.lname
, T1.number
, T2.idGuard
, T2.date
FROM
tblEmp AS T1 LEFT JOIN tblEmpGuard AS T2
ON
T1.idEmp = T2.idEmp
WHERE
date = @date
this just shows me employees having break next Sunday , but not the others. | Try
SELECT T1.idEmp
, T1.fname
, T1.lname
, T1.number
, T2.idGuard
, T2.[date]
FROM tblEmp AS T1
LEFT JOIN tblEmpGuard AS T2
ON T1.idEmp = T2.idEmp
AND T2.[date] = @date | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql server"
} |
Python get intersection of elements from list of lists
I have a `list` of lists where each list is a `string` of `list` of `int`, as shown below
a = ['[11, -12, -14, 13]',
'[8, 5, -14, 15, 13]',
'[13, 24, -14]']
I need to find a list of common integers (intersection of lists), in this case output should be `[13, -14]`, since they are common in all.
Is there a simple way to do this since the individual lists are `str` type, where I can avoid a first iteration to `eval` and then find `set`? | 1. `map()` the `ast.literal_eval()` function over list `b` to safely evaluate your list of strings into a iterator of lists.
2. Then `map()` the `set()` constructor to cast your lists to sets.
3. Finally, use `functools.reduce()` with `set.intersection()` to find the intersection of your sets.
from functools import reduce
from ast import literal_eval
answer = reduce(set.intersection, # 3
map(set, # 2
map(literal_eval, a))) # 1 | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python, python 3.x, string, list, set"
} |
Reading Excel file with multiple sheets
I have an Excel file which contains 4 sheets.
Each sheet has the same format but the data inside is different. For example:
sheet1:
sub1 sub2 sub3
person1 2 3 4
person2 9 0 1
person3 8 4 2
sheet2:
sub1 sub2 sub3
person1 5 7 8
person2 1 3 7
person3 4 1 3
Now, I know how to read the data for 1 sheet:
[data, titles] = xlsread(FileName, 'sheet1');
But when I don't know how many sheets I have in my document, how can I store all data from all sheets? | You can use `xlsfinfo` to get a list of the sheets and then loop over that list:
[status,sheets] = xlsfinfo(FileName)
for s = 1:numel(sheets)
...
[data,titles]=xlsread(FileName,sheets(s))
...
end | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "excel, matlab, repeat, import from excel, data import"
} |
Subscription based model for iPhone, Android and BlackBerry App
Can there be a standard way to handle this in all three platforms? Example would be using a single payment gateway for all. The app(on all platforms) asks for username, password, credit card info then submits to our server. Then our server authenticates and send to a payment gateway. When approved user is allowed to login to the App. Is that a good idea? Will it be allowed on all platforms?
Or does it require different approach for each platform? | On iPhone, this is not allowed. You may not avoid in any way apples standard mechanisms to pay for an app or to make in-app purchases.
There may be cases where an existing (paid) membership for a service might be complemented by a free iPhone app. For example, the free dropbox app will allow you to log in to your (paid) dropbox account. However the dropbox app does not rely on a paid account, it works with free memberships too.
As a rule of thumb: If you could handle payments through the app store, then you propably have to. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "iphone, android, blackberry, subscription"
} |
c# minimum of two numbers if one or both is greater than 0
The logic I'm looking for is if either of the numbers are >= 0 (which they don't have to be), then return the minimum of the two that is also greater than 0. The code I've written for it is so ugly that I'm ashamed to post it!
EDIT: Samples 1, -1 => 1 5,6 => 5 -1,-1 => 0
(if both are less than 0, return 0) | Is this too ugly?
private int GetSmallestNonNegative(int a , int b)
{
if (a >= 0 && b >= 0)
return Math.Min(a,b);
else if (a >= 0 && b < 0)
return a;
else if (a < 0 && b >= 0)
return b;
else
return 0;
} | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 7,
"tags": "c#"
} |
When calling a mixin in Jade, what's the difference between "+" and mixin keyword?
The docmentation tells us to call a mixin by prepending the keyword `mixin` to the actual mixin.
.bar
mixin foo(arguments)
But on different places I saw people calling a mixin by prepending a plus (+) sign, like:
.bar
+foo(arguments)
Could someone please explain the difference since the documentation does not seem to show it. I tried both examples and both seemed to work.
Is `+` just a shorthand? | Yes, it appears so. If you look at `lib/lexer.js` in the `Call mixin` section, you can see that terms beginning with a `+` get tokenized with type `call`. Later in `lib/parser.js` the `call` token causes `parseCall` to create a new mixin invocation node.
Furthermore the commit was made with with the comment:
> Added preliminary mixin block support and the new + mixin invocation syntax. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "node.js, keyword, pug, mixins, templating"
} |
Microcontroller reset
I am facing a problem of micro controller reset, I am thinking of implementing the following to find the function in which it happens, then the root cause. As soon as I enter a function I will increment a global variable and store in eeprom. Once a reset happens I can identify the event, as I will start from main, and I will read the last eeprom value. From this I can know at which function reset happened. Now my main concern is whether I will finish the write cycle of that eeprom memory location. The reset happens approximately after every 2 hours. Any better ideas or it is OK to write in eeprom. | Your approach is unlikely to help. First, the reset may be totally unrelated to the current function: a watchdog timeout or a misconfigured ISR are common causes. Second, even if you discover the function which triggers the reset, there's no indication that this function is buggy. Perhaps a variable used by this function was trashed by a stack overflow which occurred somewhere else.
My advice is to strip down your firmware to the most basic core functionality and check if that part can run cleanly. Then you will include additional functions until the reset reappears, and search for errors in the function which was included last.
Also make sure you have plenty of stack space. If you have recursive functions, start by eliminating them or at least checking them scrupulously.
Since you mention you're using CAN, I suggest you check out XCP which can be used for error logging. | stackexchange-electronics | {
"answer_score": 2,
"question_score": 1,
"tags": "embedded, eeprom"
} |
Apply function over dataframe including rbind statement
I'm looking for the fastest way to apply a fisher.test using four columns in a very large dataframe
A test example using a slow for loop is below.
Apply would be faster but I can't figure out how to use rbind within an apply function.
Also faster suggestions are very welcome.
testdf<-data.frame(a=c(80,1,3,4),b=c(100,200,300,400),c=c(1,2,3,4),d=c(200,250,350,450))
for (i in 1:nrow(testdf)){
testdf$e[i] <- fisher.test(rbind(c(testdf$a[i],testdf$b[i]),c(testdf$c[i],testdf$d[i])))$p.value
}
Many thanks for your help | You can try coerce the row into a matrix:
apply(testdf,1,function(i)fisher.test(matrix(i,ncol=2))$p.value)
As @Chuck noted, it should be byrow=TRUE, to test exactly the same matrix. I took a shortcut because with a fisher.test, you are testing association between rows and columns. As long as the diagonals are not swapped, you get the same p-value and odds ratio
If your matrix is indeed large, there are a few ways, one is get the unique values in the matrix, and calculate those pvalues.
The other way is to calculate the pvalue directly but this only works for one sided test. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "r, loops, dataframe, apply"
} |
How can I prevent a Form_activated event from looping?
I'd like the activated event to only run once. I've tried using an If condition but the Reload variable doesn't set to false and thus it keeps looping endlessly. Is there a way around this?
Form1.cs code:
private void Form1_Activated(object sender, EventArgs e)
{
if (Class1.Reload == true) {
Class1.Reload = false;
}
}
Class1.cs code:
public class Class1 {
public static void Refresh() { Reload = true; }
public static bool Reload { get; set; } | Just unsubscribe from the event the first time it is triggered.
private void Form1_Activated(object sender, EventArgs e)
{
this.Activated -= Form1_Activated;
// Do other stuff here.
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, winforms, visual studio 2015"
} |
Prolog help removing or skipping an item whilst appending
How do you skip a specific word if its part of a list and then append the rest? Usually this item is at the start of the list and sometimes it isn't so how would I work around this? | Do you mean to delete the first occurrence of an element in a list? You can use selectchk/3. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "prolog, artificial intelligence, logic"
} |
Android - How to use the PhoneGap Share plugin
I am trying to use the PhoneGap Share plugin which is supposed to bring up the native Android "Share" window which allows the user to pick which application to share to.
<
I have a hyperlink which calls the following code (provided on github).
window.plugins.share.show({
subject: 'I like turtles',
text: '
},
function () {}, // Success function
function () {
alert('Share failed')
} // Failure function);
When trying to debug the app on my phone, I get the following error:
Cannot call method 'show' of undefined at file:///android_asset/www/index.html
What do I need to do to get this to work? | I have faced the same problem today. I made it work using the following code instead of the window.plugins thing:
var share = new Share();
share.show({
subject: 'I like turtles',
text: '
function() {}, // Success function
function() {alert('Share failed')} // Failure function
); | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 8,
"tags": "javascript, android, cordova"
} |
Formating integers in percentage in php
I have two integers that are `$hours = 74` and `$minutes = 20`, the format I need to get them in is following: hours and minutes (without any spacing) in percentage of one hour. So in this case the final result should be 7433.
Just to make it more clear if the two numbers would be `$hours = 74` and `$minutes = 30`, the final result should be 7450.
I have been trying to look for similar functions, but without any success.
Any help or guidance is much appreciated. | So really what you are looking for is `$result = $hours . floor($minutes/60*100);` ?
Or if you need the leading zeroes: `$result = str_pad($hours,2,'0') . str_pad(floor($minutes/60*100),2,'0');` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "php"
} |
Comparing files and their properties
I get information of a certain set of files in my mail every day, which looks like this:
58623208 Sep 14 20:08 blbn_blfbe_drv
57904920 Sep 14 19:54 blbn_cycmn
55814208 Sep 14 06:02 clsa_Upd
38912000 Sep 14 19:12 cs_chgpp
41107456 Sep 14 19:17 csmRFbe
39403520 Sep 14 19:09 csmUAddAct
39235584 Sep 14 19:20 csmUAddSub
... and so on, for about 60 files.
Now, I need to compare all these files, one by one, with the existing files to make sure that all the files are are found matching.
`filename`, `timestamp`, `date`, and `size` are the things should be matching.
Is there any way to automate it?
I was thinking about using either `comm` or `diff`. | I assume you have GNU date, with the `-d` option:
while read size mon day time filename; do
if [[ ! -f "$filename" ]]; then
echo "ERROR: no such file: $filename" >&2
else
filesize=$(stat -c %s "$filename")
if [[ "$size" != "$filesize" ]]; then
echo "ERROR: size mismatch: $filename" >&2
else
filetime=$(date -d "$(stat -c %y "$filename")" "+%b %d %H:%M")
if [[ "$mon $day $time" != "$filetime" ]]; then
echo "ERROR: date mismatch: $filename" >&2
fi
fi
fi
done | stackexchange-unix | {
"answer_score": 2,
"question_score": 2,
"tags": "shell, text processing, scripting, files, diff"
} |
Sound over HDMI is 2x as slow after resuming from standby
I have an extremely frustrating problem with Ubuntu 16.04 LTS 64-bits on my Dell E7450: when I connect a TV over HDMI (tried a Samsung 1080p TV via this 25-ft high-speed HDMI cable with Ethernet support, and also a Visio TV via a 6-ft cable), **MOST OFTEN BUT NOT ALWAYS** the sound is 2x as slow, and everything else, e.g. video playback, is dragged down to slow-motion.
In other words, testing audio via Speaker Testing goes "Frooont Leeeft" in a low-pitch male voice (the normal is a crisp "Front Left" in a female voice").
.
Basically for a 16.04 desktop, I chose the "daily" build of package `oem-audio-hda-daily-lts-xenial-dkms` at the bottom of the page, then:
1. click the downward arrow on the left
2. click `oem-audio-hda-daily-lts-xenial-dkms_0.<timestamp>~ubuntu16.04.1_all.deb` (at bottom of page) which opens in the package manager
3. approve installation
4. reboot
I experienced this bug on my laptop (a ThinkPad X1c3) when it was still running trusty; when upgrading to Xenial didn't fix the issue, I thought it was time to do smth about it. Glad it's finally fixed! | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 3,
"tags": "sound, hdmi"
} |
Correct way to call user defined conversion operator in templated function with MSVC
I need to call a templated conversion operator inside a class like this :
struct S {
template<typename T>
operator T() const {
return T{};
}
template<typename T>
T test()
{
return operator T();
}
};
int main(){
S s;
s.test<int>();
return 0;
}
This code compiles with clang but not with MSVC(19), gives me a c2352 error. Is the correct syntax?
Demo | Syntax is correct, as work around you might be explicit with `this->operator T()`:
template<typename T>
T test()
{
return this->operator T();
}
Demo | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "c++, visual c++"
} |
Channel Entries - possible to search relationship field?
I need a list of all entries filtered by a relationship field. I thought I might be able to use the `search` parameter: < but it apparently only works on “Text Input”, “Textarea”, and “Drop-down Lists”.
I'm tempted to convert my relationship field to a Drop-down list and figure out another way to make the relationship between my channels. What are my options? Should I be using Category module somehow? | If you use Playa instead of the default relationship type, and make the field Searchable in the options, it will work as if it were a text type. But that doesn't work with the default Relationship fieldtype; you'll have to get Playa. | stackexchange-expressionengine | {
"answer_score": 5,
"question_score": 4,
"tags": "templates, channel entries, entries"
} |
How to decline "Bekannte"?
I have a big problem specially with declining _" substantiviertes Adjektiv"_ in all forms (nominative, genitive, dative and accusative) with definite and indefinite articles (bestimmte und unbestimmte Artikel). For example "Bekannte" in Duden dictionary:
> die/eine Bekannte; der/einer Bekannten, die Bekannten/zwei Bekannte.
So why we have not "n" after _" Bekannte"_ in _" zwei Bekannte"?_ Is it plural?
Or why we have _" einer Bekannten"?_ Is it dative in feminin? Why we use "n" after Bekannte" in this? | What you found is:
feminine nominative singular:
> die/eine Bekannte
>
> Die Bekannte wohnt in Köln.
> Eine Bekannte wohnt in Köln.
feminine genitive singular:
> der/einer Bekannten
>
> Georg erbarmte sich der Bekannten.
> Georg erbarmte sich einer Bekannten.
feminine nominative plural:
> die Bekannten/zwei Bekannte
>
> Die Bekannten wohnen in Köln.
> Zwei Bekannte wohnen in Köln.
_" So why ... ?"_
Because it is not a normal noun, but a nominalized adjective, and because the rules for nominalized verbs, adjectives etc. are more complicated than the rules for "real" nouns.
A much better resource than Duden is Wiktionary: < | stackexchange-german | {
"answer_score": 1,
"question_score": 1,
"tags": "word usage, declension"
} |
Find and replace an uppercase character from a string and keep the original match
I need to change a string "TestString" to this format "[tT]est[sS]tring".
I tried using `sed`:
`testString="TestString" sed 's/\([[:upper:]]\)/[&\1]/g' <<< "$testString" | tr '[[:upper:]]' '[[:lower:]]'`
The result is: `[tt]est[ss]tring`
I would like to ask for your help to find a way to make the second character inside the brackets upper case.
Thanks. | You can just use `sed` for this without having to use `tr`. The below works fine on the version from GNU
sed -E 's/([[:upper:]])/[\L\1\u&]/g' <<< "$testString"
To understand how it works
s/([[:upper:]])/[\L\1\u&]/g
# ^^^^^^^^^^^ Match the uppercase character
# ^^^^ lower case the matched letter
# ^^^^ upper case the matched letter
You could also do `s/([[:upper:]])/[\L\1\u\1]/g` because the both `\1` and `&` refer to the matching group from the search pattern.
MacOS (FreeBSD) sed doesn't support case conversion functions `\L`, `\u` by default. You can install it using `brew install gnu-sed` and invoke `gsed` to launch it. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "bash, sed, tr"
} |
Where can I get TFS SDK?
I use VS2013.
I'm finding Microsoft.TeamFoundation.Git.Client.dll and The GitHttpClient resides in Microsoft.TeamFoundation.SourceControl.WebApi.dll . I can not find them from GAC.
I think that they may be in TFS SDK. But I can only find "Microsoft Visual Studio Team Foundation Server 2012 Software Development Kit for Java" :<
Where can I get TFS SDK? | Regarding **Microsoft.TeamFoundation.Git.Client.dll** per MSDN :
> You can find the assemblies in the client object model in Program Files\Microsoft Visual Studio 12.0\Common7\IDE under ReferenceAssemblies\v2.0, ReferenceAssemblies\v4.5, and PrivateAssemblies.
I found that assembly in the PrivateAssemblies directory.
Regarding **Microsoft.TeamFoundation.SourceControl.WebApi.dll** per same page on MSDN:
> You can find the assemblies in the server object model in Program Files\Microsoft Team Foundation Server 12 under Tools and Application Tier\Web Services\bin.
That assembly is located in the bin folder of the Team Foundation Server. I also found that assembly in my GAC (although I'm not sure when it was installed). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "tfs, sdk, tfs sdk"
} |
Installing modules inside python .py file
I am deploying a custom pytorch model on AWS sagemaker, Following this tutorial. In my case I have few dependencies to install some modules.
I need pycocotools in my inference.py script. I can easily install pycocotool inside a separate notebook using this bash command,
`%%bash`
`pip -g install pycocotools`
But when I create my endpoint for deployment, I get this error that pycocotools in not defined. I need pycocotools inside my inference.py script. How I can install this inside a .py file | At the beginning of inference.py add these lines:
from subprocess import check_call, run, CalledProcessError
import sys
import os
# Since it is likely that you're going to run inference.py multiple times, this avoids reinstalling the same package:
if not os.environ.get("INSTALL_SUCCESS"):
try:
check_call(
[ sys.executable, "pip", "install", "pycocotools",]
)
except CalledProcessError:
run(
["pip", "install", "pycocotools",]
)
os.environ["INSTALL_SUCCESS"] = "True" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, amazon web services, amazon sagemaker"
} |
Does killing Shanalotte aka. The Emerald Herald change the rest of the game?
When killed Shanalotte drops the Aged Feather, and you can no longer use her services (unless revived, but it's unclear whether this is even possible). Are there any non-obvious differences to the rest of the game, especially lore-related, like changed dialogue, locations or items? | Aside from her being dead and thus unable to appear in other locations, no. You can use her services at her grave by paying some souls. | stackexchange-gaming | {
"answer_score": 5,
"question_score": 3,
"tags": "dark souls 2"
} |
Is it possible to limit the number of ethers sent to a smart contract?
I'm a newbie in ethereum programming and is playing with an ICO smart contract. I want to know if it is possible to put the below restrictions in the smart contract:
1. Can I set a maximum amount for ether that can be send to the contract address over a 24-hour period? I want to make sure that a single user doesn't buy all my tokens.
2. Can I set a maximum amount of ether to be sent to the contract address over a 24-hour period? I want to make sure that only certain amount of my tokens are sold everyday. | You can not prohibit people from sending Ether to a contract, but you can track the contrcact Ether-/Token -balance and send received Ether back once a cap is reached. You should read a few contracts from open Zepplin, its a great project to get a feeling for writing Smart Contracts. They have ressources in place, for use cases like yours.
To define Time intervals and check against them, there are two ways: I) You can use blocknumbers with "block.number". II) You can use timestamps with "block.timestamp" which returns a unix epoch
see here for details | stackexchange-ethereum | {
"answer_score": 0,
"question_score": 1,
"tags": "blockchain, ether, tokens, erc 20, ico"
} |
How would I optimally pack a set of tasks into a minimal number of time slots?
I have a set of !n independent tasks and !m time slots of the same fixed length !f, each task of arbitrary length !<=f.
How would I distribute the tasks across time slots while minimizing !m? | You are looking at bin packing problem which is NP-complete. There however exist good approximate polynomial solutions.
Refer to this link: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "algorithm"
} |
npx create-react-app myapp error "\AppData\Roaming\npm-cache\_npx\19748" does not contain a package.json file in appdata folder
OS: Windows
for creating react app using npx i've write the following command:
npx create-react-app myapp
it shows this error:
npm ERR! Could not install from "myusername\AppData\Roaming\npm-cache\_npx\19748" as it does not contain a package.json file.
How can i fix it? | this error occurs usually when name of the PC contain a space like
mycomputer name
you should fix this by redefine your npm cache root There is a simple workaround to fix this problem. 8.3 DOS path format should be used. Open command prompt in administration mode then cd to C:\Users and run this command :
C:\Users>dir /x
and find the short path for your desired directory i.e. username let us say it is MYCOMP~1 (it's not always MYCOMP~1 ) try:
npm config set cache "C:\Users\MYCOMP~1\AppData\Roaming\npm-cache" --global
be careful for space character in the pc name you should use the one you got from command prompt instead and now use:
npx create-react-app myapp
happy coding!!! | stackexchange-stackoverflow | {
"answer_score": 42,
"question_score": 7,
"tags": "node.js, reactjs, npm, create react app, npx"
} |
Deleting worksheets by macro
I'm trying to delete all sheets except the first sheet, but I get an
> error 9 "subscript out of range" appears.
How can I fix it? Thanks in advance.
Dim Udalenie As Integer
If ThisWorkbook.Worksheets.Count > 1 Then
For Udalenie = 2 To ThisWorkbook.Worksheets.Count
ThisWorkbook.Sheets(Udalenie).Delete
Next Udalenie
End If | Because each time you delete one sheet, the Excel will remove it from this sheet from Worksheets and the total sheets count will minus 1.
Dim Udalenie As Integer
If ThisWorkbook.Worksheets.Count > 1 Then
For Udalenie = 2 To ThisWorkbook.Worksheets.Count
ThisWorkbook.Sheets(2).Delete
Next Udalenie
End If | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "excel, vba"
} |
What is wrong with this form of the Maxwell-Faraday equation?
What is wrong with this form of the Maxwell-Faraday equation?
$$\oint \vec{E}\ \partial \vec l= \bigcirc \hspace{-1.4em} \int \hspace{-.6em} \int \frac{\partial \vec B}{\partial t}$$
"Line integral of the electric field is equal to the double integral of partial derivative of magnetic field with respect to time".
So far as I remember the correct form used to be "Line integral of electric field is always (negative) surface **integral of partially derived magnetic field...** " | The integral form of the Maxwell-Faraday law is $$ \oint\limits_{\partial S} \mathbf{E} \cdot d\boldsymbol\ell = -\frac{d}{dt} \int\limits_S \mathbf{B} \cdot \hat{\mathbf{n}}\,da.$$ If you want to apply the time derivative to the integral on the RHS, you must account for two effects that can cause a change in the magnetic flux: the time derivative of the magnetic field, and the velocity $\mathbf{v}$ of the surface $S$ through the field. This gives $$ \oint\limits_{\partial S} \mathbf{E} \cdot d\boldsymbol\ell = -\int\limits_S \frac{\partial\mathbf{B}}{\partial t} \cdot \hat{\mathbf{n}}\,da\; - \oint\limits_{\partial S} \mathbf{B} \times \mathbf{v} \cdot d\boldsymbol\ell.$$ (See, e.g., Jackson 3rd edition, eq. 5.137.) You are correct that there must be a minus sign on the RHS; this is the mathematical statement of Lenz's law. | stackexchange-physics | {
"answer_score": 2,
"question_score": 1,
"tags": "electromagnetism, conventions, induction"
} |
EasyMotion coloring in vim with Solarized theme?
I'm using the Solarized theme for vim (which is amazing), but the color defaults for EasyMotion are, well, downright unreadable.
When I activate EasyMotion, the leader letters are clearly visible (bright red, with Solarized Dark), but the words they key to are barely a shade different from the background (dark blue against slightly darker blue background).
How can I change this to be more readable?
* * *
SOLUTION: Edit your .vimrc file like so:
" change the default EasyMotion shading to something more readable with Solarized
hi link EasyMotionTarget ErrorMsg
hi link EasyMotionShade Comment
A la section 4.5 in the docs for the plugin. | The author of EasyMotion has written excellent documentation on what is possible with EasyMotion. The helptags that stand out to me are `EasyMotion_do_shade` and `easymotion-custom-hl`. These define whether or not to highlight the shaded text and how to hilight the shaded and target text. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 11,
"tags": "vim, themes"
} |
SSMS поддержка #region #endregion
Коллеги подскажите пожалуйста тулы с помощью которых можно реальзовать в SSMS поддержку #region #endregion как в VS С#, ну или что-то сходное по функциональности.
Кроме:
BEGIN --MyRegion
END | SSMSBoost имеет такую фукнцию:
 after the service has been deleted - which requires WdfCoInstaller01009.dll to be loaded. Since that's already been deleted, my custom action is failing. Should I be scheduling MsiProcessDrivers earlier in the InstallExecute sequence, or do people just avoid DIFx and use DPinst etc. for drivers? | Your main problem is that your driver depends on a file installed by the package.
The recommended approach would be to make the DLL dependency a temporary file. Here is an article with more details: <
Basically, the DLL can be stored in Binary table and extracted during install or uninstall. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "wix, windows installer, driver"
} |
Circular References in Java
Given an aggregation of class instances which refer to each other in a complex, circular, fashion: is it possible that the garbage collector may not be able to free these objects?
I vaguely recall this being an issue in the JVM in the past, but I _thought_ this was resolved years ago. yet, some investigation in jhat has revealed a circular reference being the reason for a memory leak that I am now faced with.
_Note: I have always been under the impression that the JVM was capable of resolving circular references and freeing such "islands of garbage" from memory. However, I am posing this question just to see if anyone has found any exceptions._ | Only a very naive implementation would have a problem with circular references. Wikipedia has a good article) on the different GC algorithms. If you really want to learn more, try (Amazon) Garbage Collection: Algorithms for Automatic Dynamic Memory Management . Java has had a good garbage collector since 1.2 and an exceptionally good one in 1.5 and Java 6.
The hard part for improving GC is reducing pauses and overhead, not basic things like circular reference. | stackexchange-stackoverflow | {
"answer_score": 42,
"question_score": 50,
"tags": "java, memory, memory management, memory leaks, garbage collection"
} |
CouchBD startkey and endkey issue
I'm using couchDB and I have a problem trying to get the information that I want. Here's an example of my keys
[1,"Demo","March"]
[1,"Demo","May"]
[1, "No Demo", "May"]
I want to get all the keys that have "Demo" in the middle, I'm trying this:
But I'm getting all the records, any idea? | You can't, sorry. you can only ask for key ranges based on _prefix_ , you can get the values between `[1, ...]` and `[999, "foo"]`, but you can't possibly write a query that will give you the values between `[..., "foo"]` and `[..., "bar"]`
For that, you need to write another view, one where the `"demo"` fragment appears first in the resulting keys. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "couchdb"
} |
transid should be unique store in laravel check (value transid should be single store)
I am confused how to store unique value in laravel i would like to store only single value transaction_id there should not be more than one value there. please suggest.
$payment = new Payment;
$payment->order_id = Input::get('orderid');
$payment->amount = (Input::get('base_amount', 0))?Input::get('base_amount'):Input::get('amount');
$payment->transaction_id = Input::get('transact');
how to check if this $payment->transaction_id already exists should not save more than one
i tried
$payment = Payment::where('transaction_id', '=', Input::get('transaction_id'))->first();
if ($payment === null) {
$payment->save();
} | You can use Request validation:
public function rules()
{
return [
'transaction_id' => 'unique'
];
}
If you use this method, you should create new Request class with `php artisan make:request MyRequest` command. Then put `rules()` in the created `MyRequest` and then you can just use it iside your store/update actions (functions) inside your RESTful controller:
public function store(MyRequest $request)
{
dd($request->all());
}
<
Also, you can use validation in your Model:
private $rules = [
'transaction_id' => 'required'
]; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, laravel"
} |
Generate mongodb compatible id using Objective C
I want to serialize a class and store its representation on server in MongoDB.Each class instance has a unique id. This id has to be compatible with MongoDB id format so that I can put it directly in the db. I was able to do it in Backbone.js (javascript) using this plugin < I am wondering if there's a way I can generate mongodb compatible ids in Objective C? | I ended up using the solution mentioned here : < The code in this gist uses "[[UIDevice currentDevice] uniqueIdentifier]" which is deprecated since iOS5 so I used OpenUDID (< instead. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "ios, objective c, mongodb"
} |
GS query record based of next records value
I am trying to get the previous `Approved` date right before the first found `Requeue` date. Doing this in pure SQL is not an issue but google sheets is making this difficult. Any ideas?
ColumnA ColumnB ColumnC
8/20/2020 Create 00310913
8/25/2020 Edit 00310913
8/26/2020 Approve 00310913
8/26/2020 Approve 00310913 <------ The `Approve` record I want
8/26/2020 Requeue 00310913 <------ First `Requeue` date
8/27/2020 Edit 00310913
8/27/2020 Approve 00310913
8/27/2020 Approve 00310913
8/27/2020 Requeue 00310913
8/27/2020 Approve 00310913
8/28/2020 Requeue 00310913
8/31/2020 Issue 00310913
9/8/2020 Close 00310913
Output
ColumnA ColumnB ColumnC
8/26/2020 Approve 00310913 | Here's one way to do it:
=QUERY(
ARRAY_CONSTRAIN(A:C,MATCH("Requeue",B:B,0)-1,3),
"select Col1,Col2,Col3
where Col2='Approve'
order by Col1 desc
limit 1"
)
1. We find the first occurrence of "Requeue", then return the table up to that record
2. Then query, looking for the last occurrence of 'Approve' in Column 2. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "google sheets, google sheets formula"
} |
PHP string not cluding + as a new operator space in string?
I am running the following:
$file_content[122] = 'Shell "cmd.exe /c cd %appdata% & test.exe -o ' . $p. ' -u ' . $user . ' -p ' . $pass . ' & pause", vbMaximizedFocus';
`$p` is basically `$_GET['p'];`
The user will enter a protocol address such as `+tcp://host` or `http+udp://host` and I basically need that `+` in the string.
My problem is that because the value for `p` has a `+` character in it, I'm not getting the expected response. | You can't send `+` through the URL as a parameter in its raw format. As PHP will read it as a space in the query string.
What you'll need to do is urlencode it **before** putting it in the URL, then decode it afterwards.
This will change the + to the encoded version
e.g., before:
$p = urlencode($some_value);
$url = 'some/path/here?p=' . $p . '&user=' . $user; // etc
// do your redirect
then after:
$p = urldecode($_GET['p']);
$file_content[122] = 'Shell "cmd.exe /c cd %appdata% & test.exe -o ' . $p. ' -u ' . $user . ' -p ' . $pass . ' & pause", vbMaximizedFocus'; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php"
} |
Create 200 news rows in table. Add average salary of original rows to the news rows?
I have been tasked with the following: Write a PL/SQL anonymous block that inserts 100 employee IDs, starting at number 3000. Use a FOR loop (similar to the 100 you added starting at 2000). Add the AVERAGE salary of the _original_ employees table (use SELECT!) in the salary column of the newly created employee rows.
So, I have created the new rows. These have employee ID's from 2000 - 3000.
I have to find the average of the all the rows that have employee ID below 2000 (the original rows in the table) and add this to the salary column of the new rows?
Can anyone give me some help with this?
Would it be something along the lines of
UPDATE emp2 -- table name
SELECT AVG( salary )
FROM emp2
WHERE employee_ID < 2000
Not too sure how to do this? | You can use the below query,
UPDATE emp2
SET salary = (SELECT AVG(salary)
FROM emp2
WHERE employee_ID < 2000
)
WHERE employee_id >= 2000; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "plsql"
} |
UIDatePicker Cutting Off Text & Not Displaying Days
My app is suddenly unable to correctly display UIDatePickers. I'm using storyboards. The Datepickers are set to just display the date. They are cutting off the month, and also not even showing the days. There's a big space in the middle. I have tried cleaning the project, resetting the simulator, checking localization settings, and checking to see if dynamic type size was set. I'm using Xcode 5.1.1 but the same thing happens in the beta of Xcode 6. Any suggestions would be appreciated.
!Image Of Issue | Ok, I figured it out. This happened as a result of trying to use UIAppearance on a tableView background color. This has nothing to do with tableViews on the face of it, but Apple must be using a tableView privately for the PickerViews. So, my attempt to set a UIAppearance via a category on a tableView background color seems to be doing something unexpected. Lesson learned. Don't try to use UIAppearance where they are not officially supported. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 10,
"tags": "ios, objective c, xcode, uidatepicker"
} |
text-shadow not applying in Opera
I've added a text block to an area of my page that uses parallax scrolling. This text block has the necessary style-rule to apply a small text shadow. Problem is, in Opera, I have to set it as `!important`, or it won't do it. Instead, it sets it to:
* {
text-shadow: transparent 0px 0px 0px,
rgba(0,0,0, 0.68) 0px 0px 0px !important
}
Weird thing is that none of my code has any instruction that tells it to do that.
It works in Firefox.
**Declaration**
h1.mainText {
color: white;
font-weight: 100;
font-size: 46px;
line-height: 1em;
text-transform: uppercase;
text-shadow: 0 1px 3px fade(black, 40%);
margin-top: 186px;
[...]
}
**Output**
!enter image description here | It's the Opera Font Rendering Extension. Have just turned it off, and it works like a charm. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, opera, shadow, css"
} |
Why are microcontroller WiFi modules expensive compared to USB WiFi adapters?
I recently bought a WiFi adapter for my Raspberry Pi for about 8 USD. At the same time, WiFi modules for Arduino and similar microcontroller boards cost several times as much.
What is fundamentally different between a USB WiFi module and one sold as a peripheral to micocontrollers? Is it just the economics of high-volume/low-cost, or something fundamentally different in the hardware?
(I've heard about the TI CC3000 WiFi chip that is supposed to be under $10, but I haven't found any place that sells just the chip.) | That is because they are not the same. Arduino/Launchpad/Hobbyist target boards are aimed at small microcontroller sales, which does not have a lot of volume, so price breaks are minimal. And microcontrollers often need more memory than is available for some of the things. A mass produced device can narrowly tailor it's processor to the task at hand.
But one of the biggest things, is that the wifi (or ethernet) chips aimed at hobbyists is that they incorporate more than just the communication protocol. Some also handle the tcp/ip stack, which is very memory intensive and hard to code. Some allow for simple serial (uart or spi or i2c) communication between the microcontroller and the wifi chip, while it does the rest. You are paying for added value.
And finally, most of the time, hobbyists are buying completed boards, not raw chips. Some of these wifi chips, like the TI CC3000 require reflowing, because they have pins underneath or bga packages. They are not easily hand soldered. | stackexchange-electronics | {
"answer_score": 6,
"question_score": 4,
"tags": "microcontroller, wifi"
} |
Basic set notation in combining different ranges of numbers
What is the proper way to specify a set which contains all even numbers between 1 and 10, and all odd numbers between 11 and 30?
Would this work?
$$ U = \\{n, m\ |\ n \ \text{is even},\ 1 \le n \le 10, m\ \text{is odd}, 11 \le m \le 30\\} $$ | I think you can't denote the elements of your set as $n,m$. What is an $n,m$? Is it a pair? You can separate the set as a union of two subsets: $$\\{n| n=2k, k\in \mathbb{N} \text{ and } 1\leq n\leq 10 \\}\cup\\{m|m=2k-1, k\in \mathbb{N} \text{ and } 11\leq m \leq 30\\}$$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "elementary set theory, notation"
} |
Show how to construct such a decreasing sequence $C_n$
It is known that by Sierpinski: If a continuum $X$ has a countable cover $\\{X_n\\}$ by pairwise disjoint closed subsets, then at most one of sets $X_i$ is non-empty. A proof is given by the first answer in this link: [Is $[0,1]$ a countable disjoint union of closed sets?]( I can understand the proof of lemma 1 and lemma 2. But I just can not figure out how by lemma 2, we can construct a decreasing sequence $C_n$. From the proof, it seems obvious, but I can not get the idea on its construction. Can any one help me? | This question is simple after I find that we can use lemma 2 iteratively. Set $X=C_1$ and use the lemma 2 again , we get $C_2$, and set $X=C_2$ again. This gives the sequence clearly. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "general topology"
} |
Concept on displaying cross-table(conjunction) data in ASP MVC
Just a rookie in .NET MVC world and still learning
I created three EF models in framework, one is clients, one is order, and items, below is the relation:
Client Order Items
PK:ID PK Order.id PK Items.ID
... FK:Client.id ...
FK:Item.id
In this case I wanna display all the client information and the item details they've bought in one table, obviously I cannot use any DBcontext here. So what should I do to combine the three table's info and output that? Create a new model on those three?
Any ideas or article are very welcomed! | I would create a ViewModel with all of the Data that you want to display. This is the model that will get populated in the controller and then it would get passed to the View.
So in the View it would use the ViewModel and wouldn't need to know about the underlying Database Model.
And in the Controller you would get the data needed and populate the ViewModel and pass that model onto the View.
Here is a page with an examples. There are plenty more out there too. < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net mvc, asp.net mvc 3, asp.net mvc 4"
} |
Pandas for partially duplicate rows, keep row and replace data with minimum or maximum value
This is what my initial dataframe looks like:
pd.DataFrame({'a':['a','b','b','c'],
'b': [1,2,3,4],
'c': [2,3,4,1],'d':[1.1,1.2,1.3,1.4]})
a b c d
0 a 1 2 1.1
1 b 2 3 1.2
2 b 3 4 1.3
3 c 4 1 1.4
For the duplicate values in column **a** , I want to keep the minimum value for column **b** and the maximum value for column **c**
The output should be like this:
a b c d
0 a 1 2 1.1
1 b 2 4 1.2
2 b 2 4 1.3
3 c 4 1 1.4
Is there a pandas function that does that? I tried looking into
pandas.DataFrame.drop_duplicates
pandas.DataFrame.duplicated
However, I didn't find anything that will work for my use case. | Use `GroupBy.transform` with `min` and `max` what return same values for unique groups:
df = pd.DataFrame({'a':['a','b','b','c'],
'b': [1,2,3,4],
'c': [2,3,4,1],'d':[1.1,1.2,1.3,1.4]})
df['b'] = df.groupby('a')['b'].transform('min')
df['c'] = df.groupby('a')['c'].transform('max')
print (df)
a b c d
0 a 1 2 1.1
1 b 2 4 1.2
2 b 2 4 1.3
3 c 4 1 1.4 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas, dataframe"
} |
Is it possible to override application.properties value from azure app settings
I have deployed a dockerized spring boot application as Azure app service using Web app for Containers. My application.properties file has a setting which I need to override after deployment. Is there any way I can make use of "Application settings" section of my app service to do this? | Looks like you can!
There is another answer here on StackOverflow works very well for dotnet, whereas in Java/Spring environment all azure app settings are treated as system environment variables and can be accessed via `System.getenv()` (See also: Microsoft Docs). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 4,
"tags": "spring, azure, docker, azure web app service"
} |
Calculating $\int e^{-|x|} \, dx$.
I have been trying to calculate $\int e^{|x|} \, dx$, but merely splitting up in two cases for $x<0$ and $x>0$ does not give the desired result, which I got by calculating it on a CAS. Suggestions would be very welcome.
Edit. I made a mistake. It's $\int e^{-|x|} \, dx$. | You can determine a primitive $F(x)$ by integrating with a fixed lower bound, say $0$; for $x\ge0$ we have $$ F(x)=\int_{0}^x e^{-|t|}\,dt=\int_{0}^x e^{-t}\,dt=\Bigl[-e^{-t}\Bigr]_0^x=1-e^{-x} $$ For $x\le0$ we have $$ F(x)=\int_{0}^x e^{-|t|}\,dt=\int_{0}^x e^{t}\,dt=\Bigl[e^{t}\Bigr]_0^x=e^x-1 $$ Now you can incorporate the arbitrary constant of integration, getting $$ \begin{cases} -e^{-x}+1+C & \text{for $x\ge0$}\\\ e^x-1+C & \text{for $x<0$} \end{cases} $$ which can also be written, since $C$ is arbitrary, $$ \begin{cases} -e^{-x}+C & \text{for $x\ge0$}\\\ e^x-2+C & \text{for $x<0$} \end{cases} $$ | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "calculus"
} |
Anyone used HDA/AC97 codec with ARM uC?
I've got bunch of spare HDA & AC97 codecs from mobos, is anyone was able to interface to them from usual ARM uC? Is it even possible?
Googling didn't helped me much. Any hints? | I found the data sheet for the ALC880:
<
You will have problems interfacing it to an ARM, as it uses S/PDIF and an unusual high-speed serial interface. It could be done with a CPLD. Or, you could forget the ARM and do everything with an XMOS chip. The interface could be done in software, and the chips have DSP capability. They are often used for high-end audio processing.
The data sheet suggests that designers contact Realtek for details of application circuits, perhaps you should try that.
The other codec is probably similar. | stackexchange-electronics | {
"answer_score": 3,
"question_score": 2,
"tags": "sound"
} |
Can I contact the secondary author if I can't reach the corresponding author?
I attempted to reach the corresponding author, for an article I had questions about, but her university e-mail was seemingly disabled because she left academia.
Learning that she started to work at a corporate job, I looked for alternative sources of communication such as business e-mail, which I failed to find as well.
In this scenario, is it acceptable to contact the secondary author since I really have no way contacting the author listed as corresponding author? | Yes, you can do that. I see no problem. You might explain that you also tried to reach the corresponding author unsuccessfully.
It is unlikely that the volume of such email will be a burden. And, they might just give you contact information for their colleague the corresponding author. | stackexchange-academia | {
"answer_score": 28,
"question_score": 16,
"tags": "etiquette, correspondence"
} |
bash scripting convert uppercase to lower case and viceversa
Kindly check and advise my script. I'm trying to get a word (min 2, max 5 chars) as its input.
User will provide the character position and then the script will change it either from lower to uppercase or uppercase to lowercase. Below is incomplete script so far:
input: `teSt 3`
output: `test`
#!/bin/bash
clear
while true
do
echo ******TEST*****
read -p 'Enter a word :' word
if [[ ${#word} -le 1 ]] || [[ ${#word} -ge 6 ]]; then
echo "Invalid input (Min of 2 and max of 5)!."
exit 1
fi
echo ${word^^*}
done | #!/bin/bash
read -p 'Enter a word : ' str id
if [[ ${#str} -le 1 ]] || [[ ${#str} -ge 6 ]]; then
echo "Invalid input (Min of 2 and max of 5)!." && exit 1
idt=$((id-1))
case ${str:idt:1} in
[[:lower:]])
r='\U';
;;
[[:upper:]])
r='\L';
;;
esac
echo $str | sed -r "s/./$r&/$id"
* * *
$ ./script.sh
Enter a word : test 1
Test
$ ./script.sh
Enter a word : Test 2
TEst
$ ./script.sh
Enter a word : teST 3
tesT | stackexchange-unix | {
"answer_score": 1,
"question_score": 3,
"tags": "bash, shell script, shell, bash expansion"
} |
Parse contents of a file between certain timestamps
I have a log file that contains a lot of information and I would like to only parse the contents of that file which fall within the last 24 hours
Each line in the file begins with a timestamp such as `Jan 31 13:13:02` and then has a log message.
I currently have a batch file that finds the start and end time like this
start=$(date +"%b %d %H:%M:%S" --date="-1 day")
end=$(date +"%b %d %H:%M:%S")
I was then hoping to use these times along with a `grep -c "data_to_find"` to find the number of occurrences of a certain log message so that I can then act on this later.
In short, How can I take into account the times and then grep the content for the number of occurrences of a string within said file?
I am on a linux system and have no issue with any solution that uses SED, AWK, GREP etc. | Not so simple without writing a shell script (especially if it's not sorted).
I would try something like this to get all the lines between 1 day ago and now (interpolate as needed), and then `grep -c` pipe whatever you want from output. Note below assumes date format is something like `Jan 31 13:13:02` (2 spaces between Month and Day)
#!/bin/bash
yest=$(date -d "1 days ago" '+%s')
today=$(date '+%s')
while read -r line; do
date=
[[ $line =~ ^[[:alpha:]]+[[:blank:]][[:blank:]][0-9]+[[:blank:]][0-9]+':'[0-9]+':'[0-9]+ ]] && date="${BASH_REMATCH[0]}"
[[ -n $date ]] && date=$(date -d "$date" '+%s')
[[ -n $date && $date -ge $yest && $date -le $today ]] && echo "$line"
done < logfile | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, bash, sed, awk, grep"
} |
Can an attacker discover email addresses without gaining server access?
Present situation: I am receiving emails at a few of my email addresses, different domain names, all housed on the same server. The emails ares spoofed (appear to be coming from each of the email addresses), but looking at the headers, they are coming from some other IP address.
I want to dismiss this threat. However I am a little concerned, as I don't know of a way for someone to discover email addresses without some access. | If you've used those email addresses anywhere, particularly on any public access forum, they were likely swept up.
If they were part of any of the multitude of public breaches that have taken place over the years, they were probably swept up.
If they were in friends or family address books and used in " _CC_ " blasts to many places, they were probably swept up.
If they are part of a reasonable guessing algorithm pattern, they may have been generated by spammers.
In general there's no email discovery method, but keep in mind that until that last couple of years, due primarily to Google efforts, federated mail server to mail server connections were generally not encrypted. This allowed content sweeps from anywhere in the path. Due to efforts by Google, about 90% now use encrypted federated connections.
There likely is no threat or concern as long as you don't respond to the emails, either intentionally or unintentionally. | stackexchange-security | {
"answer_score": 1,
"question_score": 1,
"tags": "email spoofing"
} |
Accessing variable within def clean() from def __init__()
I've established a variable inside my def **init** function inside my form that I want to be able to access within def clean() in that same form.
def __init__(self, *args, **kwargs):
super(UserOrderForm, self).__init__(*args, **kwargs)
car = 'BMW'
def clean(self):
cleaned_data = super(UserOrderForm, self).clean()
print(car)
When I print car, I'm told that
name 'car' is not defined
Is there a way to do this?
Thanks! | In Python you declare instance attributes using `self`, you must change your code to
def __init__(self, *args, **kwargs):
super(UserOrderForm, self).__init__(*args, **kwargs)
self.car = 'BMW'
def clean(self):
cleaned_data = super(UserOrderForm, self).clean()
print(self.car)
In your original code, the variable `car` does exists only inside the `__init__` method. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, django, django forms"
} |
How can I access SIM applications on my Lumia?
I have applications on my SIM that I need to access. How do I access them? | **In Windows 10 Mobile** :
Go to Settings -> Network & wireless -> Mobile & SIM -> SIM settings. Tap on "SIM applications".
**In Windows Phone 8.1** :
Go to phone settings -> mobile+SIM -> SIM settings. Tap on "SIM applications".
**In Windows Phone 8.0** :
Go to phone settings -> mobile network. Tap on "SIM applications".
**In Windows Phone 7.x** :
Go to Settings -> SIM applications. | stackexchange-windowsphone | {
"answer_score": 1,
"question_score": 1,
"tags": "system apps, sim"
} |
Why #define UNICODE has no effect in windows
I have the following code:
#define UNICODE
// so strange??
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
But the compiler still report error like this:
`error C2664: “DWORD K32GetModuleBaseNameA(HANDLE,HMODULE,LPSTR,DWORD)”: 3 “wchar_t [260]”“LPSTR” [E:\source\mh-gui\build\src\mhgui.vcxproj]`
Which means `cant convert param 3 from wchar_t[260] to LPSTR`. It's look's like that still looking for A version api? | You must put
#define UNICODE
#define _UNICODE
_BEFORE_
#include <Windows.h>
The Windows header uses `#ifdef UNICODE` (et al), so if you want to make the distinction count, the `#defines` must occur before the `#include`.
* * *
edit: Because these `#define`s are functionally global, the most reliable place to add them is in your compiler options, so the ordering doesn't matter then. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 0,
"tags": "c++, windows"
} |
Reasonably-priced, multiple endpoint heartbeat software
We've got four servers in use for a mission-critical application that all need constant connectivity to each other--six always-up connections in total. I need a way to monitor these connections and fire off, at the very least, an email when any one of them goes down. I can find centralised solutions, but nothing that really fits this bill. Any suggestions?
EDIT: Went ahead and rolled my own in Ruby. Nagios looks like a decent bit of kit, though--would've gone with it otherwise. | Like MarkM I was going to recommend Nagios - but I think you need to plan out what you are actually measuring more carefully. I would expect with 4 equeivalent nodes that there are 12 connections involved (ab, ac, ad, ba, bc, bd, ca, cb, cd, da, bd, dc) unless some of the connections are bi-directional (?).
It's quite possible using Nagios to either define active checks to be executed at intervals or to have the daemon waiting to receive a notification of status (in this case a failed communication from the initiating server) and even to trigger some automatic response handling (such as restarting a crashed webserver process). But you do need to think about how you deal with split-brain scenarios.
You can run the Nagios daemon on a dedicated server, or on one, or any number of the nodes in the cluster - but beware of launching automatic responses from multiple monitoring nodes simultaneously.
C. | stackexchange-serverfault | {
"answer_score": 2,
"question_score": 4,
"tags": "windows, network monitoring, uptime, heartbeat"
} |
How can I add an image in the page header when printing Excel 2000 spreadsheets?
I'm using Excel 2000. I have a spreadsheet document that covers several pages when printed. I am able to add page numbers and basic text to the header (and footer) of the printed sheets, but I would really like to add an image to the header in addition to the basic text. Is there a way to do it? | Microsoft Excel does not provide this for custom headers or footers in Excel 2000. A workaround is also given on that page.
Here is a workaround given on ExcelTip.com.
To add a picture (such as a company logo) to the header/ footer in Excel 97 and Excel 2000:
1. Select cell A1.
2. From the Insert menu, select Picture, and then select From File.
3. Select the picture you want, and click Insert.
4. Adjust the picture to the height and width of the row.
5. From the File menu, select Page Setup.
6. Select the Sheet tab.
7. Select Rows to repeat at top.
8. Select row 1, and then click OK. | stackexchange-superuser | {
"answer_score": 5,
"question_score": 1,
"tags": "microsoft excel, printing, microsoft excel 2000"
} |
iOS app with interface reminiscent of Finder's column view
How would I go about making a simple iOS app that simply has to display "data sheets" (just text documents basically) in a way reminiscent of OS X's Finder's Column View?
I want the interface to present a list of Manufacturers. I select one and then a bunch of Models made by that Manufacturer come up. I select one and finally I'm presented with Years. I select a Year and then I am shown a list of all variants of that Model made in that Year. When I press one of these Models I'm shown a textual data sheet for that model.
I mean, I don't even know whether to start this as a Master-Detail Application (although that sort of looks like it might work), a Page-Based Application, a Single View Application or a Tabbed Application...
Thanks | Essentially, you will nee dto get in to `UITableView`.
It's fairly simple:
<
<
Be sure to work 100% using storyboard, and Swift. In answer to your final question simpy start it as a single view app.
Interestingly, once you get good one of the toughest and most expert-level skills in iOS is dynamic height cells in table views. Example of that. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios"
} |
Cannot complete overlay FS mount within Docker container
Trying to use overlayfs within a Docker container.
root@din:~# mount -t overlay overlay -o lowerdir=/etc,upperdir=/oetc,workdir=/root/work /mnt
mount: /mnt: permission denied.
root@din:~# ls -ld /mnt
drwxrwxrwx 1 root root 4096 Jun 12 16:54 /mnt
root@din:~# ls -ld /oetc
drwxr-xr-x 2 root root 4096 Jul 26 19:53 /oetc
root@din:~# ls -ld /root/work
drwxr-xr-x 2 root root 4096 Jul 26 19:33 /root/work
I don't know how to identify what the permission problem is, or if it is symptomatic of something else. | You need to add privileges to the container.
docker run --rm -it --cap-add=SYS_ADMIN ubuntu:latest | stackexchange-superuser | {
"answer_score": 2,
"question_score": 1,
"tags": "docker, overlay"
} |
Prove $ α + β = β$ if and only if $αω ≤ β$
Here we have both $\alpha$ and $\beta$ are ordinals. I need to prove that $ α + β = β\Leftrightarrow αω ≤ β$.
It seems that maybe the forward direction can be done by induction, but could someone please show me how should I do it? May I please ask how to prove this statement? | Recall that if $\eta\leq\delta$, then there is a unique $\gamma\leq\delta$ such that $\eta+\gamma=\delta$.
Now, in the one direction, $\alpha+\beta=\alpha+(\alpha\cdot\omega+\gamma)=(\alpha+\alpha\cdot\omega)+\gamma = \dots$
In the other direction, recall that $\alpha\cdot\omega=\sup\\{\alpha\cdot n\mid n<\omega\\}$, so by induction if $\alpha+\beta=\beta$, we get that $\alpha\cdot n+\beta=\beta$ for all $n$, therefore $\alpha\cdot n\leq\beta$ for all $n$. What does that tell you about $\alpha\cdot\omega$? | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "set theory, ordinals"
} |
Incorrect work of jQuery function .text()
I'm trying to get all the text from HTML without any tags by using `$('.container').text()`. Instead of getting clear text I get text with duplicate parts.
Here is my HTML code:
<div class="v highlighted" id="4">
<span class="vn" id="4">4</span>
<span class="p">Text-0</span><br>
<span class="p">
<span class="wj">
Text-1
<span class="w">Text-2</span>
Text-3
</span>
</span><br>
</div>
<script>
console.log($(".highlighted :not(.vn)").text());
</script>
In the console I see this result:
Text-0Text-1Text-2Text-3Text-1Text-2Text-3Text-2
Does anybody know why it happens? | Look at what `.highlighted :not(.vn)` matches.
It matches:
* `<span class="p">Text-0</span>`
* `<br>`
* `<span class="p"><span class="wj">Text-1<span class="w">Text-2</span>Text-3</span></span>`
* `<span class="wj">Text-1<span class="w">Text-2</span>Text-3</span>`
* `<span class="w">Text-2</span>`
* `<br>`
Since you have some text contained in a span which is contained in another span and **both** those spans match the selector, you get the content of the outer span **and** the (identical) content of the inner span.
You probably want to use a child combinator (`>`) instead of a descendant combinator (``) in your selector.
.highlighted > :not(.vn) | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 4,
"tags": "javascript, jquery"
} |
How to find second largest number using Scanner and for loop(no array)
So I can easily accomplish task to find largest number and then if can be divided by three, print out. But do not know how to find second largest number from users sequence. Thanks for any hints!
public class SecondLargest {
public static void main(String[] args) {
int max = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers?");
int n = scan.nextInt();
System.out.println ("Write numbers: ");
for(int i=0; i<n; i++){
int c = scan.nextInt();
if(c>=max && c%3 == 0){
max = c;
}
else
System.out.println("There is no such number.");
}
System.out.println(max);
}
} | int secondLargest = 0;
.....
for (..) {
....
if (c % 3 == 0) {
if (c >= max) {
secondLargest = max;
max = c;
}
if (c >= secondLargest && c < max) {
secondLargest = c;
}
}
....
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "java, algorithm, java.util.scanner"
} |
Change a global variable in a function
I can not figure this out...
I want to:
declare a variable, run a function that changes the value of that variable and then then alert the value of the new value.
Like so:
function loadApp(){
FB.api('/me', function(response) {
var posLat;
getLocation();
console.log(posLat);
});
}
function getLocation(){
posLat = "hey";
}
The alert should display 4 but just alerts undefined. Am i bein stupid? | `posLat` is defined inside a function, therefore making it a local function that cannot be used outside of its surround scope. That's why `getLocation` can't modify it. In fact, it's creating a global variable called `posLat` on the window object. As the comments on my post suggest, set `posLat` to the return value of `getLocation`:
var posLat = getLocation();
...
function getLocation() {
return "hey";
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript"
} |
Subset data.table by condition but retain all rows belonging to group
I have data that looks like this:
require("data.table")
dt1 <- data.table(
code=c("A001", "A001","A001","A002","A002","A002","A002","A003","A003"),
value=c(40,38,55,10,12,16,18,77,87))
I would like to subset it so any group (`code`) that contains a value over or under a given number is retained. For example, if I wanted any group that contained a value over 50 then the result would look like this:
dt2 <- data.table(
code=c("A001", "A001","A001","A003","A003"),
value=c(40,38,55,77,87)) | We create a condition with `any` after grouping by 'code' to subset the rows
dt1[, if(any(value > 50)) .SD, code]
Or without the `if` condition
dt1[, .SD[any(value > 50)], code]
Or get the row indices (`.I`) and subset based on that
dt1[dt1[, .I[any(value > 50)], code]$V1] | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "r, data.table, subset"
} |
Page not found error in django where it is not supposed to rise
I am building a video player app in django. But, when going to the register route, I get this error:
Page not found (404)
Request Method: GET
Request URL:
I don't even have a url called `users/login/register`. And I have checked my `urls.py`. Here it is:
urlpatterns = [
path('register/',views.register,name='register'),
]
And here is the link that leads to this route:
<a href="{% url 'register' }">Register</a>
I have built many apps with django but have never encountered an error like this. Why am I getting this error? | You are missing a % in your a tag, it should be
<a href="{% url 'register' %}">Register</a>
Does this solve your problem? | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, django"
} |
Obsolete page about Opera bookmarks
This question is obsolete (2009). There is a newer version of it. | There are essentially two versions of Opera.
The old one that stopped development at version 12, which runs on the Presto engine.
The newer shell-of-itself version, using the Blink layout engine (also used by Google Chrome) for all versions from 15 onward. (There is nothing in-between).
There are plenty of users still using the version 12 endpoint Presto series that it's not obsolete.
Mentioning the version number doesn't hurt, and is why we try and have users specify what version they are currently using when asking questions. | stackexchange-meta_superuser | {
"answer_score": 6,
"question_score": -3,
"tags": "discussion"
} |
Wordpress - Programmatically inserting posts with NEW categories?
I have written a script that takes an XML feed of some news, and inserts each news story as a post into WordPress using wp_insert_post().
Each of these news stories has a category that I would like to add to WordPress also.
My question is, how can I create NEW categories on the fly and assign the post to that category using wp_insert_post() (or any other function)?
Thanks! | I sorted it in the end by writing the following code:
//Check if category already exists
$cat_ID = get_cat_ID( $category );
//If it doesn't exist create new category
if($cat_ID == 0) {
$cat_name = array('cat_name' => $category);
wp_insert_category($cat_name);
}
//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);
// Create post object
$new_post = array(
'post_title' => $headline,
'post_content' => $body,
'post_excerpt' => $excerpt,
'post_date' => $date,
'post_date_gmt' => $date,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array($new_cat_ID)
);
// Insert the post into the database
wp_insert_post( $new_post ); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "wordpress"
} |
Submitting AJAX form old style
I have a form for which I want to use AJAX only for validation. It has several fields and I am currently using a PHP script which I want only to check if the size of the files entered into the input fields adds to less than N Kb. That works. Now what I would like is, once I see that the total size of the files is less than N, have the form submit to self in the old way:
action="localhost" method="post"
How can I achieve that same behaviour. Thank you very much | Like Sakuto said, you should have 1 validation function that first does the AJAX validation and then allows the form submission.
Something along the lines of:
function my_form_validation(e) {
form_is_valid = validate_form_via_ajax();
if (form_is_valid) {
return true;
}
e.preventDefault();
return false
}
And your form submit event should be bound to my_form_validation()
Here's an example: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, php, jquery, ajax, forms"
} |
I'm a bit confused on bike shoe terminology. Particularly regarding Look KEO Plus Pedals - what is required to use them?
I'm a bit confused on terminology.
Clipless pedals are the clip-in style pedals. Correct? Then the cleat are the shoes you wear? Or are cleats just bottom attachments for any cycling shoe?
A used cycle I'm looking at getting has Look KEO Plus Pedals on it which says it comes with Cleats. The shoes the guy had didn't fit though. I'm not fully understanding if any bicycle shoe will fit the Look KEO Plus Pedal or if I need a particular cleat and/or shoe for it?
Terminology index - a list of bike part names and cycling concepts has a mention of Look Pedals but doesn't really go into any detail that would answer my question. | Cleats are the bottom attachment to shoes. Most road shoes use a 3 hole attachment, which is a standard size. Most pedal manufacturers have their own cleat style, but all 3-hole cleats use the same spacing as far as I know.
Your pedals may come with suitable cleats if you're buying them new, if not make sure you buy 'look keo' compatible cleats. There is another (old) style of look cleat that is incompatible. So long as it says keo you will be fine though. | stackexchange-bicycles | {
"answer_score": 4,
"question_score": 5,
"tags": "pedals, clipless, terminology, cleat"
} |
How to get access to kubernetes cluster from containerized application running inside node hosted on same cluster?
I am using kubernetes client library for c#. This method should ideally provide me with k8s config of the cluster it is running inside
`var k8sConfig = KubernetesClientConfiguration.InClusterConfig();`
Inside docker container when this run it gives
`k8s.Autorest.HttpOperationException: Operation returned an invalid status code 'Forbidden'`
Expected behaviour is to get cluster inside application so as to use its configmaps and secrets. Is there any other method to do this or are there any pre-requisites to use this method?
Please note: I am using token login from web UI for cluster dashboard | <
I asked over github too, which was answered by moderators. And this is what we need to do here. Keep "clusterrolbinding" concept in mind. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, docker, kubernetes, kubernetes cluster"
} |
c++11: initialize map with explicit initializer_list object
In C++11 I can initalize a map with an initializer_list like this:
map<string, int> mymap = {{"first", 1}, {"second", 2}};
But not like this:
initializer_list<pair<string,int>> il = {{"first", 1}, {"second", 2}};
map<string, int> mymap2{il};
Any idea why is that? Is there a different syntax for that or is it not possible at all?
Thanks. | The `initializer_list` constructor of `map` takes a list of `value_type`, which is a `pair` with first element `const`.
This will work:
initializer_list<pair<string const,int>> il = {{"first", 1}, {"second", 2}};
^^^^^^ | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 10,
"tags": "c++11, initializer list"
} |
Error when add .jar file in Classpath
Hi.
I created a project which can send email using JavaMail. But when I add the .jar file in my classpath, I get the following error message. I don't know which error is this. Because it only show the "your project contain error" message.
Please provide me some answer.
Thanks in Advance. | It's likely the jar is using classes that Dalvik does not implement. If you're using a jar compiled for Java SE it's possible. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android"
} |
Generic method, using where T : base. Why is T not considered to be of concrete type when calling other methods?
I'm wondering what I'm missing here. When debugging I'm seeing e as an instance of SpecificException but the method call is matched to the signature with the base Exception. How come? And can I get around that without adding checks for the type in my LogException method?
public string LogException<T>(T e)
where T : Exception
{
string errorMsg = e.ToString();
errorMsg += Details(e);
return errorMsg;
}
public string Details(Exception exception)
{
return "foo";
}
public string Details(SpecificException exception)
{
return "bar";
} | Overload resolution happens at _compile time_. At compile time, the compiler can't possibly know the _runtime type_ of `e`. It only knows that `e` will be of type `Exception` or a type deriving from it.
It doesn't know the concrete type, so the only correct overload to use is that for `Exception`.
To be able to achieve your goal, you can employ the DLR via the `dynamic` keyword:
errorMsg += Details((dynamic)e);
That will move the overload resolution to the runtime and at that point in time, the actual type of `e` is known, so it can choose the overload best matching it. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "c#, generics"
} |
1064 - You have an error in your SQL syntax (...) near ''
Running this sql query in mysql:
INSERT INTO Test_id_isbnyear
SELECT I.id, I.isbn, Y.year
FROM Prod_id_isbn AS I
LEFT JOIN Prod_id_year AS Y ;
Throw this error:
> # 1064 - You have an error in your SQL syntax (...) near '' at line 4
How can I get an error about a '"' if there is no such thing in my query? | Admittedly the error message isn't _super_ helpful in this case. There may be exceptions to the rule, but in my experience this _usually_ means that the syntax error is at the very end of the query. Which, in this case, it is:
SELECT I.id, I.isbn, Y.year
FROM Prod_id_isbn AS I
LEFT JOIN Prod_id_year AS Y
-- missing "ON" clause
Should be something like:
SELECT I.id, I.isbn, Y.year
FROM Prod_id_isbn AS I
LEFT JOIN Prod_id_year AS Y
ON I.SomeField = Y.SomeField | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "mysql, sql"
} |
Why can we express the heat added as the product of temperature change and some $C$?
In explaining $C_v = \left(\frac{\partial u}{\partial T}\right)_V$, my textbook first writes that $\delta q = du$ for a constant volume process, and then that that $dq=C_v dT$ 'from the definition of $C_v$' which they have given as "the energy required to raise the temperature of a unit mass of substance by one degree as the volume is maintained constant."
Then the two are equated to get $C_v = \left(\frac{\partial u}{\partial T}\right)_V$
However, what's not explained is why can dQ be expressed as the product of some quantity $C_v$ times $dT$. Intuitively it makes sense that heating a system would increase its temperature. But why would this necessarily be depending on the product of temperature change $dT$ and some $C_v$. Is this based on some empirical observation that hasn't been stated? I don't see how it follows directly from the definition | Your book has it backwards. The definition of $C_v$ is $$C_v=\left(\frac{\partial U}{\partial T}\right)_V$$From Gibbs phase rule, if you have a single phase, then U is a function of two parameters, in this case T and V. But if V is constant, then $$dU=C_vdT$$. From the first law of thermodynamics, at constant volume, no P-V work is done and so, in this case, $$dU=dQ=C_vdT$$ | stackexchange-physics | {
"answer_score": 2,
"question_score": 0,
"tags": "thermodynamics, energy, temperature"
} |
Backspace icon/representation
Is there a Unicode character for the backspace icon (as seen on some keyboards and on the Windows Phone soft keyboard)
!Windows Phone soft keyboard | Yes: `\u232B` is the "erase to the left" character: ⌫. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 8,
"tags": "windows phone 7, unicode, backspace"
} |
$\operatorname{Re}$ and $\operatorname{Im}$ of $\frac{1+it}{1-it}$
Let $w = \frac{1+it}{1-it}, w \in \mathbb C, t \in \mathbb R$
**Question** : How to calculate $\operatorname{Re}(w)$ and $\operatorname{Im}(w)$?
What I have done so far:
$ \begin{align} w &= \frac{1+it}{1-it} \\\ &= \frac{(1+it)(1+it)}{(1-it)(1+it)} \\\ &= \frac{(1+it)^2}{1+it-it-(it)^2} \\\ &= \frac{(1+it)^2}{1-(it)^2} \end{align}$
However I am running in a circle here and this does not really help me. Is there a technique to simplify complex numbers containing an additional variable? | You are almost there:$$\frac{(1+it)^2}{1-(it)^2}=\frac{1-t^2+2it}{1+t^2}=\frac{1-t^2}{1+t^2}+\frac{2t}{1+t^2}i.$$ | stackexchange-math | {
"answer_score": 2,
"question_score": -1,
"tags": "complex numbers"
} |
Printing prime numbers in Java using recursion
I wrote a similar function in C, and was able to achieve the required result unlike java. Below is the code, which checks if a number is prime recursively. Compilation says, i'm missing a return statement. The number to be checked if a prime is x. The variable i is the divisor.(ie) x/2, (x/2)-1,...0.
public int primes(int x, int i)
{
if(i==0)
return 1;
if(x%i==0)
return 0;
else
primes(x, i-1);
}
What is the complexity of this code if I had to print the first 1000 prime numbers. | In this case:
else
primes(x, i-1);
You aren't returning anything. However, the compiler must ensure that something is returned in all cases. Just return whatever the recursive method call returns:
else
return primes(x, i-1);
Also, modify the first case's condition to `i == 1` so it returns `1` on primes correctly. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "java, recursion, primes"
} |
Is it possible to start an activity in a different apk using startActivity on Android using the activity name or similar?
I have tried to write an Android application with an activity that should be launched from a different application. It is not a content provider, just an app with a gui that should not be listed among the installed applications. I have tried the code examples here and it seems to be quite easy to launch existing providers and so on, but I fail to figure out how to just write a "hidden" app and launch it from a different one.
The basic use case is:
* App A is a normal apk launchable from the application list.
* App B is a different apk with known package and activity names, but is is not visible or launchable from the application list.
* App A launches app B using the package and class names (or perhaps a URI constructed from these?).
I fail in the third step. Is it possible to do this? | Yes.
Use the package name and class name, like this (for starting Gmail):
new Intent("com.google.android.gm", "com.google.android.gm.ConversationListActivity"); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "java, android, android activity, android intent"
} |
How to hide, encrypt and password protect a volume on my smartphone?
I want to have a hidden volume on my smartphone which is encrypted and password protected.
Once you encrypt a file, this will happen:
1. new encrypted file will be created
2. original file will safely be deleted
When you later want to view, edit or use the encrypted file, a new un-encrypted version will be created.
Considering the single channel - read OR write - operation of the internal flash memory of mobile devices, this will be a very slow and battery consuming process.
On-the-fly encryption is not possible since the phone lacks a dedicated on-board encryption processor (with a boot loader verification method) and/or some really fast multi-channel memory.
Does anyone know a better way to do this? | Android has support for encrypted mounts in the kernel (the Linux `dm-crypt` code). The `vold` volume manager supports mounting a file as an encrypted partition. You can find more details in the notes.
LUKSManager does exactly this. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "android, encryption"
} |
Initial Current of Inductor?
I know that a capacitor can be charged up to store energy, then if we disconnect the capacitor from the source and hook it up to a light bulb, it will light up since the energy stored is used to power the light bulb. I was wondering whether the same thing would happen if we used an inductor instead?
If so, what is the inital current the moment it is attached to the light bulb? | Yes you can, but there are some differences with the case of the capacitor, as follows.
Where a capacitor stores energy in the form of an electric field, an inductor stores energy in the form of a magnetic field. To sustain that magnetic field requires the continuous flow of electrical current through the inductor. If you attempt to stop that current flow so that the magnetic field will collapse, the energy stored in the field will get pumped into the inductor in a direction that strives to maintain the flow of current.
The initial current through the bulb will be the same as the current flow through the inductor without the bulb, after which the bulb will grow dim and go out as the energy stored in the inductor is dissipated by the resistance of the bulb.
This tendency to keep the current flowing is so great that if you try stopping the current by breaking the wire leading to the inductor, a spark will fly between the cut ends of the wire and they may catch fire as a result. | stackexchange-physics | {
"answer_score": 2,
"question_score": 0,
"tags": "electric circuits"
} |
How do I write a Bigquery federated query towards postgres tables?
I'm confused about the federated query syntax. I'm able to query for metadata with the default connection query in bq console:
`SELECT * FROM EXTERNAL_QUERY("connection-id", "SELECT * FROM INFORMATION_SCHEMA.TABLES;");`
But I want to query the tables. So I try:
`SELECT * FROM EXTERNAL_QUERY("connection-id", "SELECT * FROM my_postgres_table;");`
Then the console shows me this:
PostgreSQL type in column type is not supported in BigQuery. You can cast it to a supported type by PostgreSQL CAST() function. at [1:15]
How do I write this query to get table results back?
Thanks! | If your external query contains a data type that is unsupported in BigQuery, the query will fail immediately. You can cast the unsupported data type to a different supported MySQL or PostgreSQL data type.
* **Unsupported PostgreSQL data types** : money, time with time zone, inet, path, pg_lsn, point, polygon, tsquery, tsvector, txid_snapshot, uuid, box, cidr, circle, interval, jsonb, line, lseg, macaddr, macaddr8
* **Resolution** : Cast the unsupported data type to STRING.
* **Example** : SELECT CAST('12.34'::float8::numeric::money AS varchar(30)); This command casts the unsupported data type money to STRING.
See more for Limitations and Data type mappings | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "google cloud platform, google bigquery"
} |
React-Router Blank Page
I'm still learning to using react-router. I just wondering why my page is blank.
App.js :
import {
BrowserRouter as Router,
Routes,
Route
} from "react-router-dom";
export default function App() {
return (
<Router>
<Routes>
<Route exact path="/" element={<MainPage/>}/>
</Routes>
</Router>
);
} | React Router v6 doesn't support **exact** anymore because all paths are match exactly by default
<Route path="/" element={<MainPage/>}/> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "reactjs, react router dom"
} |
Determining product ID from URL in magento
Here is a sample url from my company's Magento site (and we're obviously using stores in the URL hence the smi000.. code)
I understand that the category id is 312834, and the product id is 35830. I understand how to use `Mage::helper->getURL()` to get the URL, but how do I get the product ID using magento code (i.e. the "Magento Way"?) | You could get the product id from the core_url_rewrite table using the url for this, try this:
$url = Mage::helper->getURL();
$rewrite = Mage::getModel('core/url_rewrite')
->setStoreId(Mage::app()->getStore()->getId())
->loadByRequestPath($url);
$productId = $rewrite->getProductId();
$product = Mage::getModel('catalog/product')->load($productId);
Also you could get the id from the url directly (no extra query to the DB) like this:
$productId = $this->getRequest()->getParam('id'); | stackexchange-magento | {
"answer_score": 4,
"question_score": 4,
"tags": "magento 1.9, url rewrite, stores, product urls"
} |
postgres: select max returns 9 instead of 10
This is my script:
SELECT MAX(distinct TRIM(value, 'SAMPLE_VALUES_'))
FROM sample
WHERE id = 79;
My data is somehow like this:
id | value
-------------------
79 | SAMPLE_VALUES_6
79 | SAMPLE_VALUES_7
79 | SAMPLE_VALUES_7
79 | SAMPLE_VALUES_8
79 | SAMPLE_VALUES_8
79 | SAMPLE_VALUES_8
79 | SAMPLE_VALUES_9
79 | SAMPLE_VALUES_9
79 | SAMPLE_VALUES_10
79 | SAMPLE_VALUES_10
79 | SAMPLE_VALUES_10
But it always returning 9.
Is there something wrong with my script? Thanks for your help. | Cast into integer.
SELECT MAX(distinct cast(TRIM(value, 'SAMPLE_VALUES_') as integer))
FROM sample
WHERE id = 79 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "postgresql"
} |
Why is $(f(x))'$ shortened $f'(x)$
Why is $(f(x))'$ shortened $f'(x)$?
This makes the chain rule look awkward, as $(f(g(x)))'\neq f'(g(x))$, but rather $f'(g(x))\\!\times\\! g(x)$, and makes it difficult to remember.
It's also an awkward way as $(f(x))' = ('\circ f)(x)$, and changing the order of the functions makes no sense, as $'$ should come first. | Calculus seems to be a wonderful source of bad notation; I've never seen the notation $(f(x))'$ used that much. $f'(x)$ captures things better, since the $'$ mark applies to the function, not to the expression as a whole, and is what I usually see - so I would say the $(f(x))'$ is more of a corruption of $f'(x)$ than the other way round. I'd generally state the chain rule as: $$(f\circ g)'(x) = f'(g(x))g'(x)$$ which looks a lot clearer. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "notation"
} |
ColdFusion structkey starting with number
Why does this fail:
<CFIF isdefined("URL.3dfile")>...</CFIF>
with following message:
> Parameter 1 of function IsDefined, which is now URL.3dfile, must be a syntactically valid variable name.
and this won't:
<CFIF structkeyexists(URL,"3dfile")>...</CFIF>
Is the way it get's parsed not much the same? And .. are variables starting with numbers invalid or aren't they? | Seybsen - variables names should not begin with a number. This is likely a legacy of older non-java version of CF Where a variable was not part of an object.
However, in the java world everything IS an object. This leads to a syntactical nuance. If you are using variable names in dotted notation your var name will likely throw an error. But use it in other ways and it will succeed.
So this sort of syntax works `url['33foo']`
But setting a variable name directly - `33foo = true` \- will not work.
Here's a post with a full explanation.
< | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 3,
"tags": "variables, coldfusion, coldfusion 9"
} |
Data: Why is a firm stock delisted?
Shumway (1997) highlights that stock returns in cross-sectional portfolio analysis have to be adjusted for firm delistings.
The CRSP database maintains a monthly delisting file (msedelist) with further information on why a stock is delisted in the field DLSTCD. This field decodes a lot of several delisting reasons (see here) which are needed for an appropriate adjustment of this stocks return in the delisting month.
Is there an equivalent to CRSPs DLSTCD field on why a stock is delisted available in Thomson Reuters Datastream or any other data source? | If you have access to Thomson Reuters customer zone, log in and look for GCODE Database. There is a type for delisting, but not very granular.
If you don't have access to customer zone, see user guide, page 137: < | stackexchange-quant | {
"answer_score": 1,
"question_score": 2,
"tags": "equities, finance, data, data source"
} |
Converting 2 strings to DateTime
I am getting 2 strings back from an API one for the date, and one for the time. I need to convert the 2 of them into a single DateTime object with the date and time in it. the 2 strings I get back are
Date: "2017-10-17"
Time: "8:00PM"
Below is what I am trying to do and I can not get it to work. If I remove the time from it I can parse just the date, but I cant seem to figure out the pattern to add the time in it.
string date = "2017-10-17";
string time = "8:00PM"'
string startTime = $"{date} {time}";
DateTime date = DateTime.ParseExact(startTime, "yyyy-MM-dd hh:mmtt", System.Globalization.CultureInfo.CurrentCulture);
How can I get those 2 strings to combine into a single DateTime object? | string date = "2017-10-17";
string time = "8:00PM";
string startTime = $"{date} {time}";
DateTime myDate = DateTime.ParseExact(startTime, "yyyy-MM-dd h:mmtt",System.Globalization.CultureInfo.InvariantCulture); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, datetime"
} |
When Tooltip.Content gets populated?
I need to use the Tooltip.Content information of any given control.
Lets say there is a a control `TextBlock` and it is bound to a `Tooltip`. I access the Tooltip of the TextBlock by `var toolTip=(ToolTip)TextBlock.ToolTip`. The value of `toolTip.Content` remains null, but if I do a mouse hover over the control it is populated with the desired value.
How do I get the tooltip to populate its content before triggering a mouse over the control? Does the Tooltip loads its content lazily or is there something I am missing?
**Edit:**
To clarify the question above:
I was trying to show tooltip but its content was not populated with the binding value although its bound to a valid property. | I just found answer to my own question, Tooltip control doesn't get created until it is necessary. And when it gets created it sets is `PlacementTarget` to the parent control and sets its `IsOpen` property to true. When 'PlacementTarget`is set it populates the`ToolTip.Content` property.
In my case I was just trying to set `IsOpen` property without setting the `PlacementTarget`. Now after setting it the content is bound and the tooltip is shown as expected. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "wpf, tooltip, contentcontrol"
} |
How to execute command with partial result from another command?
I have:
$ module avail firefox --latest
---------------------------------------------------------- /env/common/modules -----------------------------------------------------------
firefox/83.0
I would like to extract the `firefox/83.0` part of the above result into a new command:
$ module load firefox/83.0
This is what I have so far, but it does not seem like I can pipe the result from the `grep` onto the next command:
$ module avail firefox --latest | grep firefox | echo module load
Note: this is on a version of Modules which does not have the `module load app/latest` ability. | Use a regex to capture only `firefox/83.0`, then use command substitution to use that result in the next command;
module load $(module avail firefox --latest | sed -nre 's/^firefox\/[^0-9]*(([0-9]+\.)*[0-9]+).*/\0/p'
More info on the regex: How to extract a version number using sed?
* * *
Using `xargs`;
module avail firefox --latest | sed -nre 's/^firefox\/[^0-9]*(([0-9]+\.)*[0-9]+).*/\0/p' | xargs module load | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "bash, environment modules"
} |
Eclipse: The declared package does not match the expected package
I have a problem importing an external project. I go File -> Import... -> Existing Projects into Workspace, choose the folder where the project is located and everything is imported - but the package names of the project don't seem to be what Eclipse expects. The package names all have a prefix:
prefix.packagename1
prefix.packagename2
etc.
But Eclipse expects
src.prefix1.prefix.packagename1
src.prefix1.prefix.packagename2
etc. because the directory is src/prefix1/prefix/package1
I don't really want to mess around with external code. How do I tell Eclipse to ignore the directory "src/prefix1"? Or what else can I do? | Just go into the build path and change the source path to be `src/prefix1` instead of `src`.
It may be easiest to right-click on the `src` directory and select "Build Path / Remove from build path", then find the `src/prefix1` directory, right-click it and select "Build Path / Use as source folder". | stackexchange-stackoverflow | {
"answer_score": 108,
"question_score": 89,
"tags": "java, eclipse, package"
} |
How to write to a Windows network share from a batch file?
I have a batch script on a local machine that calls a Python script on a Windows network share and should write a file there. If I run the Python script without the batch file, it runs successfully. If I run the batch file, I get this error:
Traceback (most recent call last):
File "python_script.py", line 25 in <module>
IOError: [Errno 13] Permission denied: 'outfile.txt'
The Python script lives in the same directory as "outfile.txt".
Here is the code from the Python script:
outfile = open("outfile.txt", "w")
I have also tried an absolute path, but I get an error that the "file is not found":
outfile = open("\\server\folder\subfolder\outfile.txt", "w")
I don't think it's a permission issue, because if I just run the python script "by hand" logged in as the same user, it writes the outfile to the network share. What am I missing using the batch file? | When you "call" the python script, you are actually executing it from the current directory. Since I don't think you can `cd` to a network share without mapping it, this will probably cause a permission issue.
The absolute path will work but you just need to specify the path correctly. In python, the backslash is an escape character, so you either have to escape your backslashes or use forward slashes:
outfile = open("//server/folder/subfolder/outfile.txt", "w")
See Using Python, how can I access a shared folder on windows network? | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "python, windows, batch file"
} |
Is this a nest and which wasp species?
A friend found this stuck to his insect screen today. He said it felt like dust. This wasp/bee was alive. Location is Germany.
Is this a nest?
First look:

More precisely a female, judging by the round end of the abdomen.
. I am surprised that the find line color is not the same as the color I set for the editor current line color ! How to set the Find line color ? | You should take a look at the official documentation. You can try them one by one if you can not figure out which one is your need. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "visual studio code"
} |
How do I add install a JAR and the java docs?
How to I do the following using **Maven**?
I downloaded the Admob android sdk from <
I am trying to install the Jar and the java docs that come in the downloaded ZIP file
How do I install both the JAR and the Java docs into my repo? thanks
oh btw, the javadocs are not located in a JAR, they are stored in a multilevel folder format.
Thanks | If the javadocs are not available in a remote maven repo. You have to install the **jars** into your repo. Use the Install Plugin to perform this task. This is what you have to do. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "eclipse, maven"
} |
String resource files in java
Programming in Java, what's the better way to create resource files to save the messages of the application in different languages?
If I use a properties file, inside the code everytime that I need refer to a message I have to write something like that:
ResourceBundle.getBundle("test.messages.messageFile").getString("Message1")
Exists another form to use messages and generate a code cleaner? Maybe create a class with static constants that refer to this messages? | you can use ResourceBundle, but declare it and use it as a variable.
ResourceBundle languageBundle=ResourceBundle.getbundle("test.messages.messageFile");
//later in your code you can say
languageBundle.getString("Message1");
it would help if you make this variable `public static` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "java, internationalization, nested resources"
} |
Change Yahoo Blueprint application look&feel
Is it possible to modify the "bluish style" of a mobile application developed with Yahoo Blueprint ?
I would like to use at least my own colors. | Yes, you can unofficially change the page theme to one of many predefined themes. For instance:
<page style="collection" theme="black">
See the Blueprint developer forums for more info: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mobile website, look and feel"
} |
Problem installing socket.io on Fedora Core
I'm trying to install `socket.io` on my machine, but I keep encountering errors when I run `npm install socket.io` as directed on their website. I'm not sure if I have version incompatibilities for npm or node.js or if I'm simply missing something obvious. As far as I can tell, I have the most recent stable version of both of them.
When I run the install command, the console outputs 40+ errors, and at the end I am given the line `npm not ok`. Any ideas as to what is going wrong? | What is the error?
Are you installing `npm` using code from `git`? I can only guess that you are not using a stable code, because the master branch from git is often unstable.
If that is the case, what you can do is to get the latest code from the git repository and install it again.
$ cd npm
$ git pull
$ make install
Hope it will solved your problem. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "node.js, fedora, socket.io, npm"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.