qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
18,134,815 | I've been learning C++, and this chunk of code is from a simple grading program. But when I try to get the user input, there's a problem.
If I enter a number, whether it be less than 0 or more than 100, or anything in between, my loop works fine.
But if I type in any letter, or any non-alphanumeric character (ex: +, (, %, etc.) I get an infinite loop with "Please enter a grade value between 0 and 100" printed forever.
What am I doing wrong?
Thanks.
```
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
int grade = -1; // grade will hold grade value; initialized to -1
do {
cout << "Please enter a grade value between 0 and 100." << "\n";
cin >> grade;
} while (grade < 0 || grade > 100);
cout << grade << "\n";
printGrade(grade);
return 0;
}
``` | 2013/08/08 | [
"https://Stackoverflow.com/questions/18134815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2597201/"
] | If cin does not receive valid input for the data type (int), the variable grade is not changed and remains at -1. You can test whether the input was successful like so
```
bool success = (cin >> grade);
if (! success)
{
cin.clear();
cout << "bad input\n";
break;
}
```
You can also use this as a shortcut `if (! (cin >> grade))`
Note that you need to `clear` the error state of `cin` before you use it again. | Correctly and safely reading until you get valid input is far trickier than you'd think. If there's invalid input, like a letter, the stream is set in a "failure" state, and refuses to read any more characters until you clear the state. But even if you clear the state, that input is still waiting there, in the way. So you have to ignore those characters. The easiest thing to do is simply ignore everything until the next enter key, and then try the input again.
But it gets even more complicated, because if the stream has an error, it gets set in a "bad" state, or if it reaches the end of the stream, it gets set in a "eof" state. Neither of these two are recoverable, so you must detect them and quit the program to avoid an infinite loop. Even *more* irritating, istreams have a `.fail()` function, but that checks if it's in `fail` *or* `bad`, which makes it nearly useless in my opinion. So I wrote a little `invalid_input` which checks if the stream can continue.
Note that `get_grade` sets the `fail` flag manually if the input is out-of-range.
```
#include <iostream>
#include <stdlib.h>
#include <limits>
bool invalid_input(std::istream& in)
{return in.rdstate() == std::ios::failbit;}
std::istream& get_single_grade(std::istream& in, int& grade) {
std::cout << "Please enter a grade value between 0 and 100." << "\n";
if (in>>grade && (grade<0 || grade>100))
in.setstate(std::ios::failbit);
return in;
}
bool get_grade(std::istream& in, int &grade) {
while(invalid_input(get_single_grade(in, grade))) { //while we failed to get data
in.clear(); //clear the failure flag
//ignore the line that the user entered, try to read the next line instead
in.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
return in.good();
}
int main(int argc, char* argv[]) {
int grade = -1; // grade will hold grade value; initialized to -1
if (get_grade(std::cin, grade) == false) {
std::cerr << "unxpected EOF or stream error!\n";
return false;
}
std::cout << grade << "\n";
return EXIT_SUCCESS;
}
```
As you can see [here](http://ideone.com/2tcPfE), this doesn't get into an infinite loop when given out of bounds numbers, end of file, a stream failure, or invalid characters. |
70,372,175 | Firstly, my apologies for the vague tittle. I have two tables: **Devices** and **DeviceProperties**.
```
[ Devices ]
[ id ]
[ AA ]
[ BB ]
[ CC ]
[ DeviceProperties ]
[ id ][ propertyType ][ propertyKey ][ valueType ][ value ]
[ AA ][ desired ][ scanInterval ][ Number ][ 100 ]
[ AA ][ tag ][ floor ][ Number ][ 200 ]
[ AA ][ desired ][ name ][ String ][ AA_Device ]
[ BB ][ desired ][ scanInterval ][ Number ][ 100 ]
[ BB ][ tag ][ floor ][ Number ][ 200 ]
[ CC ][ tag ][ floor ][ Number ][ 200 ]
```
I want to select all devices that have specific device properties:
```
-- Select devices that have these DeviceProperties
[ desired ][ scanInterval ][ Number ][ 100 ]
[ tag ][ floor ][ Number ][ 200 ]
```
I declare **N** variables. Each group of 4 declared variables represent a different device property/row in DeviceProperties table.
```
DECLARE @propertyType_1 nvarchar(max) = 'desired';
DECLARE @propertyKey_1 nvarchar(max) = 'scanInterval'
DECLARE @valueType_1 nvarchar(max) = 'Number'
DECLARE @value_1 nvarchar(max) = '100'
-- [ desired ][ scanInterval ][ Number ][ 100 ]
DECLARE @propertyType_n nvarchar(max) = 'tag';
DECLARE @propertyKey_n nvarchar(max) = 'floor'
DECLARE @valueType_n nvarchar(max) = 'Number'
DECLARE @value_n nvarchar(max) = '200'
-- [ tag ][ floor ][ Number ][ 200 ]
```
Assuming I had a working query, it would only return the following devices:
```
[ Devices ]
[ id ]
[ AA ]
[ BB ]
```
Device CC would not be returned because it only has DeviceProperty
```
[ tag ][ floor ][ Number ][ 200 ]
```
but not
```
[ desired ][ scanInterval ][ Number ][ 100 ]
```
I'm really confused as to what sort of a query I should be writing. A simple WHERE query does not work here. | 2021/12/16 | [
"https://Stackoverflow.com/questions/70372175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132661/"
] | Insert the required matching criteria in a temp table
```
insert into #temp (propertyType, propertyKey, valueType, value)
values ('desired', 'scanInterval', 'Number', 100),
('tag', 'floor', 'Number', 200);
```
Join it to your table, `GROUP BY` `id` and count for matching rows must be `N`. For the example given, `N = 2`
```
SELECT d.id
FROM Devices d
INNER JOIN DeviceProperties p ON d.id = p.id
INNER JOIN #temp t ON p.propertyType = t.propertyType
AND p.propertyKey = t.propertyKey
AND p.valueType = t.valueType
AND p.value = t.value
GROUP BY d.id
HAVING COUNT(*) = 2
``` | Squirrel gave me an idea. Not sure if this is an ideal approach or not but I could also do something like this:
```
select
d.deviceId
from
Devices as d
join
DeviceProperties as p
on
d.deviceId = p.deviceId
where
p.propertyType in (@pt_0, @pt_1) and
p.propertyKey in (@pk_0, @pk_1) and
p.value in (@pv_0, @pv_1)
group by
d.deviceId
having
COUNT(*) = 2
``` |
1,940,731 | [](https://i.stack.imgur.com/OF1ll.jpg)
I don't see any angles in terms of $x$ , or why $\triangle ODE$ is isosceles I would highly appreciate your hints | 2016/09/25 | [
"https://math.stackexchange.com/questions/1940731",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/366082/"
] | There's a much easier way to see this. Think of complex numbers as points in the plane. The number $i$ is the point on the $y$ axis one unit from the origin.
We want to find a point $z$ which, translated to the right by a certain amount, moves exactly to $i$. This is because we are adding a positive real number to $z$, and adding a positive real number always translates to the right.
So the point must lie on the horizontal line through $i$. This is your $b=1$ equation.
Now how far does $z$ move to the right? $|z|$ is the distance from $z$ to 0. But this distance is always a little more than the distance from $z$ to $i$ because from $z$ to $i$ is straight along the line but from $z$ to $0$ is the same distance to the right plus one unit down.
So no matter where $z$ is, if we move $z$ rightward by $|z|$ we always move it *too far* to get it exactly to $i$.
[](https://i.stack.imgur.com/5AO1U.png) | with $$z=a+bi$$ you will get the equation
$$\sqrt{a^2+b^2}+a+bi-i=0$$ this is equivalent to
$$\sqrt{a^2+b^2}+a+i(b-1)=0$$ from here we get
$$b=1$$
and $$\sqrt{a^2+b^2}+a=0$$
from the second equation we get
$$\sqrt{a^2+b^2}=-a$$
squaring gives
$$a^2+b^2=a^2$$ substracting $a^2$ gives $$b=0$$
this is a contradiction to $$b=1$$
thus the given equation does not hold |
27,210,279 | The purpose of the program is to make comments in the file begin in the same column.
if a line begins with ; then it doesn't change
if a line begins with code then ; the program should insert space before ; so it will start in the same column with the farthest ;
for example:
Before:
```
; Also change "-f elf " for "-f elf64" in build command.
;
section .data ; section for initialized data
str: db 'Hello world!', 0Ah ; message string with new-line char
; at the end (10 decimal)
```
After:
```
; Also change "-f elf " for "-f elf64" in build command. # These two line don't change
; # because they start with ;
section .data ; section for initialized data
str: db 'Hello world!', 0Ah ; message string with new-line char
; at the end (10 decimal)
```
I am a beginner in Linux and shell, so far I have got
```
echo "Enter the filename"
read name
cat $name | while read line;
do ....
```
Our teacher told us that we should use two while loop;
Record the longest length before; in the first loop and do the changes in the second while loop.
for now I don't know how to use awk or sed to find the longest length before;
Any ideas? | 2014/11/30 | [
"https://Stackoverflow.com/questions/27210279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4307962/"
] | Here is the solution, assuming that comments in your file begin with the first semi-colon (`;`) **that is not inside a string**:
```
$ cat tst.awk
BEGIN{ ARGV[ARGC] = ARGV[ARGC-1]; ARGC++ }
{
nostrings = ""
tail = $0
while ( match(tail,/'[^']*'/) ) {
nostrings = nostrings substr(tail,1,RSTART-1) sprintf("%*s",RLENGTH,"")
tail = substr(tail,RSTART+RLENGTH)
}
nostrings = nostrings tail
cur = index(nostrings,";")
}
NR==FNR { max = (cur > max ? cur : max); next }
cur > 1 { $0 = sprintf("%-*s%s", max-1, substr($0,1,cur-1), substr($0,cur)) }
{ print }
```
.
```
$ awk -f tst.awk file
; Also change "-f elf " for "-f elf64" in build command.
;
section .data ; section for initialized data
str: db 'Hello; world!', 0Ah ; message string with new-line char
; at the end (10 decimal)
```
and below is how you get to it from a naive starting point (I added a semi-colon inside your `Hello World!` string for testing - make sure to verify all suggested solutions using that).
Note that the above DOES contain 2 loops on the input as your teacher suggests, but you do not need to manually write them as awk provides the loops for you each time it reads the file. If your input file contains tabs or similar then you need to remove them in advance, e.g. by using `pr -e -t`.
Here is how you get to the above:
If you cannot have semi-colons in other contexts than as the start of comments then all you need is:
```
$ cat tst.awk
{ cur = index($0,";") }
NR==FNR { max = (cur > max ? cur : max); next }
cur > 1 { $0 = sprintf("%-*s%s", max-1, substr($0,1,cur-1), substr($0,cur)) }
{ print }
```
which you'd execute as `awk -f tst.awk file file` (yes, specify your input file twice).
If your code can contain semi-colons in contexts that are not the start of a comment, e.g. in the middle of a string, then you need to tell us how we can identify semi-colons in comment-start vs other contexts but if it can ONLY appear between singe quotes in strings, e.g. the `;` inside `'Hello; World!'` below:
```
$ cat file
; Also change "-f elf " for "-f elf64" in build command.
;
section .data ; section for initialized data
str: db 'Hello; world!', 0Ah ; message string with new-line char
; at the end (10 decimal)
```
then this is all you need to replace every string with a series of blank chars before finding the first semi-colon (which is then presumably the start of a comment):
```
$ cat tst.awk
{
nostrings = ""
tail = $0
while ( match(tail,/'[^']*'/) ) {
nostrings = nostrings substr(tail,1,RSTART-1) sprintf("%*s",RLENGTH,"")
tail = substr(tail,RSTART+RLENGTH)
}
nostrings = nostrings tail
cur = index(nostrings,";")
}
...the rest as before...
```
and finally if you don't want to specify the file name twice on the command line, just duplicate it's name in the ARGV[] array by adding this line at the top:
```
BEGIN{ ARGV[ARGC] = ARGV[ARGC-1]; ARGC++ }
``` | There are a few `printf` tricks that make this a manageable project. Take a look at the following. The script formats the assembly file with the assembly code beginning at column `0` to `code_width - 1` with the comments following at column `code_width` lined up after the code. The script is fairly well commented so you should be able to follow along.
The usage is:
```
bash nameofscript.sh input_file [code_width (default 46char)]
```
or if you make `nameofscript.sh` `executable`, then simply:
```
./nameofscript.sh input_file [code_width (default 46char)]
```
**NOTE:** this script requires **Bash**, if not run on bash, you may experience inconsistent results. If you have multiple embedded `;` in each line, the first will be considered the beginning of a comment. Let me know if you have questions.
```
#!/bin/bash
## basic function to trim (or stip) the leading & trailing whitespace from a variable
# passed to the fuction. Usage: VAR=$(trimws $VAR)
function trimws {
[ -z "$1" ] && return 1
local strln="${#1}"
[ "$strln" -lt 2 ] && return 1
local trimstr=$1
trimstr="${trimstr#"${trimstr%%[![:space:]]*}"}" # remove leading whitespace characters
trimstr="${trimstr%"${trimstr##*[![:space:]]}"}" # remove trailing whitespace characters
printf "%s" "$trimstr"
return 0
}
afn="$1" # input assembly filename
cwidth=${2:--46} # code field width (- is left justified)
[ "${cwidth:0:1}" = '-' ] || cwidth=-${cwidth} # make sure first char is '-'
[ -r "$afn" ] || { # validate input file is readable
printf "error: file not found: '%s'. Usage: %s <filename> [code_width (46 ch)]\n" "$afn" "${0//\//}"
exit 1
}
## loop through file splitting on ';'
while IFS=$';\n' read -r code comment || [ -n "$comment" ]; do
[ -n "$code" ] || { # if no '$code' comment only line
if [ -n "$comment" ]; then
printf ";%s\n" "$comment" # output the line unchanged
else
printf "\n" # it was a blank line to begin with
fi
continue # read next line
}
code=$(trimws "$code") # trim leading and trailing whitespace
comment=$(trimws "$comment") # same
printf "%*s ; %s\n" "$cwidth" "$code" "$comment" # output new format
done <"$afn"
exit 0
```
**input:**
```
$ cat dat/asmfile.txt
; Also change "-f elf " for "-f elf64" in build command.
;
section .data ; section for initialized data
str: db 'Hello world!', 0Ah ; message string with new-line char
; at the end (10 decimal)
```
**output:**
```
$ bash fmtasmcmt.sh
; Also change "-f elf " for "-f elf64" in build command.
;
section .data ; section for initialized data
str: db 'Hello world!', 0Ah ; message string with new-line char
; at the end (10 decimal)
``` |
24,258,319 | i am trying to store image in sql on server. Later i want to make these image available for download. Which approach is good:
1. By uploading image and saving path.
or
2.By converting image to base64 and then storing as BLOB type | 2014/06/17 | [
"https://Stackoverflow.com/questions/24258319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1966655/"
] | Foundation 5 tabs have been switched from `ul` to `dl` below is the structure the want
```
<dl class="tabs" data-tab>
<dd class="active"><a href="#panel2-1">Tab 1</a></dd>
....
```
[link on git](https://github.com/zurb/foundation/blob/cc02ba23bed58145c0273955262b2738b7a82d29/doc/includes/tabs/examples_tabs_basic.html)
the docs are outdated | nolawi petros' answer is the correct one: they changed the syntax without updating the documentation.
Here is the full syntax (same as the one nolavi linked to, just a bit shorter):
```
<dl class="tabs" data-tab>
<dd class="active"><a href="#panel2-1">Tab 1</a></dd>
<dd><a href="#panel2-2">Tab 2</a></dd>
</dl>
<div class="tabs-content">
<div class="content active" id="panel2-1">
<p>First panel content goes here...</p>
</div>
<div class="content" id="panel2-2">
<p>Second panel content goes here...</p>
</div>
</div>
```
On the plus side, they fixed deep-linking to an individual tab so the documentation is now correct regarding this. If you want to use deep linking you should include "data-options="deep\_linking:true" in the first line, like so:
```
<dl class="tabs" data-tab data-options="deep_linking:true">
```
Note that you'll have to call foundation.tab.js for deep linking to work; otherwise tabs seems to work out of the box. |
48,997,983 | Using the code below I get values for `precision`, `recall`, and `F scores` but I get `None` for `support`
```
import numpy as np
from sklearn.metrics import precision_recall_fscore_support
ytrue = np.array(['1', '1', '1', '1', '1','1','1','1','0'])
ypred = np.array(['0', '0', '0', '1', '1','1','1','1','0'])
precision_recall_fscore_support(ytrue, ypred, average='weighted')
```
output:
```
(0.91666666666666663, 0.66666666666666663, 0.72820512820512828, None)
```
I checked <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html> but I find it a bit unclear as to why it is `None`
Questions:
1. Why is `support` equal to `None` in my output?
2. How do I get a non-`None` output? | 2018/02/26 | [
"https://Stackoverflow.com/questions/48997983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is probably because you use php 7.2 which Magento doesn't support currently, even in 2.3 pre-release. You can downgrade to php 7.1.X and use Magento 2.2.X or downgrade to php 7.0.7.X and use Magento 2.1.X.
More information about Magento versions and its php support [here](http://devdocs.magento.com/guides/v2.1/install-gde/system-requirements-tech.html). | Change
```
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
```
To
```
foreach ($options as $name => $value){
$this->setOption($name, $value);
}
```
Reference in: <https://community.magento.com/t5/Installing-Magento-2-x/Deprecated-The-each-function-is-deprecated/td-p/80126> |
48,314,481 | Can anyone point me in the right direction why this sql query got an error?
<http://sqlfiddle.com/#!9/40058/2>
Expected results is to
get the names of Product on a table,
the count of sales on that product,
The amount (transactionamount)
and the net amount (statementdebit) | 2018/01/18 | [
"https://Stackoverflow.com/questions/48314481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902777/"
] | a transaction is a keyword please cover it with **backtick** `transaction`
you are missing one parenthesis after **transaction.transactionamount**
another thing `COUNT ()`, `SUM ()` should be like `COUNT()`,`SUM()` no extra spaces required in function.
```
SELECT
DISTINCT `transaction`.transactionservicetype AS Product,
count(`transaction`.transactionid) AS Count,
sum(`transaction`.transactionamount) AS Amount,
sum(statement.statementdebit) AS NetCost
FROM `transaction`
RIGHT JOIN statement ON `transaction`.transactionid =
statement.transactionid
WHERE `transaction`.transactiondate = '2018-01-17' AND
`transaction`.transactionservicetype = 'LBread';
``` | hope it will help you, i'm bit confuse because your table naming field naming.
this my solution
<http://sqlfiddle.com/#!9/40058/83/0>
sql query :
```
SELECT sum(a.statementdebit) debit,count(a.statementdesc) tot_prod,
sum(b.transactionamount) amount,a.statementdesc
FROM
statement a
JOIN transaction b on a.transactionid=b.transactionid
where b.transactiondate = '2018-01-17'
group by a.statementdesc
``` |
39,248,802 | I have public function beforeDelete() in almost every class of CMS. Unfortunately some clever people before me created some of them with `($rowId)` param and some of them with no parameters at all.
Parent `Main_Admin_Module` has empty function declaration like this:
```
public function beforeDelete() {}
```
but because of this, I'm getting **errors** like
>
> ERR: Declaration of Model\_EshopCategories::beforeDelete() should be
> compatible with that of Admin\_Module\_Main::beforeDelete()
>
>
>
because (obviously) declaration with `($rowId)` is not compatible with `(empty)` one.
Unfortunately this prevents Json responses since response body contains error and is therefore damaged, so I want to fix this one.
My question is: Can I simply get rid of parent method or should I rewrite every single childs beforeDelete to fix this? I tried to do `($rowId = null)` in parent method and it didn't work. | 2016/08/31 | [
"https://Stackoverflow.com/questions/39248802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3553976/"
] | It appears to me that the base method is an unnecessary burden, since it doesn't do anything and enforces rules that cannot be followed by all subclasses. Especially if it's called with different parameters under different circumstances, this method shouldn't be a part of the common API of `Admin_Module_Main` class.
My suggestion would be to delete the `beforeDelete()` method from `Admin_Module_Main`.
The alternative that doesn't require you to delete the base method would be to go through every subclass of `Admin_Module_Main` and make the parameters optional (plus the code that handles the default value in the optional parameter). This might be a better solution in case you don't know everything about the callers of `beforeDelete()` method. | One of the solution to avoid this error if you don't want to fix code in all classes is to change the error\_reporting level. Go to your php.ini configuration and update error\_reporting in a way like.
```
error_reporting = E_ALL & ~E_STRICT
```
or do in the code
```
error_reporting(E_ALL ^ E_STRICT);
```
E\_STRICT level is a reason why you see this error message. |
23,433,442 | I'm trying to solve the following problem:
Given a 3x3 grid with numbers 1-9, for example:
```
2 8 3
1 4 5
7 9 6
```
I have to sort the grid by rotating a 2x2 subgrid clockwise or counter-clockwise. The above example could be solved like this:
Rotate the top left piece clockwise:
```
2 8 3 1 2 3
1 4 5 => 4 8 5
7 9 6 7 9 6
```
Rotate the bottom right piece counter-clockwise:
```
1 2 3 1 2 3
4 8 5 => 4 5 6
7 9 6 7 8 9
```
The grid is now 'sorted'.
This IS a homework, but I'm just not getting this. Brute forcing didn't work; I have to be able to solve all given grids in <= 2000ms. One thing I tried was trying to calculate a value for all 8 possible next moves (rotate all 4 pieces in both directions), and then rotate the piece with the best value. This value was calculated by summing together all the distances of all the numbers from their correct places.
This worked for the above example, but more difficult ones are a no-go.
Could anyone point me into the correct direction? Where should I start? Does this problem have a name?
All grids are 3x3 and the rotating pieces are always 2x2.
Thanks in advance.
EDIT:
Forgot to mention the biggest thing: I have to find the smallest possible amount of turns that sorts the grid.
EDIT2:
I implemented a working algorithm with bits of advice from all the suggestion I've received. The annoying thing is, on my machine it runs the worst case scenario (987654321) in 1,5s, but on the server that tests the program it runs >2s, which means I still need to optimize. My working code as it is now
```
int find(int[][] grid) {
Queue q = new ArrayDeque<String>();
Map<String, Boolean> visited = new HashMap<String, Boolean>();
Object[] str = new Object[] { "", 0 };
for(int[] row : grid)
for(int num : row)
str[0] += Integer.toString(num);
q.add(str);
while(!q.isEmpty()) {
str = (Object[])q.poll();
while(visited.containsKey((String)str[0])) str = (Object[])q.poll();
if(((String)str[0]).equals("123456789")) break;
visited.put((String)str[0], Boolean.TRUE);
for(int i = 0; i < 4; i++) {
String[] kaannetut = kaanna((String)str[0], i);
Object[] str1 = new Object[] { (String)kaannetut[0], (Integer)str[1]+1 };
Object[] str2 = new Object[] { (String)kaannetut[1], (Integer)str[1]+1 };
if(!visited.containsKey((String)str1[0])) q.add((Object[])str1);
if(!visited.containsKey((String)str2[0])) q.add((Object[])str2);
}
}
return (Integer)str[1];
}
```
Can anyone come up with any optimizing tips?
EDIT3:
An implementation from the look-up table idea by Sirko, as I understood it:
```
import java.util.*;
class Permutation {
String str;
int stage;
public Permutation(String str, int stage) {
this.str = str;
this.stage = stage;
}
}
public class Kiertopeli {
// initialize the look-up table
public static Map<String, Integer> lookUp = createLookup();
public static int etsiLyhin(int[][] grid) {
String finale = "";
for(int[] row : grid)
for(int num : row)
finale += Integer.toString(num);
// fetch the wanted situation from the look-up table
return lookUp.get(finale);
}
public static Map<String, Integer> createLookup() {
// will hold the list of permutations we have already visited.
Map<String, Integer> visited = new HashMap<String, Integer>();
Queue<Permutation> q = new ArrayDeque<Permutation>();
q.add(new Permutation("123456789", 0));
// just for counting. should always result in 362880.
int permutations = 0;
Permutation permutation;
creation:
while(!q.isEmpty())
{
permutation = q.poll();
// pick the next non-visited permutation.
while(visited.containsKey(permutation.str)) {
if(q.isEmpty()) break creation;
permutation = q.poll();
}
// mark the permutation as visited.
visited.put(permutation.str, permutation.stage);
// loop through all the rotations.
for(int i = 0; i < 4; i++) {
// get a String array with arr[0] being the permutation with clockwise rotation,
// and arr[1] with counter-clockwise rotation.
String[] rotated = rotate(permutation.str, i);
// if the generated permutations haven't been created before, add them to the queue.
if(!visited.containsKey(rotated[0])) q.add(new Permutation(rotated[0], permutation.stage+1));
if(!visited.containsKey(rotated[1])) q.add(new Permutation(rotated[1], permutation.stage+1));
}
permutations++;
}
System.out.println(permutations);
return visited;
}
public static String[] rotate(String string, int place) {
StringBuilder str1 = new StringBuilder(string);
StringBuilder str2 = new StringBuilder(string);
if(place == 0) { // top left piece
str1.setCharAt(0, string.charAt(3));
str1.setCharAt(1, string.charAt(0)); // clockwise rotation
str1.setCharAt(4, string.charAt(1)); //
str1.setCharAt(3, string.charAt(4));
str2.setCharAt(3, string.charAt(0));
str2.setCharAt(0, string.charAt(1)); // counter-clockwise
str2.setCharAt(1, string.charAt(4)); //
str2.setCharAt(4, string.charAt(3));
}
if(place == 1) { // top right
str1.setCharAt(1, string.charAt(4));
str1.setCharAt(2, string.charAt(1));
str1.setCharAt(5, string.charAt(2));
str1.setCharAt(4, string.charAt(5));
str2.setCharAt(4, string.charAt(1));
str2.setCharAt(1, string.charAt(2));
str2.setCharAt(2, string.charAt(5));
str2.setCharAt(5, string.charAt(4));
}
if(place == 2) { // bottom left
str1.setCharAt(3, string.charAt(6));
str1.setCharAt(4, string.charAt(3));
str1.setCharAt(7, string.charAt(4));
str1.setCharAt(6, string.charAt(7));
str2.setCharAt(6, string.charAt(3));
str2.setCharAt(3, string.charAt(4));
str2.setCharAt(4, string.charAt(7));
str2.setCharAt(7, string.charAt(6));
}
if(place == 3) { // bottom left
str1.setCharAt(4, string.charAt(7));
str1.setCharAt(5, string.charAt(4));
str1.setCharAt(8, string.charAt(5));
str1.setCharAt(7, string.charAt(8));
str2.setCharAt(7, string.charAt(4));
str2.setCharAt(4, string.charAt(5));
str2.setCharAt(5, string.charAt(8));
str2.setCharAt(8, string.charAt(7));
}
return new String[] { str1.toString(), str2.toString() };
}
public static void main(String[] args) {
String grids = "2 8 3 1 4 5 7 9 6 "
+ "1 6 5 8 7 2 3 4 9 "
+ "1 6 5 8 7 2 3 4 9 "
+ "1 7 6 8 2 5 3 4 9 "
+ "8 1 5 7 4 6 3 9 2 "
+ "9 8 7 6 5 4 3 2 1 ";
Scanner reader = new Scanner(grids);
System.out.println();
while (reader.hasNext()) {
System.out.println("Enter grid:");
int[][] grid = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
grid[i][j] = reader.nextInt();
}
}
System.out.println(" Smallest: " + etsiLyhin(grid));
}
}
}
```
runs for about 1500-1600ms each time.
EDIT4: By following Sirko's advice I was able to cut the execution time down to 600ms. Here is the code as it is now:
```
import java.util.*;
class Permutation {
Byte[] value;
int stage;
public Permutation(Byte[] value, int stage) {
this.value = value;
this.stage = stage;
}
public Byte[][] rotate(int place) {
Byte[] code1 = value.clone();
Byte[] code2 = value.clone();
if(place == 0) { // top left piece
code1[0] = value[3];
code1[1] = value[0];
code1[4] = value[1];
code1[3] = value[4];
code2[3] = value[0];
code2[0] = value[1];
code2[1] = value[4];
code2[4] = value[3];
}
if(place == 1) { // top right
code1[1] = value[4];
code1[2] = value[1];
code1[5] = value[2];
code1[4] = value[5];
code2[4] = value[1];
code2[1] = value[2];
code2[2] = value[5];
code2[5] = value[4];
}
if(place == 2) { // bottom left
code1[3] = value[6];
code1[4] = value[3];
code1[7] = value[4];
code1[6] = value[7];
code2[6] = value[3];
code2[3] = value[4];
code2[4] = value[7];
code2[7] = value[6];
}
if(place == 3) { // bottom left
code1[4] = value[7];
code1[5] = value[4];
code1[8] = value[5];
code1[7] = value[8];
code2[7] = value[4];
code2[4] = value[5];
code2[5] = value[8];
code2[8] = value[7];
}
return new Byte[][] { code1, code2 };
}
public Integer toInt() {
Integer ival = value[8] * 1 +
value[7] * 10 +
value[6] * 100 +
value[5] * 1000 +
value[4] * 10000 +
value[3] * 100000 +
value[2] * 1000000 +
value[1] * 10000000 +
value[0] * 100000000;
return ival;
}
}
public class Kiertopeli {
// initialize the look-up table
public static Map<Integer, Integer> lookUp = createLookup();
public static int etsiLyhin(int[][] grid) {
Integer finale = toInt(grid);
// fetch the wanted situation from the look-up table
return lookUp.get(finale);
}
public static Map<Integer, Integer> createLookup() {
// will hold the list of permutations we have already visited.
Map<Integer, Integer> visited = new HashMap<Integer, Integer>();
Map<Integer, Boolean> queued = new HashMap<Integer, Boolean>();
Queue<Permutation> q = new ArrayDeque<Permutation>();
q.add(new Permutation(new Byte[] { 1,2,3,4,5,6,7,8,9 }, 0));
queued.put(123456789, true);
// just for counting. should always result in 362880.
int permutations = 0;
Permutation permutation;
creation:
while(!q.isEmpty())
{
permutation = q.poll();
// pick the next non-visited permutation.
while(visited.containsKey(permutation.toInt())) {
if(q.isEmpty()) break creation;
permutation = q.poll();
}
// mark the permutation as visited.
visited.put(permutation.toInt(), permutation.stage);
// loop through all the rotations.
for(int i = 0; i < 4; i++) {
// get a String array with arr[0] being the permutation with clockwise rotation,
// and arr[1] with counter-clockwise rotation.
Byte[][] rotated = permutation.rotate(i);
// if the generated permutations haven't been created before, add them to the queue.
if(!visited.containsKey(toInt(rotated[0])) && !queued.containsKey(toInt(rotated[0]))) {
q.add(new Permutation(rotated[0], permutation.stage+1));
queued.put(toInt(rotated[0]), true);
}
if(!visited.containsKey(toInt(rotated[1])) && !queued.containsKey(toInt(rotated[1]))) {
q.add(new Permutation(rotated[1], permutation.stage+1));
queued.put(toInt(rotated[1]), true);
}
}
permutations++;
}
System.out.println(permutations);
return visited;
}
public static Integer toInt(Byte[] value) {
Integer ival = value[8] * 1 +
value[7] * 10 +
value[6] * 100 +
value[5] * 1000 +
value[4] * 10000 +
value[3] * 100000 +
value[2] * 1000000 +
value[1] * 10000000 +
value[0] * 100000000;
return ival;
}
public static Integer toInt(int[][] value) {
Integer ival = value[2][2] * 1 +
value[2][1] * 10 +
value[2][0] * 100 +
value[1][2] * 1000 +
value[1][1] * 10000 +
value[1][0] * 100000 +
value[0][2] * 1000000 +
value[0][1] * 10000000 +
value[0][0] * 100000000;
return ival;
}
public static void main(String[] args) {
String grids = "2 8 3 1 4 5 7 9 6 "
+ "1 6 5 8 7 2 3 4 9 "
+ "1 6 5 8 7 2 3 4 9 "
+ "1 7 6 8 2 5 3 4 9 "
+ "8 1 5 7 4 6 3 9 2 "
+ "9 8 7 6 5 4 3 2 1 ";
Scanner reader = new Scanner(grids);
System.out.println();
while (reader.hasNext()) {
System.out.println("Enter grid:");
int[][] grid = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
grid[i][j] = reader.nextInt();
}
}
System.out.println(" Smallest: " + etsiLyhin(grid));
}
}
}
```
Huge thanks to Sirko and everyone else who gave me suggestions as well! | 2014/05/02 | [
"https://Stackoverflow.com/questions/23433442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1930935/"
] | A variant of the already proposed solution would be to generate a lookup table.
As already mentioned there are at most
```
9! = 362880
```
possible permutations for your matrix.
Each permutation can be represented using a 9-digit number containing each digit between 1 and 9 exactly once. We do this by reading the matrix rowwise, so, for example:
```
1 2 3
4 5 6 => 123456789
7 8 9
4 8 6
1 5 3 => 486153729
7 2 9
```
Starting from this, we could use a simple recursive program to precalculate the number of permutations necessary for each matrix by starting with the solution and generate all permutations. While doings so, we remember how much rotations it took us, to get to a specific permutation. We use a lookup table to store our results and a stack to store the nodes, we still need to process. In the stack we use pairs `{ node, distance to solution }` and initialize it with the pair `{ 123456789, 0 }`, which describes the sorted starting node.
```
lookup = [];
queue = [ { 123456789, 0 } ]:
while( there is a node in the queue ) {
take the first node out of the queue
// skip nodes we already processed
if( !(node in lookup) ) {
generate all permutations possible by using 1 rotation starting form node
push all generated nodes to the queue using a distance + 1
}
}
```
Afterwards we can answer for all given matrices by just a doing lookup in our result.
By having the queue always sorted by the distance to the solution, we ensure to find the shortest path. If there was no such ordering, we might find a longer path first and drop shorter ones later on.
---
One could further optimize the algorithm:
* Introduce another lookup, which signals, that a node as already been added to the queue. That way we would decrease the size of the queue drastically. | >
> *I apologize for writing a new answer, but I can't comment on invin's answer (due to not having 50 reputation) so I had to do it here.*
>
>
>
This BFS algorithm could be additionally optimized by making sure you're not expanding from any already visited states.
With [factoradic](http://en.wikipedia.org/wiki/Factoradic) you can represent any possible state with a number between 1 and 9! (362880). You can use a simple bool array (size 362880) to keep track if you have already visited a state before in the BFS. You only expand into non-visited states which I believe would drastically reduce the operation time in cases with bigger steps. |
547,255 | In a frictionless environment, why doesn't an object move at infinite acceleration if force is applied on it?
Force causes movement, so unless there is an opposing force there shouldn't be any reason for the force to cause infinite acceleration. | 2020/04/27 | [
"https://physics.stackexchange.com/questions/547255",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/262090/"
] | Because in a no friction environment an object obeys Newton's second law when a force is applied to it,
$$F=ma \tag{1},$$
the acceleration is decided by the mass of the object. When you apply a force to an object its mass decides how much it "resists" being moved by the force. | With light you could apply a force on a body, see [radiation pressure](https://en.wikipedia.org/wiki/Radiation_pressure) on Wikipedia.
No other particles respectively bodies are moving faster than light, at least we haven't found any other.
Even if you can run at no more than 30 km/h, you can throw a ball with your arms at a higher speed. But such an addition of speeds is impossible for photons. Photons can neither push nor accelerate other photons, light cannot move faster than 300,000 km/h. |
97,350 | I was reading a blogpost here: <http://mzargar.wordpress.com/2009/07/19/cauchys-method-of-induction/> ([Wayback Machine](http://web.archive.org/web/20120309055020/https://mzargar.wordpress.com/2009/07/19/cauchys-method-of-induction/))
One thing that threw me off was that after the first four large displayed equations, there is the statement "it is sufficient to prove that if the theorem holds for $n=m+1$, then it holds for $n=m$."
How is this type of induction valid? I browsed around for things like backward induction, reverse induction, and Cauchy induction, but couldn't find a justification for how this is valid.
With the usual forward induction of verifying a base case and proving $P(n)\implies P(n+1)$, it's easy to intuitively understand how induction will show a property holds for all natural numbers (or at least starting at the base case). But with this reverse induction, it seems to me that if you prove $P(m+1)\implies P(m)$, then if you were able to verify a specific case like $P(15)$, then you would only know it's true for numbers up to $15$. How does it actually prove the property for all naturals? | 2012/01/08 | [
"https://math.stackexchange.com/questions/97350",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/22569/"
] | **Hint** $\ $ This can be viewed as a sort of *interval* (or *segment*) induction.
**Lemma** $\rm\ S\subset \mathbb N\:$ satisfies $\rm\:n+1\in S\:\!\Rightarrow n \in S\:$ iff $\rm\:S\:$ is an initial segment of $\:\mathbb N$
**Proof** $ $ (hint) $ $ If $\rm\:S\ne \mathbb N\:$ then $\rm\:S = [0,m)\:$ for the least $\rm\:m\not\in S,\:$ since by induction, nonmembership ascends from $\rm\:m\:$ by $\rm\:n\not\in S\:\Rightarrow\:n+1\not\in S.\:$
**Corollary** $ $ If, additionally, $\rm\:S\:$ is unbounded then $\rm\:S = \mathbb N$
In your case $\rm\: S\ne \{\ \}\:$ is unbounded via the hypothesis $\rm\:n\in S\:\Rightarrow\:2\:\!n\in S.$ | You seem to be confused with the method of infinite descent which is used to prove that something is FALSE :
If $P(0)$ is false and if $P(n)$ implies that there exists a $m < n$ such that $P(m)$, then $P(n)$ is false for all $n$.
This correspond to prove the anteposition of the standard recurrence principle. (The anteposition of an implication $A\Rightarrow B$ is $\text{not} B \Rightarrow \text{not} A$.) |
16,648,602 | Today I was investigating on something with Fiddler, when I noticed that, when I launch Google Chrome, I have always 3 HEAD requests to some domains which seem to be randomly chosen.
Here is a sample :
```
HEAD http://fkgrekxzgo/ HTTP/1.1
Host: fkgrekxzgo
Proxy-Connection: keep-alive
Content-Length: 0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Accept-Encoding: gzip,deflate,sdch
```
Do you have any idea of why Google Chrome behaves this way ?
Thanks guys | 2013/05/20 | [
"https://Stackoverflow.com/questions/16648602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1814670/"
] | This is Chrome checking to see if your ISP converts non-resolving domains into your.isp.com/search?q=randomnonresolvingdomain
See <https://mikewest.org/2012/02/chrome-connects-to-three-random-domains-at-startup> | This algorithm seems unusable with forward proxy servers. Browser definitely asks for random page and proxy definitely returns some page -- error (50x), masked error (50x or 40x) or nice "you are lost" page with HTTP code 200 . |
1,263,074 | I've got a very simple html unordered list:
```
<ul>
<li>First</li>
<li>Second</li>
</ul>
```
The problem is that the default styling for such a list in firefox leaves a lot of space between each list item - about the same as between paragraphs in a `<p>` tag. My google-fu is proving uncharacteristically useless today - how do I reduce that vertical space? I assume there's a css element I can apply to the `<ul>` tag, but I can't seem to find anything.
(This is going in the side navigation element of a page so it needs to be as compact as possible.) | 2009/08/11 | [
"https://Stackoverflow.com/questions/1263074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] | The properties margin and padding are the correct approach.
I want to add the advice to reset your complete css with a predefined reset-css-file, like this one by Eric Meyer: [Link](http://meyerweb.com/eric/tools/css/reset/index.html)
After this you have the option to control your styles more specified. | ```css
ul {
font-size: 0;
}
ul li {
display: inline;
font-size: 16px;
}
```
Always works! |
10,555,288 | I am parsing a large text file and then calling a rate-limited Google API (mail migration) (The api docs state 1 second per call).
Even when I have Utilities.sleep(1000); inside my loop, I'm still getting this error even though I'm only setting the property one time during the loop:
>
> Service invoked too many times in a short time: properties rateMax. Try Utilities.sleep(1000) between calls. (line 146)
>
>
>
Other than not setting the properties that often, what can I do to alleviate this? Should I instead try to use the CacheService to store my property transiently? | 2012/05/11 | [
"https://Stackoverflow.com/questions/10555288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389683/"
] | Unfortunately the exact short term rate limits aren't exposed. You may want to try to increase your sleep amount, in the hopes of going above the threshold necessary to avoid the error. Ultimately I think your analysis is correct, that you should look into writing to the user properties less often. I'm not sure the CacheService is the right solution, but it depends on how you are using the information. | It really depends on the design of your app. If you are parsing the information and can aggregate that into a summary it would take less calls. Maybe sending as an email is not optimal. Could the parsed data go somewhere else and then direct the user there instead of sending emails? |
12,168,236 | I have for one customer entity multiple viewmodels depending on the existing views like Create,Update,Get,Delete. These viewmodels share the same properties up to 75% with the entity.
Should I better merge all the customer viewmodels to one big viewmodel?
So I have to map only and always from one entity to one viewmodel and the way back?
Do you see any disadvantage in flexibility for certain scenarios I have not in my mind now? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12168236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401643/"
] | As said in other answers, you should set the 'selected' option.
What some people don't mention is that your selected array should only contain the id in each element.
Example:
```
$selectedWarnings = $this->Warning->find('list', array(
'fields' => array('id')
));
echo $this->Form->input('email_warning_chb', array(
'label' => 'Email Notice',
'type' => 'select',
'multiple' => 'checkbox',
'options' => $warnings,
'selected' => $selectedWarnings
));
``` | in your controller you have to put the value like this:
```
$this->request->data['Model']['email_warning_chb'] = array(5,15,60);
```
and it will automatically display checkbox as selected.
Please ask if not work for you. |
771,819 | After installing my program on a windows vista premium, I'm getting the following exception.
The view that must be shown contains following controls: 2 textboxes, 3 labels, a button and linkbutton.
```
System.OutOfMemoryException: Out of memory.
at System.Drawing.Graphics.FromHdcInternal(IntPtr hdc)
at System.Windows.Forms.PaintEventArgs.get_Graphics()
at System.Windows.Forms.Control.PaintException(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.OnPrint(PaintEventArgs e)
at System.Windows.Forms.Control.WmPrintClient(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
```
Somebody had the same issue? How to solve it? | 2009/04/21 | [
"https://Stackoverflow.com/questions/771819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60572/"
] | Does your app make use of any custom controls or controls you've written yourself? Can you repro this problem with a very simple form?
This...
<http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/4bc34266-edf9-430c-ad5a-c6e29392eb2d>
... and this...
<http://social.expression.microsoft.com/Forums/zh-CN/netfxbcl/thread/7c4d2e73-6e73-4f10-a614-13fd76b2f419>
... appears to be a similar problems. However they generally talk about custom controls that are failing to dispose object (and, as such, leak GDI handles).
Is it possible that somewhere else in your app you're leaking handles? | Might it be possible that you only detected this on a Vista box because there is less free memory than on your Windows XP boxes? If the machines are roughly the same spec then I would guess the Vista box would have less memory free and therefore highlight issues with memory leaks more quickly.
The other possibility is that you are trying to render too much, as the call stack states there is a scrollable control, is it possible you are rendering a bunch of stuff that isn't actually visible? |
1,098,372 | I am having a disaster. My Ubuntu can not boot. The problem is summarised [here](https://askubuntu.com/questions/1098366/ubunut-18-04-failed-to-boot-faile-to-start-mysql-community-server)
I read about Ubunut recovery mode. I followed these [instructions](https://wiki.ubuntu.com/RecoveryMode). I selected `Drop to root shell promot`. I got a shell in the bottom. It has the followign text:
```
Press Enter for maintenance
(or press Contol-D to continue):
root@mypc-name:~#
```
There is a cursos blinking. When I type `pwd` it prints: `/root`
I need to recover my data to an external hard disk. Please help me in a step by step. I use Ubuntu in GUI. I use the terminal but I have no experience in mounting and working with hard disks and moving data using the shell.
Please note that I have 0 Bytes available in my hard disk. | 2018/12/04 | [
"https://askubuntu.com/questions/1098372",
"https://askubuntu.com",
"https://askubuntu.com/users/836841/"
] | Thanks to those tried to help. I solved the issue by following the same steps in the question to use recovery mode. Then I choose `Clean` (instead of `Drop to root shell prompt`). This provided few hundreds MB which allowed me to boot. | I can't make comments, but I want to help anyway.
You should try booting a live ubuntu disc/USB and select "Try without installing".. You'll get a fully working environment and automounting for your HDD and external drives. While at it you can delete at least a couple files to make some room and you'll be able to boot again |
89,357 | I have an odd situation: I have a coworker who acts like he's my boss. I've already confirmed with higher-ups that it's just not true.
He'll say all kinds of things like:
>
> *This is my department*.
>
> *I run this department*.
>
> *This is MY analyst*. (referring to me)
>
> *I need to decide how to manage your schedule*.
>
> *I'll need to decide if I'm going to let you do xyz*.
>
> *If you need him (me) to do something, talk to me first, so I can manage his time.*
>
>
>
As far as I can tell, he's mainly doing this when other people can hear. He's not even saying anything constructive.
When people walk into the room, a switch goes off, and he'll just start posturing to make himself appear to be my manager.
>
> I told you to do this... I told you to do that.
>
>
>
Finger pointing everywhere... He's just screaming nonsense that has nothing to do with anything just to put on a show. Then, when people leave the room, he flips the switch off and goes back to normal.
I'm pretty sure he's doing it when I'm not around as well.
It's getting very irritating. I pretty much don't even like to talk to him anymore. Every time he comes to talk to me, it's just a useless waste of my time, just so he can posture.
Any suggestions on how to handle this? I've had people come to me because they're confused, and I'm having to correct them. But it would be awkward if I kept going around correcting everyone. Every time he does it, I need to shower off the layer of slime just being near that. I'm not too into screaming matches; they're not my style.
Edit: Someone mentioned that this is the same problem as another post, where someone is just being bossy. This situation is different. Being bossy isn't the same as trying to convince others that you are management. Being bossy is a personality trait. Trying to convince others that you are management is dishonest. | 2017/04/18 | [
"https://workplace.stackexchange.com/questions/89357",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/68769/"
] | >
> Any suggestions on how to handle this?
>
>
>
You need to be a bit more assertive here and put him in his place without going over the top.
Take him aside and have a private, calm talk. Something like "X, we both know that you are not my boss. Let's stop pretending that you are, okay?" should help.
And the next time he says something to others in front of you implying that he is your boss, roll your eyes and say loudly "Now, now X. We've talked about this before. You have to stop pretending that you are my boss."
And don't ever respond to him as you would to a boss. Don't accept assignments from him but only from your actual boss.
Do those a few times and hopefully he will stop.
If not, it's time to have a talk with your boss. Tell your boss what you have tried so far, that it hasn't worked, and that you would now appreciate some intervention. | I was once like a milder version of your coworker! Not that creepy, bossy or old but just 2 years in my job I enjoyed delegating work to my junior colleagues. It took just couple of subtle hints from them that they did not appreciate me asking them to do something.
Point is that this has to be communicated to your coworker somehow. Either directly by you or through your manager.
You can first try to give hints yourself like referring to your boss every time he tries to be your boss like `is this coming from X?` or `I will need to check with X` first. (X being your boss).
If these type of hints do not work, then you can be more direct and say `Did X ask you to supervise or mentor me? If so, I will like to understand your role directly from them.`
If you still face the issue then best is to directly speak to your manager and express your concerns. You have to handle this carefully though because this escalation may result in some unnecessary confrontation and miscommunication. So make sure you do not accuse him of anything but just express concern about you are not clear what is his role.
However way you decide, your coworker needs to know in a gentle way that you do not like his behavior around you. |
3,511,758 | Is there any way to remove the minus sign when in editing mode and displaying only the reorder icon?
Trying since long time. Somehow succeeded in removing the indentation of table but still failed to remove the minus sign.
Also i want the reorder icon appear permanently on screen so the table view will always be in editing mode
Is there any option to do this???Please help.... | 2010/08/18 | [
"https://Stackoverflow.com/questions/3511758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363363/"
] | This is not surprising at all.
Your first constructor seems ok, the second one does miss the allocation for v.
Edit: v1 = x and v2 = y doesn't make sense without overloading operator=. | I hope this is homework!
Otherwise you should be using std::Vector
Couple of problems:
* A constructor should initialize all members.
+ Neither constructor does this.
* The copy constructor (or what seems to be) is not defined incorrectly.
* Because your class manages a RAW pointer you need to see "The rule of three"
+ ie you are missing the assignment operator
* Prefer to use initializer lists when you can |
66,693,229 | I have an array as follows
```
[0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']]
```
I need to remove the elements with classId 2 or 4 from array and the expected result should be
```
[0=>['classId'=>3,'Name'=>'Doe']]
```
How will i achieve this without using a loop.Hope someone can help | 2021/03/18 | [
"https://Stackoverflow.com/questions/66693229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6654773/"
] | You can use `array_filter` in conjunction with `in_array`.
```
$array = [0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']];
var_dump(
array_filter($array, function($item){return !in_array($item["classId"], [2,4]);})
);
```
Explanation
-----------
**`array_filter`**
Removes elements from the array if the call-back function returns false.
**`in_array`**
Searches an array for a value; returns boolean true/false if the value is (not)found. | Try this:
```
foreach array as $k => $v{
if ($v['classId'] == 2){
unset(array[$k]);
}
}
```
I just saw your edit, you could use array\_filter like so:
```
function class_filter($arr){
return ($arr['classId'] == "whatever");
}
array_filter($arr, "class_filter");
```
Note: you'll still need to loop through a multi-dimensional array I believe. |
1,373 | Can i configure Tridion 2011 SP1 to publishing over FTPS protocol (FTP over SSL)? | 2013/05/21 | [
"https://tridion.stackexchange.com/questions/1373",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/175/"
] | As mentioned already, your requirements match exactly what the Media Manager Connector is designed to do.
I do not know what the "Stub schema component" you refer to is. Basically MMC will create stub components (one for each distribution you for example link to), and a single schema that will be used by the stub components.
It's not clear to me what you mean with "the direct link from the Distribution Details window within Media Manager" either. This could refer to being logged into the SDL Media Manager UI, or browsing inside a node called Media Manager in the Tridion navigation tree, so please be very specific on what system you see various behavior on.
Some general comments, most of them already covered by others but there are a few things not covered already so I'll keep it combined here.
When configuring Media Manager, first make sure the users can navigate the Media Manager distributions from within the Tridion navigation tree directly (so in the main Tridion window, not in a component select window). Generally for this to work, the following must be the case:
1. The mount point must be configured at the same level or higher in
the BluePrint than the publication being browsed
2. The user must have at least read access to the folder configured (in the mount
point configuration) to hold the stub schema and stub components.
Now open a distribution from within Tridion. Go to the Info tab and select the "Open in xxx" button at the top of the tab page (xxx will be the name of you root node as specified in the mount point configuration). This should open the Media Manager UI with the relevant distribution selected. If this is not working, it can be an SDL Media Manager service configuration problem - if you can't determine this on your own, check the External Content Library log files on the Tridion system and post the exception details here (to make it simple delete the log, then reproduce the error - that way the log will not contain a lot of irrelevant data).
If it is a Media Manager service configuration problem it can only be resolved by SDL support. If you can't open the Media Manager UI this way you might still be able to link to Media Manager items but most likely they will not work when publishing or previewing.
Once this is working check the user can select the media when browsing for content.
1. First check the mount point shows up and distributions can be selected when inserting images into a rich text field. This is a good starting point as it does not require any further configuration
2. Then check your multimedia link. Make sure you assign the schema as a valid target for the multimedia link (as already mentioned).
Notice that any change to the mount point configuration you make should be followed by:
1) Restart the TcmServiecHost process
2) Close all client side bwowser windows or tabs with Tridion. Refreshing the Tridion window will NOT work if you happen to have another Tridion window open (even if it is just for example a component you have open). You can probably get away with refreshing specific lists from within the Tridion UI, but it is not always trivial to find out where a list is cached so if you have problems always resort to close all windows. | ECL, which is what is used for the Media Manager Connector, currently does not have a separate Schema for each sub-type. Which means that you can only create a link (by using the ECL stub Schema) to all of the items that your ECL provider contains.
The ECL stub Schema is created in the stub folder you set under the `StubFolder` element in your `ExternalContentLibrary.xml` configuration file. The [documentation](http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_ECLMediaManager_11/task_11_2DDAFF2CF95E4430AA0F27AD7A91B5F8) ([requires login](http://docportal.sdl.com/sdltridion)) mentions it as `ExternalContentLibraryStubSchema` but in your stub Schema Folder it will probably be something like: `ExternalContentLibraryStubSchema-mm` (where `mm` stands for Media Manager, or more specifically the value of the `id` attribute in the Media Manager MountPoint).
It unfortunately is not an option to try and rename that ECL stub Schema, because ECL prevents you from doing that. So you will have to live with a less descriptive name than something like Media Manager would be. But you should be able to configure your video link in your Article Schema correctly at least (in short, yes it is possible to deliver your requirements). |
249,887 | Is it possible to view 2 apps at the same, eg. 2 × Mail, in Split View? | 2016/08/19 | [
"https://apple.stackexchange.com/questions/249887",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/197019/"
] | **This is not possible in iOS 9.** Only one instance of an app can run at any given time.
There is a small change in iOS 10 allowing two instances of **Safari** to run concurrently, but that is a special case. To do that, long-press a link, and select `Open in Split View`. | This can be done only on a newer **iPad** or **iPhone 6 Plus**. running **iOS 9 or higher**. You will notice that these apps are not contained into 1 app, they are each running independently of the other. You can view each app and interact with each app but they can't communicate with each other (other than what's already allowed by the app itself).
[](https://i.stack.imgur.com/Eu4y6.jpg) |
15,103,944 | I'm a java novice. Is it possible to get data from a website and then store it in some sort of data structure? For example, the program gets the value of a stock from yahoo finance at a given time and stores it. Like I said, I'm not that proficient with Java and I'd like to know if this could be done. If it can be, is it very hard to do it? | 2013/02/27 | [
"https://Stackoverflow.com/questions/15103944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2113277/"
] | I've used [JSoup](http://jsoup.org/) extensively. If you only need to customize a program to extract data from a website whose layout or structure does not change often, `JSoup` would be enough and handy.
Assuming you know the basics about how to program(not necessarily familiar with `Java`) and understand what constitutes the Web(e.g., what is `html`,`dom`,etc), I'd expect you to pick up how to do Web scraping with `JSoup` pretty quick. | Yes you can download arbitrary web page into a Java string and parse the contents, however such solution wouldn't be reliable. If the author changes the structure of the website your code would immediately break.
Popular way of doing such integration is by [RESTful web service](http://en.wikipedia.org/wiki/Representational_state_transfer). The data provider would have a set of URL & parameters which you can call, and returns the stock price data (in xml or JSON format) |
47,194,100 | When I add behavior='autocomplete' to my input field, width is changing and not scaling anymore with browser/screen resize.
Someone experienced with easyAutocomplete has the same problem?
Thank you very much.
This code without data-behavior IS RESPONSIVE
```
<form>
<input class="form-control" type="text" placeholder="search">
</form>
```
This code with data-behavior="autocomplete" is NOT RESPONSIVE
```
<form>
<input class="form-control" type="text" placeholder="search" data-behavior="autocomplete">
</form>
```
<http://easyautocomplete.com> - jQuery autocomplete plugin | 2017/11/09 | [
"https://Stackoverflow.com/questions/47194100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8152465/"
] | You can use easy-autocomplete like below, no need to put data-behavior.
Also, you need to override CSS applied by the easy-autocomplete library.
```js
var options = {
data: ["blue", "green", "pink", "red", "yellow"]
};
$("#example").easyAutocomplete(options);
```
```css
.easy-autocomplete{
width:100% !important
}
.easy-autocomplete input{
width: 100%;
}
.form-wrapper{
width: 500px;
}
```
```html
<link href="https://unpkg.com/easy-autocomplete@1.3.5/dist/easy-autocomplete.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/easy-autocomplete@1.3.5/dist/jquery.easy-autocomplete.js"></script>
<form class="form-wrapper">
<input id="example" class="form-control" type="text" placeholder="search">
</form>
``` | With your jQuery easyautocomplete plugin you just need to set option adjustWidth to false and then you don’t need to touch your CSS.
```
var options = {
...
adjustWidth: false,
...
};
$("#example").easyAutocomplete(options);
``` |
50,655 | ***Doctor Who*** has a long history of multi episode stories, sometimes two or three in a row. Series 9 of New Who has a couple (1/2, 3/4, 7/8).
But I can't seem to confirm if episode 5 "***The Girl Who Died***" and Episode 6 "***The Woman Who Lived***" are a two part story. They both focus on Ashildr, later self-named as Lady *Me*. Had they not been sequentially aired, then I wouldn't consider them a two-parter, but their airing implies it. The later Series 9 episodes 11 and 12 (Heaven Sent, Hell Bent) also seem like a two-parter, but its mostly superficial themes and the titles.
Is there any proof either way about episode 5 and 6 being a two-parter? | 2016/03/23 | [
"https://movies.stackexchange.com/questions/50655",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/23541/"
] | Officially, yes and no.
-----------------------
Before the series started airing, pre-production publicity said that *The Girl Who Died* and *The Woman Who Lived* would be two parts of the same story, although a more loosely linked two-parter than many of the others in the series. From [this article](http://www.digitalspy.com/tv/doctor-who/feature/a647843/doctor-who-series-9-everything-we-know-so-far/) from August 2015 (emphasis mine):
>
> Details have so far emerged about **8 episodes, divided into 4 two-parters** - though Moffat has noted that some of these dual episodes are "just linked" rather than adopting the traditional two-part format.
>
>
> "**It's not just two-parters - it's occasionally taking one strand and keeping it going**," he explained. "There's two-parters where the episodes are quite different, two-parters that are quite traditional - just to change the rhythm of it."
>
>
>
Later on in the same article, it's confirmed that *The Girl Who Died* / *The Woman Who Lived* is one of those loosely connected two-parters:
>
> **Episodes 5 & 6 - 'The Girl Who Died' / 'The Woman Who Lived'**
>
>
> The first example of a non-traditional two-parter - these two linked instalments are penned by different writers, with Moffat and 'Flatline' scribe Mathieson working together on episode 5, and episode 6 penned solo by *Torchwood*'s Tregenna.
>
>
> These two episodes were shot together in one production block, but since they might only be loosely connected, it's unclear which cast members will appear in episode 5 and which will appear in 6 - or indeed, if the entire cast will appear in both.
>
>
>
All the above suggests that these two episodes *are* considered to form a two-parter. However, the BBC Blog page found by @Richard in [his answer](https://movies.stackexchange.com/a/50661/27759) suggests that they *aren't*. So as far as official word goes, you can choose what you want to believe.
In practice, no.
----------------
The stories of these two episodes are entirely different and linked only by a single character. In my view, they're no more strongly linked to each other than to *Face the Raven* - which in turn of course is linked to *Heaven Sent* and *Hell Bent*, so at that point we'd be looking at a five-parter story. Much better to consider *The Girl Who Died* and *The Woman Who Lived* as stand-alone episodes which both feature a recurring character of Series 9.
My view is shared by several more official reviewers. For instance, in an article published January 2016, [Doctor Who Magazine editor Tom Spilsbury said](http://www.doctorwhomagazine.com/):
>
> Controversially (perhaps), we've *[at the magazine]* decided not to combine The Girl Who Died and The Woman Who Lived, or Face the Raven, Heaven Sent and Hell Bent – as despite their linked nature, the individual styles of each episode meant that we couldn't really consider them as true multi-parters, and we didn't want to short change readers by forcing you to give a combined score.
>
>
>
And the [reviews](http://www.screennerds.blogspot.co.uk/2015/10/doctor-who-s9e5-girl-who-died-review.html) [written](http://www.screennerds.blogspot.co.uk/2015/10/doctor-who-s9e6-women-who-lived-review.html) by our own [Dr R Dizzle](https://movies.stackexchange.com/users/8686/dr-r-dizzle) also reflect the view that these episodes aren't really a proper two-parter. From his blog (emphasis mine):
>
> "The Girl Who Died" has a straight forward beginning, middle and end, a complete narrative that only introduces the fact that it is a two-parter after the main story of the episode has been told.
>
>
> ["The Woman Who Lived"] coming immediately after "The Girl Who Died" makes these two episodes feel like a poorly linked two-parter rather than **the related but firmly singular episodes that they should be seen as**.
>
>
> | "The Girl Who Died" and "The Woman Who Lived" are not a two-parter and neither are "Heaven Sent" and "Hell Bent". Steven Moffat confirmed in DWM that the episodes are standalones.
"Heaven Sent" and "Hell Bent" were produced separately and did not have a TBC. While "The Girl Who Died" had a TBC, that doesn't necessarily indicate a two-parter, there was a TBC at the end of "The Almost People" and "The Name of the Doctor". "The Woman Who Lived" had no previously, which every two-parter ever has had. "The Girl Who Died", "The Woman Who Lived", "Heaven Sent" and "Hell Bent" all had a beginning, a middle and an end, which is not the case with two-parters. "The Girl Who Died" and "The Woman Who Lived" had different writers, having the same writer is a basic requirement for a two-parter.
Just think about like this, if you take out the final moments of each of the episodes, there is little to no continuation. |
59,532,087 | The below code works in scala-spark
```
scala> val ar = Array("oracle","java")
ar: Array[String] = Array(oracle, java)
scala> df.withColumn("tags",lit(ar)).show(false)
+------+---+----------+----------+--------------+
|name |age|role |experience|tags |
+------+---+----------+----------+--------------+
|John |25 |Developer |2.56 |[oracle, java]|
|Scott |30 |Tester |5.2 |[oracle, java]|
|Jim |28 |DBA |3.0 |[oracle, java]|
|Mike |35 |Consultant|10.0 |[oracle, java]|
|Daniel|26 |Developer |3.2 |[oracle, java]|
|Paul |29 |Tester |3.6 |[oracle, java]|
|Peter |30 |Developer |6.5 |[oracle, java]|
+------+---+----------+----------+--------------+
scala>
```
how do I get the same behavior in pyspark?. I tried below, but it doesn't work and throws Java error
```
>>> from pyspark.sql.types import *
>>> tag=["oracle","java"]
>>> df2.withColumn("tags",lit(tag)).show()
```
Error
```
: java.lang.RuntimeException: Unsupported literal type class java.util.ArrayList [oracle, java]
``` | 2019/12/30 | [
"https://Stackoverflow.com/questions/59532087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6867048/"
] | I found the below list comprehension to work
```
>>> arr=["oracle","java"]
>>> mp=[ (lambda x:lit(x))(x) for x in arr ]
>>> df.withColumn("mk",array(mp)).show()
+------+---+----------+----------+--------------+
| name|age| role|experience| mk|
+------+---+----------+----------+--------------+
| John| 25| Developer| 2.56|[oracle, java]|
| Scott| 30| Tester| 5.2|[oracle, java]|
| Jim| 28| DBA| 3.0|[oracle, java]|
| Mike| 35|Consultant| 10.0|[oracle, java]|
|Daniel| 26| Developer| 3.2|[oracle, java]|
| Paul| 29| Tester| 3.6|[oracle, java]|
| Peter| 30| Developer| 6.5|[oracle, java]|
+------+---+----------+----------+--------------+
>>>
``` | There is difference between `ar` declare in `scala` and `tag` declare in `python`. `ar` is `array` type but `tag` is `List` type and `lit` does not allow `List` that's why it is giving error.
You need to install `numpy` to declare `array` like below
```
import numpy as np
tag = np.array(("oracle","java"))
```
Just for reference if you use `List` in `scala`, it will also give error
```
scala> val ar = List("oracle","java")
ar: List[String] = List(oracle, java)
scala> df.withColumn("newcol", lit(ar)).printSchema
java.lang.RuntimeException: Unsupported literal type class scala.collection.immutable.$colon$colon List(oracle, java)
at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:78)
at org.apache.spark.sql.catalyst.expressions.Literal$$anonfun$create$2.apply(literals.scala:164)
at org.apache.spark.sql.catalyst.expressions.Literal$$anonfun$create$2.apply(literals.scala:164)
at scala.util.Try.getOrElse(Try.scala:79)
at org.apache.spark.sql.catalyst.expressions.Literal$.create(literals.scala:163)
at org.apache.spark.sql.functions$.typedLit(functions.scala:127)
at org.apache.spark.sql.functions$.lit(functions.scala:110)
``` |
33,750,760 | Today i come across the peculiar behaviour of equlaity operator.
I’d expect the answer to be false. We’re testing for reference equality
here, after all – and when you box two values, they’ll end up in different boxes, even if the values are the same, right
```
Object x = 129;
Object y = 129;
boolean equality = (x == y);
System.out.println(equality);
```
OUTPUT : FALSE
```
Object x = 12;
Object y = 12;
boolean equality = (x == y);
System.out.println(equality);
```
OUTPUT : TRUE
Can some one help me understanding why this is behaving like this. | 2015/11/17 | [
"https://Stackoverflow.com/questions/33750760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848411/"
] | == is a reference comparison. It looks for the "same" object instead of "similar" object.
Since values between -128 to 127 are returned from cache and the same reference is returned, your second comparison returns true.
But values above 127 are not returned from cache so the reference differs and your first comparison returns false.
Good question btw :) | It is always recommended to use `object1.equals(onject2)` to check for equality because when you compare using **`==`** it is **reference comparison** and not comparison of value. |
30,676,949 | I have an olap cube which i want to access. I am trying to execute mdx query. here is my simple test program:
```
static void Main(string[] args)
{
using (OleDbConnection cn = new OleDbConnection())
{
cn.ConnectionString = "secret";
cn.Open();
string MDX = "SELECT [Measures].[Amount] "+ " ON ROWS, " + "[Dim Client].[Common Client Name].&[test Name] "+ " ON COLUMNS " + "from [CubeName];";
OleDbCommand command = new OleDbCommand(MDX, cn);
System.Data.DataSet ds = new System.Data.DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter(command);
adp.Fill(ds);
Console.WriteLine(ds.Tables[0].Rows[0][1]);
}
}
```
I am keep getting following error : `Incorrect syntax near the keyword 'ON'.` and i cant figure out what i am doing wrong. If i execute exact same query directly from management studio, cube response without errors. | 2015/06/05 | [
"https://Stackoverflow.com/questions/30676949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/899039/"
] | Please try:
```
db.counters('counters').findAndModify
```
instead of:
```
db.collection['counters'].findAndModify
``` | From the mongodb docs:
>
> Existing collections can be opened with collection
>
>
>
> ```
> db.collection([[name[, options]], callback);
>
> ```
>
> If strict mode is off, then a new collection is created if not already
> present.
>
>
>
So you need to do this:
```
db.collection('counters', function(err, collection){
collection.findAndModify({
query: {
name: 'comments'
},
update: {
$inc: {
counter: 1
}
},
new: true
}, function(err, doc) {
if (err) throw err;
if (!doc) {
console.dir('No counter found for comments.');
} else {
console.dir('Number of comments: ' + doc.counter);
}
});
});
``` |
48,754,073 | I know that this question has been asked a lot but I can't seem to find an answer I am looking for. I am getting this error:
```
Uncaught TypeError: $(...).find(...).hasClass(...).val is not a function
at attach_selectors (commercial.js:768)
at HTMLDocument.<anonymous> (commercial.js:117)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
at Function.ready (jquery-1.11.0.min.js:2)
at HTMLDocument.K (jquery-1.11.0.min.js:2)
```
I understand it has something to do with the val() but if anyone can point me in the right direction that would be great. Do I need to create a new function?
```css
var stInput=$("form").find("input").hasClass("st-search").val();
$("#submitSearch").off("click").on("click", function(e) {
e.preventDefault();
$(".gsc-search-button").find(stInput).click();
}
);
```
```html
<form class="st-search">
<div class="gcse-search"><input type="text" class="st-default-search-input" placeholder="Search..." />
<xsl:text> </xsl:text>
</div>
<button class="btn btn-secondary-bel gsc-search-button gsc-search-button-v2" id="submitSearch" title="search">Search</button>
</form>
``` | 2018/02/12 | [
"https://Stackoverflow.com/questions/48754073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9351580/"
] | `hasClass` returns either `true` or `false` which doesn't have a `val` function. Perhaps you want to adjust your selector to `$('form.st-search')`? | **This line returns a boolean rather than a jQuery object**
```
var stInput = $("form").find("input").hasClass("st-search");
```
**Probably you want to do this:**
```
var stInput = $("form").find("input").val();
``` |
28,364,676 | I want to have a function, in Python (3.x), which force to the script itself to terminate, like :
```
i_time_value = 10
mytimeout(i_time_value ) # Terminate the script if not in i_time_value seconds
for i in range(10):
print("go")
time.sleep(2)
```
Where "mytimeout" is the function I need : it terminate the script in "arg" seconds if the script is not terminated.
I have seen good solutions for put a timeout to a function [here](https://code.google.com/p/verse-quiz/source/browse/trunk/timeout.py) or [here](https://stackoverflow.com/questions/13821156/timeout-function-using-threading-in-python-does-not-work), but I don't want a timeout for a function but for the script.
Also :
* I know that I can put my script in a [function](https://stackoverflow.com/questions/21827874/timeout-a-python-function-in-windows?rq=1) or using something like subprocess and use it with a
timeout, I tried it and it works, but I want something more simple.
* It must be Unix & Windows compatible.
* The function must be universal i.e. : it may be add to any script in
one line (except import)
* I need a function not a 'how to put a timeout in a script'. | 2015/02/06 | [
"https://Stackoverflow.com/questions/28364676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/359671/"
] | I would use something like this.
```
import sys
import time
import threading
def set_timeout(event):
event.set()
event = threading.Event()
i_time_value = 2
t = threading.Timer(i_time_value, set_timeout, [event])
t.start()
for i in range(10):
print("go")
if event.is_set():
print('Timed Out!')
sys.exit()
time.sleep(2)
``` | A little bit of googling turned [this answer](http://code.activestate.com/recipes/577028-timeout-any-function/) up:
```
import multiprocessing as MP
from sys import exc_info
from time import clock
DEFAULT_TIMEOUT = 60
################################################################################
def timeout(limit=None):
if limit is None:
limit = DEFAULT_TIMEOUT
if limit <= 0:
raise ValueError()
def wrapper(function):
return _Timeout(function, limit)
return wrapper
class TimeoutError(Exception): pass
################################################################################
def _target(queue, function, *args, **kwargs):
try:
queue.put((True, function(*args, **kwargs)))
except:
queue.put((False, exc_info()[1]))
class _Timeout:
def __init__(self, function, limit):
self.__limit = limit
self.__function = function
self.__timeout = clock()
self.__process = MP.Process()
self.__queue = MP.Queue()
def __call__(self, *args, **kwargs):
self.cancel()
self.__queue = MP.Queue(1)
args = (self.__queue, self.__function) + args
self.__process = MP.Process(target=_target, args=args, kwargs=kwargs)
self.__process.daemon = True
self.__process.start()
self.__timeout = self.__limit + clock()
def cancel(self):
if self.__process.is_alive():
self.__process.terminate()
@property
def ready(self):
if self.__queue.full():
return True
elif not self.__queue.empty():
return True
elif self.__timeout < clock():
self.cancel()
else:
return False
@property
def value(self):
if self.ready is True:
flag, load = self.__queue.get()
if flag:
return load
raise load
raise TimeoutError()
def __get_limit(self):
return self.__limit
def __set_limit(self, value):
if value <= 0:
raise ValueError()
self.__limit = value
limit = property(__get_limit, __set_limit)
```
It might be Python 2.x, but it shouldn't be terribly hard to convert. |
37,601,055 | I'm trying to implement in java this little project: I want to rename the episodes of an entire season in a series using a text file that has the names of all the episodes in that season.
To that end I wrote a code that reads the text file and stores every line of text (the name of an episode) as a string array, where every element of the array stores the name of one episode. Also, I wrote a code that takes the **FIRST** element of that array (an array called arrayLines[]) and renames a given file.
This code works like a charm.
What I want to do next is to create a char array for every element in the string array arrLines[].
The pseudo-code i'm thinking to implement is something like this:
```
for(int i=0; i<arrLines.length; i++){
char line_i+1[] = arrLines[i];
}
```
and thus getting many arrays with the names line\_1, line\_2,..., line\_arrLines.length, with the name of every episode stored as a char array.
How can I implement something like this? | 2016/06/02 | [
"https://Stackoverflow.com/questions/37601055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6395210/"
] | Just use a 2-dimensional `char` array:
```
char[][] lines = new char[arrLines.length][];
for (int i = 0; i < arrLines.length; i++) {
lines[i] = arrLines[i].toCharArray();
}
```
If you have Java 8, you can use Streams:
```
char[][] lines = Arrays.stream(arrLines)
.map(String::toCharArray)
.toArray(char[][]::new);
``` | You can use the String toCharArra method.
```
for(int i = 0; i < strArray.length; i++) {
char[] charArray = strArray[i].toCharArray();
}
``` |
16,856,588 | How do I return a Worksheets Object Reference? I've been perusing through various Google searches with nada results.
For example, I have a functioning code like so. wSheet already dim'ed:
```
Public wSheet As Worksheet
...
Set wSheet = ActiveWorkbook.Worksheets("ExampleSheet")
wSheet.Range("A1").Value = "Hello"
```
However, I want wSheet to now call a module that supplies it to the correct reference. Something like this:
```
Public wSheet As Worksheet
...
Set wSheet = myModule.get_ExampleSheet
wSheet.Range("A1").Value = "Hello"
```
And then have a function in module myModule
```
Function get_ExampleSheet() As Worksheets
get_ExampleSheet = ActiveWorkbook.Worksheets("ExampleSheet")
End Function
```
Everything I try gives me various runtime errors. Is there anyway to get this to work?
Thanks and advance! | 2013/05/31 | [
"https://Stackoverflow.com/questions/16856588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275094/"
] | You are returning the wrong type of object in your function.
```
Function get_ExampleSheet() As Worksheets
get_ExampleSheet = ActiveWorkbook.Worksheets("ExampleSheet")
End Function
```
This currently has several errors.
```
Function get_ExampleSheet() As Worksheet
Set get_ExampleSheet = ActiveWorkbook.Sheets("Sheet1")
End Function
```
Note I changed:
1. Return type to `Worksheet` (you are trying to set a variable, wSheet, which is of type `Worksheet` to a `Worksheets` type variable)
2. Added `set` keyword
3. Changed to `.Worksheets` to `.Sheets` to return the specific sheet you are interested in | In order to return an Object from a function, you need to provide the `Set` keyword:
```
Function get_ExampleSheet() As Worksheet
Set get_ExampleSheet = ActiveWorkbook.Worksheets("ExampleSheet")
End Function
``` |
335,457 | I bought a Western Digital 1TB Caviar Green hard drive. I want to store my files on it but also want to encrypt it so I've downloaded TrueCrypt. However TrueCrypt says that I can't encrypt the entire device as it has partitions - I can encrypt individual partitions though.
If I look in diskpart it only has one partition called *Partition 1*. I formatted it, still one partition. If I delete that partition in diskpart, then the disk becomes raw and I need to use Disk Management in Windows 7 to create a new simple volume before I can put things on the drive again.
**Does an external hard drive *need to have* partitions?** I think in this case it is one partition that takes up 100% of the space. However, doesn't that mean there will be an unencrypted partition table present when I encrypt the partition?
I wanted to be able to claim the drive is second hand and was securely erased if stopped by customs; having a partition table makes that seem less... plausible. | 2011/09/14 | [
"https://superuser.com/questions/335457",
"https://superuser.com",
"https://superuser.com/users/97807/"
] | This is possible using an eSATA external drive and TrueCrypt, but not a USB drive, in my experience.
If you have the option of using eSATA, just back up your data, delete all the partitions, and choose "Encrypt a non-system partition/drive" in TrueCrypt, then select the drive.
TrueCrypt will not encrypt the entire drive on a USB drive under Windows. I am doing exactly what you suggest, and bought an eSATA enclosure to replace the USB one I had been using, because of this limitation. | Why not just encrypt the single partition? Since it takes up the entire volume, it's functionally identical to encrypting the entire disk except that the partition table itself won't be encrypted ... and that makes no difference at all. |
45,764,333 | I am trying to create and use a DLL in Xamarin.Forms Project. This is given in the Charles Petzold's book 'Creating Mobile Apps using Xamarin.Form'.
It gives the following method to access the library that I have created
**"From the PCL project of your application solution, add a reference to the library PCL assembly which is the dynamic-link library generated from the library project"**
My library project is this
FILE: HslColorExtension.cs
```
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Xamarin.FormsBook.Toolkit
{
public static class Toolkit
{
public static void Init()
{
}
}
public class HslColorExtension : IMarkupExtension
{
public HslColorExtension()
{
}
public double H { set; get; }
public double S { set; get; }
public double L { set; get; }
public double A { set; get; }
public object ProvideValue(IServiceProvider servicePRovider)
{
return Color.FromHsla(H, S, L, A);
}
}
}
```
THE actual project is CustomExtensionDemo
In that the MainPage.xaml is
```
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="clr-namespace:Xamarin.FormsBook.Toolkit;assemby=Xamarin.FormsBook.Toolkit"
x:Class="CustomExtensionDemo.MainPage">
<StackLayout>
<Label Text="UTKARSH">
<Label.BackgroundColor>
<toolkit:HslColorExtension H="0" S="1" L="0.5"/>
</Label.BackgroundColor>
</Label>
</StackLayout>
</ContentPage>
```
THE METHOD HOW I ADDED THE DLL TO THE APPLICATION
FROM THE LIBRARY IS TOOK THE PATH THAT GENERATED THE DLL
C:\Users\admin\Desktop\Xamarin.FormsBook.Toolkit\Xamarin.FormsBook.Toolkit\obj\Debug
The name of the DLL is
Xamarin.FormsBook.Toolkit.dll
[](https://i.stack.imgur.com/zY31Z.png)
I added the reference to the actual project. browsed the path to
C:\Users\admin\Desktop\Xamarin.FormsBook.Toolkit\Xamarin.FormsBook.Toolkit\obj\Debug
and added the DLL : Xamarin.FormsBook.Toolkit.dll
[](https://i.stack.imgur.com/ZcxcF.png)
Everything compiled correctly **But I am getting a complete white screen on the Android Phone I am having .**
POINTS:
**1. I have set MainPage.xaml as the MainPage in the App.xaml.cs.**. I have tried to put Label without the property element syntax and that worked.
I have not checked on iOS I think that there it would have the same problem as the problem could be in method of using the DLL in the application.
IDE:VS 2017
THE ERROR THAT IS DISCUSSED IN THE BELOW DISCUSSION
[](https://i.stack.imgur.com/rIrT8.png)
NOW I REQUIRE SOME WAY TO REMOVE THE "Windows Phone Silverlight 8.1" AND IT DOES NOT GIVE OPTION TO REMOVE THAT.
[](https://i.stack.imgur.com/FMWu7.png) | 2017/08/18 | [
"https://Stackoverflow.com/questions/45764333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390618/"
] | It seems that reloadData and also reloadDataForRowIndexes:columnIndexes: both produce odd behavior in High Sierra. My way around this is as follows:
```
-(void)refreshAllCells {
NSMutableIndexSet* rowIndexes = [[NSMutableIndexSet alloc] init];
if (self.myTable.numberOfRows != 0)
[rowIndexes addIndexesInRange:NSMakeRange(0, (self.myTable.numberOfRows))];
[self.myTable removeRowsAtIndexes:rowIndexes withAnimation:NO];
[self.myTable insertRowsAtIndexes:rowIndexes withAnimation:NO];
}
```
If there is a better answer I would still love to see it. | I'm seeing this as well in 10.13, when 10.12 had worked just fine. I was able to work around this problem by, oddly enough, re-adding the cell view's subviews in its `[layout]`:
```
- (void)layout{
if([self needsLayout]){
for(NSView* v in [[self subviews] copy]){
[self addSubview:v];
}
}
[super layout];
}
``` |
50,534,626 | I want to make a bash script that outputs a msg when a device with a specific MAC addr connects to my "MyNetwork" AP.
```
airbase-ng -a 00:00:00:00:00:00 --essid "MyNetwork" -c 6 wlan0mon | grep 'BB:BB:BB:BB:BB:BB'
```
This command **correctly** outputs airbase-ng lines containing **only** the spesific MAC addr: BB:BB:BB:BB:BB:BB
When adding this command to a bash script, the "Hello iPhone" msg does not output, even if I am connecting with the correct MAC address
**SOLUTION**
```
#!/bin/bash
while true; do
if airbase-ng -a 00:00:00:00:00:00 --essid "MyNetwork" -c 6 wlan0mon -q | grep 'BB:BB:BB:BB:BB:BB';
then
echo "Hello iPhone!"
fi
#insert exit condition here
if false; then
break
fi
#5 second sleep
sleep 5
done
```
What am I doing wrong? | 2018/05/25 | [
"https://Stackoverflow.com/questions/50534626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553529/"
] | You have to update the display of your computer with `pygame.display.flip` after you draw the line.
```
pygame.draw.line(screen, Color_line, (60, 80), (130, 100))
pygame.display.flip()
```
That's usually done at the bottom of the while loop once per frame. | Try giving a width to the line (the last parameter to the line method) and update the display
```
pygame.draw.line(screen, Color_line, (60, 80), (130, 100), 1)
pygame.display.update()
``` |
9,425,706 | Is this possible to share data between two applications on the same device?
Or can I allow some other application to use my application's information / data or in any other way?
For example, the first application is for event management, and I use it to save some event. The second application is for reminders, which will get data from the other application in order to remind me about the event.
This is just a simple example, not a real scenario. | 2012/02/24 | [
"https://Stackoverflow.com/questions/9425706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877873/"
] | From **iOS 8** I've successfully Access Same folder in using "**App Group Functionality.**" I'm extending answer of @siejkowski.
**Note:** It will work from same developer account only.
For that you have to follow below steps.
1. first Enable "App Groups" from your developer account.
2. Generate Provisioning profile. and use it.
Now You have to create Two Apps. Sample Name
1. Demo\_Share\_One
2. Demo\_Share\_Two
Now We are copying images from **Demo\_Share\_One** to Sharing folder which is created by default when you enable App Groups and run app. and will access all those images from **Demo\_Share\_Two**.
You have to Take Group Name which was set to your developer account.lets say `group.filesharingdemo`.
Add Below method in Both apps to get Relative path of sharing folder url.
```
- (NSString *) getSharedLocationPath:(NSString *)appGroupName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *groupContainerURL = [fileManager containerURLForSecurityApplicationGroupIdentifier:appGroupName];
return [groupContainerURL relativePath];
}
```
Now we are Copying Images from Bundle from **Demo\_Share\_One**
```
-(IBAction)writeImage:(id)sender
{
for (int i = 0; i<15; i++)
{
NSString *strSourcePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"hd%d",i+1] ofType:@"jpg"];
NSString *strDestinationPath = [[self getSharedLocationPath:@"group.filesharingdemo"] stringByAppendingPathComponent:[NSString stringWithFormat:@"hd%d",i+1]] ;
BOOL filewrite = [[NSFileManager defaultManager]copyItemAtPath:strSourcePath toPath:strDestinationPath error:nil];
if (filewrite)
NSLog(@"File write");
else
NSLog(@"can not write file");
}
}
```
Now in **Demo\_Share\_Two** to access those images
```
NSString *pathShared = [[self getSharedLocationPath:@"group.filesharingdemo"] stringByAppendingPathComponent:[NSString stringWithFormat:@"hd%d.jpg",number]];
NSLog(@"%@",pathShared);
//BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:pathShared];
imgView.image = [UIImage imageWithContentsOfFile:pathShared];
```
And Now You will get all images which your write from **Demo\_Share\_One**.
So From now onwards if you want to share this folder two your third app. just add that app in your group. So it is too easy to access same elements in Your Multiple apps.
>
> if you will not enable App Groups in your AppID then you will get [self getSharedLocationPath:@"group.filesharingdemo"] is null.
>
>
>
Thanks to Apple for *Share Elements from your own apps functionality*. Happy Coding. :) | You can use <https://github.com/burczyk/Camouflage> to read and write NSData to iOS Camera Roll as .bmp file and share it between apps :)
Brand new solution! |
56,536,184 | Similar to [this question](https://stackoverflow.com/q/6198339/188046) except I want this as ideally a per-document setting or mode line. The ideal would be something like:
```
#+STARTUP: showlevels 3
```
Or if needed as a mode line:
```
# -*- org-showlevels: 3 -*-
```
And be equivalent to running `C-3 S-tab` when loading the file.
This does not appear to be directly supported in the initial visibility settings in the org-mode manual: <https://orgmode.org/manual/Initial-visibility.html> | 2019/06/11 | [
"https://Stackoverflow.com/questions/56536184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188046/"
] | New startup options for this are available in Emacs Org mode master since today.
The implementation is slightly different than your suggestion Elliott, since startup keywords cannot have argument (to the best of my knowledge). But the following will now work if you are using Org mode master:
>
> #+STARTUP: show3levels
>
>
>
(3 can be changed to any of 2,3,4,5) | You can replicate what `C-3 S-tab` does with the `org-content` command:
```
# -*- eval:(org-content 3) -*-
```
From the docstring:
>
> Show all headlines in the buffer, like a table of contents. With
> numerical argument N, show content up to level N.
>
>
> |
9,578,990 | I have some VB6 code that needs to be migrated to VB.NET, and I wanted to inquire about this line of code, and see if there is a way to implement it in .NET
```
Dim strChar1 As String * 1
```
Intellisense keeps telling me that an end of statement is expected. | 2012/03/06 | [
"https://Stackoverflow.com/questions/9578990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/709150/"
] | That's known as a "fixed-length" string. There isn't an exact equivalent in VB.NET.
>
> **Edit**: Well, OK, there's **[VBFixedStringAttribute](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.vbfixedstringattribute.aspx)**, but I'm pretty sure that exists solely so that automated migration tools can more easily convert VB6 code to VB.NET for you, and it's not really the ".NET way" to do things. Also see the warnings in the article for details on why this still isn't exactly the same thing as a fixed-length string in VB6.
>
>
>
Generally, fixed-length strings are only used in VB6 if you are reading fixed-size records from a file or over the network (i.e. parsing headers in a protocol frame).
For example, you might have a file that contains a set of fixed-length records that all have the format **(integer, 1-character-string, double)**, which you could represent in VB6 as a user-defined type:
```
Public Type Record
anInteger As Integer
aSingleCharacter As String * 1
aDouble As Double
End Type
```
This way, VB6 code that reads from the file containing records in this format can read each fixed-sized record stored in the file, and in particular, it will only read 1 byte for `aSingleCharacter`. Without the `* 1`, VB6 would have no idea how many characters to read from the file, since a `String` can normally have any number of characters.
In VB.NET, you can do one of the following, depending on your needs:
* If the length matters (i.e. you need to read exactly one byte from some data source, for example) consider using an array instead, such as
`Dim aSingleByteArray(1) As Byte`
* Alternatively, you could use one of the **[Stream](http://msdn.microsoft.com/en-us/library/system.io.stream.aspx)** classes. In particular, if you are reading data from a network socket or a file, consider using **[NetworkStream](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx)** or **[FileStream](http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx)**, respectively. A **Stream** is meant for byte-for-byte access (i.e. raw binary access). **[StreamReader](http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx)** is a related class that simplifies reading data when it is text-based, so that might be good if you are reading a text file, for example. Otherwise (if dealing with binary data), stick with one of the **Stream** classes.
* If the length doesn't matter, you could just use a "normal" `String`. That is to say:
`Dim aNormalString As String`
Which answer is "correct" really depends on why it was declared that way in the original VB6 code. | ALthough this question was asked ages ago, VB.NET actually has a native fixed-length string -- <VbFixedArray(9)> Public fxdString As Char() 'declare 10-char fixed array. Doing this with scalars actually creates VB6-style Static Arrays. |
11,036 | Вот предложения:
1. Уверенность каждого за свой завтрашний день.
2. У обеих братьев были одинаковые костюмы
3. Войдя в воду, я почувствовал, что всё тело покрылось мурашками
4. Согласно приказу директора предприятие перешло на круглосуточную работу.
5. Он всегда считал своего соседа отъявленным врагом | 2012/10/18 | [
"https://rus.stackexchange.com/questions/11036",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/1294/"
] | В первых двух предложениях - грамматические ошибки.
1. Уверенность в завтрашнем дне
2. У обоих братьев
Речевые недочеты в 1,2 и последнем предложении уже отметили. | Вопрос был именно о лексической норме?
Уверенность каждого за свой завтрашний день.-грамматическая ошибка, не лексическая.
У обеих братьев были одинаковые костюмы.-грамматическая (обеих вместо обоих)+ лексическая - плеоназм(смысловое излишество: у обоих одинаковые)
Войдя в воду, я почувствовал, что всё тело покрылось мурашками - норма.
Согласно приказу директора предприятие перешло на круглосуточную работу.-неудачная метонимия:предприятие перешло не на работу, а на график работы.
Он всегда считал своего соседа отъявленным врагом - лексическая несочетаемость. |
18,770,870 | Trying to get following result when I hover

for markup below
```
<ul>
<li><a href="#">Current Month</a></li>
<li><a href="#">Current Week</a></li>
<li><a href="#">Previous Month</a></li>
<li><a href="#">Previous Week</a></li>
<li><a href="#">Next Month</a></li>
<li><a href="#">Next Week</a></li>
<li><a href="#">Team Calendar</a></li>
<li><a href="#">Private Calendar</a></li>
<li><a href="#">Settings</a></li>
</ul>
```
Can't figure out solution using CSS3 border-radius. Any suggestions?
Update
======
Please don't post dotted lists. I need solution for arrowed list.
It's not same thing: when you use arrow, you need to set it as `background-image` of `li`.
There is another way, to set arrow as a bullet picture, but this time you have no way to control gap between arrow and link. | 2013/09/12 | [
"https://Stackoverflow.com/questions/18770870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/978733/"
] | ```
li:hover {
background-color:#e4e4e4;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
```
[jsfiddle](http://jsfiddle.net/SEzxP/)
**EDIT**
If you want to use arrows instead, just use the `:before` pseudo element.
```
ul {
list-style-type:none;
}
li {
padding:5px;
}
li:hover {
width:100px;
background-color:#e4e4e4;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
li:before {
content:"> ";
}
```
[updated jsFiddle](http://jsfiddle.net/SEzxP/1/)
Just replace the `>` with your image.
**EDIT 2**
To have the background only over the text, just add that style to the link instead of the `li` then.
<http://jsfiddle.net/SEzxP/2/>
**EDIT 3**
To use an image instead, just use `url()` after content
```
li:before { content:url('http://www.nationalacademies.org/xpedio/groups/system/documents/webgraphics/na_right_arrow.gif') /* with class ModalCarrot ??*/
}
```
[Updated jsFiddle](http://jsfiddle.net/SEzxP/3/) | ```
body {
background-color: #F3F3F3;
}
ul {
list-style: none;
margin: 0;
padding: 0;
font-family: Arial, Tahoma;
font-size: 13px;
border-left: 1px solid #4AFFFF;
padding-left: 10px;
}
li {
margin: 0;
padding: 0;
}
li:before {
content: " ";
display:inline-block;
border-style: solid;
border-width: 5px 0 5px 5px;
border-color: transparent transparent transparent #000000;
}
li a {
margin-left: 5px;
display: inline-block;
border-radius: 3px;
color: #000;
padding: 3px 5px;
text-decoration: none;
width: 150px;
}
li a:hover {
background-color: #DBDBDB;
font-weight: bold;
}
```
This should be ezactly how you want it!
<http://jsfiddle.net/2JJaW/> |
15,858,766 | I write a script where must find some files in a user-defined directory which may contain tilde (thus, it's possible to have `user_defined_directory='~/foo'`). The construct looks like
```
found_files=$(find "$user_defined_directory" -type f … )
```
I use quotes to cover possible spaces in that path, but tilde expansion does not work in quotes according to man page. I know about `:` operator that probably can do this expansion, but I can’t figure out how to use it here.
The ‘user-defined-directory’ is being taken from another configuration file in user $HOME directory. It is not passing to my script as a parameter, it’s being parsed from that another config in the script I write. | 2013/04/07 | [
"https://Stackoverflow.com/questions/15858766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685107/"
] | You can use `"${user_defined_directory/#~/$HOME}"` to replace a "~" at the beginning of the string with the current user's home directory. Note that this won't handle the `~username/subdir` format, only a plain `~`. If you need to handle the more complex versions, you'll need to write a much more complex converter. | Tilde definitely doesn't expand inside quote. There might be some other bash trick but what I do in this situation is this:
```
find ~/"$user_defined_directory" -type f
```
i.e. move starting `~/` outside quotes and keep rest of the path in the quotes. |
29,019,277 | I created a form that uses phpMailer to email the results to the website owner. Of course, before I add the owner's email address I use mine to test that the form works. When I use my email the form sends perfectly, however, when I use the owner's address it throws the error "could not instantiate mail function" and won't send the form. The error only occurs with email addresses associated with the owner's domain. Any idea why this could be happening?
If I type this into the command line it works fine:
```
echo 'test' | mail -s 'test' me@example.com
```
edit: I wasn't initially using SMTP, but it's now configured as shown below. The error message is now "SMTP Error: The following recipients have failed xxx@somedomain.com" and the end result is still the same. It can e-mail to a number of gmail test addresses but has issue with the owner's email@hisdomain.com. Further, with SMTPDebug it's now producing the error "RCPT TO command failed: 550 No Such User Here" The owner's e-mail, however, works without issue when e-mailed through gmail, outlook, etc.
phpMailer code:
```
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->Debugoutput = "error_log";
$mail->Host = "mail.mydomain.com";
$mail->SMTPAuth = true;
$mail->Username = "admin@mydomain.com";
$mail->Password = "XXXXXXXXXXXXXXX";
$mail->CharSet = 'UTF-8';
$mail->AddReplyTo($emailAddress);
$mail->SetFrom("admin@mydomain.com");
$mail->AddAddress($toAddress,$toName);
$mail->Subject = $emailSubject;
$mail->isHTML(true);
$mail->Body = $emailBody;
$mail->AltBody = strip_tags($emailBody);
// Attempt to send the e-mail
if (!$mail->send()) {
//error handling
}
``` | 2015/03/12 | [
"https://Stackoverflow.com/questions/29019277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755541/"
] | The easiest solution would be to split your messages and handlers to multiple projects. Usually in scenarios like yours, there is some sort of logical separation between these messages/handlers groups that you want to control by your configuration (or command line) parameters.
NServiceBus scans all assemblies it finds in the application folder to find all handlers and other marker interfaces. You can limit the list of assemblies by using (V5):
```
configuration.AssembliesToScan(myListOfAssemblies);
```
You can construct the list of assemblies based on your configuration parameters. If you have different deployment where you want to use different set of handlers, you can just deploy those assemblies that you need at that particular installation.
You can use one assembly or set of assemblies for your messages and these are configured using your DefiningEventsAs call, and have separate assemblies for handlers.
The documentation about NServiceBus assembly scanning can be found [here](http://docs.particular.net/nservicebus/assembly-scanning). | It sounds like you want to turn off auto subscription:
```
config.DisableFeature<AutoSubscribe>();
```
You can then individually subscribe to messages:
```
Bus.Subscribe<MyMessage>();
```
You probably want to first unsubscribe to ALL messages at startup (Bus.Unsubscribe), then re-subscribe to the ones you are interested in. Otherwise your subscriptions will still be present from the last time you ran the application. |
4,255,980 | >
> **Possible Duplicate:**
>
> [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)
>
>
>
Hello. I have a stupid program in c++ consisting in a header file with a class using template and a cpp file with implementations of methods.
This is the header:
```
namespace SynQueueing {
template < class T, unsigned long SIZE = 0 >
class CommQueue {
public:
CommQueue();
~CommQueue();
}
}
```
This is cpp
```
#include "myheader.h"
using namespace SynQueueing;
/* Default constructor */
template < class T, unsigned long SIZE >
CommQueue<T, SIZE>::CommQueue() {
}
/* Default destructor */
template < class T, unsigned long SIZE >
CommQueue<T, SIZE>::~CommQueue() {
}
```
In main I simply create an object of CommQueue
CommQueue cq;
Including CommQueue.h of course in cpp main file.
Well, compiler get crazy telling me this:
>
> /tmp/ccvJL8VI.o: In function `main':
>
>
> entry.cpp:(.text+0x2c): undefined reference to `SynQueueing::CommQueue::CommQueue()'
>
>
> entry.cpp:(.text+0x10e): undefined reference to `SynQueueing::CommQueue::~CommQueue()'
>
>
> entry.cpp:(.text+0x135): undefined reference to `SynQueueing::CommQueue::~CommQueue()'
>
>
> collect2: ld returned 1 exit status
>
>
>
entry.cpp is the file where main is located.
Any idea?
Thanks | 2010/11/23 | [
"https://Stackoverflow.com/questions/4255980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517414/"
] | For templates you usually have to put the implementation in the .h/.hpp file. This may seem unnatural, but think of templates as some special "macros" that the compiler expands once you give the actual types or values (in your case, the type `T`, and the value `SIZE`). As most compilers are implemented (in your case GCC), the compiler has to find the code to insert at the time it is compiling and it sees an instantiation of the template you've defined. | The idea is that a template defines a "family" of functions or types. That is why you cannot simply define the functions in a .cpp file and expect to compile it *once* to an .obj. Every time a new template parameter *T* is used, a new type is created, and new functions need to be compiled.
There are infinitely many choices of *T*, and so the template function's definition needs to be available to the compiler every time it is instantiated, not just the compiled code in some .obj file to be linked in, like for regular functions. |
58,883,736 | I have a JAR dependency that I am required to use. There is one component in that JAR that is interfering with a part of my Spring Boot application. I need to exclude that ONE component, and changing the component definition in the JAR dependency is not currently possible.
I have tried the following, but it does not work, the bean is still loaded:
```
@SpringBootApplication
@ComponentScan(useDefaultFilters = false, excludeFilters = [Filter(type = FilterType.ASSIGNABLE_TYPE, classes = [SomeBean::class])])
```
The bean is defined as:
```
@RestController
class SomeBean {
```
NOTE: These snippets are in Kotlin. | 2019/11/15 | [
"https://Stackoverflow.com/questions/58883736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713861/"
] | Try this
```
@SpringBootApplication(exclude = { SomeBean.class })
``` | Doesn't the `@Bean`/`@Component`/etc. or `@Configuration` have any [Conditional](https://docs.spring.io/spring-boot/docs/1.2.1.RELEASE/reference/html/boot-features-developing-auto-configuration.html#boot-features-condition-annotations) annotation on it (e.g.: `@ConditionalOnMissingBean`, `@ConditionalOnProperty`, etc.)? That would be the right solution for this problem. Can you ask the maintainer to add proper conditions? So that you (and other users) don't need to hack this around.
There is a terrible hack though: [BeanDefinitionRegistry#removeBeanDefinition](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/support/BeanDefinitionRegistry.html#removeBeanDefinition-java.lang.String-) |
101,133 | I have an LG G Pad 7.0 running Android KitKat (4.4.2). Could I update it to Android 5, even though there is no release for the G Pad 7?
I would also by fine with the latest version of CyanogenMod.
Also, I am very new to Android, but is it flexible in the way that you can change the Android version easily, or install another UI? | 2015/02/28 | [
"https://android.stackexchange.com/questions/101133",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/96283/"
] | After THREE YEARS of searching for a fix... I think I just found a solution - and felt obligated to spread the information. Just plug the headphones in slowly... That's actually all there was to it... The notification icon for a plugged in audio jack at the top of the screen will show up differently if you did it right.
This reddit post: <https://www.google.com/amp/s/amp.reddit.com/r/LGG3/comments/2siwyp/is_there_a_rom_or_fix_that_makes_g3_detect_all/> the user RandomGenera7ed tells us to plug the jack into the headphone plug slowly - causing it to show up as a three prong headphone jack and not a four prong jack (four prong jacks have a mike wire that can have pause/skip/volume-change/GOOGLE VOICE functionality while three prong audio jacks do not). Apparently plugging a three prong jack in too quickly confuses the phone into thinking it has a four prong jack plugged in. | If the headphones were working previously on the phone and now they just suddenly stopped working, then it's likely that the phone's audio hardware has malfunctioned.
Alternatively, there is also a small possibility that some drivers have been updated on your phone to detect Apple headphones and not allow them to be used. (This is a conspiracy theory, but Apple does do this with their Lightning connector such that if you buy a counterfeit one or buy from some other vendor it won't work).
Have you tried a totally different set of headphones (not Apple ones) on this phone?
Does the headphone jack fit totally/properly in the port? Sometimes a little fidgeting with it and pressing a little harder gets some of the grooves to click into place so that the right connections are flush against each other. (Had this issue on a Nexus 7 with Apple Earpods)
Personally i've tested Apple Earpods (iPhone 5 headphones) on a Google Nexus 4 and 5 (both LG devices) and they work. However on a Samsung Galaxy Ace the same set of headphones behaved quite similar to what you described. They worked initially, but then started doing weird things with playing and pausing music, and not showing up in the notifications. Also the mic didn't work for me. It causes some loud ringing noise on the other end.when you're on hands-free with the headphones. |
28,906,096 | Given the [Play Framework 2.3 Computer Database sample application](https://github.com/playframework/playframework/tree/2.3.x/samples/java/computer-database), I would like to practice adding a unique constraint on an attribute. Let's say I want the `name` attribute of the `Computer` class to be unique. I've tried to do this by adding a `validate()` function (and a getter) to `Computer.java`:
```
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<ValidationError>();
if(Computer.find.where().eq("name", getName()).findRowCount() != 0){
errors.add(new ValidationError("name", "Name must be unique. That value is already taken."));
}
return errors;
}
public String getName() {
return name;
}
```
This check works when creating new records in the database, however, this now causes a validation error when you **update** a Computer object but don't change the name. Is there a way to add a [uniqueness constraint, similar to Rails](http://guides.rubyonrails.org/active_record_validations.html#uniqueness)? How can I validate uniqueness in Play?
Thanks!
**UPDATE**: see the [answer by davide](https://stackoverflow.com/a/28913174/1092403).
I ended up using the `@Column(unique = true)` constraint from the javax.persistence API. This doesn't generate an error in Play forms; instead, it throws a `PersistenceException`. Therefore I had to add change my controller to achieve the behavior I wanted. Both the `create()` and `update()` actions need a try/catch like this:
```
try {
computerForm.get().save();
} catch (PersistenceException pe) {
flash("error", "Please correct errors below.");
formData.reject("name", "Name conflict. Please choose a different name.");
return badRequest(createForm.render(computerForm));
}
```
**UPDATE 2**: each of the answers below is a possible solution | 2015/03/06 | [
"https://Stackoverflow.com/questions/28906096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1092403/"
] | react-bootstrap seems to complain if the children of an Accordion are not Panels, and by wrapping Panel inside of my Content class I was doing just that.
To solve this problem I had to step away from React's convention. Rather than creating a class Content, I created another js file rather than a react.js file. By treating this file like a normal js file, I was able to call on a function inside of this file which maps over each 'this.state.contents' and return a Panel object.
This whole file will return an array of Panel class. | The easiest way to do it is making a condition inside the eventKey parameter.
```
<Card key={item.id}>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey={index === 0 ? '0' : index}>
{item.title}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={index === 0 ? '0' : index}>
<Card.Body>
CARD BODY
</Card.Body>
</Accordion.Collapse>
</Card>
``` |
12,820,935 | I would like to find unit tests (written with JUnit) which never fail. I.e. tests which have something like
```
try {
// call some methods, but no assertions
} catch(Throwable e) {
// do nothing
}
```
Those tests are basically useless, because they will never find a problem in the code. So is there a way to make each (valid) unit test fail? For instance each call to any assert method would throw an exception? Then tests which still remain green are useless. | 2012/10/10 | [
"https://Stackoverflow.com/questions/12820935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1735071/"
] | Well, one approach is to use something like [Jester](http://jester.sourceforge.net/) which implements [mutation testing](http://en.wikipedia.org/wiki/Mutation_testing). It doesn't do things quite the way you've suggested, but it tries to find tests which will still pass however much you change the production code, but randomly mutating it and rerunning the tests. | I'm not sure about what you want but I understand that the Units are already written, so the only way I can imagine is to override the asserts methods, but even with this you will have to change a little bit the unit code. |
1,910,749 | I am reading a book that is talking about serializing and deserializing files or sending data via web services. My question is.. Is it mandatory to use serialization when using web services. Also when saving files locally using serialization, what is the significants of doing so ?
I know that it saves the data into binary data. Is this to compress the data ??
I Appreciate the responses. thanks! | 2009/12/15 | [
"https://Stackoverflow.com/questions/1910749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201934/"
] | Perhaps the best way is to let your server actually fetch the page from the other server, then deliver it as content to the browser.
In that way, the external URL is never sent to the browser and therefore it doesn't know anything about it. Instead all the client sees is a URL to your server. Doing it this way would allow you to set whatever security you want on your page.
Pretty much every web language (.Net, PHP, java, etc ) all have support for doing this server side.
**UPDATE**
Due to the changes to the question, here is a new approach: Use the [Google Calendar API.](http://code.google.com/apis/calendar/data/2.0/developers_guide.html) It's built for exactly the situation you are in. It will allow you to display the google calendar within your site as well as manage the access control list via code. | Why do you want to do this? You really can't completely hide the url of another page, unless you fetch the page and hide it by displaying it on a POSTED form page on your site.
You could try overlaying it in a frame, but the url still could be found.
If you want something simple, to prevent people from causally not bookmarking the url, setup a POSTED link or form that directs to an framed viewer, (embedding the page within another). If anyone bookmarks or shares the page without POSTED data, it can display page not found or access not permitted. |
58,250,341 | I have a `*.cpp` file that I compile with C++ (not a C compiler). The containing function relies on a cast (see last line) which seems to be defined in C (please correct if I am wrong!), but not in C++ for this special type.
```
[...] C++ code [...]
struct sockaddr_in sa = {0};
int sockfd = ...;
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
bind(sockfd, (struct sockaddr *)&sa, sizeof sa);
[...] C++ code [...]
```
Since I compile this in a C++ file, is this now defined or undefined behaviour? Or would I need to move this into a `*.c` file, to make it defined behaviour? | 2019/10/05 | [
"https://Stackoverflow.com/questions/58250341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10050942/"
] | This is defined in both C++ and C. It does not violate strict aliasing regulations as it does not dereference the resulting pointer.
Here's the [quote from C++](https://timsong-cpp.github.io/cppwp/expr.reinterpret.cast#7) (thanks to @interjay and @VTT) that allows this:
>
> An object pointer can be explicitly converted to an object pointer of a different type.
>
>
>
Here's the [quote from C](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p7) (thanks @StoryTeller) that allows this:
>
> A pointer to an object type may be converted to a pointer to a different object type.
>
>
>
These specify that one pointer type can be converted to another pointer type (and then optionally converted back) without consequence.
And here's the [quote from POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/netinet_in.h.html) that allows this specific case:
>
> The **sockaddr\_in** structure is used to store addresses for the Internet address family. Pointers to this type shall be cast by applications to **struct sockaddr \*** for use with socket functions.
>
>
>
As this function (`bind`) is part of the C standard library, whatever goes on inside (specifically, dereferencing the type-casted pointer) does not have undefined behavior.
---
To answer the more general question:
C and C++ are two different languages. If something is defined in C but not in C++, it's defined in C but not in C++. No implied compatibility between the two languages will change that. If you want to use code that is well-defined in C but is undefined in C++, you'll have to use a C compiler to compile that code. | Calls between C and C++ code all invoke Undefined Behavior, from the point of view of the respective standards, but most platforms specify such things.
In situations where parts of the C or C++ Standard and an implementation's documentation together define or describe an action, but other parts characterize it as Undefined, implementations are allowed to process code in whatever fashion would best serve their customers' needs or--if they are indifferent to customer needs--whatever fashion they see fit. The fact that the Standard regards such matters as outside their jurisdiction does not imply any judgment as to when and/or how implementations claiming suitability for various purposes should be expected to process them meaningfully, but some compiler maintainers subscribe to a myth that it does. |
4,318,481 | writing a simple monte carlo simulation of a neutron beam. Having trouble with the geometry logic (whether something is in one environment or another). My issue is that Ruby seems to be processing the conditions sequentially and keeping the first value it comes to.
The code below illustrates this quite nicely:
```
def checkPosition(*args)
polyCylRad = 2.5
polyCylFr = 15
polyCylB = -2.0
borPolyBoxL = 9.0 / 2
pbCylRad = 3.0
pbBoxL = 10.0 / 2
cdBoxL = 9.5 / 2
position = Array.new
material = String.new
args.each do |item|
position << item.inspect.to_f
end
xSquared = position.at(0) ** 2
ySquared = position.at(1) ** 2
zSquared = position.at(2) ** 2
modX = Math.sqrt(xSquared)
modY = Math.sqrt(ySquared)
modZ = Math.sqrt(zSquared)
puts xSquared
puts Math.sqrt(ySquared + zSquared) <= polyCylRad
puts (position.at(0) >= polyCylB)
puts (position.at(0) <= polyCylFr)
puts (position.at(0) >= polyCylB)and(position.at(0) <= polyCylFr)
puts (position.at(0) <= polyCylFr)and(position.at(0) >= polyCylB)
puts zSquared
polyCylinder = (Math.sqrt(ySquared + zSquared) <= polyCylRad)and((position.at(0) >= polyCylB)and(position.at(0) <= polyCylFr) )
puts polyCylinder
borPolyBox = ((modX <= borPolyBoxL)or(modY < borPolyBoxL)or(modZ <= borPolyBoxL)) and not((modX >= cdBoxL)or(modY >= cdBoxL)or(modZ >= cdBoxL)) and not(Math.sqrt(ySquared + zSquared) <= polyCylRad)
puts borPolyBox
cadmiumShield = ((modX <= cdBoxL)or(modY < cdBoxL)or(modZ <= cdBoxL)) and not((modX >= pbBoxL)or(modY >= pbBoxL)or(modZ >= pbBoxL)) and not(Math.sqrt(ySquared + zSquared) <= polyCylRad)
puts cadmiumShield
leadShield = ( ((modX <= pbBoxL)or(modY <= pbBoxL)or(modZ <= pbBoxL)) or ((position.at(0) <= ployCylFr)and(Math.sqrt(ySquared + zSquared) <= pbCylRad)) ) and not(Math.sqrt(ySquared + zSquared) <= polyCylRad)
puts leadShield
if (polyCylinder) : material = "poly"
elsif(borPolyBox) : material = "borPoly"
elsif(cadmiumSheild) : material = "cd"
elsif(leadSheild) : material = "pb"
elsif(material == nil) : position = Array.new
end
thisEnvironment = Array.new
thisEnvironment << position << material
puts thisEnvironment.at(0)
puts thisEnvironment.at(1)
end
checkPosition(40, 0, 0)
```
call the code whatever you want, but give it \*args as an argument (I am lazy and may want to add more args in the future) then call it with 3 floats, wrt the geometry set up in the logic and you'll see what I mean.
My question is: how do I get it to work like it should (ie evaluating the logic correctly) without a whole bunch of nested if's? (which is what I am about to remake, however it is a nightmare to read and memory is cheap.) | 2010/11/30 | [
"https://Stackoverflow.com/questions/4318481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525713/"
] | You've typed "Sheild" a few times where you probably meant "Shield"
In the context you're using them, you should be using `&&` instead of `and`, `||` instead of `or`, and `!` instead of `not`. The reason is that `or` and `and` have such a low precedence that they will cause your assignment operators to not work the way you want. For example,
```
a = b and c
```
evaluates as
```
(a = b) and c
```
Such that a is always assigned the value b, and then in the result is truthy, c is evaluated (and discarded). On the other hand,
```
a = b && c
```
evaluates as
```
a = (b && c)
```
Which is what you want in this code.
Beyond that, I would move all of this code into a class, so that I can create lots of little methods for things:
```
class PositionChecker
def initialize(*args)
@x, @y, @z = *args
end
def checkPosition
...
end
end
```
Look for opportunities to replace local variables in checkPosition with method calls. For example, you could move borPolyBox into its own method (once all of the values it uses are methods of their own):
```
class PositionChecker
...
def borPolyBox
((modX <= borPolyBoxL)||(modY < borPolyBoxL)||(modZ <= borPolyBoxL)) && !((modX >= cdBoxL)||(modY >= cdBoxL)||(modZ >= cdBoxL)) && !(Math.sqrt(ySquared + zSquared) <= polyCylRad)
end
...
end
```
Once you've got all of these predicates as their own method, you can create a method to determine the material, like so:
```
def material
[
[:polyCylinder, 'poly'],
[:borPolyBox, 'borPoly'],
[:cadmiumShield, 'cd'],
[:leadShield, 'pb'],
].each do |method, name|
return name if send(method)
end
nil
end
```
And one for the position:
```
def position
[@x, @y, @z] if material
end
```
Continue along this line until nothing is left but a bag of teeny, focused methods. | Change all `and` and `or` to `&&` and `||`.
Never seen anyone actually use `array.at(index)` instead of `array[index]` before.
I also recommend against `*args` in favor of a Hash parameter as a kind of named parameters
```
def test(params)
x = params[:x] || raise("You have to provide x!")
y = params[:y] || raise("You have to provide y!")
z = params[:z] || raise("You have to provide z!")
puts x, y, z
end
```
and call it with (Ruby 1.9+ syntax)
```
test({x: 42, y: 4711, z: 93})
```
>
> 42
>
> 4711
>
> 93
>
>
> |
5,828,013 | >
> **Possible Duplicate:**
>
> [How to use scroll view on iPhone?](https://stackoverflow.com/questions/617796/how-to-use-scroll-view-on-iphone)
>
>
>
hi everyone,
i was working with the scroll view , i want to scroll a simple page , how can it be done on iphone, i mean what changes we need to do on interface builder , and what class and code is to be added.
thanks in advance | 2011/04/29 | [
"https://Stackoverflow.com/questions/5828013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/766047/"
] | You need to drag a `UIScrollView` in your file.xib then a `UIView` which will be definitely longer than the typical `UIView`. Then drag that `UIView` into `UIScrollView`.
Now drag that `UIScollView` in the `UIView` which is linked to the FilesOwner's View.
Now in your `file.h` make an outlet of `UIScrollView`
```
IBOutlet UIScrollView *scrolldown;
```
then link it with the `UIScrollView` in the InterfaceBuilder.
then in your `viewDidLoad` method write these lines.
```
[scrolldown setScrollEnabled:YES];
[scrolldown setContentSize:CGSizeMake(320, 650)]; //(320, 650) is the size of View which is inside the UIScrollView.
``` | Add in .h file
--------------
```
@interface ScrollImageViewController : UIViewController {
UIScrollView *scrollView;
}
@property(nonatomic,retain)UIScrollView *scrollView;
@end
```
and in .m add the following line in viewdidload
-----------------------------------------------
```
scrollView.contentSize = CGSizeMake(320, 800);
```
also synthesize the property
```
@synthesize scrollView;
``` |
2,935,913 | DO they use a php page to analyze the link, and return all of the images as josn?
Is there a way to do this with just javascript, so you dont have to go to the server to analyze the page? | 2010/05/29 | [
"https://Stackoverflow.com/questions/2935913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335016/"
] | You could remove any character that is not a digit or a decimal point and parse that with [`floatval`](http://php.net/floatval):
```
$number = 1200.00;
$parsed = floatval(preg_replace('/[^\d.]/', '', number_format($number)));
var_dump($number === $parsed); // bool(true)
```
And if the number has not `.` as decimal point:
```
function parse_number($number, $dec_point=null) {
if (empty($dec_point)) {
$locale = localeconv();
$dec_point = $locale['decimal_point'];
}
return floatval(str_replace($dec_point, '.', preg_replace('/[^\d'.preg_quote($dec_point).']/', '', $number)));
}
``` | Thanks to @ircmaxell, I came up with this:
```
$t_sep = localeconv()['thousands_sep'];
$num = (float) str_replace($t_sep? $t_sep : ',', '', $numStr);
``` |
328,091 | I have a computer (laptop) at work that I have installed Thunderbird on and set all of these rules, created contacts, and updated calendars on. I don't want to have to go through all of that process over again on my desktop at home. Is there a tool/add-on or simple way to accomplish this? | 2011/08/25 | [
"https://superuser.com/questions/328091",
"https://superuser.com",
"https://superuser.com/users/47225/"
] | Just sync the whole profile folder [over Dropbox](http://solicitingfame.com/2009/10/05/how-to-dropbox-your-firefoxthunderbird-profiles/). | Another solution, which I use for non-syncing apps,
would be symbolically linking (scriptable, cross-platform)
certain files (filter \*.dat file, etc)
from a Resilio Sync folder (free, self-hosted, infinite space) *a la* Dropbox.
Using this method you cannot open it on both computers.
As for syncing mail, DO NOT BOTHER WITH THIS MANUALLY. Just switch to an IMAP mail server and THIS IS DONE FOR YOU. (Don't use POP)
As for Calendar, THIS IS DONE FOR YOU, just use Cal-DAV (Google Cal, or OwnCloud for self-hosted)
As for Contacts, THIS IS DONE FOR YOU, just use CardDAV (Owncloud) |
41,195,168 | I know this isn't in the scope of a `Array.map` but I'd like to wait until the previous item has finished its promise before starting the next one. It just happens that I need to wait for the previous entry to be saved in the db before moving forwards.
```
const statsPromise = stats.map((item) => {
return playersApi.getOrAddPlayer(item, clubInfo, year); //I need these to wait until previous has finished its promise.
});
Promise.all(statsPromise)
.then((teamData) => {
..//
});
```
`playersApi.getOrAddPlayer` returns a `new Promise`
**Edit**
Reading more on it, it seems its important to show playersApi.getOrAddPlayer
```
getOrAddPlayer: function (item, clubInfo, year) {
return new Promise((resolve, reject) => {
var playerName = item.name.split(' '),
fname = playerName[0].caps(),
sname = playerName[1].caps();
Players.find({
fname: fname,
sname: sname,
}).exec()
.then(function(playerDetails, err){
if(err) reject(err);
var savePlayer = new Players();
//stuff
savePlayer.save()
.then(function(data, err){
if(err) reject(err);
item._id = data._id;
resolve(item);
});
});
});
}
``` | 2016/12/17 | [
"https://Stackoverflow.com/questions/41195168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240363/"
] | If you are fine with using promise library, you can use [Promise.mapSeries by Bluebird](http://bluebirdjs.com/docs/api/promise.mapseries.html) for this case.
Example:
```
const Promise = require("bluebird");
//iterate over the array serially, in-order
Promise.mapSeries(stats, (item) => {
return playersApi.getOrAddPlayer(item, clubInfo, year));
}).then((teamData) => {
..//
});
``` | I gave it a thought but I didn't find a better method than the reduce one.
Adapted to your case it would be something like this:
```
const players = [];
const lastPromise = stats.reduce((promise, item) => {
return promise.then(playerInfo => {
// first iteration will be undefined
if (playerInfo) {
players.push(playerInfo)
}
return playersApi.getOrAddPlayer(item, clubInfo, year);
});
}, Promise.resolve());
// assigned last promise to a variable in order to make it easier to understand
lastPromise.then(lastPlayer => players.push(lastPlayer));
```
You can see some explanation about this [here](https://joost.vunderink.net/blog/2014/12/15/processing-an-array-of-promises-sequentially-in-node-js/). |
31,170,484 | I am working on a macro, a part of which takes input from the user asking what he/she would like to rename the sheet. It works fine, but I run into a runtime error if the name provided by the user is already being used by a different sheet. I understand why the error occurs but am not sure as to how I could warn the user and handle the error.
My code is as follows:-
```
'Change sheet name
Dim sheetname As String
sheetname = InputBox(Prompt:="Enter Model Code (eg 2SV)", _
Title:="Model Code", Default:="Model Code here")
wsCopyTo.Name = sheetname
``` | 2015/07/01 | [
"https://Stackoverflow.com/questions/31170484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4552638/"
] | There are two ways to handle this.
First, trap the error, check if there was an error, and advise, then put the error trapping back to what it was
```
Dim sheetname As String
sheetname = InputBox(Prompt:="Enter Model Code (eg 2SV)", _
Title:="Model Code", Default:="Model Code here")
On Error Resume next
Err.Clear 'ensure previously unhandled errors do not give a false positive on err.number
wsCopyTo.Name = sheetname
If Err.Number = ?? then 'go back and ask for another name
On Error Goto 0
```
Second, check all the current sheet names, and see if there is a match
```
Dim sheetname As String
Dim sh 'as Sheet
sheetname = InputBox(Prompt:="Enter Model Code (eg 2SV)", _
Title:="Model Code", Default:="Model Code here")
for each sh in ActiveWorkbook.Sheets
If lower(sh.name)=lower(sheetname) then
'Goback and ask for another name
Next
wsCopyTo.Name = sheetname
``` | The simplest way is to create a Worksheet variable and Set it to what user has input (you might want to **Trim()** as well to remove leading and trailing spaces).
If it's Nothing then name is safe to use. If **Not Is Nothing** then it already exists.
```
Dim oWS As Worksheet
On Error Resume Next
Set oWS = ThisWorkbook.Worksheets(sheetname)
If oWS Is Nothing Then
' Safe to use the name
Debug.Print """" & sheetname & """ is save to use."
Err.Clear
wsCopyTo.Name = sheetname
If Err.Number <> 0 Then
MsgBox "Cannot use """ & sheetname & """ as worksheet name."
Err.Clear
End If
Else
Debug.Print """" & sheetname & """ exists already! Cannot use."
' worksheet with same name already!
' handle it here
End If
Set oWS = Nothing
On Error GoTo 0
```
You could also put it into a loop until a unused sheetname is found. |
1,097,595 | Toshiba L640
<http://www.cnet.com/products/toshiba-satellite-l640-14-core-i3-350m-windows-7-home-premium-64-bit-3-gb-ram-250-gb-hdd-series/specs/>
I recently had an issue with cooling so I disassembled it and dusted it all and reassembled it. This however did not fix the issue so I took it apart again and replaced the fan and the stock thermal paste. I cleaned the CPU and gpu with isopropyl and applied a thin layer of paste (and cleaned a small spill). Replacing the fan did improve the airflow drastically but now it won't stay on for more than 1.5 minutes regardless of weather I leave it in BIOS, launch safe mode or normally. Although launching normally did cause a blue screen. Launching safe mode does get to the log in screen but I don't have time to log in before it shuts off.
I realise there are probably a dozen things I could have done that permanently damaged my laptop during disassembly and it's a bit of a stretch to expect a working solution.
Cheers for any advice you have. | 2016/07/06 | [
"https://superuser.com/questions/1097595",
"https://superuser.com",
"https://superuser.com/users/614128/"
] | You can create a bootable usb using the command `dd` :
```
sudo dd if=/path/to/windows.iso of=/dev/sdx bs=4M
sync
```
example: the output of `fdisk -l` is `/dev/sdb1` :
```
sudo dd if=/home/user/Downloads/windows.iso of=/dev/sdb
sync
``` | There is WinUSB which works quite well.
Add the following rep: ppa:colingille/freshlight
and install WinUSB |
35,563 | I have some items in my ubuntu 12.04 desktop. I want to transfer them into the Sdcard of one of the avds in my android emulator (android-sdk-linux) which I have installed on the same system.
Like to know how to do the above. | 2012/12/17 | [
"https://android.stackexchange.com/questions/35563",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/24020/"
] | **1. Using command line:** Here's how you can [copy files to an SD card image](http://developer.android.com/tools/devices/emulator.html#sdcard-files).
You have to use `adb push` to copy files from Desktop to Emulator and `adb pull` for the reverse. Here's the syntax to [copy files to or from an Emulator/Device Instance](http://developer.android.com/tools/help/adb.html#copyfiles):
Copy from desktop to emulator:
```
adb push <local> <remote>
```
Copy from emulator to desktop:
```
adb pull <remote> <local>
```
Here `<local>` is path of file / folder on your desktop and `<remote>` is path of file / folder on your emulator.
Here is an example:
```
adb push foo.txt /sdcard/foo.txt
```
foo.txt will be pushed (copied) to the emulator.
---
**2. Using DDMS UI:** Here's how to [work with emulator's file system using DDMS](http://developer.android.com/tools/debugging/ddms.html#emulator).
1. In the Devices tab, select the emulator that you want to view the file system for.
2. To copy a file from the device, locate the file in the File Explorer and click the Pull file button.
3. To copy a file to the device, click the Push file button on the File Explorer tab.
I personally prefer the adb pull and adb push commands as you can copy multiple files (in a single directory) with just one line command, using DDMS you can copy only one file at a time (no directory). | To transfer data from desktop to an emulator's SdCard on Linux do this:
* Create the SD Card:
Let's create a 64MB sd card for our Android emulator. From a terminal do this:
```
# cd ~/android-sdk-linux/tools
# ./mksdcard 64M ~/Desktop/sdcard.iso
```
* Now you can use the 'Eclipse Android SDK and AVD Manager' to create a new Android virtual device that can use the path to the sd card you created.
* Write Data to the SD Card:
From a terminal:
```
# cd ~/android-sdk-linux/tools
# ./ddms
```
* This will start the Dalvik Debug Monitor Server. Then:
1. Launch your AVD with SD card from Eclipse that you created earlier
2. From DDMS, go to 'Device -> File Explorer'
3. Select the 'sdcard' folder
4. Click the 'push file onto device' button
5. Find your file and click open
6. That's it!
Now from inside your code you can get to the sd card's path with:
```
Environment.getExternalStorageDirectory()
```
More you can read [here](http://www.tylerfrankenstein.com/create-android-emulator-sd-card-and-write-data-to-it). |
15,199,934 | I have a problem when Extracting data from a Dictionary object. Count of the Dictionary is displaying as 1, but the one value it is displaying is null. I want to display a AlertView when there is no data in the Dictionary object. I thought of displaying the AlertView when the count is '0', but it returning '1'.
I am extracting this dictionary object from a WebService using JSON.
```
{
"My Data" = null;
}
```
Used this code for getting the "My Data" value into the Dictionary variable Datas.
```
Datas = (NSDictionary *) [details objectForKey:@"My Data"];
if ([Datas count] == 0) {
//code for showing AlertView....
}
```
Please help me to display a UIAlertView when the Dictionary value having null.... | 2013/03/04 | [
"https://Stackoverflow.com/questions/15199934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987063/"
] | `NSDictionary` and other collections cannot contain `nil` values. When `NSDictionary` must store a `null`, a special value [`[NSNull null]`](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/Reference/Reference.html) is stored.
Compare the value at `@"My Data"` to `[NSNull null]` to determine if the corresponding value is `null` or not.
```
// Since [NSNull null] is a singleton, you can use == instead of isEqual
if ([details objectForKey:@"My Data"] == [NSNull null]) {
// Display the alert
}
``` | ```
if ([[details objectForKey:@"My Data"] isEqual:[NSNull null]] || [[details objectForKey:@"My Data"] isEqualToString:@""]) {
UIAlertView *altTemp = [UIAlertView alloc]initWithTitle:@"Value Null" message:@"Your Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[altTemp show];
[altTemp release];
}
``` |
71,004 | I suspect someone broke into my house last night. Nothing was stolen of course, I would have went to the police otherwise.
The reason for my suspicion is a note that I found just beside the door. There were only few people who could get into my house, though I have restricted them to do so! The maid *Margret*, my girlfriend *Aaliyah* and the house owner *Chester*. I am sure *Chester* has kept duplicate keys for the house to himself, *Margret* and *Aaliyah* always have the keys. but I am still not sure if anyone of them or someone else broke into my house.
I have attached the message here.
>
> Rgffvvoi Cgdxz Hf Ahjy Gvqmhug Auyt Lnvt Xyze Hinas Iope Aipta Yuew
> Gagp
>
>
>
Also my notebook seemed to be misplaced on the table, it was kept open like someone checked it in a hurry and left it open there. There was also a note written on the page, a riddle of some kind, which I am sure I did not write.
>
> Crucial advice in a Sequence of prominent,
>
> Extract the components, only the dominant,
>
>
> Unravel the tangle with a Glass in Hand,
>
> Then offer Once "a single grain from the desert of sand".
>
>
>
I tried to crack what all this might mean, no luck so far. Maybe you can help me figure out the message?
>
> Also I strongly feel they might have left the clue for me to know who it was. (this can be considered as a hint, if you have found the name already)
>
>
>
Hint 1:
>
> The occurrence of the name in in the note has a particular order.
>
>
>
Hint 2:
>
> The order in Hint 1 is somehow **not** related to the first half of the riddle.
>
>
>
Hint 3:
>
> The Capital letters in riddle provide hints for solving steps and the cipher.
>
>
>
---
This is my first attempt at creating a puzzle. I would love to get feedback to improve my next puzzles. | 2018/08/30 | [
"https://puzzling.stackexchange.com/questions/71004",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/2368/"
] | So far I have caught four things here:
1.
>
> Dominant means Capital letters of the cipher - RCHAGALXHIAYG (length = 13) - something relating to rot13 cipher technique
>
>
>
2.
>
> If we leave the letters of Name "AALIYAH" here, we get fibonacci sequence from the index of the remaining letters - (R, C, H, G, X, G) -> (1, 2, 3, 5, 8, 13)
>
>
>
3.
>
> CSEUGHTO - all the capital letters in the note in your notebook is an anagram for -> "HUGE COST"
>
>
>
4.
>
> Glass in Hand and "a single grain from the desert of sand" might have something to do with time or hour-glass.
>
>
>
I am yet to connect these dots. | I think the author is
>
> Aaliyah, since you can find her name in the capital letters of the note
>
>
> |
2,873,807 | I have implemented a web app using session state management as per the instructions found on:
<http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx>
<http://en.aspnet-bhs.info/post/State-Server-Partitioning.aspx>
My SessionIDManager inheritor includes the code:
```
public class SessionIdManager : System.Web.SessionState.SessionIDManager
{
public override string CreateSessionID(System.Web.HttpContext context)
{...}
```
My web.config includes the code:
```
<machineKey
validationKey="1234567890123456789012345678901234567890AAAAAAAAAA"
decryptionKey="123456789012345678901234567890123456789012345678"
validation="SHA1"
decryption="Auto"
/>
...
<sessionState
mode="StateServer"
partitionResolverType="PartitionResolver"
sessionIDManagerType="SessionIdManager"
cookieless="false"
timeout="20"
/>
```
But the CreateSessionID method never gets called and so the session IDs do not get amended with the appropriate server ID.
Can someone tell me what is going on or what I might also need to consider that isn't mentioned in the articles?
I am using .NET2 with VS2k5.
Thanks,
Matt. | 2010/05/20 | [
"https://Stackoverflow.com/questions/2873807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71376/"
] | You can't. template are compile time only.
You can build at compile time all the possible templates values you want, and choose one of them in run time. | way too late, i know, but what about this:
```
// MSVC++ 2010 SP1 x86
// boost 1.53
#include <tuple>
#include <memory>
// test
#include <iostream>
#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/begin.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/unpack_args.hpp>
#include <boost/mpl/apply.hpp>
// test
#include <boost/range/algorithm/for_each.hpp>
/*! \internal
*/
namespace detail
{
/*! \internal
*/
namespace runtime_template
{
/*! \internal
fwd
*/
template <
typename Template
, typename Types
, typename Map // top level map iterator
, typename LastMap // top level map iterator
, int Index
, bool Done = std::is_same<Map, LastMap>::value
>
struct apply_recursive_t;
/*! \internal
fwd
*/
template <
typename Template
, typename Types
, typename Map // top level map iterator
, typename LastMap // top level map iterator
, typename First
, typename Last
, int Index
, bool Enable = !std::is_same<First, Last>::value
>
struct apply_mapping_recursive_t;
/*! \internal
run time compare key values + compile time push_back on \a Types
*/
template <
typename Template
, typename Types
, typename Map // top level map iterator
, typename LastMap // top level map iterator
, typename First
, typename Last
, int Index // current argument
, bool Enable /* = !std::is_same<First, Last>::value */
>
struct apply_mapping_recursive_t
{
typedef void result_type;
template <typename TypeIds, typename T>
inline static void apply(const TypeIds& typeIds, T&& t)
{ namespace mpl = boost::mpl;
typedef typename mpl::deref<First>::type key_value_pair;
typedef typename mpl::first<key_value_pair>::type typeId; // mpl::int
if (typeId::value == std::get<Index>(typeIds))
{
apply_recursive_t<
Template
, typename mpl::push_back<
Types
, typename mpl::second<key_value_pair>::type
>::type
, typename mpl::next<Map>::type
, LastMap
, Index + 1
>::apply(typeIds, std::forward<T>(t));
}
else
{
apply_mapping_recursive_t<
Template
, Types
, Map
, LastMap
, typename mpl::next<First>::type
, Last
, Index
>::apply(typeIds, std::forward<T>(t));
}
}
};
/*! \internal
mapping not found
\note should never be invoked, but must compile
*/
template <
typename Template
, typename Types
, typename Map // top level map iterator
, typename LastMap // top level map iterator
, typename First
, typename Last
, int Index
>
struct apply_mapping_recursive_t<
Template
, Types
, Map
, LastMap
, First
, Last
, Index
, false
>
{
typedef void result_type;
template <typename TypeIds, typename T>
inline static void apply(const TypeIds& /* typeIds */, T&& /* t */)
{
BOOST_ASSERT(false);
}
};
/*! \internal
push_back on \a Types template types recursively
*/
template <
typename Template
, typename Types
, typename Map // top level map iterator
, typename LastMap // top level map iterator
, int Index
, bool Done /* = std::is_same<Map, LastMap>::value */
>
struct apply_recursive_t
{
typedef void result_type;
template <typename TypeIds, typename T>
inline static void apply(const TypeIds& typeIds, T&& t)
{ namespace mpl = boost::mpl;
typedef typename mpl::deref<Map>::type Mapping; // [key;type] pair vector
apply_mapping_recursive_t<
Template
, Types
, Map
, LastMap
, typename mpl::begin<Mapping>::type
, typename mpl::end<Mapping>::type
, Index
>::apply(typeIds, std::forward<T>(t));
}
};
/*! \internal
done! replace mpl placeholders of \a Template with the now complete \a Types
and invoke result
*/
template <
typename Template
, typename Types
, typename Map
, typename LastMap
, int Index
>
struct apply_recursive_t<
Template
, Types
, Map
, LastMap
, Index
, true
>
{
typedef void result_type;
template <typename TypeIds, typename T>
inline static void apply(const TypeIds& /* typeIds */, T&& t)
{ namespace mpl = boost::mpl;
typename mpl::apply<
mpl::unpack_args<Template>
, Types
>::type()(std::forward<T>(t));
}
};
/*! \internal
helper functor to be used with invoke_runtime_template()
\note cool: mpl::apply works with nested placeholders types!
*/
template <typename Template>
struct make_runtime_template_t
{
typedef void result_type;
template <typename Base>
inline void operator()(std::unique_ptr<Base>* base) const
{
base->reset(new Template());
}
};
} // namespace runtime_template
} // namespace detail
/*! \brief runtime template parameter selection
\param Template functor<_, ...> placeholder expression
\param Maps mpl::vector<mpl::vector<mpl::pair<int, type>, ...>, ...>
\param Types std::tuple<int, ...> type ids
\param T functor argument type
\note all permutations must be compilable (they will be compiled of course)
\note compile time: O(n!) run time: O(n)
\sa invoke_runtime_template()
\author slow
*/
template <
typename Template
, typename Map
, typename Types
, typename T
>
inline void invoke_runtime_template(const Types& types, T&& t)
{ namespace mpl = boost::mpl;
BOOST_STATIC_ASSERT(mpl::size<Map>::value == std::tuple_size<Types>::value);
detail::runtime_template::apply_recursive_t<
Template
, mpl::vector<>
, typename mpl::begin<Map>::type
, typename mpl::end<Map>::type
, 0
>::apply(types, std::forward<T>(t));
}
/*! \sa invoke_runtime_template()
*/
template <
typename Template
, typename Map
, typename Base
, typename Types
>
inline void make_runtime_template(const Types& types, std::unique_ptr<Base>* base)
{
invoke_runtime_template<
detail::runtime_template::make_runtime_template_t<Template>
, Map
>(types, base);
}
/*! \overload
*/
template <
typename Base
, typename Template
, typename Map
, typename Types
>
inline std::unique_ptr<Base> make_runtime_template(const Types& types)
{
std::unique_ptr<Base> result;
make_runtime_template<Template, Map>(types, &result);
return result;
}
////////////////////////////////////////////////////////////////////////////////
namespace mpl = boost::mpl;
using mpl::_;
class MyClassInterface {
public:
virtual ~MyClassInterface() {}
virtual double foo(double) = 0;
};
template <int P1, int P2, int P3>
class MyClass
: public MyClassInterface {
public:
double foo(double /*a*/) {
// complex computation dependent on P1, P2, P3
std::wcout << typeid(MyClass<P1, P2, P3>).name() << std::endl;
return 42.0;
}
// more methods and fields (dependent on P1, P2, P3)
};
// wrapper for transforming types (mpl::int) to values
template <typename P1, typename P2, typename P3>
struct MyFactory
{
inline void operator()(std::unique_ptr<MyClassInterface>* result) const
{
result->reset(new MyClass<P1::value, P2::value, P3::value>());
}
};
template <int I>
struct MyConstant
: boost::mpl::pair<
boost::mpl::int_<I>
, boost::mpl::int_<I>
> {};
std::unique_ptr<MyClassInterface> Factor(const std::tuple<int, int, int>& constants) {
typedef mpl::vector<
MyConstant<0>
, MyConstant<1>
, MyConstant<2>
, MyConstant<3>
// ...
> MyRange;
std::unique_ptr<MyClassInterface> result;
invoke_runtime_template<
MyFactory<_, _, _>
, mpl::vector<MyRange, MyRange, MyRange>
>(constants, &result);
return result;
}
int main(int /*argc*/, char* /*argv*/[])
{
typedef std::tuple<int, int, int> Tuple;
const Tuple Permutations[] =
{
std::make_tuple(0, 0, 0)
, std::make_tuple(0, 0, 1)
, std::make_tuple(0, 1, 0)
, std::make_tuple(0, 1, 1)
, std::make_tuple(1, 0, 0)
, std::make_tuple(1, 2, 3)
, std::make_tuple(1, 1, 0)
, std::make_tuple(1, 1, 1)
// ...
};
boost::for_each(Permutations, [](const Tuple& constants) { Factor(constants)->foo(42.0); });
return 0;
}
``` |
66,911,516 | I have been using the following Excel VBA macro to bring back data from a website. It worked fine until a few days ago when the website stopped supporting IE. Of course the macro just fails now as there is no data on the webpage to bring back to Excel, just a message saying, "Your browser, Internet Explorer, is no longer supported." Is there a way to have the "Get method" (MSXML2.XMLHTTP) use Chrome instead of IE to interact with the website? BTW, my default browser is already set to "Chrome".
```
Dim html_doc As HTMLDocument ' note: reference to Microsoft HTML Object Library must be set
Sub KS()
' Define product url
KS_url = "https://www.kingsoopers.com/p/r-w-knudsen-just-blueberry-juice/0007468210784"
' Collect data
Set html_doc = New HTMLDocument
Set xml_obj = CreateObject("MSXML2.XMLHTTP")
xml_obj.Open "GET", KS_url, False
xml_obj.send
html_doc.body.innerHTML = xml_obj.responseText
Set xml_obj = Nothing
KS_product = html_doc.getElementsByClassName("ProductDetails-header")(0).innerText
KS_price = "$" & html_doc.getElementsByClassName("kds-Price kds-Price--alternate mb-8")(1).Value
do Stuff
End Sub
``` | 2021/04/01 | [
"https://Stackoverflow.com/questions/66911516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2604372/"
] | [](https://imgflip.com/i/543w7g)
The check for this is a basic server check on user agent. Tell it what it wants to "hear" by passing a supported browser in the UA header...(or technically, in this case, just saying the equivalent of: "Hi, I am not Internet Explorer".)
It can be as simple as `xml.setRequestHeader "User-Agent", "Chrome"`. I said basic because you could even pass `xml.setRequestHeader "User-Agent", "I am a unicorn"`, so it is likely an exclusion based list on the server for Internet Explorer.
```
Option Explicit
Public Sub KS()
Dim url As String
url = "https://www.kingsoopers.com/p/r-w-knudsen-just-blueberry-juice/0007468210784"
Dim html As MSHTML.HTMLDocument, xml As Object
Set html = New MSHTML.HTMLDocument
Set xml = CreateObject("MSXML2.XMLHTTP")
xml.Open "GET", url, False
xml.setRequestHeader "User-Agent", "Mozilla/5.0"
xml.send
html.body.innerHTML = xml.responseText
Debug.Print html.getElementsByClassName("ProductDetails-header")(0).innerText
Debug.Print "$" & html.getElementsByClassName("kds-Price kds-Price--alternate mb-8")(1).Value
Stop
End Sub
```
Compare that with adding no UA or adding `xml.setRequestHeader "User-Agent", "MSIE"`. | Study the article here by *Daniel Pineault* and this paragraph:
[Feature Browser Emulation](https://www.devhut.net/2019/10/18/everything-you-never-wanted-to-know-about-the-access-webbrowser-control/)
Also note my comment dated 2020-09-13. |
8,309 | Suppose there is a person who openly denies the divinity of the Torah, breaks the Sabbath and declares himself an atheist, but goes to synagogue for the sense of community or for cultural reasons. Can he be counted in the minyan, lead the prayers, or read from the Torah? I am asking of course from a traditional or Orthodox perspective. | 2011/06/16 | [
"https://judaism.stackexchange.com/questions/8309",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/691/"
] | No. In general, if the person is willing to violate the sabbath in public and even in front of a great rabbi, we assume he cannot count for a minyan. Rabbi Nachum Rabinovitch, (*All Jews Are Responsible for One Another*, from "Tradition and the Nontraditional Jew") based on the Rambam, says that chilul shabbos may not disqualify them if they are a *tinok shenishba*, but they have to accept the halachik requirements of a minyan to be counted for one. The Rambam said that the kaarites could not be counted for a Zimun because they rejected such halachos, so they cannot just be counted in for social reasons. | one doesn't have to also be an apikores someone who simply does not keep shabbos is not to be counted as part of the minyan. this is the straightforward halacha
here are some things to consider though. there are no apikorsim today. in order to be an apekoris one has to have a great deal of Torah knowledge and understand everything that one is rejecting to begin with. This does not fit the description of many people and possible no one in our time.
The baalei teshuvah movement has grown and continues to grown over time. consider that many people who have reconnected with yiddishkeit would have never done so if they were thrown out of synagogue or even slighted by not being counted in the minyan. After all a yid is a yid and this person coming to the shul is there to learn about something completely new to them that they didn't even know existed or didn't really understand before.
makes me think of the case of which a husband and wife divorce and remarry and therefore and not allowed to remarry each other. however, a genuine teshuvah can bring them back together.
I'm sure you can find better written answers in halachic guidelines written specifically for this subject as it is most relevant in kiruv type shuls. as of right now I am unaware of a specific source for such a thing but perhaps if you go to the aish hatorah website or chabad.org they can help you find something |
37,006,225 | I need to refresh the dataset on a powerbi desktop file. The data source is an excel file placed on my onedrive for business folder - to which I have access to. I also saved my pbix file in the folder, however I am using a Mac as of the moment and the only way I'm thinking of is to share the pbix file from one drive to my colleague from work. Will that work, or is there any other way to refresh the data without connecting to the desktop file?
P.S. I've check the refresh, but since my work laptop is offline - I can't schedule a refresh | 2016/05/03 | [
"https://Stackoverflow.com/questions/37006225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172172/"
] | To avoid having lengthy JSON structure inline in your fixtures, YAML provide a useful `>` operator
```
fixture_id:
existing_column: "foobar"
data: >
{
"can_edit": true,
"can_se": true,
"can_share": true,
"something_else": true
}
``` | I was maintaining a legacy Rails 4.2 application and needed to put JSON store value into a fixture. I made the following monkey patch to fix the problem. Hope this helps someone:
```rb
module ActiveRecord
class Fixture
def to_hash
h = fixture
model_class.attribute_names.each do |name|
typedef = model_class.type_for_attribute(name)
h[name] = typedef.coder.dump(h[name]) \
if typedef.is_a? ActiveRecord::Type::Serialized
end
h
end
end
end
``` |
30,602 | [](https://i.stack.imgur.com/Ll7Fg.png)
Undoubtedly, the largest empire in the existence of human history was the Mongol Empire, once a hodgepodge of warring nomadic tribes from Central Asia before banding together under the banner of Temujin, better known as Genghis Khan.
But what was the key to the Mongol Empire's size? Was the horse, the most ideal creature to use for long-distance travel, the exclusive reason? Or were there other factors involved? | 2016/06/29 | [
"https://history.stackexchange.com/questions/30602",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/15700/"
] | Instead of a long list of factors, it actually comes down to one point: **military**. They were the superpower from 13th century onward and had the best military, by which I mean **[Operational Art](http://www.au.af.mil/au/awc/awcgate/opart/opart-jrm.htm)**. This is from the Air War College of **[US Air Force](http://www.af.mil/)** (see link before):
>
> **Overview of Operational Art**
>
>
> Joint Force Commanders (JFCs) employ operational art, in concert with strategic guidance and direction received from superior leaders, in developing campaigns and operations. Operational art is the use of military forces to achieve strategic goals through the design, organization, integration, and conduct of strategies, campaigns, major operations, and battles.
>
>
> Operational art helps commanders use resources efficiently and effectively to achieve strategic objectives. Without operational art, war would be a set of disconnected engagements, with relative attrition the only measure of success or failure. Operational art requires broad vision, the ability to anticipate, and effective joint and multinational cooperation. Operational art is practiced not only by JFCs, but also by their senior staff officers and subordinate commanders.
>
>
>
In terms of [pitched-battles](https://en.wikipedia.org/wiki/Pitched_battle), the Mongol army was more than 700 years ahead of other armies (i.e. *rest of us*). The other armies never understood why they kept losing and the first '*Western*' army that did were the **USSR** during **World War II** (influence from Golden Horde?): [**doctrine of deep battle**](https://en.wikipedia.org/wiki/Red_Army_tactics_in_World_War_II).
Only in the last few decades, with better research on Mongolian military and history, did modern armies finally begin to appreciate the Mongol generals' superiority:
* ***[Command and Control Began with Subotai Bahadur, the Thirteenth Century Mongol General (2010)](http://www.dtic.mil/get-tr-doc/pdf?AD=ADA600354)*** by ***Lieutenant Commander Sean Slappy, United States Navy***
* ***[Genghis Khan’s Greatest General: Subotai the Valiant (2006)](https://rads.stackoverflow.com/amzn/click/com/0806137347)*** by **[Richard A. Gabriel](https://en.wikipedia.org/wiki/Richard_A._Gabriel)**, a professor of history and politics at the [**U.S. Army War College**](https://en.wikipedia.org/wiki/United_States_Army_War_College)
To be clear, I am not saying that no other military leader since the Mongols had an ability in Operational Art. For instance, **[General Matthew Ridgway clearly demonstrated this](https://www.ausa.org/publications/general-matthew-b-ridgway-commander%E2%80%99s-maturation-operational-art)** during Korea War, 1950. | By intervening in the internal affairs of other large empires (China, Persia, Kievan Rus) etc., and winning.
China, for instance, was split between the [Jin and Song dynasties](https://en.wikipedia.org/wiki/Jin%E2%80%93Song_Wars). So the Mongols allied with the Song against the Jin, and after defeating the Jin, gathered up Chinese "not Songs" against the Song.
In Persia, the Mongols benefited from the fact that the Sultan of Kwarazem was at odds with his "boss," the Caliph of Bagdad. Each of them had to worry about the other, as well as the Mongols, so the Mongols beat both.
In Russia, it was the "other way." They had beaten a Turkish people called the Cumans around the Caspian Sea. The King of the Cumans was the father in law of the King of the Galicians, (which later became part of the Ukraine), and he dragged his son in law into a war with the Mongols, and [both lost.](https://en.wikipedia.org/wiki/Battle_of_the_Kalka_River) |
34,383,548 | Backstory: I've made a lot of large and relatively complex projects in Java, have a lot of experience in embedded C programming. I've got acquainted with scheme and CL syntax and wrote some simple programms with racket.
Question: I've planned a rather big project and want to do it in racket. I've heard a lot of "if you "get" lisp, you will become a better programmer", etc. But every time I try to plan or write a program I still "decompose" the task with familiar stateful objects with interfaces.
Are there "design patterns" for lisp? How to "get" lisp-family "mojo"? How to escape object-oriented constraint on your thinking? How to apply functional programming ideas boosted by powerful macro-facitilties? I tried studying source code of big projects on github (Light Table, for instance) and got more confused, rather than enlightened.
EDIT1 (less ambigious questions): is there a good literatue on the topic, that you can recommend or are there good open source projects written in cl/scheme/clojure that are of high quality and can serve as a good example? | 2015/12/20 | [
"https://Stackoverflow.com/questions/34383548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2335364/"
] | A number of "paradigms" have come into fashion over the years:
structured programming, object oriented, functional, etc. More will come.
Even after a paradigm falls out of fashion, it can still be good at solving the particular problems that first made it popular.
So for example using OOP for a GUI is still natural. (Most GUI frameworks have a bunch of states modified by messages/events.)
---
Racket is multi-paradigm. It has a `class` system. I rarely use it,
but it's available when an OO approach makes sense for the problem.
Common Lisp has multimethods and CLOS. Clojure has multimethods and Java class interop.
And anyway, basic stateful OOP ~= mutating a variable in a closure:
```
#lang racket
;; My First Little Object
(define obj
(let ([val #f])
(match-lambda*
[(list) val]
[(list 'double) (set! val (* 2 val))]
[(list v) (set! val v)])))
obj ;#<procedure:obj>
(obj) ;#f
(obj 42)
(obj) ;42
(obj 'double)
(obj) ;84
```
Is this a great object system? No. But it helps you see that the essence of OOP is encapsulating state with functions that modify it. And you can do this in Lisp, easily.
---
What I'm getting at: I don't think using Lisp is about being "anti-OOP" or "pro-functional". Instead, it's a great way to play with (and use in production) the basic building blocks of programming. You can explore different paradigms. You can experiment with ideas like "code is data and vice versa".
I don't see Lisp as some sort of spiritual experience. At most, it's like Zen, and satori is the realization that all of these paradigms are just different sides of the same coin. They're all wonderful, and they all suck. The paradigm pointing at the solution, is not the solution. Blah blah blah. :)
---
My practical advice is, it sounds like you want to round out your experience with functional programming. If you must do this the first time on a big project, that's challenging. But in that case, try to break your program into pieces that "maintain state" vs. "calculate things". The latter are where you can try to focus on "being more functional". Look for opportunities to write pure functions. Chain them together. Learn how to use higher-order functions. And finally, connect them to the rest of your application -- which can continue to be stateful and OOP and imperative. That's OK, for now, and maybe forever. | The "Gang of 4" design patterns apply to the Lisp family just as much as they do to other languages. I use CL, so this is more of a CL perspective/commentary.
Here's the difference: Think in terms of methods that operate on families of types. That's what `defgeneric` and `defmethod` are all about. You should use `defstruct` and `defclass` as containers for your data, keeping in mind that all you really get are accessors to the data. `defmethod` is basically your usual class method (more or less) from the perspective of an operator on a group of classes or types (multiple inheritance.)
You'll find that you'll use `defun` and `define` a lot. That's normal. When you do see commonality in parameter lists and associated types, then you'll optimize using `defgeneric`/`defmethod`. (Look for CL quadtree code on github, for an example.)
Macros: Useful when you need to glue code around a set of forms. Like when you need to ensure that resources are reclaimed (closing files) or the C++ "protocol" style using protected virtual methods to ensure specific pre- and post-processing.
And, finally, don't hesitate to return a `lambda` to encapsulate internal machinery. That's probably the best way to implement an iterator ("let over lambda" style.)
Hope this gets you started. |
3,756 | I have an underlying function f(x,y,z) that is computationally intensive, but is smooth and continuous. I'm needing to find the function values along a line in xyz. Currently, I'm calculating f at discrete steps and I'm wondering if there is a way to get *Mathematica* to automatically chose the step size and work out an interpolating function based on some inputs like how accurate I need it to be and what the initial step size should be. I'm thinking it would kind of work like the mesh function does in plotting by evaluating functions more often in areas of higher complexity.
Does anyone have any ideas where to start? | 2012/03/31 | [
"https://mathematica.stackexchange.com/questions/3756",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/895/"
] | As far as I know, there is no built-in function to do this. However, what you can do is a heavy abuse of `Part` to extract the points from a `Plot` object:
```
g = Plot[Sin[x], {x, 0, 2 Pi}]
```
>
> 
>
>
>
The `InputForm`, i.e. how Mathematica sees this picture internally, looks like like this:
>
>
> ```
> Graphics[{{{}, {}, {Hue[0.67, 0.6, 0.6], Line[{{1.2*^-7, 1.2*^-7}, [long list of points]} ... (options etc)
>
> ```
>
>
You can now extract these points by using `Part`, i.e. `[[ ]]`:
```
points = g[[1, 1, 3, 2, 1]]
```
>
>
> ```
> {{0., 0.}, {0.01, 0.01}, {0.02, 0.02}, {0.03, 0.03}, {0.06, 0.06}, ...
>
> ```
>
>
This can now be used for a `ListPlot` to visualize the points extracted:
```
ListPlot[points]
```
>
> 
>
>
>
The density of points and the recursion can be set usual when plotting, i.e. `PlotPoints` and `MaxRecursion`.
Remarks:
1. I've rounded the values above heavily so it doesn't blow up the answer. Usually the numbers are much more precise.
2. Bear in mind that this does extractions from `Plot` that are not supposed to be done. For this reason, you should be especially careful setting plotting parameters and things like these, as I could imagine that some of them may change the structure of the `Graphics` object you're extracting the data from. | Whenever I want to do cheap adaptive sampling along a function, I used to do what David did back in old versions of *Mathematica*. Nowadays, I proceed like so:
```
pts = Cases[Normal[Plot[Sin[x], {x, 0, 2 π}, Mesh -> All]], Point[pt_] :> pt, ∞];
```
`ListPlot[pts]` should yield an image similar to the one in David's answer. A similar procedure can be done for parametrically-defined plane curves (via `ParametricPlot[]`) and space curves (via `ParametricPlot3D[]`). |
425,273 | I edited .bashrc file with PATH value, but when I open a new terminal after this, none of command is working.
When i am opening a new terminal its giving :
```
bash: export: `/usr/lib/java/jdk1.7.0_51': not a valid identifier
bash: export: `=/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/shilpa/sqllib/bin:/home/shilpa/sqllib/adm:/home/shilpa/sqllib/misc:/home/shilpa/sqllib/db2tss/bin:/bin': not a valid identifier
bash: export: `/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/shilpa/sqllib/bin:/home/shilpa/sqllib/adm:/home/shilpa/sqllib/misc:/home/shilpa/sqllib/db2tss/bin:Downloads/hadoop-1.2.1/bin': not a valid identifier
shilpa@ubuntu:~$ ls
bash: ls: No such file or directory
```
Please help me with this. | 2014/02/23 | [
"https://askubuntu.com/questions/425273",
"https://askubuntu.com",
"https://askubuntu.com/users/251560/"
] | Probably you messed up the .bashrc file in your home directory.
Check it for errors or make a backup copy of the file and replace it with the example copy in `/etc/skel/.bashrc` | You have add some wrong code inside the bashrc file. Just type following raw in a new terminal. if it gives errors do it twice.
```
PATH=/bin:/usr/bin
``` |
60,566,445 | Say I have a master branch and a feature branch called FA1 that is branched off master and I have another feature branch called FA2 that is branched off FA1.
When I'm working on FA2 and I want to bring changes from FA1, I do: `git rebase -i FA1`.
However, at some point FA1 gets merged into master and I want to change FA2 to be based off master now, it no longer makes sense that is branched off FA1.
What is the proper approach to change the target branch of FA2 to be master OR in other words, for FA2 to be up to date with master. | 2020/03/06 | [
"https://Stackoverflow.com/questions/60566445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196150/"
] | Make FA2 derive directly from master :
```
git checkout FA2
git rebase FA1 FA2
git rebase --onto master FA1 FA2
```
see the [rebase documentation](https://git-scm.com/docs/git-rebase) | >
> [...] it no longer makes sense that is branched off FA1 [...]
>
>
>
This is not quite true. Whether branch `FA2` still exists or not, `FA1` stays branched off *the same commit*.
If you then need to bring into `FA2` recent commits merged into `master`, yes, you can indeed rebase `FA2` on `master` as you did before with `FA1`. |
14,453,270 | When we create a Subclass object which extends an abstract class, the abstract class constructor also runs . But we know we cannot create objects of an abstract class. Hence does it mean that even if a constructor completes running without any exception, there is no guarantee whether an object is created? | 2013/01/22 | [
"https://Stackoverflow.com/questions/14453270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163607/"
] | >
> Hence does it mean that even if a constructor completes running
> without any exception, there is no guarantee whether an object is
> created?
>
>
>
Simply speaking, a `constructor` does not create an object. It just *initializes* the *state* of the object. It's the `new` operator which creates the object. Now, let's understand this in little detail.
When you create an object using statement like this:
```
new MyClass();
```
The object is first created by the `new` operator. Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object.
---
Now consider the case of `Abstract class` and it's concrete `SubClass`, when you do like this:
```
AbstractClass obj = new ConcreteClass();
```
`new` operator creates an object of `ConcreteClass`, and invokes its constructor to initialize the state of the created object. In this process, the constructor of the abstract class is also called from the `ConcreteClass` constructor, to initialize the state of the object in the abstract class.
So, basically the object of `AbstractClass` is not created. It's just that it's constructor is invoked to initialize the state of the object.
**Lessons Learnt:**
* The object is created by `new` operator, and not by the invocation of the constructor itself. *So, the object is **already created before any constructor** is invoked.*
* Constructor is just used to initialize the state of the object created. It does not create an object itself.
* An object state can also be contained in an abstract super class.
* So, the purpose of invocation of `Abstract class` constructor, is only to initialize the object completely, and no object is created in process.
**See:**
* [Creation of new Class Instance - JLS-Section#12.5](http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5) | Barring any exceptions, the abstract class constructor is only run from within the subclass's constructor (as the first statement). Therefore you can be sure that every time a constructor is run, it is in the process of creating an object.
That said, you may call more than one constructor in the process of creating a single object, such as `Subclass()` calling `Subclass(String)` which calls `AbstractClass` via a `super()`call, and so forth. |
2,905,023 | From Excel, I need to open an Access database and run one of the database's macros.
I'm using Excel and Access 2007. Here is my code in Excel:
```
Sub accessMacro()
Dim appAccess As New Access.Application
Set appAccess = Access.Application
appAccess.OpenCurrentDatabase "C:\blah.mdb"
appAccess.Visible = True
appAccess.DoCmd.RunMacro "RunQueries.RunQueries"
appAccess.CloseCurrentDatabase
End Sub
```
In the Access database, there is a procedure named RunQueries in a module named RunQueries.
I get:
>
> Runtime error '2485':
>
> Microsoft Access Office can't find the object 'RunQueries.'
>
>
>
I also tried
```
appAccess.DoCmd.RunMacro "RunQueries"
```
and I get the same errors message.
I argued against it, and I have to do it this way (meaning, I have to use Excel as a frontend to open several Access dbs and run their macros). | 2010/05/25 | [
"https://Stackoverflow.com/questions/2905023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123930/"
] | ```
Sub accessMacro()
Dim appAccess As Access.Application
Set appAccess = New Access.Application
appAccess.OpenCurrentDatabase "C:\blah.mdb"
appAccess.Visible = True
appAccess.DoCmd.RunMacro "Macro Name" '<-- As it appears in the Macro Group in the Access Interface.
appAccess.CloseCurrentDatabase
End Sub
``` | The msdn site didn't shed too much light, but I have a feeling that their disclaimer applies here. Here's what they mentioned:
>
> If you run Visual Basic code containing the RunMacro method in a
> library database, Microsoft Access looks for the macro with this name
> in the library database and doesn't look for it in the current
> database.
>
>
>
Of course they don't mention how exactly to remedy this issue! But after reviewing the answers above I think it would be helpful to post a full answer:
```
Sub accessMacro()
Dim appAccess As New Access.Application
Set appAccess = Access.Application
appAccess.OpenCurrentDatabase "C:\blah.mdb"
appAccess.Visible = True
appAccess.Run "RunQueries"
appAccess.CloseCurrentDatabase
End Sub
```
This worked when I ran it. Good luck! :D
-Reverus |
8,224,700 | How can I check whether a C# variable is an empty string `""` or null?
I am looking for the simplest way to do this check. I have a variable that can be equal to `""` or null. Is there a single function that can check if it's not `""` or null? | 2011/11/22 | [
"https://Stackoverflow.com/questions/8224700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975566/"
] | Since .NET 2.0 you can use:
```
// Indicates whether the specified string is null or an Empty string.
string.IsNullOrEmpty(string value);
```
Additionally, since .NET 4.0 there's a new method that goes a bit farther:
```
// Indicates whether a specified string is null, empty, or consists only of white-space characters.
string.IsNullOrWhiteSpace(string value);
``` | if the variable is a string
```
bool result = string.IsNullOrEmpty(variableToTest);
```
if you only have an object which may or may not contain a string then
```
bool result = string.IsNullOrEmpty(variableToTest as string);
``` |
8,158,784 | I have a problem with my code posted below, set and get methods. I want to call it like this `this.LastError.Set(1);`
But it gives me this error: *'int' does not contain a definition for 'Set' and no extension method 'Set' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)*
```
public class MyClass
{
private int ERROR_NUM = 0;
public int LastError
{
get { return ERROR_NUM; }
set { ERROR_NUM = value; }
}
bool IsLoaded()
{
int count = Process.GetProcessesByName("AppName").Length;
if (count == 1) return true;
if (count > 1) this.LastError.Set(1);
return false;
}
}
```
I know this is probably a dumb question so sorry for that, I've been fighting with this thing for a couple hours now and I've even gone so far as to try and give the LastError its own class. This is my first day on C#. | 2011/11/16 | [
"https://Stackoverflow.com/questions/8158784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820750/"
] | The whole point of properties is that they look like fields, you can get and set them like fields:
```
this.LastError = 1; // set the value
int lastError = this.LastError; // get the value
```
The property is compiled as two methods, `set_LastError()` and `get_LastError()`. You can't use them from C#, but the compiler can and compiles the code above to something like:
```
this.set_LastError(1);
int lastError = this.get_LastError();
``` | To set a property in C# simply use the "=" operator.
```
this.LastError = <myvalue>;
``` |
73,460,571 | I have a spreadsheet that is connected a Hubspot workflow. When a deal is closed in our CRM, Hubspot creates a new row on the sheet with 3 pieces of data from the deal. Due to Hubspot's recommended best practices for working with Google Sheets integration, I have another sheet where I reference data from the sheet that receives the data. The problem arose when I realized that the reference sheet would not automatically refresh when new data was written to the synced sheet. So, I created a macro that copies the formula down using the fill handle every 5 minutes. This rescans the synced sheet and writes any new data to the reference sheet. This morning I woke up and there was some new data that should have been copied over to the reference sheet -- however it wasn't. I checked that the macro is running every 5 minutes, and it is. For the hell of it, I went to the menu and manually ran the macro and, to my surprise, it actually worked! I want this to be fully automated though and don't want to have to manually run a macro everytime I want the data to get copied over.
Data gets synced here 
Data is referenced here 
Macro Code:
```js
/** @OnlyCurrentDoc */
function RefreshData() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A75').activate();
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('A75:A223'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
spreadsheet.getRange('B75').activate();
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('B75:B234'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
spreadsheet.getRange('C75').activate();
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('C75:C232'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
spreadsheet.getRange('C75:C232').activate();
};
``` | 2022/08/23 | [
"https://Stackoverflow.com/questions/73460571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11354588/"
] | recurse. You can't remove while enumerating. Make a list first, then remove
NOTE: this works for the nested controls
```cs
private removeList = new Dictionary<Control, Label>();
private void EnumerateLabels(Control ctrl)
{
foreach (var c in ctrl.Controls)
{
if (c is Label && c.Name.StartsWith("ToClear"))
removeList.Add(ctrl, c);
EnumerateLabels(c); // recurse children
}
}
```
usage
```cs
// assuming `this` is a form
EnumerateLabels(this);
foreach (var kvp in removeList)
kvp.Key.Controls.Remove(kvp.Value);
```
Disclaimer - not tested | You can do it via `RemoveAll`:
```
this.Controls.RemoveAll(c => (c is Label) && c.Name.StartsWith("ToClear"));
```
See more here: <https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=net-6.0> |
3,745,491 | I would like to test my application with new Samsung Galaxy Tab tablet.
What parameter should I set in the emulator to emulate this device?
* What resolution and density should I set?
* How can I indicate that this is a large screen device?
* What hardware does this tablet support?
* What is the max heap size?
* Which Android version? | 2010/09/19 | [
"https://Stackoverflow.com/questions/3745491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361832/"
] | Go to this link ... <https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml>
Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.
Happy Android developments guys!!! | I don't know if it is help.
Create an AVD for a tablet-type device:
Set the target to "Android 3.0" and the skin to "WXGA" (the default skin).
You can check this site.
<http://developer.android.com/guide/practices/optimizing-for-3.0.html> |
9,442,694 | Is this even possible, few argue its possible and i saw it here too [link](https://stackoverflow.com/questions/677595/initialize-final-variable-before-constructor-in-java).. but when i personally tried it gives me compile time errors..
i mean this,
```
Class A{
private final String data;
public A(){
data = "new string";
}
}
```
Thanks in advance.. | 2012/02/25 | [
"https://Stackoverflow.com/questions/9442694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/746710/"
] | Yes, it is possible. Class is written with small case c. Otherwise your code is perfectly fine (except for identation):
```
public class A {
private final String data;
public A() {
data = "new string";
}
}
``` | It is likely that you are having more than one constructor, in that case you must initialize the final instance field in each of those constructors. |
36,770,865 | I have the following string:
>
> 2016-04-29T00:00:00+01:00
>
>
>
I want to turn it into a Unix date timestamp using Python.
I've tried this to convert it into a date object:
```
dt = datetime.datetime.strptime(validated_data.get('scheduled_datetime', None), '%Y-%m-%dT%H:%M:%SZ')
```
But I get the following error:
```
time data '2016-04-29T00:00:00+01:00' does not match format '%Y-%m-%dT%H:%M:%S'
``` | 2016/04/21 | [
"https://Stackoverflow.com/questions/36770865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578822/"
] | ```
2016-04-29T00:00:00+01:00
```
is not in a form that [`strptime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) can understand. It supports
>
> `%z` UTC offset in the form +HHMM or -HHMM
>
>
>
but note that there is no colon `:` in the timezone!
So first remove the colon `:` from your input and then use `%z`. | If you want to return the current date in a specific format, you should use time.strftime().
```
import time
currentDate = time.strftime('%Y-%m-%dTT%H:%M:%SZ')
```
No need to over complicate things with datetime.
Note: You may need to change some of the formatting characters in order to get the output you want. |
63,603,021 | My problem is similar to this: [R dplyr rowwise mean or min and other methods?](https://stackoverflow.com/questions/31598935/r-dplyr-rowwise-mean-or-min-and-other-methods#31601490)
Wondering if there is any [dplyr](/questions/tagged/dplyr "show questions tagged 'dplyr'") functions (or combination of functions such as `pivot_` etc.), that might give the desired output in a usual *dplyr one-liner*?
```
library(tidyverse); set.seed(1);
#Sample Data:
sampleData <- data.frame(O = seq(1, 9, by = .1), A = rnorm(81), U = sample(1:81,
81), I = rlnorm(81), R = sample(c(1, 81), 81, replace = T)); #sampleData;
#NormalOuput:
NormalOuput <- sampleData %>% summarise_all(list(min = min, max = max));
NormalOuput;
#> O_min A_min U_min I_min R_min O_max A_max U_max I_max R_max
#> 1 1 -2.2147 1 0.1970368 1 9 2.401618 81 14.27712 81
#Expected output:
ExpectedOuput <- data.frame(stats = c('min', 'max'), O = c(1, 9), A = c(-2.2147,
2.401618), U = c(1, 81), I = c(0.1970368, 14.27712), R = c(1, 81));
ExpectedOuput;
#> stats O A U I R
#> 1 min 1 -2.214700 1 0.1970368 1
#> 2 max 9 2.401618 81 14.2771200 81
```
Created on 2020-08-26 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
**Note:**
The number of columns might be huge in the real scenario, so the names cannot be called directly.
**EDIT**
At best, I get this:
```
sampleData %>% summarise(across(everything(), list(min = min, max = max))) %>%
t() %>% data.frame(Value = .) %>% tibble::rownames_to_column('Variables')
Variables Value
1 O_min 1.0000000
2 O_max 9.0000000
3 A_min -2.2146999
4 A_max 2.4016178
5 U_min 1.0000000
6 U_max 81.0000000
7 I_min 0.1970368
8 I_max 14.2771167
9 R_min 1.0000000
10 R_max 81.0000000
``` | 2020/08/26 | [
"https://Stackoverflow.com/questions/63603021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9592557/"
] | I would suggest a mix of `tidyverse` functions like next. You have to reshape your data, then aggregate with the summary functions you want and then as strategy you can re format again and obtain the expected output:
```
library(tidyverse)
sampleData %>% pivot_longer(cols = names(sampleData)) %>%
group_by(name) %>% summarise(Min=min(value,na.rm=T),
Max=max(value,na.rm=T)) %>%
rename(var=name) %>%
pivot_longer(cols = -var) %>%
pivot_wider(names_from = var,values_from=value)
```
The output:
```
# A tibble: 2 x 6
name A I O R U
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Min -2.21 0.197 1 1 1
2 Max 2.40 14.3 9 81 81
``` | While playing with `pivot_longer`, I discovered that this two-step one-liner also works (building on the answer by @Gregor Thomas, here only one `pivot_` in stead of two or more):
```
sampleData %>%
summarise(across(everything(), list(min, max))) %>%
pivot_longer(everything(), names_to = c(".value", "stats"),
names_sep = "_")
# A tibble: 2 x 6
stats O A U I R
<chr> <dbl> <dbl> <int> <dbl> <dbl>
1 1 1 -2.21 1 0.197 1
2 2 9 2.40 81 14.3 81
```
More here: <https://tidyr.tidyverse.org/reference/pivot_longer.html#examples> |
264,380 | In the review system you can only review 20 posts in each queue, except the Close Votes queue which gives 40 reviews.
And if you did complete this queue then you can do more review the next day.
So questions raised:
1. Is there any option available that a user can do more than 20 reviews?
2. Is there a moderation privilege for more reviews?
3. Is it available in the near future? Or do we have to contact to moderators for more reviews in a queue?
We all know that moderation is a vital part of SO, I'm very eager to know any positive spotlight for the above concern. | 2015/08/28 | [
"https://meta.stackexchange.com/questions/264380",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/266872/"
] | No, as far as I know, there are no plans to increase the reviews per day for ordinary users.
Worth to mention that only on Stack Overflow we have 40 close reviews per day, due to the huge queue in there, on other sites it's the usual 20.
If you really want more, do your best, and nominate yourself to become a moderator: moderators have unlimited reviews per day. | I would imagine there are various reasons behind the decision to limit, one of the most notable ones is from [an answer](https://meta.stackexchange.com/a/102223/230506) by Jeff Atwood:
>
> We really want vote diversity here, so that's the point of the limits
> -- if the same 2 folks are vetting all the edits, that's not a sufficient set of eyeballs on those edits
>
>
>
Also, having a higher daily review cap means you open up the doors to more bad reviews, from robo-reviewers, people just aiming for badges, etc. And even those attempting to do good reviews should perhaps take a break - i.e. 20 reviews in a day is enough for anyone really.
This does of course hinder our getting more reviews done by those users who would carry out good reviews with their additional - but such is the world, the few can spoil it for the many because the negative effect of the few outweighs the benefits of the many.
---
>
> We all know that moderation is a vital part of SO, I'm very eager to
> know any positive spotlight for the above concern.
>
>
>
What concern? Is there a *need* for users doing *more* reviews than they can now? Is there a queue with a problem?
Even on Stack Overflow (ignoring close votes) the queues are turned around pretty quickly.
When I see a few hundred reviews in Triage or LQP, 5 or 10 mins later they're all done. |
4,911 | I have a problem with SQL code in a PDF document. For code representation I'm using the `listings` package. Everything works perfect until I copy-paste that code from the created PDF document. I get some phantom spaces in string type.
When people are reading my PDF document, they need to copy-paste some of the code. Visually the code looks good in PDF, but when I try to copy-paste my code to NotePad or any other editor I get some unexpected spaces in strings.
In the example below, when I copy-paste my SQL code, instead of getting:
```
SELECT ST_Area(the_geom)
FROM katastar
WHERE kc_broj = '1414';
```
I get
```
SELECT ST_Area(the_geom)
FROM katastar
WHERE kc_broj = ' 1414 ';
```
See the spaces in between quotes.
```
\documentclass{article}
\usepackage{listings,xcolor}
\lstset{
tabsize=4,
basicstyle=\scriptsize,
%upquote=false,
aboveskip=\baselineskip,
columns=fixed,
showstringspaces=false,
extendedchars=true,
breaklines=true,
prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
frame=single,
showtabs=false,
showspaces=false,
identifierstyle=\ttfamily,
keywordstyle=\color[rgb]{0,0,1},
commentstyle=\color[rgb]{0.133,0.545,0.133},
stringstyle=\color[rgb]{0.627,0.126,0.941},
language=SQL
}
\begin{document}
\begin{lstlisting}
SELECT ST_Area(the_geom)
FROM katastar
WHERE kc_broj = '1414';
\end{lstlisting}
\end{document}
``` | 2010/11/04 | [
"https://tex.stackexchange.com/questions/4911",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/1687/"
] | This behaviour is caused by `\lstset{columns=fixed}`. Changing to `columns=flexible` or `columns=fullflexible` should make it go away. | I was looking for a subject about this problem to write what I found out playing around with the fontfamilies.
I used the option columns=fullflexible on my example but it created other problems that was serious to leave them like this.
For example I have the following code in a lstlisting environment.
```
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Package: ExampleMyBoxed %
% %
% version: 0-1 (beta) %
% Author: Kostis Leledakis %
% %
% License: Do anything you want %
% %
% Date: 01/Jul/2017 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\NeedsTeXFormat{LaTeX2e}[1995/05/16]
```
the above code with the option columns=fullflexible gives the next result:
[](https://i.stack.imgur.com/bzzXn.png)
But if I remove that option and add the option
basicstyle=\fontfamily{pcr}\selectfont,
then the above problem disappears **from the pdf** and I can copy paste from the pdf to a text editor. The result in the pdf is:
[](https://i.stack.imgur.com/ztSe2.png)
Of course the above text will not be copied with it's spaces to the text editor... We have to fix it manually... but the rest of the text will not contain extra spaces (it will contain less but may be you can fix it too by combining my answer here with the answer of @PhilippeGoutet [here](https://tex.stackexchange.com/questions/19949/how-to-make-listings-code-indentation-remain-unchanged-when-copied-from-pdf) I will make a comment there too because his method with "phantom spaces" doesn't work on my (linux) pdf readers).
Anyway even if you find a solution to add the spaces too even if you don't find and you lose some spaces.. setting :
```
basicstyle=\fontfamily{pcr}\selectfont
```
removes the extra spaces without the need of fullflexible columns... |
127,283 | When I typed the search into Google most of the responses were websites selling clothing and the ratio of womens versus women's was about 1:1. Searching for mens versus men's and the version with apostrophes appears almost 90% of the time. For boys versus boy's or girls versus girl's it is a 3:2 ratio in favor of no apostrophes.
So there's a general trend for leaving the apostrophe out. But "womens" looks wrong.
I suppose the same question applies to public bathrooms as well. Is the women's room or the womens room? | 2013/09/15 | [
"https://english.stackexchange.com/questions/127283",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/52117/"
] | Women's room is "correct" as it follows the typical orthography rules. There is the possessive 's after the word "women." Women's room is correct because you want to use the possessive (men's, women's).
"Womens" is "incorrect" by any standard. It should never appear. | **Singlular**
* man
* woman
* boy
* girl
**Plural**
* men
* women
* boys
* girls
**Names of clothing departments/restrooms (plural, non-possessive)**
* Men
* Women
* Boys
* Girls
**Names of clothing departments/restrooms (plural, possessive)**
* Men's
* Women's
* Boys'
* Girls' |
1,290,307 | I get an error when trying to install both AJDT and Scala 2.7.5 plugin into Eclipse 3.5.
I remember seeing a message at one point that there was a known problem with the two being installed, and the solution was to install a pre-release version of Scala plugin, from May I believe, then install AJDT.
But, I don't remember which version and I can't find a link to download the older pre-release version.
So, I am wondering if someone knows how I can get both installed.
Thank you.
---
Edit:
I tried it just now and got this error, so AJDT 1.7.0 won't work. :(
```
Cannot complete the install because of a conflicting dependency.
Software being installed: Scala Eclipse Plugin 2.7.5.final (ch.epfl.lamp.sdt.feature.group 2.7.5.final)
Software being installed: AspectJ Development Tools 2.0.0.e35x-20090624-1600 (org.eclipse.ajdt.feature.group 2.0.0.e35x-20090624-1600)
Only one of the following can be installed at once:
JDT Weaving 2.0.0.e35x-20090624-1600 (org.eclipse.contribution.weaving.jdt 2.0.0.e35x-20090624-1600)
JDT Weaving 1.6.4.20090313172428 (org.eclipse.contribution.weaving.jdt 1.6.4.20090313172428)
Cannot satisfy dependency:
From: Scala Eclipse Plugin 2.7.5.final (ch.epfl.lamp.sdt.feature.group 2.7.5.final)
To: org.eclipse.contribution.weaving.jdt [1.6.4.20090313172428]
Cannot satisfy dependency:
From: AspectJ Development Tools 2.0.0.e35x-20090624-1600 (org.eclipse.ajdt.feature.group 2.0.0.e35x-20090624-1600)
To: org.eclipse.contribution.weaving.jdt [2.0.0.e35x-20090624-1600]
``` | 2009/08/17 | [
"https://Stackoverflow.com/questions/1290307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67566/"
] | According to [this thread](http://www.scala-lang.org/node/2560),
>
> 2.7.5.final is compatible with AJDT 1.7.0 on Eclipse 3.5.
>
>
>
If you have [AJDT (AspectJ Development Tools) 2.0.x](http://www.eclipse.org/ajdt/), could you try to downgrade to 1.7.0 as [suggested in this thread](http://www.scala-lang.org/node/2807)?
As the OP ([James Black](https://stackoverflow.com/users/67566/james-black)) himself details in the comments, both AJDT versions are actually 2.0!
From "[AJDT 2.0.0 - New and Noteworthy](http://www.eclipse.org/ajdt/whatsnew200/)":
>
> * Release for AJDT targeting Eclipse 3.5: 2.0.0\_e35x2009XXXXXX
> * Release for AJDT targeting Eclipse 3.4: 2.0.0\_e34x2009XXXXXX
>
>
> So this means that **AJDT 1.6.5 has been renamed AJDT 2.0.0\_e34x and AJDT 1.7.0 has been renamed AJDT 2.0.0\_e35x**.
>
> Although this is potentially confusing in the short term, we believe in the long term, this will be more informative and users will be able to read the version and immediately know which Eclipse version it targets and also what feature level it contains.
>
>
>
---
To complete this answer with the OP's feedback:
* [AJDT update site](http://eclipse.ialto.org/tools/ajdt/35/dev/update/)
* "[Eclipse Galileo, AJDT, Scala Eclipse plugin 2.7.5](http://www.nabble.com/Eclipse-Galileo,-AJDT,-Scala-Eclipse-plugin-2.7.5-td24357850.html)"
>
>
> >
> > Hmm ... if you can live with one of the 1.7.0 AJDT builds you should be OK.
> >
> > Cheers, Miles
> >
> >
> >
>
>
> Thanks for the tip - it works!
>
> I used [`ajdt_1.7.0.20090513085548_archive.zip`](http://eclipse.ialto.org/tools/ajdt/35/dev/update/ajdt_1.7.0.20090513085548_archive.zip) from the AJDT downloads.
>
> cheers Porter
>
>
> | Here is the message I couldn't find, looking for AJDT 1.7 was the help I needed:
<http://www.nabble.com/Eclipse-Galileo,-AJDT,-Scala-Eclipse-plugin-2.7.5-td24357850.html>
You can get the file from:
<http://eclipse.ialto.org/tools/ajdt/35/dev/update/>
I unzipped this zip file into the Eclipse directory, then installed Scala 1.7.5. |
43,545,818 | I have a form with the following input of a username:
```
<div class="form-group">
<label class="control-label col-sm-2" for="affuser">Affected User: <font color="red">*</font></label>
<div class="col-sm-10">
<input type="affuser" class="form-control" name="affuser" id="affuser" placeholder="Username" value="" required="required">
</div>
```
I would now like to check if this user is also in an active directory of my company. So when a username is written in the input field and the cursor gets out of the field (for example) then there should be a check if this user is in the AD or not. If it is then the borders should become green, if not the borders of the input field should become red. And if there is a "wrong" input the field should also not be able to be submitted.
How can I solve this as good as possible? | 2017/04/21 | [
"https://Stackoverflow.com/questions/43545818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7740040/"
] | You can achieve smooth movement of text, by using your third method a.k.a the offscreen canvas.
However, it is not really possible to achieve smooth text rendering on canvas.
This is because texts are usually rendered with smart smoothing algorithms, at [sub-pixel level](https://en.wikipedia.org/wiki/Subpixel_rendering) and that canvas doesn't have access to such sub-pixel level, so it leaves us with blurry texts as a best.
Of course, you could try to implement a font-rasterization algo by yourself, SO user Blindman67 provided [a good explanation along with a trying here](https://stackoverflow.com/questions/40066166/canvas-text-rendering-blurry/40074278#40074278), but it depends on so much parameters (which device, UA, font etc.) that making it on a moving target is almost a no-go.
So if you need perfect text rendering, on animated content, **SVG is your friend**. But even in SVG, text animation looks somewhat choppy.
```css
text{
font: bold 16px Helvetica;
fill: white;
}
```
```html
<svg>
<g id="group">
<circle fill="blue" cx="15" cy="15" r="15"/>
<text y="20" x="15" text-anchor="middle">AB
</text>
<animateTransform attributeName="transform"
attributeType="XML"
type="translate"
from="0 0"
to="80 150"
dur="20s"
repeatCount="indefinite"/>
</g>
</svg>
```
Otherwise, for canvas, the best you could get would be to double the size of your canvas, and scale it down with CSS after-ward, using the offscreen canvas method.
```js
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var scale = devicePixelRatio *2;
canvas.width *= scale;
canvas.height *= scale;
function initTextsSprites(texts, radius, padding, bgColor, textColor, shadowColor) {
// create an offscreen canvas which will be used as a spritesheet
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
radius *= scale;
padding *= scale;
var d = radius * 2;
var cw = (d + (padding * 2));
canvas.width = cw * texts.length;
canvas.height = d * 2 + padding * 2;
var topAlignText = 6 * scale; // just because I don't trust textBaseline
var y;
// drawCircles
ctx.fillStyle = bgColor;
ctx.shadowOffsetX = ctx.shadowOffsetY = 2;
ctx.shadowBlur = 6;
ctx.shadowColor = shadowColor;
y = (radius * 2) + padding;
ctx.beginPath();
texts.forEach(function(t, i) {
var cx = cw * i + padding * 2;
ctx.moveTo(cx + radius, y)
ctx.arc(cx, y, radius, 0, Math.PI * 2);
})
ctx.fill();
// drawBlueTexts
ctx.textAlign = "center";
ctx.font = "bold "+(16 * scale)+"px Helvetica";
ctx.shadowOffsetX = ctx.shadowOffsetY = ctx.shadowBlur = 0;
y = padding + topAlignText;
texts.forEach(function(txt, i) {
var cx = cw * i + padding * 2;
ctx.fillText(i, cx, y);
});
// drawWhiteTexts
ctx.fillStyle = 'white';
var cy = (radius * 2) + padding + topAlignText;
texts.forEach(function(txt, i) {
var cx = cw * i + padding * 2;
ctx.fillText(txt, cx, cy);
});
return function(index, x, y, w, h) {
if (!w) {
w = cw;
}
if (!h) {
h = canvas.height;
}
// return an Array that we will able to apply on drawImage
return [canvas,
index * cw, 0, cw, canvas.height, // source
x, y, w, h // destination
];
};
}
var texts = ['', 'AA', 'AB', 'AC'];
var getTextSprite = initTextsSprites(texts, 15, 12, "blue", "white", "rgba(0, 0, 0, 0.4)");
// just to make them move independently
var objs = texts.map(function(txt) {
return {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
speedX: Math.random() - .5,
speedY: Math.random() - .5,
update: function() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0) {
this.speedX *= -1;
this.x = 0;
}
if (this.y < 0) {
this.speedY *= -1;
this.y = 0;
}
if (this.x > canvas.width) {
this.speedX *= -1;
this.x = canvas.width;
}
if (this.y > canvas.height) {
this.speedY *= -1;
this.y = canvas.height;
}
}
}
});
function anim() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
objs.forEach(function(o, i) {
o.update();
ctx.drawImage.apply(ctx, getTextSprite(i, o.x, o.y));
})
requestAnimationFrame(anim);
}
anim();
```
```css
#canvas1 {
border: 1px solid;
width: 500px;
height: 300px;
}
```
```html
<canvas id="canvas1" width="500" height="300"></canvas>
``` | It's because of this:
```
var radius = 15;
var cnv = createHiDPICanvas(radius*2, radius*2, 2);
var ctx = cnv.getContext("2d");
```
When you increase the size of the canvas you're creating to `createHiDPICanvas(2000,2000, ...)`, the movement smoothes out. Right now you're creating a very small resolution canvas (30px by 30px), and the text looks jittery because it's moving across a very small range of pixels.
Example: <https://jsfiddle.net/6xr4njLm/>
Longer explanation of createHiDPICanvas: [How do I fix blurry text in my HTML5 canvas?](https://stackoverflow.com/questions/15661339/how-do-i-fix-blurry-text-in-my-html5-canvas) |
44,559,079 | Here is my model validation for check email-id exists or not
```
email:{
type:Sequelize.STRING,
validate:{
notEmpty:{
args:true,
msg:"Email-id required"
},
isEmail:{
args:true,
msg:'Valid email-id required'
}
},
unique: {
args:true,
msg: 'Email address already in use!'
}
}
```
All other validations are working fine except `unique` email validion | 2017/06/15 | [
"https://Stackoverflow.com/questions/44559079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425593/"
] | ```
email: {
type : DataTypes.STRING,
validate : {
isEmail: {
msg: "wrong format email"
},
notEmpty: {
msg: 'Email not null'
},
isUnique: function(value, next){
'table'.find({
where : {
email:value,
id:{[Op.ne]: this.id}
}
}).then(function(result){
if(result === null){
return next()
}else{
return next(' Email already use')
}
}).catch(err =>{
return next()
})
}
}
}
``` | Try this
```
email:{
type:Sequelize.STRING,
validate:{
notEmpty:{
args:true,
msg:"Email-id required"
},
isEmail:{
args:true,
msg:'Valid email-id required'
}
},
unique: { msg: 'Email address already in use!' }
}
``` |
30,659,833 | I am confused about the case that have multiple constraint annotations on a field, below:
```
public class Student
{
@NotNull
@Size(min = 2, max = 14, message = "The name '${validatedValue}' must be between {min} and {max} characters long")
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
```
Test case:
```
public class StudentTest
{
private static Validator validator;
@BeforeClass
public static void setUp()
{
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
System.out.println(Locale.getDefault());
}
@Test
public void nameTest()
{
Student student = new Student();
student.setName(null);
Set<ConstraintViolation<Student>> constraintViolations = validator.validateProperty(student, "name");
System.out.println(constraintViolations.size());
System.out.println(constraintViolations.iterator().next().getMessage());
}
}
```
The result is:
```
1
Can't be null
```
That is, when the @NotNull constraint is violated, it will not continue. Yes, this is the right situation. When one check is failed, we don't want it check the next constraint. But the situation is different when I used custom constraint.
I defined two custom constraints ACheck and BCheck.
```
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { ACheckValidator.class })
public @interface ACheck
{
String message() default "A check error";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { BCheckValidator.class })
public @interface BCheck
{
String message() default "B check error";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
public class ACheckValidator implements ConstraintValidator<ACheck, String>
{
public void initialize(ACheck constraintAnnotation)
{
}
public boolean isValid(String value, ConstraintValidatorContext context)
{
return false;
}
}
public class BCheckValidator implements ConstraintValidator<BCheck, String>
{
public void initialize(BCheck constraintAnnotation)
{
}
public boolean isValid(String value, ConstraintValidatorContext context)
{
return false;
}
}
```
There is not specific info about custom constraint, and I change the Student.java and use custom constraint like that:
```
@ACheck
@BCheck
private String name;
```
Test again, and the result is:
```
2
B check error
```
That is, when the @ACheck constraint is violatedm, it also wil check @BCheck, Why this happens, anything else I had ignored? | 2015/06/05 | [
"https://Stackoverflow.com/questions/30659833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649567/"
] | Add condition `&& places.getCount() > 0`
Example from documentation:
```
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
Log.i(TAG, "Place found: " + myPlace.getName());
} else {
Log.e(TAG, "Place not found");
}
places.release();
}
});
``` | Need places.getCount() check as well. Please refer here <https://developers.google.com/places/android-api/place-details> |
167,450 | For quite a while now the print option does not show up under the share menu, as if the share action seems to be missing its share action.
After a while of searching with my google-fu, I have been unable to come up with a working solution, with the two things coming up is:
- Check in your share menu - *If it was there then I wouldn't be looking for an answer*
- There isn't any fix - *yet*
**Objectives:**
* Get Print share action working/shown in Google Chrome
* Get Print share action working/shown in any share menu (when applicable)
**(Un-)Usefull Info:**
Android Version: 5.1.1
Device: Samsung xCover3 (SM-G388f)
Chrome version (Stable): 55.0.2883.91
Chrome Flags Enabled(Chrome://flags):
* `#enable-media-document-download-button`
* `#show-saved-copy`
* `#enable-downloads-ui`
* `#offline-pages-sharing`
* `#enable-ntp-download-suggestions`
Imgur Album Illustrating my point: [http://imgur.com/a/cCxza](https://imgur.com/a/cCxza)
I believe the item disappeared front the share menu after rooting. I have then during that time and now reflashed the firmware and rest the device (for reasons not related to this). I can verify that printing works (I can print from Gmail, and the print APK is still enabled/installed.
Hopefully I've given enough of a picture/details to help narrow down the cause of the problem, and hopefully we will be able to get a fix. | 2017/01/22 | [
"https://android.stackexchange.com/questions/167450",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/121800/"
] | I was able to figure it out.
I just open `chrome://flags` and reset it to defaults as I didn't find anything with the word 'print'.
And, it worked, I am able to print as I could before. | Try a soft reset. Press & hold the power + volume-down buttons together and hold for 12-15 seconds. The print icon should then reappear in the Chrome menu.
Thanks & shout out to Tim at Mequon, WI, Verizon store. |
23,109,342 | I have two tables:
>
> document table (documentID, userID) and sers table (UserID, FirstName, LastName).
>
>
>
For example
document table:
```
documentID = 1 | userID = 2 | modifiedUser = 2
documentID = 3 | userID = 1 | modifiedUser = 1
```
user table:
```
userID = 1 | firstName = Bob | lastName = Hope
userID = 2 | firstName = John | lastName = Doe
```
I need SQL query to select all columns from document table but should concatenate first and last name of user rather than userID
My output should be :
```
documentID = 1 | userID = John Doe | modifiedUser = John Doe
documentID = 3 | userID = Bob Hope | modifiedUser = Bob Hope
```
Any ideas? | 2014/04/16 | [
"https://Stackoverflow.com/questions/23109342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961497/"
] | ***you need this:***
```
SELECT A.documentID,
CONCAT_WS(' ', B.firstName, B.lastName) AS userID
FROM document A, USER B
WHERE B.userID = A.userID
ORDER BY A.documentID;
```
***output should like:***
```
+----------+----------+
|documentID| userID |
+----------+----------+
| 1 | jhon doe |
+----------+----------+
| 3 | bob hope |
+----------+----------+
```
***update:1***
```
SELECT A.documentID,
CONCAT_WS(' ', B.firstName, B.lastName) AS userID,
CONCAT_WS(' ', B.firstName, B.lastName) AS modifiedUser
FROM document A, USER B
WHERE B.userID = A.userID
ORDER BY A.documentID;
```
***output like:***
```
+----------+----------+------------+
|documentID| userID |modifiedUser|
+----------+----------+------------+
| 1 | jhon doe | jhon doe |
+----------+----------+------------+
| 3 | bob hope | bob hope |
+----------+----------+------------+
```
***<http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws>*** | ```
SELECT d.documentID, concat_ws(' ', u.firstName, u.lastName) AS userID
FROM document d, user u
WHERE u.userID = d.userID ;
``` |
38,375,088 | I'm having a blank page with that little sample I try to make in angularjs to learn Angular.
I have no errors in console, just a blank page
```
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Parc Automobile</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" media="screen" charset="utf-8">
<script src="app/app.js"/>
</head>
<body ng-app="parcAutoApp" ng-controller="autoCtrl">
<div class="container-fluid">
<div class="row section">
<div class="col-md-4 col-md-offset-4">
<form>
<div class="form-group">
<label for="no_vehicule">N° du véhicule</label>
<input type="text" class="form-control" id="no_vehicule" placeholder="N° du véhicule" ng-model="vehicule.no">
</div>
<div class="form-group">
<label for="marque_vehicule">Marque du véhicule</label>
<input type="text" class="form-control" id="marque_vehicule" placeholder="Marque du véhicule" ng-model="vehicule.marque">
</div>
<div class="form-group">
<label for="modele_vehicule">Modèle du véhicule</label>
<input type="text" class="form-control" id="modele_vehicule" placeholder="Modèle du véhicule" ng-model="vehicule.modele">
</div>
<div class="form-group">
<label for="immat_vehicule">Immatriculation du véhicule</label>
<input type="text" class="form-control" id="immat_vehicule" placeholder="Immatriculation du véhicule" ng-model="vehicule.immat">
</div>
<div class="form-group">
<label for="km_vehicule">Kilométrage du véhicule</label>
<div class="input-group">
<input type="text" class="form-control" id="km_vehicule" placeholder="Kilométrage du véhicule" ng-model="vehicule.kms">
<div class="input-group-addon">km</div>
</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="addAuto(vehicule)">Ajouter un véhicule</button>
</form>
</div>
</div>
<div class="row section">
<div class="col-md-4 col-md-offset-4">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Numéro</th>
<th>Marque</th>
<th>Modèle</th>
<th>Immatriculation</th>
<th>Kilométrage</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="vehicule in vehicules">
<td>{{ vehicule.no }}</td>
<td>{{ vehicule.marque }}</td>
<td>{{ vehicule.modele }}</td>
<td>{{ vehicule.immat }}</td>
<td>{{ vehicule.kms }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
angular.module('parcAutoApp', []);
.factory('vehiculesFactory', [function() {
return {
vehicules: [],
addToVehicules: function(vehicule) {
this.vehicules.push(vehicule);
},
getVehicules: function() {
return this.vehicules;
},
getNbVehicules: function() {
return this.vehicules.length;
},
};
}])
.controller('autoCtrl', function($scope, vehiculesFactory) {
$scope.addAuto = function(vehicule) {
vehiculesFactory.addToVehicules(vehicule);
};
$scope.vehicules = vehiculesFactory.getVehicules();
});
```
What can be the cause of this blankpage please ?
Thanks in advance | 2016/07/14 | [
"https://Stackoverflow.com/questions/38375088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5551931/"
] | Use dumpcap for this :
```
dumpcap -i your_interface_here -a duration:3 -w log.pcap | grep '^Packets received/dropped'
```
`dumpcap manpage says:`
>
> -a
>
> Specify a criterion that specifies when Dumpcap is to stop writing
> to a capture file. The criterion is of the form test:value, where
> test is one of:
>
>
>
> ```
> duration:value Stop writing to a capture file after value seconds
> have elapsed.
>
> ```
>
> -i
>
> capture interface
>
> -w
>
> Write raw packet data to outfile.
>
>
> | You can try `iptables -vL`, it shows dropped packet count by iptable rule.
```
s1=$(iptables -vL | grep rule | awk '{ print $1}')
sleep 3
s2=$(iptables -vL | grep rule | awk '{ print $1}')
echo "$(($s2-$s1))"
```
**rule** stands for defined rules in iptables. |
46,474,154 | We are transitioning to DNN 9.01.01 build, but it seems that the import/export feature is not working properly. I submitted an import but it has been sitting on submitted status for the last 8 hours.
Is this a known issue or is there configuration on the server that preventing the import/export to work?
Our instance is installed on Azure
Thanks | 2017/09/28 | [
"https://Stackoverflow.com/questions/46474154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5828571/"
] | This thread hasn't been touched in a long time but I dug around and found the problem. I fixed this problem by directly editing the DNN database. I'm on version 9.4 although, I'm sure this would work with any version as this issue is apparently caused some wonky code in the Azure AppService deployment packages.
To resolve, I just had to manually edit the dbo.Schedule table. I use Azure Data Studio because I'm on a Mac but SSMS or any other manager will work as well. I'm sure you can even use the DNN built-in editor although I'm not very familiar with it.
While digging through the dependencies I noticed that unlike the non-operational Export/Import job, all the working jobs had a NULL value in the "Server" field whereas the Export/Import job had the Azure server name written to it. I manually changed the value of this field to NULL and the Site Import job that had been perpetually spinning, started immediately.
Also, for posterity, you will want to make sure you don't have 15 different import jobs queued up before you do this because they will ALL begin processing once you commit the new value to the DB. If it took you a few times to figure out they were spinning you will probably want to go to the scheduler and delete anything you don't want to run prior to the DB edit.
Hope this helps save someone else some time. Cheers! | I had this issue, when checking the other task scheduled for execution I noticed the server field was empty while on the import/export there were comma separated inputs. When I cleared the import/export field the task ran correctly.
[](https://i.stack.imgur.com/9urN4.png) |
14,024,715 | I am trying to send email through an application in asp.net using c#. I searched a lot and mostly found the following code to send email using c# in asp.net:
```
MailMessage objEmail = new MailMessage();
objEmail.From = new MailAddress(txtFrom.Text);
objEmail.To.Add(txtTo.Text);
objEmail.CC.Add(txtCC.Text);
objEmail.Bcc.Add(txtBCC.Text);
objEmail.Subject = txtSubject.Text;
try
{
SmtpClient mail = new SmtpClient();
mail.EnableSsl = true;
mail.DeliveryMethod = SmtpDeliveryMethod.Network;
mail.Credentials = new NetworkCredential(txtFrom.Text, txtPassword.Text);
mail.Timeout = 20000;
mail.UseDefaultCredentials = false;
mail.Host = "smtp.gmail.com";
mail.Port = 587;
mail.Send(objEmail);
Response.Write("Your Email has been sent sucessfully - Thank You");
}
catch (Exception exc)
{
Response.Write("Send failure due to : <br />" + exc.ToString());
}
```
But constantly I am receiving the following error:
>
> "System.Net.Mail.SmtpException: Failure sending mail. --->
> System.IO.IOException: Unable to read data from the transport
> connection: An existing connection was forcibly closed by the remote
> host. ---> System.Net.Sockets.SocketException: An existing connection
> was forcibly closed by the remote host at
> System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32
> size, SocketFlags socketFlags) at
> System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset,
> Int32 size) --- End of inner exception stack trace --- at
> System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset,
> Int32 size) at System.Net.DelegatedStream.Read(Byte[] buffer, Int32
> offset, Int32 count) at System.Net.BufferedReadStream.Read(Byte[]
> buffer, Int32 offset, Int32 count) at
> System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
> caller, Boolean oneLine) at
> System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader
> caller) at System.Net.Mail.CheckCommand.Send(SmtpConnection conn,
> String& response) at
> System.Net.Mail.StartTlsCommand.Send(SmtpConnection conn) at
> System.Net.Mail.SmtpConnection.GetConnection(ServicePoint
> servicePoint) at
> System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
> at System.Net.Mail.SmtpClient.GetConnection() at
> System.Net.Mail.SmtpClient.Send(MailMessage message)"
>
>
> | 2012/12/24 | [
"https://Stackoverflow.com/questions/14024715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1927148/"
] | Your code looks reasonable, so you need to figure out what is preventing it from working.
Can you eliminate the possibility of a firewall problem? Most medium or large organizations tend to block ports 25, 465 and 587 - they simply don't want any unauthorized mail going out. If you suspect this might be the case, you could try if from outside the network (i.e. your home machine) although some ISPs will also block ports.
If the firewall isn't blocking your connections, verify that your credentials work - this can be done by sending via Thunderbird, Outlook, or equivalent. Try setting up a test using unencrypted mail - root thru your spam folder, paste a few into spamcop or equivalent, and look for an open relay. Alternatively, there are some commercial email providers that support unencrypted email. | You can check this out .. simple code and its works for gmail account ...
```
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(TextFRM.Text);
msg.To.Add(TextTO.Text);
msg.Subject = TextSUB.Text;
msg.Body = TextMSG.Text;
SmtpClient sc = new SmtpClient("smtp.gmail.com");
sc.Port = 25;
sc.Credentials = new NetworkCredential(TextFRM.Text, TextPSD.Text);
sc.EnableSsl = true;
sc.Send(msg);
Response.Write("Mail Send");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
``` |
37,623,732 | Problem: Getting a set of random numbers between two values that will have a certain mean value.
Let say we getting n number of random number where the number will be between 1 and 100. We have a mean of 25.
My first approach is to have 2 modes where we have aboveMean and belowMean where the first random number is the initial range 1 and 100. Every subsequent number will check the total sum. If the total sum is above the mean, we go to case aboveMean which is then get a random number between 1 and 25. If the total sum is below the mean, we do case belowMean then get a random number between 26 and 100.
I need some idea on how to approach this problem beside the crude get a random number to add it to the total then get the average. If it above the mean in question, we get a random number below the mean and so forth. While it does work, doesn't seem to be the best method.
I'm guessing I should brush up on probability to approach this random number generator. | 2016/06/03 | [
"https://Stackoverflow.com/questions/37623732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888722/"
] | Take some good distribution and use it. Say, [Binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution). Use `B(99,24/99)`,
so sampled values are in the range 0...99, with parameter `p` equal to 24/99.
So if you have routine which sample from B, then all you need is to add 1
to be in he range 1...100
Mean value for binomial would be `p*n`, in this case equal to 24. Because you're adding 1, your mean value would be 25 as required. C++11 has binomial RNG in the
standard library
Some code (not tested)
```
#include <iostream>
#include <random>
int main() {
std::default_random_engine generator;
std::binomial_distribution<int> distribution(99, double(24)/double(99));
for (int i=0; i != 1000; ++i) {
int number = distribution(generator) + 1;
std::cout << number << std::endl;
}
return 0;
}
``` | you have to go into some probabilities theory. there are a lot of methods to judge on random sequence. for example if you lower the deviation you will get triangle-looking-on-a-graph sequence, which can in the end be proven not trully random. so there is not really much choice than getting random generator and discarding the sequences you don't like. |
1,736 | I am wondering if there are any packages for python that is capable of performing survival analysis. I have been using the survival package in R but would like to port my work to python. | 2010/08/16 | [
"https://stats.stackexchange.com/questions/1736",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/172/"
] | AFAIK, there aren't any survival analysis packages in python. As mbq comments above, the only route available would be to [Rpy](http://rpy.sourceforge.net/).
Even if there were a pure python package available, I would be very careful in using it, in particular I would look at:
* How often does it get updated.
* Does it have a large user base?
* Does it have advanced techniques?
One of the benefits of R, is that these standard packages get a massive amount of testing and user feed back. When dealing with real data, unexpected edge cases can creep in. | [PyIMSL](http://www.vni.com/campaigns/pyimslstudioeval/) contains a handful of routines for survival analyses. It is Free As In Beer for noncommercial use, fully supported otherwise. From the documentation in the Statistics User Guide...
Computes Kaplan-Meier estimates of survival
probabilties: kaplanMeierEstimates()
Analyzes survival and reliability data using Cox’s
proportional hazards model: propHazardsGenLin()
Analyzes survival data using the generalized
linear model: survivalGlm()
Estimates using various parametric modes: survivalEstimates()
Estimates a reliability hazard function using a
nonparametric approach: nonparamHazardRate()
Produces population and cohort life tables: lifeTables() |
30,675,561 | I added a resource for a module as follows:
```
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>nbm-maven-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<moduleType>eager</moduleType>
<nbmResources>
<nbmResource>
<directory>${basedir}/resources</directory>
<targetPath>resources</targetPath>
<includes>
<include>*.db</include>
</includes>
<excludes>
<exclude>*trace*</exclude>
</excludes>
</nbmResource>
</nbmResources>
</configuration>
</plugin>
```
The file shows in the Netbeans application at: `target/app name/app name/resources/card_manager.mv.db`. That looks fine.
Now I'm trying to get that file location as follows:
```
File db = InstalledFileLocator.getDefault().locate("card_manager.mv.db",
"module.codename.base", false);
```
But db is always null. Any idea? | 2015/06/05 | [
"https://Stackoverflow.com/questions/30675561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198108/"
] | You can run setup.exe one more time and install Oracle Administration Assistant for Windows in the same ORACLE\_HOME directory, use Custom installation type
).
After install check the folder and you'll see deinstall directory. Run the deinstall.bat as Administrator. | You can use the Oracle Universal Installer but you need to start from the lowest level of the repository. If you directly select the whole environment, it won't work. |
5,852,459 | how do i create object-instances on runtime in python?
say i have 2 classes:
```
class MyClassA(object):
def __init__(self, prop):
self.prop = prop
self.name = "CLASS A"
def println(self):
print self.name
class MyClassB(object):
def __init__(self, prop):
self.prop = prop
self.name = "CLASS B"
def println(self):
print self.name
```
and a dict
```
{('a': MyClassA), ('b': MyClassB)}
```
how can i create dynamic an instance of one of my two classes, depending of i choose 'a' or 'b'.
kind of this:
```
somefunc(str):
if 'a': return new MyClassA
if 'b': return new MyClassB
```
to get "CLASS B" on calling: `somefunc('a').println`
but in a more elegant and dynamic way (say i add more classes to the dict on runtime) | 2011/05/02 | [
"https://Stackoverflow.com/questions/5852459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282204/"
] | You might create a dispatcher, which is a dictionary with your keys mapping to classes.
```
dispatch = {
"a": MyClassA,
"b": MyClassB,
}
instance = dispatch[which_one]() # Notice the second pair of parens here!
``` | You create a class instance by calling the class. Your class dict `{('a': MyClassA), ('b': MyClassB)}` returns classes; so you need only call the class:
```
classes['a']()
```
But I get the sense you want something more specific. Here's a subclass of `dict` that, when called with a key, looks up the associated item and calls it:
```
>>> class ClassMap(dict):
... def __call__(self, key, *args, **kwargs):
... return self.__getitem__(key)(*args, **kwargs)
...
>>> c = ClassMap()
>>> c['a'] = A
>>> c['b'] = B
>>> c('a')
<__main__.A object at 0x1004cc7d0>
``` |
5,940,627 | Anyone know how to code speech recognition that Microsoft speech recognition will detect set word.... any references i have put all the code which can make recognition but do know how to code Microsoft speech recognition will detect set word....
My coding:
```
Option Explicit
Dim rs As New ADODB.Recordset
Dim recognizer As SpInprocRecognizer
Dim MyGrammer As ISpeechRecoGrammar
Dim grammar As ISpeechRecoGrammar
Dim InputFile As SpeechLib.SpFileStream
Private Sub Form_Load()
Set RC = New SpInProcRecoContext
Set recognizer = RC.recognizer
Set myGrammar = RC.CreateGrammar
myGrammar.DictationSetState SGDSActive
Dim Category As SpObjectTokenCategory
Set Category = New SpObjectTokenCategory
Category.SetId SpeechCategoryAudioIn
Dim Token As SpObjectToken
Set Token = New SpObjectToken
Token.SetId Category.Default()
Set recognizer.AudioInput = Token
Out 888, 0
End Sub
``` | 2011/05/09 | [
"https://Stackoverflow.com/questions/5940627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730669/"
] | Before, SSR M.S. and releated company make TTS - Text-To-Speech, basic engine for TTS is foenemmology - phonemes for speak P.C. to louds and phonemes for speech recognition over mcirophone. How like P.C. speak words it except of human to say words to microphone, but a lot of words have same speak and different write in the sentence. In the other hand, SSR engine except tempo, pronuanciation-(For example: Clear-north-american-low-accented speak english language (not loud, just clear speak) ), middle-average of power of your speak words in the microphone against of out of louds and some time for training SSR engine for collect information about that in own data-system. SSR use work of TTS and of own engine for specific language to produce speech recognition. | Just to be clear, there are two types of speech recognition, dictation and command and control. In dictation mode, you are listening for every word possible and trying to find a match. This is good for dictation type systems where a person is speaking and you wish to transcribe everything. A good example of dictation grammar is converting a voicemail to text. Command and control uses a limited grammar which increases accuracy. If by "set word" you mean a set number of words, then command and control is what you want. An example would be an IVR system where you play a prompt and wait for a response, "Please press 1 for sales and 2 for support". The grammar would only contain "1 or 2". The word one might sound like a lot of different words if we were searching through the entire language dictionary, but comparing the difference between only the words 1 and 2 is easy. Here is one sample to help anyone learning about speech recognition:
<http://msdn.microsoft.com/en-us/library/ms720589(v=vs.85).aspx>
You can see how to load a grammar from a file and how to structure an XML file that holds your grammar. |
14,886,938 | First of all, sorry for my english, I wrote this with some help of Google Translate.
I'm trying to make an application like Google Wave with PHP and Ajax. I have a textarea that when the user input something, the javascript on the page detected with `oninput` and send the contents of the textarea to the server and the server stores the contents into the database.
What I'm doing is that every time when i send the content by XHR, there is `XHR.abort()` that always interrupts the previous XHR request. The data that is in the database are fine, however, sometimes it is stored a previous version.
I know it happens because PHP has not stopped the execution even though the client has made an abort and sometimes the previous request has taken more time that the last request and completed after the last request, so I read the manual of functions of "ignore\_user\_abort" and "connection\_aborted", but the problem persist.
I created this script to simulate the situation and I hoped when I aborted the connection (press 'stop', close the tab/window), there are not any new data on the database, but after 5 seconds, there still I have new data, so I need help to rollback the transaction when user abort the connection.
Here is the script to simulate (PDO\_DSN, PDO\_USER, PDO\_PASS are defined):
```
<?php
ignore_user_abort(true);
ob_start('ob_gzhandler');
$PDO = new PDO(PDO_DSN, PDO_USER, PDO_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$PDO->beginTransaction();
$query = $PDO->query('INSERT INTO `table` (`content`) VALUES (' . $PDO->quote('test') . ')');
sleep(5);
echo ' ';
ob_flush();
flush();
if (connection_aborted()) {
$PDO->rollBack();
exit;
}
$PDO->commit();
ob_end_flush();
``` | 2013/02/15 | [
"https://Stackoverflow.com/questions/14886938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015609/"
] | If you are finding `XHR.abort()` and `connection_aborted()` unreliable, consider other ways to send an out-of-band signal to inform the running PHP request that it should not commit the transaction.
Are you running [APC](http://php.net/manual/en/book.apc.php) (or could you be)?
Instead of invoking `XHR.abort()`, you could send another XHR request signaling the abort. The purpose of this request would be to record a special key in the APC user cache. This key's presence would indicate to the running PHP request that it should roll back.
To make this work, each XHR request would need to carry a (relatively) unique transaction identifier, e.g. as a form variable. This identifier would be generated randomly, or based on the current time, and would be sent in the initial XHR as well as the "abort" XHR and would allow the abort request to be correlated to the running request. In the below example, the transaction identifier is in form variable `t`.
Example "abort" XHR handler:
```
<?php
$uniqueTransactionId = $_REQUEST['t'];
$abortApcKey = 'abortTrans_' . $uniqueTransactionId;
apc_store($uniqueTransactionId, 1, 15);
```
Example revised database write XHR handler:
```
<?php
$PDO = new PDO(PDO_DSN, PDO_USER, PDO_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$PDO->beginTransaction();
$query = $PDO->query('INSERT INTO `table` (`content`) VALUES (' . $PDO->quote('test') . ')');
$uniqueTransactionId = $_REQUEST['t'];
$abortApcKey = 'abortTrans_' . $uniqueTransactionId;
if (apc_exists($abortApcKey)) {
$PDO->rollBack();
exit;
}
$PDO->commit();
```
You may still have timing issues. The abort may still arrive too late to stop the commit. To deal with this gracefully, you could modify the database write handler to record an APC key indicating that the transaction had committed. The abort handler could then check for this key's existence, and send back a meaningful XHR abort result to advise the client, "sorry, I was too late."
Keep in mind, if your application is hosted on multiple live servers, you will want to use a shared cache such as `memcached` or `redis`, since APC's cache is only shared across processes on a single machine. | As Marc B pointed, PHP can't detect if the browser is disconnected without sending some output to the browser. The problem is, you have enabled output buffering at the line `ob_start('ob_gzhandler');` and that prevents PHP from sending output to the browser.
You either have to remove that line or add a ob\_end\_\* (for example: `ob_end_flush()`) along with the echo/flush calls. |
30,090 | My first rebus, so I hope that it makes sense.
>
> Given that $f(z)=\dfrac{1}{(z-A)^n}$, is it true that
> $A=[N,\ldots,O]$?
>
>
>
Hint:
>
> $f$, $n$, and $z$ are not important
>
>
>
Hint:
>
> It's about fruits
>
>
> | 2016/04/01 | [
"https://puzzling.stackexchange.com/questions/30090",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/20562/"
] | The community wiki answer is
>
> No.
>
>
>
Community wiki argument:
>
> 1. $A$ is a pole of the function
>
> 2. $[N..O]$ is the $N$-$O$-range, respectively the EN-O-RANGE.
>
> 3. Now the question is: IS A-POLE EQUAL TO EN-O-RANGE?
>
> 4. And the answer is: No, since you cannot compare apples to oranges.
>
>
> | Is it:
>
> A Polar Molecule?
>
>
>
So the following (ie.$A=[N..O]$) is :
>
> True, as $[N..O]$ (read as $N$ to $O$),ie. $N\_2O$ is a polar molecule.
>
>
> |
5,104,094 | In JSF MVC framework who is Model, View, and Controller? | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187141/"
] | This depends on the point of view (pun intented).
In the big architectural picture, your own JSF code is the **V**:
**M** - Business domain/Service layer (e.g. EJB/JPA/DAO)
**V** - Your JSF code
**C** - FacesServlet
In the developer picture, the architectural **V** is in turn dividable as below:
**M** - Entity
**V** - Facelets/JSP page
**C** - Managed bean
In the smaller client picture, the developer **V** is in turn dividable as below:
**M** - JSF component tree
**V** - Rendered HTML output
**C** - Client (webbrowser)
In the yet smaller JavaScript picture, the client **V** is in turn dividable as below:
**M** - HTML DOM tree
**V** - Visual presentation
**C** - Event listener functions (enduser interaction and Ajax)
So it's basically a M(M(M(MVC)C)C)C ;)
Note that some starters and even some —very basic— tutorials mingle/copy/flatten the entity's properties in the managed bean, which would effectively make the controller a model. Needless to say that this is poor design (i.e. not a clean MVC design).
The code snippets in the following answers illustrate the right MVC approach:
* [JSF Controller, Service and DAO](https://stackoverflow.com/questions/30639785/jsf-controller-service-and-dao)
* [Creating master-detail pages for entities, how to link them and which bean scope to choose](https://stackoverflow.com/questions/8459903/creating-master-detail-pages-for-entities-how-to-link-them-and-which-bean-scope)
* [Passing a JSF2 managed pojo bean into EJB or putting what is required into a transfer object](https://stackoverflow.com/questions/9246141/passing-a-jsf2-managed-pojo-bean-into-ejb-or-putting-what-is-required-into-a-tra/9249012#9249012)
* [Filter do not initialize EntityManager](https://stackoverflow.com/questions/7934447/filter-do-not-initialize-entitymanager/7934604#7934604)
* [javax.persistence.TransactionRequiredException in small facelet application](https://stackoverflow.com/questions/16526267/javax-persistence-transactionrequiredexception-in-small-facelet-application/16542568#16542568)
In the books [The Definitive Guide to JSF in Java EE 8](https://rads.stackoverflow.com/amzn/click/com/1484233867), chapter 8 "Backing beans", page 276, and [The Definitive Guide to Jakarta Faces in Jakarta EE 10](https://rads.stackoverflow.com/amzn/click/com/B09VNVZYP6), chapter 8 "Backing Beans", page 288, the below Venn diagram is used to illustrate the position of the backing bean in the MVC paradigm within the context relevant to the JSF developer. Copyright disclaimer: aforementioned books are written by me and the picture is created by me.
[](https://i.stack.imgur.com/A3Ki3.png) | Java Server Faces is an MVC web framework where the MVC components are as follows,
1. **Model** - It is the managed bean class annotated with @ManagedBean, which has properties to hold the data and respective getters and setters. The managed bean class can also contain the business logic.These are also known as backing beans which can have different scopes like request, session, application.
2. **View** - The user interface shown to the client i.e. .xhtml files. It gets the data from the managed beans and it is rendered as the response.
3. **Controller** - javax.servlet.webapp.FacesServlet is the centralized controller class which is basically a servlet. Any request that comes to the JSF first goes to the FacesServlet controller. Unlike the JSP in which we write our own controller class, in JSF the controller servlet is a fixed part of the framework and we do not write it.
MVC flow-
[](https://i.stack.imgur.com/AqfdP.jpg) |
864,741 | In a server block, if I have no location block defined, it seems Nginx is serving any files. For example, if the request is "/foo.html", it will serve this file if it is found under root.
Is it possible to make nginx serve files only if they match a location? A request to "/foo.html" would not work if I have not defined any location block, for example. | 2017/07/23 | [
"https://serverfault.com/questions/864741",
"https://serverfault.com",
"https://serverfault.com/users/182146/"
] | You have to turn on ssl.
SSL is a protocol, HTTP is an another protocol. At the server side, port number won't implicitly specify protocols. You can run either one at any ports. At the other hand, browsers implicitly try to communicate using http at port 80 and https (ssl) at 443.
Naturally, if the two party speaks different language, communication error occurs.
It doesn't matter if you just want to redirect something, opening a websocket or get a web-page, you must comply the browser expectations OR specify explicitly what you want.
You can say `http://some.site.com:443/` to force the client (browser) to use the non implicit protocol (http without 's' on 443) which will most possibly work with your current config. But the right thing to do here is not to confuse your users and always include ssl (and all bells and whistles) whenever using port 443. | You've made a number of error
* Not listening on SSL
* Not specifying SSL keys and certificates
* Specifying a domain in two server blocks
* Missing slashes
If you don't know about SSL try reading my [Nginx/SSL tutorial](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-5-free-https-https2-for-wordpress-using-lets-encrypt-aws/), which will help you get a free Let's Encrypt SSL certificate.
Here's a config to try
```
server {
listen 80;
server_name domain.ltd;
return 301 https://www.domain.ltd/$request_uri;
}
server {
listen 443 ssl;
server_name domain.ltd;
ssl_certificate ....; # Insert certificate references
ssl_certificate_key ...; # Insert certificate key references
return 301 https://www.domain.ltd/$request_uri;
}
server {
listen 443 ssl;
server_name www.domain.ltd;
ssl_certificate ....; # Insert certificate references
ssl_certificate_key ...; # Insert certificate key references
...main config goes here
}
``` |
24,265 | Let $s\_n = \sum\_{i=1}^{n-1} i!$ and let $g\_n = \gcd (s\_n, n!)$. Then it is easy to see that $g\_n$ divides $g\_{n+1}$. The first few values of $g\_n$, starting at $n=2$ are $1, 3, 3, 3, 9, 9, 9, 9, 9, 99$, where $g\_{11}=99$. Then $g\_n=99$ for $11\leq n\leq 100,000$.
Note that if $n$ divides $s\_n$, then $n$ divides $g\_m$ for all $m\geq n$. If $n$ does not divide $s\_n$, then $n$ does not divide $s\_m$ for any $m\geq n$.
If $p$ is a prime dividing $g\_n$ but not dividing $g\_{n-1}$ then $p=n$, for if $p<n$ then $p$ divides $(n-1)!$ and therefore $p$ divides $s\_n-(n-1)!=s\_{n-1}$, whence $p$ divides $g\_{n-1}$.
So to show that $g\_n\rightarrow \infty$ it suffices to show that there are infinitely many primes $p$ such that $1!+2!+\cdots +(p-1)! \equiv 0$ (mod $p$). | 2010/05/11 | [
"https://mathoverflow.net/questions/24265",
"https://mathoverflow.net",
"https://mathoverflow.net/users/1243/"
] | This is so close to the Kurepa conjecture which asserts that $\gcd\left(\sum\_{k=0}^{n-1}k!,n!\right)=2$ for all $n\geq 2$, which was settled in 2004 by D. Barsky and B. Benzaghou "Nombres de Bell et somme de factorielles". So what they proved is that $K(p)=1!+\cdots+(p-1)!\neq -1\pmod{p}$ for any odd prime $p$. This goes against Kevin Buzzard's heuristic that $K(p)$ is random mod $p$. Let me mention two ways you can restate the fact $p|K(p)$:
a) It is equivalent to $K(\infty)=\sum\_{k=1}^{\infty}k!$ not being a unit in $\mathbb Z\_p$.
b) It is equivalent to $\mathcal B\_{p-1}=2\pmod{p}$ where $\mathcal{B} \_n$ is the $n$th Bell number. (It is easy to show that $\mathcal B \_{p}=2\pmod{p}$)
I forgot to mention that the conjecture that $p>11$ doesn't divide $K(p)$ is in question B44 of R. Guy's "Unsolved Problems in Number theory". | An amusing (but perhaps useless) observation: the property $1! + \ldots + (p-1)! = 0 \hbox{ mod } p$ is also equivalent to the matrix product property
$$\left( \begin{array}{ll} 1 & 1 \\\ 0 & 1 \end{array} \right) \begin{pmatrix} 2 & 1 \\\ 0 & 1 \end{pmatrix} \ldots \begin{pmatrix} p & 1 \\\ 0 & 1 \end{pmatrix} = \begin{pmatrix} 0 & 0 \\\ 0 & 1 \end{pmatrix} \hbox{ mod } p.$$
Another reformulation: if $f: F\_p \times F\_p \to F\_p$ is the map $f(x,y) := (x-1,xy+1)$, then $f^p(0,0) = (0,1)$, where $f^p$ is the p-fold iterate of f.
A third reformulation: $p | \lfloor (p-2)!/e \rfloor$ (assuming p is odd). |
65,856,936 | ```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PetsHotelSystem.User_Control
{
public partial class UC_UpdateRoom : UserControl
{
function fn = new function();
string query;
public UC_UpdateRoom()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void UC_UpdateRoom_Load(object sender, EventArgs e)
{
query = "select * from rooms";
DataSet ds = fn.getData(query);
DataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
if(txtRoomNo.Text != "" && txtType.Text != "" && txtBed.Text != "" && txtPrice.Text !="")
{
string roomno = txtRoomNo.Text;
string type = txtType.Text;
string bed = txtBed.Text;
Int64 price = Int64.Parse(txtPrice.Text);
query = "insert into rooms (roomNO, roomType, bed, price) values ('" + roomno + "','" + type + "','" + bed + "','" + price + "')";
fn.setData(query, "Room Added.");
UC_UpdateRoom_Load(this, null);
}
else
{
MessageBox.Show("Fill all fields.", "Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}```
```
Running the above piece of code returns the following error:
>
> WARNING: Exception thrown: 'System.Data.SqlClient.SqlException' in
> System.Data.dll Additional information: Cannot insert the value NULL
> into column 'roomID', table 'myHotel.dbo.rooms'; column does not allow
> nulls. INSERT fails. The statement has been terminated.
>
>
>
How to fix it? | 2021/01/23 | [
"https://Stackoverflow.com/questions/65856936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15064302/"
] | When you need to have some logic which is `depend` on changing a variable, it's better to keep those logic inside `useEffect`
```
const interval = useRef(null);
const timeout = useRef(null);
useEffect(() => {
interval.current = setInterval(
() => (image === 4 ? setImage(1) : setImage((i) => i + 1)),
5000
);
timeout.current = setTimeout(() => {
clearInterval(interval.current);
}, 5000);
return () => {
clearInterval(interval.current);
clearTimeout(timeout.current);
}
}, [image]);
```
one point to remember is that if you use a `variable` instead of using `useRef` it can increase the possibility of clearing the wrong instance of interval or timeout during the rerenders. `useRef` can keep the instance and avoid any unwanted `bugs` | Anytime that you rerender your component, you will run the whole function once. So you will set an interval every time you use setImage(). In order to prevent this, you have to use side effect functions. here you should use `useEffect()` because you have a functional component. in order to make `useEffect()` only run once, you have to pass an empty array for dependecy array; So your useEffect will act like `componentDidMount()` in class components. try the code below:
```
let interval = null
useEffect(() => {
interval = setInterval(
() => (image === 4 ? setImage(1) : setImage(image + 1)),
5000
)
setTimeout(() => {
clearInterval(interval);
}, 5000)
}, [])
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.