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 |
|---|---|---|---|---|---|
34,230,227 | I'm trying to match these kind of character sequences:
```
sender=11&receiver=2&subject=3&message=4
sender=AOFJOIA&receiver=p2308u48302rf0&subject=(@#UROJ)(J#OFN:&message=aoefhoa348!!!
```
Where the delimiters between (key, val) pair is the '&' character.
I'd like to group them in a way I can get access to the key and the value of each pair.
I tried something like:
```
([[:alnum:]]+)=([[:alnum:]]+)
```
But then I miss the:
```
subject=(@#UROJ)(J#OFN:
```
I couldn't find a way to allow these type of characters to be accepted.
To be more specific, if there are `n` pairs of key-value, I would like to have `n` matches, each consisting of 2 groups - 1 for the key, 1 for the value.
I'd be glad if you helped me out with this.
Thanks | 2015/12/11 | [
"https://Stackoverflow.com/questions/34230227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3454745/"
] | <https://regex101.com/r/hN7qG9/1>
I guess that will solve your problem:
>
> /([^?=&]+)(=([^&]\*))?/ig
>
>
>
**output:**
>
> sender=11
>
> receiver=2
>
> subject=3
>
> message=4
>
> sender=AOFJOIA
>
> receiver=p2308u48302rf0
>
> subject=(@#UROJ)(J#OFN:
>
> message=aoefhoa348!!!
>
>
>
>
and you can acess each patter:
```
$1 - first pattern (sender)
$2 - second pattern (=11)
$3 - second pattern without '='(11)
```
[reference](http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/)
```js
var string = 'sender=11&receiver=2&subject=3&message=4'
var string2 = 'sender=AOFJOIA&receiver=p2308u48302rf0&subject=(@#UROJ)(J#OFN:&message=aoefhoa348!!!';
var regex = /([^?=&]+)(=([^&]*))?/ig;
var eachMatche = string.match(regex);
for (var i = 0; i < eachMatche.length; i++) {
snippet.log(eachMatche[i]);
snippet.log('First : '+eachMatche[i].replace(regex,'$1'));
snippet.log('Second : '+eachMatche[i].replace(regex,'$3'));
}
var eachMatche = string2.match(regex);
for (var i = 0; i < eachMatche.length; i++) {
snippet.log(eachMatche[i]);
snippet.log('First : '+eachMatche[i].replace(regex,'$1'));
snippet.log('Second : '+eachMatche[i].replace(regex,'$3'));
}
```
```html
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
``` | All the special characters in your example fall unter the "punctuation" group, see :
<https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html>
If that still isn't enough, you could try to make your own character regex class. Like [@# etc...] . Keep in mind that you will have to escape special java characters with an extra /. |
2,164,981 | why are the structure declarations in assembly different from those in the win32 api documentation.(i am coming from c++ and trying my hand at assembly language)
for example i got this function prototype from icezelion's tutorials(tutorial3)
```
WNDCLASSEX STRUCT DWORD
cbSize DWORD ?
style DWORD ?
lpfnWndProc DWORD ?
cbClsExtra DWORD ?
cbWndExtra DWORD ?
hInstance DWORD ?
hIcon DWORD ?
hCursor DWORD ?
hbrBackground DWORD ?
lpszMenuName DWORD ?
lpszClassName DWORD ?
hIconSm DWORD ?
WNDCLASSEX ENDS
```
Hey wait...I know that "WNDCLASSEX" structure, in my offline version of the win32 api documentation, its declared as....
```
typedef struct _WNDCLASSEX { // wc
UINT cbSize;
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HANDLE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
HICON hIconSm;
} WNDCLASSEX;
```
Why is it that the asm version uses DWORD's only contrary to what is in the win32 api documentation?
Am i using the wrong docs or what? and if i am can someone post me a download link for WIN32 api documentation meant for asm programmers?
Help, am confused.
**Edited**: Here is the link to the tutorial i was refering to:
[iczelion's win32 asm tutorial 3](http://win32assembly.online.fr/tut3.html) | 2010/01/29 | [
"https://Stackoverflow.com/questions/2164981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200399/"
] | The size of all those different C types is DWORD. Assembly is NOT strongly typed - all it knows about each variable is the number of bytes. | In assembly, regardless of whether a high level structure has pointers or ints, the reality is that their associated high-level datatypes are of BYTE, WORD and DWORD, in your case, the structure are all 32 bit hence DWORD (a WORD is 16bit, DWORD is 32bits). Do not be mislead into thinking the structure in assembly is different to the structure in C, it is very much the same. Assembler has primitive data types, regardless of pointers, structures etc, what sets them apart is how it is loaded into a register (depending on the syntax):
```
mov eax, dword ptr [bx]
```
This assembler sample is a demonstration of loading the `eax` register with the value pointed to by the `bx` register, effectively same thing as
```
int bx = 5;
int *eax;
ptr = &bx
```
Hope this helps,
Best regards,
Tom. |
25,416,102 | I see that Admob ads have a dependency on playstore services library. I was wondering if this means that if I distribute my app via channels other than play store it will serve ads or not. | 2014/08/20 | [
"https://Stackoverflow.com/questions/25416102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54082/"
] | If you can structure your code so that you return from each branch, it can be a lot cleaner. Sometimes this may entail extracting a method. And ternary operators, if your language supports them, can make matters clearer if used judiciously
```
if (dog == 'alive')
return cat == 'alive' ? 'bothLiving' : 'justDog';
return cat == 'alive' ? 'justCat' : 'bothDead';
``` | You may use different bits to represent animal's state (alive or dead). Then it's a simple switch statement like
```
switch (state) {
case 0: // None alive
...
break;
case 1: // 0th bit alive only(say dog)
...
break;
case 2: // 1st bit alive only (say cat)
....
break;
case 3: // 0th and 1st bit alive (dog and cat)
}
```
And when you want to add more just use next bit and add 'case' inside switch statement. |
6,067,370 | Currently running [Arch Linux](http://en.wikipedia.org/wiki/Arch_Linux), I decided to install [Aircrack-ng](http://en.wikipedia.org/wiki/Aircrack-ng) and try it out on my own wireless network. So I installed it, and I get an error upon Aireplay that states something along the lines of
>
> Either patch this, or use the flag --ignore-negative-one
>
>
>
So I used the flag at first. It seems to work, but I can't get a handshake. This might just be me, but I wasn't sure. So I decided to find that patch. I went to Aircrack's website and found it. I followed the instructions and it was fine up until "make". At that point, it outputted:
```
config.mk:199: "WARNING: CONFIG_CFG80211_WEXT will be deactivated or not working because kernel was compiled with CONFIG_WIRELESS_EXT=n. Tools using wext interface like iwconfig will not work. To activate it build your kernel e.g. with CONFIG_LIBIPW=m."
make -C /lib/modules/2.6.38-ARCH/build M=/home/kyle/Desktop/compat-wireless-2011-05-16 modules
make: *** /lib/modules/2.6.38-ARCH/build: No such file or directory. Stop.
make: *** modules Error 2
```
What can I do to fix this so I can use Aircrack?
---
`uname -r` outputs "2.6.38-ARCH" (without quotes). | 2011/05/20 | [
"https://Stackoverflow.com/questions/6067370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/762109/"
] | Lua is a dynamic language and functions are just a kind of value that can be called with the `()` operator. So you don't really need to forward declare the function so much as make sure that the variable in scope when you call it is the variable you think it is.
This is not an issue at all for global variables containing functions, since the global environment is the default place to look to resolve a variable name. For local functions, however, you need to make sure the local variable is already in scope at the lexical point where you need to call the value it stores, and also make sure that at run time it is really holding a value that can be called.
For example, here is a pair of mutually recursive local functions:
```
local a,b
a = function() return b() end
b = function() return a() end
```
Of course, that is also an example of using tail calls to allow infinite recursion that does nothing, but the point here is the declarations. By declaring the variables with `local` before either has a function stored in it, those names are known to be local variables in lexical scope of the rest of the example. Then the two functions are stored, each referring to the other variable. | You can forward declare a function by declaring its name before declaring the actual function body:
```
local func1
local func2 = function()
func1()
end
func1 = function()
--do something
end
```
However forward declarations are only necessary when declaring functions with local scope. That is generally what you want to do, but Lua also supports a syntax more like C, in which case forward declaration is not necessary:
```
function func2()
func1()
end
function func1()
--do something
end
``` |
5,414,775 | I am confused with the time complexity of the following piece of code....
```
i = 0
//first row
if(board[i][0] == win && board[i][1] == win && board[i][2] == win)
return win;
//second row
if(board[i+1][0] == win && board[i+1][1] == win && board[i+1][2] == win)
return win;
//third row
if(board[i+2][0] == win && board[i+2][1] == win && board[i+2][2] == win)
return win;
//first col
if(board[0][i] == win && board[1][i] == win && board[1][i] == win)
return win;
//second col
if(board[0][i+1] == win && board[1][i+1] == win && board[2][i+1] == win)
return win;
//third col
if(board[0][i+2] == win && board[1][i+2] == win && board[2][i+2] == win)
return win;
//first diag
if(board[i][i] == win && board[i+1][i+1] == win && board[i+2][i+2] == win)
return win;
//second diag
if(board[i+2][i] == win && board[i+1][i+1] == win && board[i][i+2] == win)
return win;
``` | 2011/03/24 | [
"https://Stackoverflow.com/questions/5414775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66593/"
] | This is obviously a trap question to see if you understood the concept of time complexity.
Time complexity measures the order of magnitude that an algorithm needs if applied to larger and larger input. Your example does depend only on a constant number of inputs, this why the others correctly said O(1). In essence this means that time complexity is not the correct tool to measure its efficiency, quality or whatsoever. | As the other answers suggest, it is O(1). But this is not considered as good coding practice. You can use a loop to generalize it. |
11,087,951 | I am trying to connect to the ejb service in glassfish server through Java Web start.
I am getting the following error while getting the initial context. I have also added the code snippet for getting the initial context.
One interesting is when I run the program as a simple java program outside of java web start in a netbeans IDE, it is working fine.
I added all the relevant jar files from the glassfish modules folder into the java web start.
```
java.lang.NullPointerException
at com.sun.enterprise.naming.impl.SerialContext.<init>(SerialContext.java:275)
at com.sun.enterprise.naming.impl.SerialContext.<init>(SerialContext.java:334)
at com.sun.enterprise.naming.impl.SerialInitContextFactory.createInitialContext(SerialInitContextFactory.java:358)
at com.sun.enterprise.naming.impl.SerialInitContextFactory.getInitialContext(SerialInitContextFactory.java:353)
at com.sun.enterprise.naming.SerialInitContextFactory.getInitialContext(SerialInitContextFactory.java:69)
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.<init>(Unknown Source)
at gov.ca.lc.util.ServiceLocator.getInitialContext(ServiceLocator.java:140)
at gov.ca.lc.util.ServiceLocator.getVotesEJB(ServiceLocator.java:103)
at gov.ca.lc.scenemanagement.AbstractVotingScene.getCommitteeList(AbstractVotingScene.java:143)
at gov.ca.lc.scenemanagement.AbstractVotingScene.<init>(AbstractVotingScene.java:65)
at gov.ca.lc.scenes.MenuScene.<init>(MenuScene.java:56)
at gov.ca.lc.menu.StartVoting.startUp(StartVoting.java:47)
at org.mt4j.MTApplication.setup(MTApplication.java:328)
at processing.core.PApplet.handleDraw(PApplet.java:1580)
at processing.core.PApplet.run(PApplet.java:1502)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Animation Thread" java.lang.NullPointerException
at gov.ca.lc.scenemanagement.AbstractVotingScene.getCommitteeList(AbstractVotingScene.java:143)
at gov.ca.lc.scenemanagement.AbstractVotingScene.<init>(AbstractVotingScene.java:65)
at gov.ca.lc.scenes.MenuScene.<init>(MenuScene.java:56)
at gov.ca.lc.menu.StartVoting.startUp(StartVoting.java:47)
at org.mt4j.MTApplication.setup(MTApplication.java:328)
at processing.core.PApplet.handleDraw(PApplet.java:1580)
at processing.core.PApplet.run(PApplet.java:1502)
at java.lang.Thread.run(Unknown Source)
Following is my code to get the initial context
private static InitialContext getInitialContext()
throws NamingException {
Properties props = null;
try{
// props=new Properties();
// props.load(new FileInputStream(new File("jndi.properties")));
// System.out.println(props.get("java.naming.factory.initial"));
props=new Properties();
props.setProperty("java.naming.factory.initial","com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs ", "com.sun.enterprise.naming");//ur server ip
props.setProperty("java.naming.factory.state ", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");//ur server ip
props.setProperty("org.omg.CORBA.ORBInitialHost", "165.107.33.181");//ur server ip
props.setProperty("org.omg.CORBA.ORBInitialPort","3700"); //default is 3700
}catch(Exception ex){
ex.printStackTrace();
}
return new InitialContext(props);
}
``` | 2012/06/18 | [
"https://Stackoverflow.com/questions/11087951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1437884/"
] | I have the same problem. I use JMS and I need to add other jars. At first I tried using gf-client.jar, but it does not work through Java Web start. So I've added jars listed in
[Connecting a remote JMS client to GlassFish 3](https://stackoverflow.com/questions/5489937/connecting-a-remote-jms-client-to-glassfish-3) . It works outside of Java Web start. | I don't know what the relevant jar files are for you, but just in case we have a different view on that area: I use just appserv-rt.jar and java-ee.jar using the same properties you use for initial context and it works fine. Don't add anything else you don't need and try again. |
20,740 | In the given image below, Fux writes a counterpoint to a cantus firmus given to him as part of his studies by his fictitious teacher *Aloysious*.
A rule that is often emphasised is that one should remain in the mode (in this case, the mixolydian mode), and there should be **NO** accidentals, except in the second to last bar where the 7th has to be raised.
Note that the cantus firmus is in the upper stave and the counterpoint in the lower. Also this, if not evident, is ***Second Species CounterPoint***

Thus, the question is as follows. **In the fourth to last bar Fux raises the 7th - why?** By doing so he has exited the mode | 2014/07/04 | [
"https://music.stackexchange.com/questions/20740",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/12397/"
] | First of all, the clefs are not quite right and the bottom part should be an octave lower (this is inferrable from the illegal 4th in the penultimate bar).
Modes in Renaissance style are not the strict collections of 7 notes used in "modal" pop and jazz songs. Instead, a mode tells us where the tonic is located within a field of 11 notes, 7 diatonic and freely used (A,B,C,D,E,F,G) and 4 chromatic (B-flat, F-sharp, C-sharp, and G-sharp).
**Flats** are used primarily to avoid the tritone; thus if your melody wants to go to B but the cantus firmus is on an F, you can use B-flat instead. (Flats are used for other purposes too, such as the "una nota super la" rule and certain cadences in Dorian, but that's another story.)
**Sharps** are used primarily in cadences, as you correctly point out, and also in cases which at the time were caused "causa pulchritudinis": using a major third in a triad which would normally be minor for its richness of sound (an epic example is the opening phrase of Palestrina's "Stabat Mater").
It appears that Fux is trying to achieve the latter category of effect but, as is clear from reading an updated counterpoint manual such as Jeppesen or Gauldin, he got a few things slightly wrong. A sharped note should function melodically as a leading tone to the next higher note; in this case, the F-sharp would be correct if followed by G, although that would cause problems in the next bar. | I know it's an old discussion, but I thought I might add my five cents:
I'm working on the "Gradus" these days (Mann's translation) and have asked myself the same question. Then I remembered that in footnote 9 to Chapter one Mann says that "the tritone is to be avoided even when reached stepwise (f-g-a-b) IF THE LINE IS NOT CONTINUED STEPWISE AND IN THE SAME DIRECTION". Could it be that Fux simply wanted to avoid the melodic tritone in bars 7-9 of the tenor voice (b-a-g-f) by sharpening the f, since he did not continue stepwise to e but skipped to d instead? |
2,710,009 | A user can have many addresses, but I want to retrieve the latest entry for the user.
In sql I would do:
```
SELECT TOP 1 *
FROM UserAddress
WHERE userID = @userID
```
How can I create a criteria query with the same logic?
Is there a TOP functionality? | 2010/04/25 | [
"https://Stackoverflow.com/questions/2710009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Assuming that you have some timestamp column (eg. InsertedAt):
```
User user = ...;
var crit = DetachedCriteria.For<UserAddress>()
.Add(Restrictions.Eq("User", user))
.AddOrder(Order.Desc("InsertedAt"))
.SetMaxResults(1);
``` | Since the ordering of the contents of a table are subject to movement (reindexing etc), I'd suggest that you have a time stamp of some description to indicate which is the latest. Then get the first ordered by that field. |
51,934,432 | My dataset looks like this below
```
Id Col1
--------------------
133 Mary 7E
281 Feliz 2D
437 Albert 4C
```
What I am trying to do is to take the 1st two characters from the 1st word in Col1 and all the whole second word and then merge them.
My final expected dataset should look like this below
```
Id Col1
--------------------
133 MA7E
281 FE2D
437 AL4C
```
Any suggestions on how to accomplish this is much appreciated. | 2018/08/20 | [
"https://Stackoverflow.com/questions/51934432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4574190/"
] | We can also do this in `paste0` together the output of `substr` and `str_split` within a `dplyr` pipe chain:
```
df <- data.frame(id = c(133,281,437),
Col1 = c("Mary 7E", "Feliz 2D", "Albert 4C"))
library(stringr)
df %>%
mutate(Col1 = toupper(paste0(substr(Col1, 1, 2),
stringr::str_split(Col1, ' ')[[1]][-1])))
``` | rather than one row solution this is easy to interpret and modify
```
xx_df <- data.frame(id = c(133,281,437),
Col1 = c("Mary 7E", "Feliz 2D", "Albert 4C"))
xx_df %>%
mutate(xpart1 = stri_split_fixed(Col1, " ", simplify = T)[,1]) %>%
mutate(xpart2 = stri_split_fixed(Col1, " ", simplify = T)[,2]) %>%
mutate(Col1_new = paste0(substr(xpart1,1,2), substr(xpart2, 1, 2))) %>%
select(id, Col1 = Col1_new) %>%
mutate(Col1 = toupper(Col1))
```
result is
```
id Col1
1 133 MA7E
2 281 FE2D
3 437 AL4C
``` |
27,797,706 | i have to make a chart on luggage Statistics.
The code below will show 4 bars per month, in a bar-chart.
i have a sidebar(not given here) were i can fill in the range of details i want (Example, 1 January till 20 August).
now i thought of something like a for loop, wich sets a line depening on the amount of months.
in the example above this will be te following code
```
dataset.addValue(getMissing(), series1, Month1);
dataset.addValue(getMissing(), series1, Month2);
dataset.addValue(getMissing(), series1, Month3);
dataset.addValue(getMissing(), series1, Month4);
dataset.addValue(getMissing(), series1, Month5);
dataset.addValue(getMissing(), series1, Month6);
dataset.addValue(getMissing(), series1, Month7);
dataset.addValue(getMissing(), series1, Month8);
```
how do i make a loop which adds the codeline, AND increase the Month
Kind regards
```
// row keys...
String series1 = "Luggage Lost";
String series2 = "Customer Missing";
String series3 = "Recovered";
String series4 = "Forever Lost";
// column keys...
String Month1 = "January";
String Month2 = "February";
String Month3 = "March";
String Month4 = "April";
String Month5 = "May";
String Month6 = "June";
String Month7 = "July";
String Month8 = "August";
String Month9 = "September";
String Month10 = "October";
String Month11 = "November";
String Month12 = "December";
// create the dataset...
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int aantalmaanden = 0; aantalmaanden==0; aantalmaanden--) {
}
dataset.addValue(getMissing(), series1, Month1);
dataset.addValue(getMissing(), series1, Month2);
dataset.addValue(getMissing(), series1, Month3);
dataset.addValue(getMissing(), series1, Month4);
dataset.addValue(getMissing(), series1, Month5);
dataset.addValue(getFound(), series2, Month1);
dataset.addValue(getFound(), series2, Month2);
dataset.addValue(getFound(), series2, Month3);
dataset.addValue(getFound(), series2, Month4);
dataset.addValue(getFound(), series2, Month5);
dataset.addValue(getHandel(), series3, Month1);
dataset.addValue(getHandel(), series3, Month2);
dataset.addValue(getHandel(), series3, Month3);
dataset.addValue(getHandel(), series3, Month4);
dataset.addValue(getHandel(), series3, Month5);
dataset.addValue(getForeverlost(), series4, Month1);
dataset.addValue(getForeverlost(), series4, Month2);
dataset.addValue(getForeverlost(), series4, Month3);
dataset.addValue(getForeverlost(), series4, Month4);
dataset.addValue(getForeverlost(), series4, Month5);
return dataset;
}
``` | 2015/01/06 | [
"https://Stackoverflow.com/questions/27797706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4295974/"
] | Netease is promoting their new mobile email app "邮箱大师", and they currently blocked any imap client other than their offical clients and several popular clients such as thunderbird, foxmail.
I don't know how do they identified the client. Anyway, may it's time for you to switch to other email service provider. At least QQ mail works well. | Please show us the debug output produced by your IMAP library. It seems that the server administrators have configured their server to always reject LOGIN even though you are on a secure SSL connection. That's an interesting choice, but some providers do that. Talk to their support about how you are supposed to connect to their service. |
36,093,359 | This is driving me around the bend. All the documentation on vectors is ridiculously deep.
In a class I want to declare a vector equal in length to the length of a string I've already declared. It sounds easy enough.
If I use:
```
class Test {
private:
size_t size = 10;
std::vector<int> array(size);
};
```
I get "only static const integral data members can be initialized within a class"
If I:
```
std::vector<int> array(anarray.length());
```
I get the fantastically unhelpful:
error C2061: syntax error : identifier 'anarray'
How do I do it? | 2016/03/18 | [
"https://Stackoverflow.com/questions/36093359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067256/"
] | In-class initialization requires use of the `type var = value;` syntax or the uniform initialization syntax.
For your needs, it is more appropriate to use `type var = value;` syntax.
```
class Test {
private:
std::size_t size = 10;
std::vector<int> array = std::vector<int>(size);
};
```
You can initialize `size` using:
```
std::size_t size{10};
```
However, if you use
```
std::vector<int> array{size};
```
it will try to create a `std::vector` with one element containing the value of `size`. That's not what you are interested in. | Data members are usually initialized in the member initialization list:
```
class Test
{
std::vector<int> array;
public:
Test() : array(10)
{ // ^^^^^^^^^
}
};
``` |
465,232 | This is the problem:
There are two players A and B. Player A starts and chooses a number in the range 1 to 10. Players take turn and in each step add a number in the range 1 to 10. The player who reaches 100 first wins.
In the program, player A is the user and player B is the computer. Besides that the computer must force a win whenever possible. For instance, if the player A reaches 88 at some point, the computer must choose 89, as this is the only way to force a win.
The problem i face is how do I do the forcing on the part of the computer. Need some guidance on that. | 2013/08/11 | [
"https://math.stackexchange.com/questions/465232",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/86653/"
] | First player starts with $1$ and then at each turn after picks $11-n$ where $n$ was the other player's choice. That means the numbers are $11k+1$ after first player's turn, and therefore you get to $89$ at turn $9$.
If first player even chooses any other value, then second player should choose so the sum is $11k+1$ for some $k$ and can force a win. | Let's assume we will add in range $1$ to $a$ ($1 \leq a$) and we want to reach $0 \leq b$. Then, you should stay on the numbers which gives ($b$ mod $a+1$) in mod $a+1$. For example, if $a = 10$ and $b = 100$, you should say $1,12,23,34,45,56,67,78,89$. So, if you start, say $1$ and whatever computer says, say $12$ (and you can do that because computer can't say $12$ but whatever it says you can say it) and go like that, win!
For example, when you said $1$, it can say only $2, 3, 4, 5, 6, 7, 8, 9, 10, 11$ and you can say $12$ in any situation, and this goes like that.
Also you might want to think about that for fun: Let's assume we can add the numbers in a set $S$, and we want to reach $x$. Is there an algorithm which gives exact solution (as like I gave in first paragraph for a special $S$) for any $S$? |
63,417,657 | I wrote the following code:
```cpp
#include <iostream>
using namespace std;
const int * myFunction()
{
int * p = new int(5);
return p;
}
int main()
{
int * q = myFunction();
cout << "*q=" << *q;
cout << endl;
return 0;
}
```
I purposely wrote the above code to receive an error. The mistake I made is that I stated the return type of function `myFunction()` as `const int *` but when I called `myFunction()` in `main()`, the pointer variable `q` was not declared `const`. The return type of `myFunction()` must match exactly to the type of variable which is going to receive its return value (am I correct here? This is what I have understood).
So, I fixed the error by correcting line 11 as `const int * q = myFunction();`. Now the type of the (pointer)variable `q`, which is `const int *`, matched exactly to the return type of `myFunction()` and the code compiled without error, producing output as `*q=5` (is my understanding up to this point correct?).
Then, I wrote the following code:
```cpp
#include <iostream>
using namespace std;
const int * const myFunction()
{
int * p = new int(5);
cout << "p: " << p;
return p;
}
int main()
{
int a;
const int * q = myFunction();
cout << "\nq=" << q;
cout << "\n*q=" << *q;
delete q;
q = &a;
cout << "\nq: " << q;
cout << endl;
return 0;
}
```
I was expecting an error here, too. Because now the return type of `myFunction()` is `const int * const` but the (pointer)variable `q` had type `const int *`. `q` was not declared as a constant pointer. But the program compiled and I got output as follows:
```
p: 0x36cb8
q=0x36cb8
*q=5
q: 0x61ff08
```
I am confused why the second code compiles and runs. What I thought is whoever is going to receive the return value from `myFunction()` should always take care of it (i.e. it cannot be allowed to take a different memory address), but the pointer variable `q` took a different memory location. | 2020/08/14 | [
"https://Stackoverflow.com/questions/63417657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13149182/"
] | >
> The return type of myFunction must match exactly to the type of variable which is going the receive it's return value. (Am I correct here? This is what I have understood.)
>
>
>
No, the return type must not match exactly to the type of the variable. But it must be possible to implicitly convert the return type to the type of the variable.
For example something like this will compile:
```
int someInt = getMeAFloat();
```
If `getMeAFloat` returns a `float`, this will compile because a `float` can be implicitly converted to an `int`. (Note that this gives you a warning and is bad because you lose the extra information of the `float`, but I am just trying to bring my point across)
Your first example does not compile because normally a `const int*` can not be converted to a `int*`.
As pointed out by user4581301 the second `const` in your second example does not matter, because only the value of the pointer, which is returned, gets assigned to the pointer in the main function. The second `const` makes the pointer itself constant, which has no effect on the value.
That means that `const int * const myFunction()` is equal to `const int * myFunction()` | In the 2nd code, `q` is a `const int *` - a non-const "pointer to a `const int`". Since `q` itself is not `const`, it can be re-assigned to point at a new address.
The compiler allows `q = &a;` because an `int*` (ie, what `&a` returns since `a` is an `int`) can be assigned to a `const int*`. In other words, a "pointer to non-const data" can be assigned to a "pointer to const data", effectively making read-only access to otherwise-writable data.
The reverse is not true - a "pointer to const data" cannot be assigned to a "pointer to non-const data", as that would allow writable access to read-only data - which is why the 1st code fails to compile. |
33,377,872 | How can I get automatically primaryKey name of any table in yii framework.I want to use primary key automatically in `framework\gii\generators\model\templates\default\model.php` .
primaryKey is XXX
```
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>' XXX DESC',
),
));
``` | 2015/10/27 | [
"https://Stackoverflow.com/questions/33377872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4826469/"
] | `find` gives the Output `---------- file.txt :10` when working with files. If it processes STDIN, it gives you only the number:
```
find /v /c "" <file.txt
```
to get this Output into a variable, use this `for` Statement:
```
for /f %%i in ('find /v /c "" ^<file.txt') do set myint=%%i
echo %myint%
```
(for use on the commandline, use single `%i` instead of `%%i`) | I believe you'll need to pipe the results of `find` into another utility such as [`findstr`](https://technet.microsoft.com/en-us/library/bb490907.aspx)2.
Reason being: The /C option `Displays only the count of lines containing the string.`.
Depending upon the search `filepath` you provide, there could be multiple entries that return. In order to make sure the results are meaningful, `find` has to provide you with the `filepath` in order to provide you with the appropriate context.
So you would want to issue something1 like:
```
int myInt = exec('find /v /c "" 'filepath' | findstr /r ': [0-9]*');
```
1 *Please note: I haven't validated that regex within `findstr` will work.*
2 *Apparently `findstr` [returns the entire line as well](https://stackoverflow.com/questions/33377867/use-find-to-return-only-the-number#comment54550389_33378071) so you'll need to find a different command.* |
20,519,192 | I know you can set user [profiles](https://stackoverflow.com/questions/1914286/oracle-set-query-timeout) or set a general timeout for query.
But I wish to set timeout to a specific query inside a procedure and catch the exception, something like :
```
begin
update tbl set col = v_val; --Unlimited time
delete from tbl where id = 20; --Unlimited time
begin
delete from tbl; -- I want this to have a limited time to perform
exception when (timeout???) then
--code;
end;
end;
```
Is this possible? is there any timeout exceptions at all I can catch? per block or query? didn't find much info on the topic. | 2013/12/11 | [
"https://Stackoverflow.com/questions/20519192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1026199/"
] | No, you can not set a timeout in pl/sql. You could use a host language for this in which you embed your sql and pl/sql. | ```none
MariaDB> select sleep(4);
+----------+
| sleep(4) |
+----------+
| 0 |
+----------+
1 row in set (4.002 sec)
MariaDB>
```
See: <https://mariadb.com/kb/en/sleep/> |
24,601,235 | I am having some trouble with the csrf of sails.js, I activated it and create the hidden field like in the sailsjs documentation, but when I submit the form I always get this response:
```
Error: Forbidden
at Object.exports.error (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:62:13)
at createToken (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/node_modules/connect/lib/middleware/csrf.js:82:55)
at /Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/node_modules/connect/lib/middleware/csrf.js:48:24
at routes.before./* (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/lib/hooks/csrf/index.js:26:28)
at _bind.enhancedFn (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/lib/router/bind.js:375:4)
at callbacks (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
at param (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
at pass (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
at nextRoute (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
at callbacks (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
```
Somebody can help me to find a solution? I think it is a simple thing to do, I just don't know what is this "simple thing" | 2014/07/06 | [
"https://Stackoverflow.com/questions/24601235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839867/"
] | If your app is in production mode, it will mask the csrf mismatch response with "Forbidden" as per the default forbidden.js file.
You can override this by creating the file "api/responses/forbidden.js" and copying the contents of this into it
<https://github.com/balderdashy/sails/blob/master/lib/hooks/responses/defaults/forbidden.js#L35>
Notice that I highlighted the line causing this, this is where you will add a check for data === 'CSRF Mismatch' and avoid changing the data to undefined, or change the response however you want it. | First of all you need to get CSRF token by calling the webservice (/csrfToken). In response, you'll get a token. You need to send that token in all subsequent requests to server.
```
$http.get($scope.baseUrl + '/csrfToken')
.success(function(csrfObj) {
csrfToken = csrfObj._csrf;
});
$http.post('/chat/addconv/',{user:$scope.chatUser,message: $scope.chatMessage, _csrf:csrfToken});
``` |
816,968 | Determine $\displaystyle{\lim\_{n\to\infty} x\_n}$ if $$\left(1+\frac{1}{n}\right)^{n+x\_n}=e,\forall n\in \mathbb{N} $$
I have typed 2 methods giving two different answers
---
### Method 1
$$\lim\_{n\to\infty}\left(1+\frac{1}{n}\right)^{n+x\_n}=\lim\_{n\to\infty}e\\\implies
\lim\_{n\to\infty}\left(1+\frac{1}{n}\right)^{n}\cdot\lim\_{n\to\infty}\left(1+\frac{1}{n}\right)^{x\_n}=e\\\implies
e\cdot\lim\_{n\to\infty}\left(1+\frac{1}{n}\right)^{x\_n}=e
\\\implies
\lim\_{n\to\infty}\left(1+\frac{1}{n}\right)^{x\_n}=1$$
We know:
$$\lim\_{x\to a}\left(f\left(x\right)^{g\left(x\right)}\right)=L\Rightarrow\ln L=g\left(x\right)\lim\_{x\to a}\ln\left(f\left(x\right)\right)$$
$$\therefore 0=x\_n\lim\_{n\to\infty}(\ln(1+\frac{1}{n}))$$
Now $\lim\_{n\to\infty}(\ln(1+\frac{1}{n}))=0$ therefore $x\_n$ can be anything.
---
### Method 2
Take log both sides and get
$$\left(x\_n+n\right)\ln\left(1+\frac{1}{n}\right)=1$$
Also as $$t=\frac{1}{n};n\to\infty;t\to0$$
Now $$x\_n=\frac{1}{\ln\left(1+t\right)}-\frac{1}{t}=\frac{t-\ln\left(1+t\right)}{t^2\left(\frac{\ln\left(1+t\right)}{t}\right)}$$
$$\lim\_{n\to\infty}x\_n=\lim\_{t\to0}\frac{t-\ln\left(1+t\right)}{t^2\left(\frac{\ln\left(1+t\right)}{t}\right)}=\lim\_{t\to0}\frac{t-\ln\left(1+t\right)}{t^2}\cdot\lim\_{t\to0}\frac{1}{\frac{\ln\left(1+t\right)}{t}}=\frac{1}{2}\cdot1$$
(Used certain standard limits which you can solve by series or wikipedia for more methods.)
---
Please help.
(By the way I typed the note in [Mathquill](http://mathquill.com/demo.html). Really nice to use) | 2014/06/01 | [
"https://math.stackexchange.com/questions/816968",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/154556/"
] | We have $$ \left(1+\frac{1}{n}\right)^{x\_n} =e\left(1+\frac{1}{n}\right)^{-n}$$ hence $$x\_n =\frac{1}{\ln\left(1+\frac{1}{n}\right)} -n$$ and therefore $$\lim\_{n\to\infty} x\_n =\frac{1}{2}.$$ | You are still solving two different problems. In the first case, you are saying:
>
> If I know that $$\lim\_{n\to\infty} \left(1+\frac1n\right)^{n+x\_n} = e$$ can I determine $\lim\_{n\to\infty} x\_n$?
>
>
>
Your conclusion is correct, you cannot determine $\lim x\_n$ based in this information. For example, if $\forall n x\_n=0$, then $\lim\_{n\to\infty} \left(1+\frac1n\right)^{n+x\_n} = e$, and $\lim\_{n\to\infty}x\_n = 0$, while if $\forall n x\_n=1$, it still satisfies the condition.
But the second approach says:
>
> If I know that $$\left(1+\frac1n\right)^{n+x\_n} = e$$ can I determine $\lim\_{n\to\infty} x\_n$?
>
>
>
This is a lot more information. This entirely specifies the values $x\_n$, while the previous condition only gives you some really loose information about the sequence. So it is no surprise that you can conclude more about $x\_n$ if you have the entire sequence rather than just a property that can match lots of different sequences. |
44,505,904 | Suppose I have an RDD of integers, how to apply a median filter to it if the window for the filter is 3?
All of the map and filter methods in Spark that I looked into, process only one element at a time. But to find the median within a window, we'd want to know the values of all the elements with in the window at the same time.
I am new to Spark, any help would be greatly appreciated. | 2017/06/12 | [
"https://Stackoverflow.com/questions/44505904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6526073/"
] | To support font family on `API` lower than 26, we need to use
```
<font app:fontStyle="normal" app:fontWeight="400" app:font="@font/myfont-Regular"/>
```
instead of
```
<font android:fontStyle="normal" android:fontWeight="400" android:font="@font/myfont-Regular"/>
``` | Here is an example, min sdk support 18 (in app)
<https://github.com/mukundrd/androidFonts> |
44,939 | I distinctly recall reading a Wikipedia page listing multiple theories on the origin of existence itself. One in particular, described in the title, was fascinating and came to mind recently, but I can't recall its name or find the page. I'd like to dig back into it - does anyone know the theory name or page?
Again, that theory of the origin of existence is that it arises simply because all possibilities must be exhausted and this is one of them.
I've tried digging around Wikipedia with no luck so far on these pages:
* <https://en.wikipedia.org/wiki/List_of_unsolved_problems_in_physics>
* <https://en.wikipedia.org/wiki/Problem_of_why_there_is_anything_at_all>
* <https://en.wikipedia.org/wiki/Abiogenesis> | 2017/07/28 | [
"https://philosophy.stackexchange.com/questions/44939",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/17837/"
] | Wittgenstein has noted that all of logic is a set of tautologies. If you want something other than tautologies, you need an inductive base.
From a basic logic point of view, statistics never support an argument. So all observations of frequency are not conclusive. But we generally live in a world that also acknowledges science, at least at some basic level shared by both Aristotelian and modern scientific standards.
You can actually count observed instances and say 'there are N observed instances'. If you have enough resources, you can find that 'm +/- s% of the population with a certainty of d%' does whatever. To declare arguments like that illogical holds one far too close to a place where absolutely nothing that is not tautological can be proved.
And their informal equivalents are not illogical, they are just informal.
Whether N is 'enough', or whether it is 'large' are subjective, but declaring talk about them 'illogical' as the base of an argument because they lie outside the strict bounds of philosophical logic is simply evasive.
One can agree to deal with likelihoods, or one can discard science as a whole. Since modern life depends upon science to a ridiculous degree -- agree to deal with likelihoods. At that point this argument has an obvious logical means of solution. Use the word on people to whom it applies, and see if insult results in a large enough part of the population to establish its effect with an acceptable p-value. | >
> "A large portion of people find it offensive"
>
>
>
This is a logical fallacy. It's called an [argumentum ad populum](https://en.wikipedia.org/wiki/Argumentum_ad_populum).
All of Alice's statements are in fact a mere repetition of the same logical fallacy.
For Bob and Alice to settle the argument with logic, Alice will first have to acknowledge that her argument is fallacious.
Then, she'll have to listen to the arguments Bob has for his position and look for fallacies or other errors in those arguments.
Then, Alice should provide her counter-arguments against Bob's arguments. Bob should listen to those arguments and look for errors in those.
Then, Bob should counter those counter-arguments with counter-counter-arguments. etc.
Alice and Bob should continue this process of each coming up with counter-arguments against the arguments of the other until one of them no longer is capable of providing any counter-arguments.
The person who is incapable of finding any flaws in the arguments of the other and therefore of providing valid counter-arguments is the person who loses the argument.
Alternatively, you may come to a point where you feel that this process is too tedious or where you realize that both of you simply don't have sufficient data to back up your claims. In that case, you agree to disagree. |
43,820 | I have a folder and within it there are many links.
I make those links absolute, so that I can move them about within the folder and they still point to the same data. Relative links would break if I moved them within the folder.
But the problem arises when i move the folder to another system, say an external hard drive or server. Then all the absolute links have the wrong base in their address.
If it were possible to have the links have a variable within their address pointing, then that would solve this problem.
Is that possible? | 2012/07/24 | [
"https://unix.stackexchange.com/questions/43820",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/8563/"
] | I guess the answer to your problem are variant symbolic links, though they only exist on DragonFlyBSD to the best of my knowledge (see that previous question: [Dynamic Symlinks](https://unix.stackexchange.com/questions/7529/dynamic-symlinks) ) | You can't have your cake and eat it. Relative links are generally better, because you can move them around and copy all or part of the tree to another location.
If you move a file within the hierarchy, it's not clear what *should* happen: if there are links `a -> b` and `c -> d`, and you run `mv b d`, should `a` now point to `d`? It's up to you to decide. Symbolic links point to a location; if you want to point to a file, use a hard link (this is not possible for directories).
If you move a file but still want to find it under its old location, add a symbolic link from the old location to the new location. |
69,318,826 | I have a hard time to convert a given tensorflow model into a tflite model and then use it. I already posted a [question](https://stackoverflow.com/questions/69305190/object-detection-with-tflite) where I described my problem but didn't share the model I was working with, because I am not allowed to. Since I didn't find an answer this way, I tried to convert a public model ([ssd\_mobilenet\_v2\_fpnlite\_640x640\_coco17\_tpu](http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8.tar.gz)).
[Here](https://colab.research.google.com/github/tensorflow/models/blob/master/research/object_detection/colab_tutorials/convert_odt_model_to_TFLite.ipynb#scrollTo=TIY3cxDgsxuZ) is a colab tutorial from [the object detection api](https://github.com/tensorflow/models/tree/master/research/object_detection). I just run the whole script without changes (its the same model) and downloaded the generated models (with and without metadata). I uploaded them [here](https://drive.google.com/drive/folders/1dN7kGm_MLrq2riKk5h3fAUosaNuo32qY) together with a sample picture from the coco17 train dataset.
I tried to use those models directly in python, but the results feel like garbage.
Here is the code I used, I followed this [guide](https://heartbeat.comet.ml/running-tensorflow-lite-object-detection-models-in-python-8a73b77e13f8). I changed the indexes for rects, scores and classes because otherwise the results were not in the right format.
```
#interpreter = tf.lite.Interpreter("original_models/model.tflite")
interpreter = tf.lite.Interpreter("original_models/model_with_metadata.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
size = 640
def draw_rect(image, box):
y_min = int(max(1, (box[0] * size)))
x_min = int(max(1, (box[1] * size)))
y_max = int(min(size, (box[2] * size)))
x_max = int(min(size, (box[3] * size)))
# draw a rectangle on the image
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (255, 255, 255), 2)
file = "images/000000000034.jpg"
img = cv2.imread(file)
new_img = cv2.resize(img, (size, size))
new_img = cv2.cvtColor(new_img, cv2.COLOR_BGR2RGB)
interpreter.set_tensor(input_details[0]['index'], [new_img.astype("f")])
interpreter.invoke()
rects = interpreter.get_tensor(
output_details[1]['index'])
scores = interpreter.get_tensor(
output_details[0]['index'])
classes = interpreter.get_tensor(
output_details[3]['index'])
for index, score in enumerate(scores[0]):
draw_rect(new_img,rects[0][index])
#print(rects[0][index])
print("scores: ",scores[0][index])
print("class id: ", classes[0][index])
print("______________________________")
cv2.imshow("image", new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
This leads to the following console output
```
scores: 0.20041436
class id: 51.0
______________________________
scores: 0.08925027
class id: 34.0
______________________________
scores: 0.079722285
class id: 34.0
______________________________
scores: 0.06676647
class id: 71.0
______________________________
scores: 0.06626186
class id: 15.0
______________________________
scores: 0.059938848
class id: 86.0
______________________________
scores: 0.058229476
class id: 34.0
______________________________
scores: 0.053791136
class id: 37.0
______________________________
scores: 0.053478718
class id: 15.0
______________________________
scores: 0.052847564
class id: 43.0
______________________________
```
and the resulting image
[](https://i.stack.imgur.com/Fs99G.jpg).
I tried different images from the orinal training dataset and never got good results. I think the output layer is broken or maybe some postprocessing is missing?
I also tried to use the converting method given from the [offical tensorflow documentaion](https://www.tensorflow.org/lite/convert#convert_a_savedmodel_recommended_).
```
import tensorflow as tf
saved_model_dir = 'tf_models/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8/saved_model/'
# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
```
But when I try to use the model, I get a `ValueError: Cannot set tensor: Dimension mismatch. Got 640 but expected 1 for dimension 1 of input 0.`
Has anyone an idea what I am doing wrong?
**Update:** After Farmmakers advice, I tried changing the input dimensions of the model generating by the short script at the end. The shape before was:
```
[{'name': 'serving_default_input_tensor:0',
'index': 0,
'shape': array([1, 1, 1, 3], dtype=int32),
'shape_signature': array([ 1, -1, -1, 3], dtype=int32),
'dtype': numpy.uint8,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}}]
```
So adding one dimension would not be enough. Therefore I used `interpreter.resize_tensor_input(0, [1,640,640,3])` . Now it works to feed an image through the net.
Unfortunately I sill can't make any sense of the output. Here is the print of the output details:
```
[{'name': 'StatefulPartitionedCall:6',
'index': 473,
'shape': array([ 1, 51150, 4], dtype=int32),
'shape_signature': array([ 1, 51150, 4], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:0',
'index': 2233,
'shape': array([1, 1], dtype=int32),
'shape_signature': array([ 1, -1], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:5',
'index': 2198,
'shape': array([1], dtype=int32),
'shape_signature': array([1], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:7',
'index': 493,
'shape': array([ 1, 51150, 91], dtype=int32),
'shape_signature': array([ 1, 51150, 91], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:1',
'index': 2286,
'shape': array([1, 1, 1], dtype=int32),
'shape_signature': array([ 1, -1, -1], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:2',
'index': 2268,
'shape': array([1, 1], dtype=int32),
'shape_signature': array([ 1, -1], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:4',
'index': 2215,
'shape': array([1, 1], dtype=int32),
'shape_signature': array([ 1, -1], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}},
{'name': 'StatefulPartitionedCall:3',
'index': 2251,
'shape': array([1, 1, 1], dtype=int32),
'shape_signature': array([ 1, -1, -1], dtype=int32),
'dtype': numpy.float32,
'quantization': (0.0, 0),
'quantization_parameters': {'scales': array([], dtype=float32),
'zero_points': array([], dtype=int32),
'quantized_dimension': 0},
'sparsity_parameters': {}}]
```
I added the so generated tflite model to the [google drive](https://drive.google.com/drive/folders/1dN7kGm_MLrq2riKk5h3fAUosaNuo32qY).
**Update2:** I added a directory to the [google drive](https://drive.google.com/drive/folders/1dN7kGm_MLrq2riKk5h3fAUosaNuo32qY) which contains a notebook that uses the full size model and produces the correct output. If you execute the whole notebook it should produce the following image to your disk.
[](https://i.stack.imgur.com/GFHaf.jpg) | 2021/09/24 | [
"https://Stackoverflow.com/questions/69318826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6620870/"
] | [`search`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) converts any string you give it to a *regular expression*. `[]` is special in regular expressions, it defines a character class.
I suspect you want [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes), not `search`, which looks for exactly what you pass it.
```js
const result = ids.includes("[" + myid + "]") ? "found" : "not found";
```
(Or with a template literal:
```js
const result = ids.includes(`[${myid}]`) ? "found" : "not found";
```
) | ### The nasty trap is that you need to double-escape the square bracket
Whatever you pass into the `.search()` method is assumed to be a regular expression. In a regular expression, the "[" and "]" are the delimiters for a set of characters, allowing a match with any one of those characters.
For example the regular expression `[A-Z34]` will match with any capital letter or the digits 3 or 4.
Unfortunately your data contains `[` and `]` as characters within it.
You need one `\` for Javascript and one `\` for the regular expression parser, so that your code correctly looks for exactly the string `[1]`.
```js
const ids = '[2][13]';
const myid = '1';
const result = ids.search('['+myid+']') !== -1 ? 'found' : 'not found';
console.log(result) // found
const result2 = ids.search('\['+myid+'\]') !== -1 ? 'found' : 'not found';
console.log(result2) // found
const result3 = ids.search('\\['+myid+'\\]') !== -1 ? 'found' : 'not found';
console.log(result3) // not found
``` |
3,594,024 | How to create OSGi bundle from jar library? | 2010/08/29 | [
"https://Stackoverflow.com/questions/3594024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/294069/"
] | First check out if you can find a osgi enabled version of your library from repositories
1. SpringSource <http://www.springsource.com/repository>
2. Fusesource <http://repo.fusesource.com/>
If you don't find the OSGi enabled versions. You can go ahead with using the pax tool - [PaxConstruct](http://wiki.ops4j.org/display/paxconstruct/Pax+Construct) or use the [aQute's Bnd tool](https://bnd.bndtools.org/). | Late arrival to the party:
If you're using **Gradle**, you can add the jar as a normal dependency of your project if you apply the [osgi-run](https://github.com/renatoathaydes/osgi-run) plugin.
The osgi-run plugin will wrap the jar transparently into a bundle for you, exporting every package in it and calculating all its imports. As Gradle will know the jar's transitive dependencies, it will do the same for them as well, if necessary.
The jar(s) will be part of the OSGi runtime osgi-run creates, which you can then start up with `gradle runOsgi` or `gradle createOsgi`, then executing either the `run.sh` or `run.bat` scripts.
The actual wrapping is done by [Bnd](http://bnd.bndtools.org/), the swiss knife of the OSGi world, of course.
If you want to configure how the wrapping happens (what should be imported/exported, usually), you can do it easily in the Gradle build file, see the [documentation](https://github.com/renatoathaydes/osgi-run#wrapping-non-bundles-flat-jars) for details.
Example:
```
wrapInstructions {
// use regex to match file name of dependency
manifest( "c3p0.*" ) {
// import everything except the log4j package - should not be needed
instruction 'Import-Package', '!org.apache.log4j', '*'
instruction 'Bundle-Description', 'c3p0 is an easy-to-use library for making traditional ' +
'JDBC drivers "enterprise-ready" by augmenting them with functionality defined by ' +
'the jdbc3 spec and the optional extensions to jdbc2.'
}
}
``` |
24,297,737 | I'd like to place an `ImageView` behind an `ImageButton`. What's the best way to go about doing this? | 2014/06/19 | [
"https://Stackoverflow.com/questions/24297737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2580984/"
] | I believe the easiest way to do this is to wrap both the `ImageView` and `ImageButton` in a `FrameLayout`. eg:
```
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/your_image" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" />
</FrameLayout>
``` | The easiest way is to use an `ImageButton` only.
`ImageButton` has a `background` attribute for the background image
and a `src` attribute for the image in the foreground.
*See this existing [example](https://stackoverflow.com/a/2283993/320111) on StackOverflow.*
```
<ImageButton
android:id="@+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/album_icon"
android:background="@drawable/round_button" />
```
 |
13,637,956 | I have a base class with a static pointer member. When I assign that static pointer member in a derived class, that static member appears NULL when referenced from the methods of the base class.
This is not the behavior I expect. Shouldn't the static pointer member still be assigned regardless of where it is accessed from? Am I wrong about the expected behavior?
The static member is a pointer to a base class. I realize that what I am trying to achieve is probably best accomplished by static polymorphism using templates ( [Static polymorphism definition and implementation](https://stackoverflow.com/questions/4557141/static-polymorphism-definition-and-implementation) ) but I still do not understand why in this scenario the pointer member itself is NULL.
Edit: the behavior is NOT demonstrated in this SSCE. What bugs or common errors would cause the behavior I describe? My actual production scenario is significantly more complicated than this, but the structure is almost exactly the same. I am literally in the VS2010 debugger observing `Base::staticMember == not null`, then call to `Base::staticMethod()`, and inside `Base::staticMethod()`, `Base::staticMember` is null. I am baffled.
```
#include <iostream>
class Base {
public:
static Base *staticMember;
static void baseMethod();
};
Base *Base::staticMember = NULL;
class Derived : public Base {
public:
void derivedMethod();
};
void Base::baseMethod() {
// here staticMember == NULL, the unexpected behavior
if(staticMember == NULL) {
std::cout << "NULL";
} else {
std::cout << "NOT NULL";
}
};
void Derived::derivedMethod() {
staticMember = new Derived();
}
int main(int argc, void *argv[]) {
Derived *derived = new Derived();
derived->derivedMethod();
Base::baseMethod();
}
``` | 2012/11/30 | [
"https://Stackoverflow.com/questions/13637956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/753089/"
] | No repro on a fixed up and simplified version of your code:
```
#include <iostream>
#include <iomanip>
struct Base {
static Base* staticMember;
static void baseMethod();
};
Base* Base::staticMember;
void Base::baseMethod() {
std::cout << std::boolalpha << (staticMember == nullptr) << std::endl;
}
struct Derived : Base {
void derivedMethod();
};
void Derived::derivedMethod() {
staticMember = this;
}
int main() {
Derived derived;
derived.derivedMethod();
Base::baseMethod();
}
```
Prints "false".
**Always give a [Short, Self Contained, Correct (Compilable), Example](http://www.sscce.org/), or your question is meaningless.** | Maybe you have accidentally declared
class Derived {
static Base \*staticMember;
};
So you have two staticMembers floating around.
This is why an SSCE is useful, to keep people like me from making unfounded guesses. |
63,615,554 | In laravel 5.8 my swagger documentation is displaying fine but when I enter execute then its coming with 'Could not render n, see the console.' error.
[](https://i.stack.imgur.com/LyrO0.png)
**composer.php**
```
"darkaonline/l5-swagger": "5.8.*"
```
what can be the reason? anyone please suggest. TIA | 2020/08/27 | [
"https://Stackoverflow.com/questions/63615554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6901052/"
] | Let's try this:
1. Tools -> Options -> Authentication
2. Click "Edit" on Your Account
3. Click "Refresh OAuth Token"
It works for me :) | Tools/Options/Authentication, delete your github account, add again. Works for me. |
25,740,431 | Hello all I am creating a program for finding the date of birth when the exact age is given. For example if age of a man is 21 years 10 months and 22 days(up to current date) how can i find the exact date of birth. I will be thankful if anyone help me with isuue.
What i tried is here.
here d,m and y are text field for days months and years.
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int da = Integer.parseInt(d.getText());
da = -da;
int mo = Integer.parseInt(m.getText());
mo = -mo;
int ye = Integer.parseInt(y.getText());
ye = -ye;
SimpleDateFormat ddd = new SimpleDateFormat("dd");
SimpleDateFormat mmm = new SimpleDateFormat("MM");
SimpleDateFormat yyy = new SimpleDateFormat("yyyy");
Calendar cal = Calendar.getInstance();
cal.getTime();
cal.add(Calendar.DATE, da);
cal.set(Integer.parseInt(yyy.format(cal.getTime())), Integer.parseInt(mmm.format(cal.getTime())), Integer.parseInt(ddd.format(cal.getTime())));
cal.add(cal.MONTH, mo);cal.set(Integer.parseInt(yyy.format(cal.getTime())), Integer.parseInt(mmm.format(cal.getTime())), Integer.parseInt(ddd.format(cal.getTime())));
cal.add(cal.YEAR, ye);
System.out.println(getDate(cal));
}
```
My problem is if I enter 21 year 10 months and 22 days as the age of a person the date given by compiler is 18/12/1992 but actual date should be 17/10/1992.
Please help me with this issue. | 2014/09/09 | [
"https://Stackoverflow.com/questions/25740431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3992215/"
] | Here is Java 8 solution implemented by [Date & Time API](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html):
```
int dobYear = 21;
int dobMonth = 10;
int dobDay = 22;
LocalDate now = LocalDate.now();
LocalDate dob = now.minusYears(dobYear)
.minusMonths(dobMonth)
.minusDays(dobDay);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(dob.format(formatter));
```
Output: `18/10/1992`. | You are subtracting the days first, then the months and last the years. This is wrong in my opinion because you don't know how many leap year may have been in all the years.
Try
```
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, ye);
cal.add(Calendar.MONTH, mo);
cal.add(Calendar.DAY_OF_MONTH, da);
```
doing so I get: Sun Oct 18 11:24:52 CET 1992 |
7,103,312 | I'm using following code for textarea:
```
$('#ajaxSendMessage').live('keyup', function(event) {
if (event.keyCode == 13) {
controller.sendMessage($(this).val(), $("#ajaxAnswerTo").val());
}
});
```
This code works, but `$("#ajaxAnswerTo").val()` have new line characte when I click enter...
For example: I entered: helo world and then moved cursor to helo world, updated it to hello and clicked enter. The result code will be: hell\no world.
How to remove this \n? | 2011/08/18 | [
"https://Stackoverflow.com/questions/7103312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568975/"
] | Ensure that account running your process where the service is hosted has access rights to the database. For example in case of IIS the account running the application pool where the service is hosted must have login to database server and it must have permissions to do all necessary operations in your database. | Problem :- I had the same problem with hosted WCF service on one of our windows servers. Application was unable to connect with the service.
Solution :- Had to reset app/pool of WCF service
Thanks |
47,971,712 | I have files with these filename:
```
ZATR0008_2018.pdf
ZATR0018_2018.pdf
ZATR0218_2018.pdf
```
Where the 4 digits after `ZATR` is the issue number of magazine.
With this regex:
```
([1-9][0-9]*)(?=_\d)
```
I can extract `8`, `18` or `218` but I would like to keep minimum 2 digits and max 3 digits so the result should be `08`, `18` and `218`.
How is possible to do that? | 2017/12/25 | [
"https://Stackoverflow.com/questions/47971712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297545/"
] | ```
(?:[1-9][0-9]?)?[0-9]{2}(?=_[0-9])
```
or perhaps:
```
(?:[1-9][0-9]+|[0-9]{2})(?=_[0-9])
```
(<https://www.freeformatter.com/regex-tester.html>, which claims to use the XRegExp library, that you mention in another answer doesn't seem to backtrack into the `(?:)?` in my first suggestion where necessary, which makes it very different from any regex engine I've encoutered before and makes it prefer to match just the `18` of `218` even though it starts later in the string. But it does work with my second suggestion. | I propose you:
```
^ZATR0*(\d{2,3})_\d+\.pdf$
```
demo code [here](https://regex101.com/r/MZ0vRi/1/). Result:
>
> Match 1 Full match 0-17 `ZATR0008_2018.pdf` Group 1. 6-8 `08`
>
>
> Match 2 Full match 18-35 `ZATR0018_2018.pdf` Group 1. 24-26 `18`
>
>
> Match 3 Full match 36-53 `ZATR0218_2018.pdf` Group 1. 41-44 `218`
>
>
> |
3,806,534 | >
> Question: Suppose $f:(-\delta,\delta)\to (0,\infty)$ has the property that $$\lim\_{x\to 0}\left(f(x)+\frac{1}{f(x)}\right)=2.$$ Show that $\lim\_{x\to 0}f(x)=1$.
>
>
>
My approach: Let $h:(-\delta,\delta)\to(-1,\infty)$ be such that $h(x)=f(x)-1, \forall x\in(-\delta,\delta).$ Note that if we can show that $\lim\_{x\to 0}h(x)=0$, then we will be done. Now since we have $$\lim\_{x\to 0}\left(f(x)+\frac{1}{f(x)}\right)=2\implies \lim\_{x\to 0}\frac{(f(x)-1)^2}{f(x)}=0\implies \lim\_{x\to 0}\frac{h^2(x)}{h(x)+1}=0.$$ Next I tried to come up with some bounds in order to use Sandwich theorem to show that $\lim\_{x\to 0} h(x)=0,$ but the bounds didn't quite work out. The bounds were the following: $$\begin{cases}h(x)\ge \frac{h^2(x)}{h(x)+1},\text{when }h(x)\ge 0,\\h(x)<\frac{h^2(x)}{h(x)+1},\text{when }h(x)<0.\end{cases}$$
How to proceed after this? | 2020/08/28 | [
"https://math.stackexchange.com/questions/3806534",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/751630/"
] | Setting $y = f(x) + \dfrac{1}{f(x)} \to 2$ we have
$$
f(x) = \frac{y\pm\sqrt{y^2-4}}{2} \to \frac{2\pm\sqrt{2^2-4}}{2} = 1.
$$
The limit can be justified using the squeeze theorem, since $f(x) = \frac{y\pm\sqrt{y^2-4}}{2},$ i.e. $f(x)$ equals either $\frac{y-\sqrt{y^2-4}}{2}$ or $\frac{y+\sqrt{y^2-4}}{2},$ implies $\frac{y-\sqrt{y^2-4}}{2} \leq f(x) \leq \frac{y+\sqrt{y^2-4}}{2}$. | I will start off with a fairly general lemma about limiting behavior of roots of a parameterized polynomial equation:
**Lemma:** Consider the polynomial equation $x^n + t\_{n-1} x^{n-1} + t\_{n-2} x^{n-2} + \cdots + t\_0 = 0$. Then as $t\_{n-1}, \ldots, t\_0 \to 0$, all $n$ complex roots of this equation also approach 0. To be precise: for every $\epsilon > 0$, there exists $\delta > 0$ such that whenever $|t\_i| < \delta$ for $i = 0, \ldots, n-1$ and $x^n + t\_{n-1} x^{n-1} + \cdots + t\_0 = 0$, it follows that $|x| < \epsilon$.
**Proof:** If $x$ is a root of the polynomial equation, then it follows that $|t\_{n-i} x^{n-i}| \ge \frac{1}{n} |x|^n$ for some $i \in \{ 1, \ldots, n \}$ -- since otherwise, we would have $|x^n + t\_{n-1} x^{n-1} + \cdots + t\_0| \ge |x|^n - |t\_{n-1} x^{n-1}| - \cdots - |t\_0| > 0$, giving a contradiction. Therefore, for this value of $i$, we have $|x| \le |t\_{n-i} n|^{1/i}$ ("even if $x=0$"). Since $|t\_{n-i} n|^{1/i} \to 0$ for each $i$ as $t\_0, \ldots, t\_{n-1} \to 0$, the desired result follows. $\square$
---
Now, to apply this lemma to the original problem, let us set $g(x) := f(x) + \frac{1}{f(x)} - 2$. Then $f(x) - 1$ satisfies the equation $(f(x) - 1)^2 - g(x) (f(x) - 1) - g(x) = 0$; and by assumption, we have $g(x) \to 0$ as $x \to 1$. Therefore, by a typical "composition of limits" type argument combined with the lemma above, we can conclude that $f(x) - 1 \to 0$ as $x \to 1$. |
581,193 | there seem to be no stage.border property in AS 3?
my class extends Sprite, what is best way to draw border around flash object? | 2009/02/24 | [
"https://Stackoverflow.com/questions/581193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20979/"
] | this.graphics.lineStyle(0,0x555555,0.5);
this.graphics.drawRect(0,0,this.width,this.height);
where "this" is your Sprite object. | OXMO456's code has a typo. Below is the fixed version:
```
this.graphics.lineStyle(0,0x555555,0.5);
this.graphics.drawRect(0,0,this.width,this.height);
```
Also, I should mention that this.width and this.height both start as 0 when the application starts, so putting the code above in the constructor of the main MovieClip won't do anything -- it will draw a rectangle 0 by 0 large. One work around would be to put the code above in a ADDED\_TO\_STAGE event handler. |
2,219,169 | Integrate the given:
$$\int 3x\sqrt {x+5} dx$$.
My Attempt:
$$\int 3x\sqrt {x+5} dx$$
$$3\int x\sqrt {x+5} dx$$
What should I do next? | 2017/04/05 | [
"https://math.stackexchange.com/questions/2219169",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/354073/"
] | Set $u=x+5$, so the integrand becomes $3(u-5)\sqrt{u} = 3u^{3/2}-15u^{1/2}.$ (And here $dx=du$.) In general, square roots and addition don't get along well together, so when you see $\sqrt{a\pm b}$, you can make the difficulty go away by substituting $u=a \pm b.$ | Hint : Take $x+5=t^2$. Then the integral reduces to $$3\int (t^2-5)t 2t dt=6\int t^4-5t^2 $$ |
12,862,655 | When signing an apk after a long break from Android development I was surprised that I'm no longer able to enter an **empty keystore password** to unlock it. Is it just me or has this been possible before? If so, when did that change and how can I manage to unlock the keystore anyway?
Some background: maybe I'm just crazy and didn't use an empty password for the keystore before, but the one and only possible password that I could have been using instead doesn't work either (I swear, there's no chance I'd have used another password!). | 2012/10/12 | [
"https://Stackoverflow.com/questions/12862655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198996/"
] | Try default android debug mode keystore password which is `android` or java cacerts default `changeit`/`changeme`. | If all of the above fail you can try cracking it. Related question: [Android - Forgot keystore password. Can I decrypt keystore file?](https://stackoverflow.com/questions/8894987/android-forgot-keystore-password-can-i-decrypt-keystore-file) |
124,628 | We have a VF custom button on lead record that sends details of lead via email to a selected contact but when the email is sent it doesn't shows up on lead activity history, is there any way to track the emails being sent through this button?
Apex class
```
/*Controller to send This lead to any selected Contact */
public class EmailController {
public Lead leadRecord {get;set;}
public String TemplateID {get;set;}
public String subject { get; set; }
public String body { get; set; }
public String htmlBody { get; set; }
public EmailTemplate ET{ get; set; }
public EmailController(ApexPages.StandardController controller) {
String lid = '';
TemplateID = '';
htmlBody ='';
if(ApexPages.currentPage().getParameters().get('id') != null )
lid = ApexPages.currentPage().getParameters().get('id');
system.debug('lidid ' + lid );
try{
leadRecord = [select Status,ID,Contact__c,Name,Company,NumberOfEmployees,Street,City,State,PostalCode,Country,Website,Salutation,FirstName,
LastName,Title,Department__c,Email,Phone,MobilePhone,Fax,Product__c,Industry,Specialty__c,Rating,BuyingTimeframe__c,LeadSource,WebFormDetail__c,
Description,Marketing_Comments__c from Lead where id = : lid];
//Change the Template name below.
ET = [Select ID,HTMLValue,Subject from EmailTemplate where name = 'Lead Email' ];
if (ET != null){
TemplateID = ET.id;
htmlBody = ET.HTMLValue ;
Subject = ET.Subject;
ReplaceTags();
}
}
catch(Exception e){
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,e.getMessage()));
}
}
public void ReplaceTags(){
if(htmlBody.indexOf('{!Lead.Id}') >-1)
htmlBody = htmlBody.replace('{!Lead.Id}',nullToString(leadRecord.Id));
if(htmlBody.indexOf('{!Lead.Name}') >-1)
htmlBody = htmlBody.replace('{!Lead.Name}',nullToString(leadRecord.Name));
if(htmlBody.indexOf('{!Lead.Company}') >-1)
htmlBody = htmlBody.replace('{!Lead.Company}',nullToString(leadRecord.Company));
if(htmlBody.indexOf('{!Lead.NumberOfEmployees}') >-1)
htmlBody = htmlBody.replace('{!Lead.NumberOfEmployees}',nullToString(String.valueOf(leadRecord.NumberOfEmployees)));
if(htmlBody.indexOf('{!Lead.Address}') >-1){
String Address = '' ;
Address = Address + nullToString(String.valueOf(leadRecord.Street));
Address = Address + ' ' + nullToString(leadRecord.City);
Address = Address + ','+ nullToString(leadRecord.State);
Address = Address + ' ' + nullToString(leadRecord.PostalCode);
Address = Address + ' ' + nullToString(leadRecord.Country);
htmlBody = htmlBody.replace('{!Lead.Address}',Address);
}
if(htmlBody.indexOf('{!Lead.Street}') >-1)
htmlBody = htmlBody.replace('{!Lead.Street}',nullToString(String.valueOf(leadRecord.Street)));
if(htmlBody.indexOf('{!Lead.City}') >-1)
htmlBody = htmlBody.replace('{!Lead.City}',nullToString(leadRecord.City));
if(htmlBody.indexOf('{!Lead.State}') >-1)
htmlBody = htmlBody.replace('{!Lead.State}',nullToString(leadRecord.State));
if(htmlBody.indexOf('{!Lead.PostalCode}') >-1)
htmlBody = htmlBody.replace('{!Lead.PostalCode}',nullToString(leadRecord.PostalCode));
if(htmlBody.indexOf('{!Lead.Country}') >-1)
htmlBody = htmlBody.replace('{!Lead.Country}',nullToString(leadRecord.Country));
if(htmlBody.indexOf('{!Lead.FirstName} ') >-1)
htmlBody = htmlBody.replace('{!Lead.FirstName} ',nullToString(leadRecord.FirstName) );
if(htmlBody.indexOf('{!Lead.LastName}') >-1)
htmlBody = htmlBody.replace('{!Lead.LastName}',nullToString(leadRecord.LastName));
if(htmlBody.indexOf('{!Lead.Title}') >-1)
htmlBody = htmlBody.replace('{!Lead.Title}',nullToString(leadRecord.Title));
}
public PageReference send() {
List<Messaging.SingleEmailMessage> email = new List<Messaging.SingleEmailMessage>();
if(leadRecord.Contact__c == null){
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Please select contact and Try again.'));
return null;
}
if (TemplateID != null){
// Query Contact Email ID
try{
Contact c = [Select Id,Email,Name from Contact where ID =: leadRecord.Contact__c];
if (c.Email != null && c.Email != ''){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
if(htmlBody.indexOf('{!Contact.Name}') >-1)
htmlBody = htmlBody.replace('{!Contact.Name}',nullToString(c.name));
String[] toAddresses = new String[] {c.email};
mail.setTargetObjectId(c.id);
mail.setSubject(Subject);
mail.setToAddresses(toAddresses);
mail.setHtmlBody(HtmlBody);
mail.setsaveAsActivity(true);
mail.setTreatTargetObjectAsRecipient(false);
// mail.setTargetObjectId(LeadRecord.Id);
email.add(mail);
Messaging.sendEmail(email);
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Email sent successfully!'));
leadRecord.Status = 'Tracking';
update leadRecord;
}
else{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Selected Contact has no Valid Email Address, kindly update the contact and Try again.'));
return null;
}
}catch(Exception e){}
}
return new PageReference('/' + leadRecord.id);
}
public String nullToString(String s){
if (s== null)
return '';
else
return s;
}
public PageReference cancel(){
return new PageReference('/' + leadRecord.id);
}
}
```
VF Page:
```
<apex:page standardcontroller="Lead" extensions="EmailController" showheader="false">
<apex:form >
<apex:pageBlock title="Please select the Contact below">
<br/>
<apex:pageMessages />
<b><apex:outputLabel value="To" for="To"/>:</b><br />
<apex:inputField value="{!leadRecord.Contact__c}" id="To" />
<br />
<br />
<b><apex:outputLabel value="Subject" for="Subject"/>:</b><br />
<apex:outputText value="{!ET.subject}" id="Subject" />
<br />
<br />
<apex:inputTextArea value="{!htmlBody}" id="Body" rows="30" cols="80" richText="true" disabled="true" />
<br /><br /><br />
<apex:commandButton value="Send Email" action="{!send}" />
<apex:commandButton value="Cancel & Return" action="{!Cancel}" />
</apex:pageBlock>
</apex:form>
</apex:page>
``` | 2016/06/03 | [
"https://salesforce.stackexchange.com/questions/124628",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/9919/"
] | you need to use `saveAsActivity` to add this as activity.
```
mail.saveAsActivity(true);
```
This is the missing key here.
**Update:**
Use the `leadId` in `targetObject` Id to add in the Activity under lead and set the contact email address in to address to send email to contact.
```
String[] toAddresses = new String[] {usr.email};
mail.setToAddresses(toAddresses);
```
And in the end set the `mail.setTreatTargetObjectAsRecipient(false);` so that your lead email will not get email.
Complete email code for reference
```
String[] toAddresses = new String[] {c.email};
mail.setTargetObjectId(c.Id);
mail.setSubject(Subject);
mail.setToAddresses(toAddresses);
mail.setHtmlBody(HtmlBody);
mail.setsaveAsActivity(true);
mail.setTreatTargetObjectAsRecipient(false)
email.add(mail);
Messaging.sendEmail(email);
``` | You have to set `setSaveAsActivity` and `setWhatId`.
>
> Update
>
>
>
In your code, you have set `TargetObjectId` twice as `mail.setTargetObjectId(c.id);` and `mail.setTargetObjectId(LeadRecord.Id);`. Thats why when you comment `mail.setTargetObjectId(LeadRecord.Id);` it is sent to Contact.
I was going through your code and **I believe your Lead does not have email address** and you are not logging the exception `catch(Exception e){}` anywhere. Can you
please update this line
`catch(Exception e){}`
with this new line
`catch(Exception e){System.debug('The following exception has occurred: ' + e.getMessage());}`
and see what is the error message in debug log. |
38,581,697 | I have a following piece for loop in a function which I intended to parallelize but not sure if the load of multiple threads will overweight the benefit of concurrency.
All I need is to send different log files to corresponding receivers. For the timebeing lets say number of receivers wont more than 10. Instead of sending log files back to back, is it more efficient if I send them all parallel?
```
for(int i=0; i < receiversList.size(); i++)
{
String receiverURL = serverURL + receiversList.get(i);
HttpPost method = new HttpPost(receiverURL);
String logPath = logFilesPath + logFilesList.get(i);
messagesList = readMsg(logPath);
for (String message : messagesList) {
StringEntity entity = new StringEntity(message);
log.info("Sending message:");
log.info(message + "\n");
method.setEntity(entity);
if (receiverURL.startsWith("https")) {
processAuthentication(method, username, password);
}
httpClient.execute(method).getEntity().getContent().close();
}
Thread.sleep(500); // Waiting time for the message to be sent
}
```
Also please tell me how can I make it parallel if it is gonna work? Should I do it manual or use ExecutorService? | 2016/07/26 | [
"https://Stackoverflow.com/questions/38581697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1702957/"
] | ```
XmlDocument newdoc = new XmlDocument();
newdoc.InnerXml = " <?xml version="1.0" encoding="utf-8" ?>
<Resorces>
<Resource id="3" name="loreum ipsum" downloadcount="5"></Resource>
<Resource id="2" name="loreum ipsum" downloadcount="9"></Resource>
</Resorces>";
List<string> list = new List <string>();
var selectnode = "Resorces/Resource";
var nodes = newdoc.SelectNodes(selectnode);
foreach (XmlNode nod in nodes)
{
string id = nod["id"].InnerText;
string name = nod["name"].InnerText;
string downloadcount = nod["downloadcount"].InnerText;
list.Add(id);
list.Add(name);
list.Add(downloadcount);
}
Console.WriteLine(list.Count);
``` | You can get by this
```
XDocument doc = XDocument.Load(xmlpath);
List<Report> resourceList = doc.Descendants("Resorces")
.First()
.Elements("Resource")
.Select(report => new Report()
{
ResourceId = (int)report.Attribute("id"),
ResourceName = (string)report.Attribute("name"),
DownloadCount = (int)report.Attribute("downloadcount")
}).ToList();
``` |
603,980 | According to my desk clock, it is now Monday, 1:00 a.m.
I wish to mention in an e-mail preparations for a storm which is expected to arrive Monday around 8:00 p.m., that is, 19 hours from now.
The storm is not expected to come "tonight": rather, it is expected to come the following night.
The storm is not expected to come "tomorrow night", either: that would be Tuesday night, whereas the storm is expected to come Monday night.
What is the least awkward way to refer to the night in question? Have I discovered a lexical gap? If I have, then why does this gap exist: why has no one bothered to fill it? | 2023/02/27 | [
"https://english.stackexchange.com/questions/603980",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/210038/"
] | Choose the answers-in-comments that fits your requirements:
The 'small hours' of Monday morning can be regarded as still part of Sunday night in some contexts, but not all. The only way to make it clear is to say "The storm is expected tonight (Monday)". –
Kate Bunting
It is potentially ambiguous: at 1 am Monday it's common to say "tomorrow" meaning Monday if none of you have gone to bed/sleep yet: "tomorrow" often refers to the time after you next sleep, and "tomorrow night" works the same. Often it's clear from context what is meant, but if you're giving weather alerts you need to be unambiguous. –
Stuart F
Once you decide that 1 PM is no longer tonight, then Monday night is tomorrow night. "The storm is not expected tonight." –
Yosef Baskin
My answer is the same as the OP's: "a storm is expected to arrive Monday around 8:00 p.m., that is, 19 hours from now." Nothing is clearer than that. | While "tonight" may sometimes be ambiguous in the middle of the night, very often context will make it clear whether you mean the current night in progress or the upcoming night.
For instance, if you say:
>
> There's a storm coming tonight, I'm going to board up the windows in the morning.
>
>
>
it's obvious that you mean Monday night, not sometime around now. But if you say:
>
> There's a storm coming tonight, we'd better get off the road as soon as possible.
>
>
>
you presumably mean the current night. Of course, you could also just say "coming soon" in this case, there's no need to specify the period of the day.
Also, if you say "later tonight", it usually means the current night.
On the other hand, "tomorrow night" will almost always be confusing if you use it in the early morning, and I don't think there are any contextual disambiguations. Just say "Monday night" or "Tuesday night" to avoid the problem. |
11,003,586 | I have a table like "groups" that stores a list of groups that my "users" can belong to. In the User model, this is accomplished with `belongs_to :group`. In my view, I want to display the group name. I'm trying to do that with `@user.group.name`.
The problem is that not every user is assigned to a group, so `@user.group` for example would be `nil`. So, I get a `NoMethodError: undefined method 'name' for nil:NilClass` which is frustrating.
What is the best way to work around this problem? | 2012/06/12 | [
"https://Stackoverflow.com/questions/11003586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186100/"
] | The simplest way would be to do something like this:
```
<% if @user.group.present? %>
<%= @user.group.name %>
<% end %>
```
However, according to the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter), a model should only talk to it's immediate association/should not know about its association's methods.
So, ideally, you should do something like this (in your User model):
```
delegate :name, :to => :group, :prefix => true, :allow_nil => true
```
Which you can then access through `@user.group_name`. It will return `nil` if there is no associated group, but will not raise an exception. This is equivalent to
```
def group_name
group.try(:name)
end
``` | I would create a method with a good name, so it would be easy to reuse the code.
```
def is_assigned?
self.group
end
<% if @user.is_assigned? %>
...
<% end %>
``` |
150,895 | Is there a state in Rubik's cube which can be considered to have the highest degree of randomness (maximum entropy?) asssuming that the solved Rubik's cube has the lowest? | 2012/05/28 | [
"https://math.stackexchange.com/questions/150895",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/5622/"
] | Assuming 'most random' means 'takes the most number of moves to solve the cube', then [the answer is 20](http://cube20.org/). This site also has an example of a state that requires at least 20 moves to solve. This result is from 2010, and is a computer-assisted proof. | If you're considering maximal entropy as I think your question alludes to, you need to maximize the degeneracy of the states since $S \equiv k \ln \Omega$, where $\Omega$ is the number microstates.
It doesn't make sense to consider a single state of the cube to be most random...we could just as well consider our chosen state to be "solved" and that would make it the least "random" in that sense. It makes more sense to consider an ensemble of cubes to be the most random state. In this case, the ensemble of cubes with the highest degeneracy is 18 moves away from being solved, with degeneracy of roughly 29 quintillion. [[1]](http://www.cube20.org/) |
31,464 | I'm trying to do some distribution calculations on a couple of tokens and could use an export of the token holders list that I can find in Etherscan when I search for a specific token. Since Etherscan is showing the list I was hoping the API would have a function for this, but it looks to me like it doesn't. Please bear with me as I am totally new to this and am not able to really build anything. I know how to fiddle with some APIs and that's about it. | 2017/11/23 | [
"https://ethereum.stackexchange.com/questions/31464",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/23548/"
] | I have created a standalone tool which does the same.
* Take a token contract address
* Iterate over all `Transfer` events for token using `eth_getLogs` JSON-RPC API
* Build a local database of these events
* Allow you to use SQL to query any account balance on any point of time (block num)
[You can find the command line application execution example how to build the token holder database here](https://docs.tokenmarket.net/erc-20-holders.html)
[The core Python logic is here](https://github.com/TokenMarketNet/sto/blob/master/sto/ethereum/scanner.py).
You can also trivially export this list from SQLite database to CSV file.
There are some quirks here and there: for example detecting mint / creation event for some tokens is not straightforward. Thus, you will may negative balance on the account receiving initial total supply if you rely on `Transfer` event only. | Try this: [<https://etherscan.io/exportData?type=tokens&contract=0xa02e3bb9cebc03952601b3724b4940e0845bebcf>
Replace *Contract* with your token contract address |
58,087,772 | I'm trying to modify [this](https://github.com/aws-samples/aws-cdk-examples/blob/master/python/lambda-s3-trigger/s3trigger/s3trigger_stack.py) AWS-provided CDK example to instead use an existing bucket. Additional [documentation](https://docs.aws.amazon.com/cdk/latest/guide/resources.html#resources_importing) indicates that importing existing resources is supported. So far I am unable to add an event notification to the existing bucket using CDK.
Here is my modified version of the example:
```
class S3TriggerStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# create lambda function
function = _lambda.Function(self, "lambda_function",
runtime=_lambda.Runtime.PYTHON_3_7,
handler="lambda-handler.main",
code=_lambda.Code.asset("./lambda"))
# **MODIFIED TO GET EXISTING BUCKET**
#s3 = _s3.Bucket(self, "s3bucket")
s3 = _s3.Bucket.from_bucket_arn(self, 's3_bucket',
bucket_arn='arn:<my_region>:::<my_bucket>')
# create s3 notification for lambda function
notification = aws_s3_notifications.LambdaDestination(function)
# assign notification for the s3 event type (ex: OBJECT_CREATED)
s3.add_event_notification(_s3.EventType.OBJECT_CREATED, notification)
```
This results in the following error when trying to `add_event_notification`:
```
AttributeError: '_IBucketProxy' object has no attribute 'add_event_notification'
```
The `from_bucket_arn` function returns an `IBucket`, and the `add_event_notification` function is a method of the `Bucket` class, but I can't seem to find any other way to do this. Maybe it's not supported. Any help would be appreciated. | 2019/09/24 | [
"https://Stackoverflow.com/questions/58087772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4024884/"
] | I managed to get this working with a [custom resource](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html). It's TypeScript, but it should be easily translated to Python:
```js
const uploadBucket = s3.Bucket.fromBucketName(this, 'BucketByName', 'existing-bucket');
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler'))
});
const rsrc = new AwsCustomResource(this, 'S3NotificationResource', {
onCreate: {
service: 'S3',
action: 'putBucketNotificationConfiguration',
parameters: {
// This bucket must be in the same region you are deploying to
Bucket: uploadBucket.bucketName,
NotificationConfiguration: {
LambdaFunctionConfigurations: [
{
Events: ['s3:ObjectCreated:*'],
LambdaFunctionArn: fn.functionArn,
Filter: {
Key: {
FilterRules: [{ Name: 'suffix', Value: 'csv' }]
}
}
}
]
}
},
// Always update physical ID so function gets executed
physicalResourceId: 'S3NotifCustomResource' + Date.now().toString()
}
});
fn.addPermission('AllowS3Invocation', {
action: 'lambda:InvokeFunction',
principal: new iam.ServicePrincipal('s3.amazonaws.com'),
sourceArn: uploadBucket.bucketArn
});
rsrc.node.addDependency(fn.permissionsNode.findChild('AllowS3Invocation'));
```
This is basically a CDK version of the CloudFormation template laid out in [this example](https://aws.amazon.com/premiumsupport/knowledge-center/cloudformation-s3-notification-lambda/). See the docs on the [AWS SDK](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketNotificationConfiguration-property) for the possible `NotificationConfiguration` parameters. | AWS [now supports](https://aws.amazon.com/blogs/aws/new-use-amazon-s3-event-notifications-with-amazon-eventbridge/) s3 eventbridge events, which allows for adding a source s3 bucket by name. So this worked for me. Note that you need to enable eventbridge events manually for the triggering s3 bucket.
```
new Rule(this, 's3rule', {
eventPattern: {
source: ['aws.s3'],
detail: {
'bucket': {'name': ['existing-bucket']},
'object': {'key' : [{'prefix' : 'prefix'}]}
},
detailType: ['Object Created']
},
targets: [new targets.LambdaFunction(MyFunction)]
}
);
``` |
390,015 | When I boot up after installing that package, my monitors don't work.
I know that I can still get to a tty and that the system is working because I can run 'eject cdrom' and I can play the bell noise, but I can't see anything.
I know that it's specifically this package because I reinstalled the OS, rebooted, and everything was fine. Then I installed linux-firmware-nonfree and rebooted, and now the monitors don't work.
Debian 9.1.0
Nvidia GTX 970 | 2017/09/02 | [
"https://unix.stackexchange.com/questions/390015",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/223417/"
] | Well, nvidia drivers aren't the top top ones I've faced.
The probable reason may be some incompatibility between your xorg and your (non-free, binary) nvidia drivers.
The first what I would do in your place: removing the linux-firmware-nonfree and reboot.
Second, you may think on a kernel upgrade (if you aren't on the latest version of your distro).
My third try would be to load a more recent nvidia driver package from their upstream package distribution: <https://launchpad.net/~graphics-drivers/+archive/ubuntu/ppa> . These are for Ubuntu, but you will have a good chance to make them working also on Debian.
If your card is older, you may try an older nvidia driver release - nvidia likes to forget about their older cards.
[Here](https://wiki.debian.org/NvidiaGraphicsDrivers#Debian_9_.22Stretch.22) you can find the Debian sources for proprietary nvidia packages. | I reinstalled the OS and instead of installing linux-firmware-nonfree I installed nvidia-driver. This fixed the issue. |
224,159 | *Context*:
I have a very similar problem to the one exposed [here](https://electronics.stackexchange.com/questions/30719/analog-voltage-level-conversion-level-shift), and in the best rated answer (by Olin Lathrop), he says we need a *rail to rail* output opamp.
*My question*:
1. What is a **rail to rail** opamp? (In what characteristic does it differ from a regular opamp?)
2. What is a **rail to rail output** opamp? (In what characteristic does it differ from a rail to rail opamp?) | 2016/03/23 | [
"https://electronics.stackexchange.com/questions/224159",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/100869/"
] | "*Rail-to-rail*" is a marketing term used to describe an op amp whose dynamic range is able to reach the extremes of the supply voltage. This can refer to either the output or both the input and output.
It is not possible for the output to exceed the positive or negative supply voltage (which is why these are commonly referred to in US-English as "supply rails"). This is one of the key differences between the ideal op amp model and the real article.
As a counterexample, the ancient LM741 op amp is not "rail to rail", and here's why: in the datasheet **Electrical Characteristics** table, the **Output Voltage Swing** is rated +/-16V under the test condition of supply voltage=+/-20V. So the output can only get within about 4V of the supply rails. (There is some dependency on the output load resistance.) This is the key specification you can check on the Electrical Characteristics table pertinent to rail-to-rail output.
This limited dynamic range is very problematic at lower supply voltages. Attempting to operate the LM741 from +/-5V supplies, leaves only about +/-1V of dynamic range for the output. And operating LM741 from a single +5V supply leaves no dynamic range at all: the output is generally stuck in the middle and LM741 is not usable at such a low supply voltage.
It's also possible for some op-amps to accept inputs that are at or even beyond the rails -- Maxim Integrated makes a line of op amps marketed as "*beyond the rails*" (for input). | Rail to rail means that the op-amp inputs and outputs can operate near the supply voltages. Many op-amps that operate on relatively high voltage rails (I.e. +/-15v) can only drive the output to within 3 or 4 volts of the rail - for example, with a bipolar 15 volt supply, the amp may only be able to drive up to +/-12v. Same goes for inputs. The op-amp input circuitry in a rail to rail op-amp has to be designed to operate correctly near the rails. Rail to rail op-amps are especially useful when you have to use low power supply voltages. In fact, some op-amps will pretty much stop working altogether with low enough supply voltages as it won't be able to drive its output at all.
So, to sum up:
A rail to rail output op-amp is capable of driving its output very close to the power supply rails, while a rail to rail op-amp additionally supports input voltages near the power rails. |
800,294 | Windows 7 Enterprise x64
So I made a mistake and ran a dubious executable program downloaded from the internet. I was making a dvd and I didn't know how to download videos from funnyordie.com, so I went out on a limb and tried Wondershare Allmytube. It did what I wanted but it seemed really sketchy and it made my laptop start working so hard that my fan kicked on without any user input, so I turned off the wifi and uninstalled it right away and now I'm paranoid that I'm a part of some botnet or someone's got my saved chrome passwords.
Even after I uninstalled it, there were still files in C:/Program Files (x86)/Common Files/Wondershare, C:/Program Files/Common Files/Wondershare, C:/ProgramData/Wondershare, and there was a .exe on my desktop. I found someone with the same problem on this forum: <http://www.smartestcomputing.us.com/topic/71056-wondershare-helper-compact/>
The only problem is their solution was specific to that user's machine, and I can't download the *fixlist.txt* supplied by the admin in this thread to see what he did. However, I did run the Farbar Recovery Scan Tool as this person did, and I found some references to Wondershare in the *FRST.txt* file.
Under the heading *Registry (Whitelisted)*, I found these lines:
**HKLM-x32...\Run: [Wondershare Helper Compact.exe] => C:\Program Files (x86)\Common Files\Wondershare\Wondershare Helper Compact\WSHelper.exe**
**HKLM-x32...\Run: [DelaypluginInstall] => C:\ProgramData\Wondershare\AllMyTube\DelayPluginI.exe**
Under the heading *Internet (Whitelisted)*, I found this line:
**BHO-x32: Wondershare AllMyTube 4.2.0 -> {067DF9EC-26B7-40DC-8DB8-CD8BE85AE367} -> C:\ProgramData\Wondershare\AllMyTube\WSBrowserAppMgr.dll No File**
Under the heading *Firefox*, I found this line:
**FF HKLM-x32...\Firefox\Extensions: [AllMyTube@Wondershare.com] - C:\ProgramData\Wondershare\AllMyTube\AllMyTube@Wondershare.com**
How do I take all references to Wondershare off of whitelists? It seems like that's a security threat and I'm trying to patch it. (I have also run malwarebytes, and it detected and removed several threats.) Am I looking at this problem the right way? | 2014/08/20 | [
"https://superuser.com/questions/800294",
"https://superuser.com",
"https://superuser.com/users/359575/"
] | I found a useful tip on another website about this Wondershare issue.
1. Go into registry editor.
2. Collapse all the files.
3. Go under "edit" and hit "find" - type in `Wondershare` and it will call up instances of the file (one by one).
4. You have to delete them manually.
5. Hit `F3` to find the next instance of the file until you go through the entire registry.
I bet I had 30 different registry keys with the Wondershare on it. Computer working great now. | I found Control.Alt.Delete then Processes. Delete any under wondershare then go back to the regular uninstaller and remove. Worked for me |
6,427,530 | I'm not very good at regular expressions at all.
I've been using a lot of framework code to date, but I'm unable to find one that is able to match a URL like `http://www.example.com/etcetc`, but it is also is able to catch something like `www.example.com/etcetc` and `example.com/etcetc`. | 2011/06/21 | [
"https://Stackoverflow.com/questions/6427530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/793197/"
] | I have been using the following, which works for all my test cases, as well as fixes any issues where it would trigger at the end of a sentence preceded by a full-stop (`end.`), or where there were single character initials, such as 'C.C. Plumbing'.
The following regex contains multiple `{2,}`s, which means two or more matches of the previous pattern.
```none
((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]{2,}\.([a-zA-Z0-9\&\.\/\?\:@\-_=#]){2,}
```
**Matches** URLs such as, but not limited to:
* <https://example.com>
* <http://example.com>
* example.com
* example.com/test
* example.com?value=test
**Does not match** non-URLs such as, but not limited to:
* C.C Plumber
* A full-stop at the end of a sentence.
* Single characters such as `a.b` or `x.y`
**Please note:** Due to the above, this **will not** match any single character URLs, such as: `a.co`, but it will match if it is preceded by a URL scheme, such as: `http://a.co`. | I was getting so many issues getting [the answer from anubhava](http://%20https://stackoverflow.com/a/6427654/7778012) to work due to recent PHP allowing `$` in strings and the preg match wasn't working.
Here is what I used:
```
// Regular expression
$re = '/((https?|ftp):\/\/)?([a-z0-9+!*(),;?&=.-]+(:[a-z0-9+!*(),;?&=.-]+)?@)?([a-z0-9\-\.]*)\.(([a-z]{2,4})|([0-9]{1,3}\.([0-9]{1,3})\.([0-9]{1,3})))(:[0-9]{2,5})?(\/([a-z0-9+%-]\.?)+)*\/?(\?[a-z+&$_.-][a-z0-9;:@&%=+\/.-]*)?(#[a-z_.-][a-z0-9+$%_.-]*)?/i';
// Match all
preg_match_all($re, $blob, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
// The first element of the array is the full match
``` |
14,558,417 | I am trying to interface my Nokia N95 with Proteus. It works almost fine, except of one thing. When I want to get the response from the modem, I use `unsigned char input[20]` and `scanf("%s",input)`. When the modem receives a call, it send `RING` to the port, but what I get with `scanf` is `RIG` or `RNG`. What might be the problem?
```
#include <regx51.h>
#include <stdio.h>
#include <string.h>
sbit TE = P2^4;//for transmitting
unsigned char ch;
unsigned char ch2;
long i;
short bakar=0;
unsigned char Command_AT[]="AT\r";
unsigned char xdata Command_CPIN[]="AT+CPIN =\"0000\"\r";
unsigned char Command_CMGF[]="AT+CMGF=1\r";
unsigned char Command_CMGS[]="AT+CMGS =\"5555\"\r";
unsigned char msg_report[]="Ok";
unsigned char CtrlZ=0x1A;
unsigned char xdata Status_Ok[]="AT\rOK";
unsigned char Command_CHUP[]="AT+CHUP\r";
unsigned char input[10];
void iniSerial()
{
TMOD=0x20;
TH1=0XFD;
SCON=0x50;
TR1=1;
TI=1;
RI=0;
}
void delay()
{
for(i=1;i<=30000;i++); //Dont know how much exactly
}
void delay2()
{
for(i=1;i<=50000;i++);
}
void sendDeliveryReport()
{
puts(Command_AT);
delay();
puts(Command_CMGF);
delay();
puts(Command_CMGS);
delay();
puts(msg_report);
while(TI == 0);
SBUF = 0x1A;
}
void checkRing()
{
while(bakar!=1)
{
scanf("%s",&input);//problem is here
if(strcmp(input,"RING") == 0)
{
bakar=1;
delay();
puts(Command_CHUP);
}
delay2();
}
}
void main()
{
delay2(); //Wait for GSM modem to start.
TE=1; //Don't trasmit yet
iniSerial();
checkRing();
TE=0;
iniSerial();
sendDeliveryReport();
while(1); //Pause forever
}
``` | 2013/01/28 | [
"https://Stackoverflow.com/questions/14558417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1993293/"
] | Does that code really compile? The if-statement in void checkRing() has mismatched paranthesis.
ps. Sorry for the "answer" instead of a comment, but my reputation does not allow comments. | I must say that this code seems to invite a hacker attack.
The line `scanf("%s",&input);` reads bytes until a newline, into the buffer on the stack. If more than 10 bytes are read, the buffer overflows and the stack is corrupted.
From there, the way to overwriting the return address and executing arbitrary code is short.
You must either use `fgets`, which allows you to limit the number of bytes read, followed by `fscanf` to stop at a delimiter, or use, as Daniel Fischer suggested, the format string `"%9s"` which won't store more than 10 bytes in the buffer (9 + terminating null). |
6,628,358 | I know what this means, and I have searched Google, and MSDN. But, how else am I going to get around this?
I have a function in my razor code inside the App\_Code folder (using WebMatrix), and I get info from the database, do some calculations, then update the database with the new total.
But, how am I to pass variables to my method in the App\_Code folder if it won't let me?
Here's what I've got:
EditQuantity.cshtml (root folder):
```
try
{
Base baseClass;
baseClass.CalculateTotalPriceInCart(Request.QueryString["PartNumber"], Request.QueryString["Description"], Session["OSFOID"], true);
Response.Redirect("~/Cart.cshtml");
}
catch(Exception exmes)
{
message = exmes;
}
```
And, Base.cs (inside App\_Code folder):
```
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using WebMatrix.Data;
/// <summary>
/// Summary description for ClassName
/// </summary>
public class Base
{
public void CalculateTotalPriceInCart(var PartNumber, var Description, var OrderId, bool IsBoxed)
{
var database = Database.Open("OSF");
var query = "";
var result = "";
decimal price = 0.00M;
if(IsBoxed)
{
// Select item.
query = "SELECT Boxes, BoxPrice FROM Cart WHERE OrderId = '" + OrderId + "' AND PartNumber = '" + PartNumber + "' AND Description = '" + Description + "' AND IsBoxed = 1";
result = database.Query(query);
// Recalculate Price.
foreach(var item in result)
{
price = result.Boxes * result.BoxPrice;
}
// Update item.
query = "UPDATE Cart SET BoxPrice = '" + price + "' WHERE OrderId = '" + OrderId + "' AND PartNumber = '" + PartNumber + "' AND Description = '" + Description + "' AND IsBoxed = 1";
database.Execute(query);
}
}
}
```
I've tried a few things to see if it'd work, but nope. I'm obviously doing it wrong, but this is how I do it in Desktop apps, I don't get why it'd be different here for WebPages, and how shold I go about doing this?
Thank you! | 2011/07/08 | [
"https://Stackoverflow.com/questions/6628358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789564/"
] | you can't use `var` as the type of a method parameter. It has to be a real type (string, int, Object, etc). `var` can only be used inside of a method (like in your foreach) | as usual, this is dumb.
Why not use declare it as the type of the return type of the constructor?.
as a "rule" var should only be used with constructors.
If you have some deep problem with that.. introduce dim into csharp;
just change the token for a class reference when compiling. |
3,434 | `UNDER CONSTRUCTION`
====================
I noticed (or re-noticed, studies say people's attention span on the internet decreases by . . . Oh I love that GIF, it never gets old) that we have an [Editor's Lounge](http://chat.stackexchange.com/rooms/49035/ell-editors-lounge). Nice.
There have been previous attempts at retagging stuff, but have failed. I thought the reason was a lack of interest, but it really is just that we don't know how to edit. When I'm editing,
* I don't know what tags to put instead of the damned [grammar](https://ell.stackexchange.com/questions/tagged/grammar "show questions tagged 'grammar'"). [usage](https://ell.stackexchange.com/questions/tagged/usage "show questions tagged 'usage'") is almost just as bad. [meaning](https://ell.stackexchange.com/questions/tagged/meaning "show questions tagged 'meaning'"), eh, probably.
* I don't exactly know how to rewrite a poorly written title. I feel weird when a lot of my edited titles now look like "is X correct?"
* I don't know how to use formatting, exactly. Should I use blockquotes for example sentences, backticks, bold, italics, or what? What about dictionary definitions? Consistency isn't a must, but it stops havoc from being wrecked and makes you feel nice.
* Heck, I don't even know if I should edit the learner's grammar. Meta is divisive about this.
[*Editorial note: Edits welcome to add more bullet points.*]
Each of the answers below cover one of the bullet points.
* [What tags to use](https://ell.meta.stackexchange.com/a/3435/14111)
* [How to format properly](https://ell.meta.stackexchange.com/a/3436/14111)
* [link to answer 3]
* [link to answer 4] | 2017/02/04 | [
"https://ell.meta.stackexchange.com/questions/3434",
"https://ell.meta.stackexchange.com",
"https://ell.meta.stackexchange.com/users/14111/"
] | [](http://languagelearning.stackexchange.com) | [](https://interpersonal.stackexchange.com/) |
14,455,039 | I'm not a DBA and I don't know what is the best solution. I have two tables,
```
Custumers Table
CustomerId (primary key, identity)
...
```
and
```
Suppliers Table
SupplierId (primary key, identity)
...
```
and I want to store multiple telephone number and multiple emails. I thought to create two other tables, Emails and Telephones and use those in join with my Custumers and Suppliers, something like
```
Telephones Table
Id
UserId (reference to SuppliersId or CustomerId)
Value
...
```
But if I use as key for custumers and suppliers an Identity I'll have for sure problems. I'm thinking to do something like
```
Telephones Table
Id
SuppliersId
CustumersId
Value
...
```
But I don't know if is a good design. Any advice?
Thank you | 2013/01/22 | [
"https://Stackoverflow.com/questions/14455039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016255/"
] | A good design would be
* Customers: Table of customers - CustomerId, Other columns
* Suppliers: Table of suppliers - SupplierId, Other columns
* Telephones: Table of telephones - TelephoneId, other columns
* CustomerTelephones: CustomerId, TelephoneId
* SupplierTelephones: SupplierId, TelephoneId | you can do like
```
Customers: Table of customers - CustomerId, Other columns
Suppliers: Table of suppliers - SupplierId, Other columns
Telephones: Table of telephones - TelephoneId,TypeId,TypeName, other columns
```
where TypeName will be `Customers` or `Suppliers`, ant `TypeId` will be id of the resp. |
4,750 | I think I understand the (quite easy) basic grammar now...
I just need some way to learn the words, but I don't just want to learn them off a list.
Some kind of text with each line in English and Esperanto would be perfect, so I learn it while reading...
Where do I find some material like this? | 2018/03/25 | [
"https://esperanto.stackexchange.com/questions/4750",
"https://esperanto.stackexchange.com",
"https://esperanto.stackexchange.com/users/1414/"
] | Duolingo – Did you know that Duolingo has an Esperanto course? If you’re very busy, you can use this program to learn Esperanto from your smartphone in your downtime.
Lernu – This excellent website has three different Esperanto courses, depending on your learning style. I recommend you start with Ana Pana. The site also has live chat, an active forum, and the best Esperanto dictionary available.
Kurso de Esperanto – free downloadable program that teaches you the grammar of Esperanto from start to finish. | Each of [the exercises of the *Fundamento*](http://www.akademio-de-esperanto.org/fundamento/ekzercaro.html) includes a gloss. Although later exercises do expect you to already know the words from earlier exercises.
I personally found these exercises very helpful. Especially because they also demonstrate some nuances that aren’t covered in the grammar rules themselves. |
1,862,526 | I have an ASP.NET application where only users authenticated by Windows (i.e. logged on user) have access to most pages. Now, my client wants to be able to 'log on' through this app, with a custom login dialogue/page.
Is Authentication the way to achieve this, and how do I go about it? | 2009/12/07 | [
"https://Stackoverflow.com/questions/1862526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | Just tweak the JButton.
```
button= new JButton("MenuItem");
button.setOpaque(true);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusable(false);
button.addActionListener(new buttonHandler());
menuBar.add(button);
```
`setContentAreaFilled` makes it see-through,
`setBorderPainted` gets rid of the border,
`setFocusable` gets rid of the tiny border around the text. | I had something like this happen recently I had a JMenuBar that only had 2 JMenuItems in (so note that I haven't tried this in a mixed JMenu and JMenuItem environment.
At first I ended up changing the Layout to a FlowLayout with a left alignment, but that left too much space in-between the components. I messed around with trying to do various things, but was very unsatisfied. What I ended up doing was just using a JMenu, but overriding some of it's behaviors so that it pretended to be a JMenuItem. Like so:
```
JMenuBar mainMenuBar = new JMenuBar();
final JMenu quitMenuItem = new JMenu("Quit");
quitMenuItem.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent e) {
System.exit(0);
}
public void menuDeselected(MenuEvent e) {}
public void menuCanceled(MenuEvent e) {}
});
quitMenuItem.setPopupMenuVisible(false);
final JMenu aboutMenuItem = new JMenu("About");
aboutMenuItem.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent e) {
JOptionPane.showMessageDialog(MainFrame.this, "Assignment 3 With Swing UI. Author: T.Byrne", "About", JOptionPane.INFORMATION_MESSAGE);
aboutMenuItem.setSelected(false);//otherwise it will still be selected after the dialog box.
}
public void menuDeselected(MenuEvent e) {}
public void menuCanceled(MenuEvent e) {}
});
aboutMenuItem.setPopupMenuVisible(false);
mainMenuBar.add(quitMenuItem);
mainMenuBar.add(aboutMenuItem);
this.setJMenuBar(mainMenuBar);
``` |
16,690 | I am brewing my first kit beer. I want to set aside one gallon and make a high ABV batch. I am brewing a honey wheat and adding jalapeño. How would I make the higher ABV and what would the technical name be? Imperial witbier? | 2015/12/21 | [
"https://homebrew.stackexchange.com/questions/16690",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/13069/"
] | First: It is your first brew! Relax. Brew it and THEN start playing. There is a lot of things you need to get used to. But it is up to you. :)
You can follow thesquaregroot's answer, or you can alter the abv in a different way:
Brew the beer and let it ferment in two fermenters, where the one fermenter is the one gallon one that will be made special. When fermentation starts to slow down on the "special" fermenter add extra sugar. You can use DME, table sugar, honey, etc.
You can get calculators online that will tell you now much ABV you will get from sugar additions.
Remember that your yeast has limitations on how much ABV it can survive in, so make sure you do not exceed that amount.
As you are adding jalapenos it will be a Fruit/Spice/Herb beer with a base of (probably) Imperial Wheat. Witbier has lemon/orange zest and coriander. | Assuming you're doing a partial boil (e.g. boiling 3 gallons and adding water to reach a target 5 gallons), you could just take a gallon post-boil and a proportional amount of water to the larger batch (i.e. two thirds of the additional 2 gallons).
Of course if you're targeting a specific ABV it may be more complicated to calculate but you could use a similar method with a different boil size to achieve a desired original gravity.
As for the name I think it would depend somewhat on the ABV but imperial witbier seems reasonable. |
60,549,660 | I have a simple chat module that allows accounts to create multi-user rooms.
* Given the below schema - is it possible to create a query that will check if room with given users already exist?
* If this check could lead to performance issues - can you propose other design or approach?
[](https://i.stack.imgur.com/Z1jsR.png)
**Example data:**
```
- chat_id: 1, users: [1, 2, 3]
- chat_id: 2, users: [2, 3]
- chat_id: 3, users: [1]
- chat_id: 4, users: [5, 6]
```
**Desired queries:**
```
Check if chat room for users [2, 3] exists => true, id: 2
Check if chat room for users [1, 2, 3] exists => true, id: 1
Check if chat room for users [2, 6] exists => false
Check if chat room for users [1, 2, 6] exists => false
```
I'm using postgres 11.2
**EDIT**:
I should also be able to get the chat id if given combination exists. | 2020/03/05 | [
"https://Stackoverflow.com/questions/60549660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4904588/"
] | Based on the other answers, I ended up writing my own query:
```
SELECT chat_id FROM chat_account
WHERE chat_id IN (
SELECT c2.chat_id
FROM chat_account c2
WHERE c2.account_id IN (2, 3)
)
GROUP BY chat_account.chat_id
HAVING array_agg(chat_account.account_id) = ARRAY[2, 3]
``` | you need something like this
```
with selected_users as (select * from accounts where id in (2,3)),
users_chat_rooms as (
select chat_id,
array_agg(account_id order by account_id asc) users_in_room
from chat_account
group by chat_id
)
select * from users_chat_rooms
where chat_id in (select chat_id from chat_account where account_id in (select id from selected_users))
and users_in_room = (select array_agg(id order by id asc) from selected_users)
```
see fiddle <https://dbfiddle.uk/?rdbms=postgres_11&fiddle=f360a05c57a33f5c130fcfa0d55429ff>
probably you will be showing this to a specific user, so you can filter for the "logged in" user's chats.
```
select * from users_chat_rooms
where chat_id in (select chat_id from chat_account where account_id = <logged_in_user>)
and users_in_room = (select array_agg(id order by id asc) from selected_users)
``` |
1,794 | I just remarked that some of the questions on the main page are formatted differently than others. All questions which have been tagged with `biblatex` have a yellow background. Is this a new feature or just a browser issue?
 | 2011/09/29 | [
"https://tex.meta.stackexchange.com/questions/1794",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/3240/"
] | It may be that you favorited [biblatex](https://tex.stackexchange.com/questions/tagged/biblatex "show questions tagged 'biblatex'"), as Martin explained, but it also can be that you just happened to *visit* a lot of questions with the [biblatex](https://tex.stackexchange.com/questions/tagged/biblatex "show questions tagged 'biblatex'") tag: you can have *implicit* "frequented" tags. See this post on meta.SO for more details: [Why are “etymology” questions on german.sx highlighted for me?](https://meta.stackexchange.com/q/96389) | To add to the other answers. Favoring tags is one way to watch and highlight certain preferred content on Stack Exchange. The two other ways to watch content that I can think of is favoring questions (i.e. your favorite questions) and subscribing to tags by either e-mail (the subscribe link in the hover of tags) or rss (the rss link in the hover of tags). |
42,581,035 | Defined model like below (No property, but just one method):
```
namespace PartyInvitesInProASPNETMVC5.Models
{
public class MyAsyncMethods
{
public static Task<long?> GetPageLength()
{
HttpClient client = new HttpClient();
var httpTask = client.GetAsync("http://www.google.com");
return httpTask.ContinueWith((Task<HttpResponseMessage> antecedent) => {
return antecedent.Result.Content.Headers.ContentLength;
});
}
}
}
```
Written Controller Action Method like below:
```
public ActionResult GooglePageLength()
{
var content = MyAsyncMethods.GetPageLength();
return View(content);
}
```
I am not understanding how to generate view for the above action method. Modified code like below from the default generated view. But, still getting error.
```
@model PartyInvitesInProASPNETMVC5.Models.MyAsyncMethods.GetPageLength()
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Google Page Length</title>
</head>
<body>
<div>@Convert.ToInt32(@Model)@*How to write code here?*@
</div>
</body>
</html>
```
Below is the error I am getting:
The model item passed into the dictionary is of type 'System.Threading.Tasks.ContinuationResultTaskFromResultTask`2[System.Net.Http.HttpResponseMessage,System.Nullable`1[System.Int64]]', but this dictionary requires a model item of type 'System.Nullable`1[System.Int32]'. | 2017/03/03 | [
"https://Stackoverflow.com/questions/42581035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338944/"
] | You should wait for the result in the controller with await:
```
public async Task<ActionResult> GooglePageLength()
{
long? content = await MyAsyncMethods.GetPageLength();
return View(content);
}
```
Then make your view model type `long?`:
```
@model long?
```
You are currently passing the task that completes asynchronously to the view. And you are also setting the model type as the function that returns the task (did not know you could even do that).
Normally you should wait for the result of the task asynchronously with await, and then return the result as the model for the view. | Modified the action method like below.
```
public ActionResult WellsFargoPageLength()
{
ViewBag.PageLength = MyAsyncMethods.GetPageLength().Result;
return View();
}
```
Deleted the View and created once again keeping the above modified action method in mind. |
217,810 | I need to make a field required on the edit form. It does not appear on the New Form. I can't set it as required at the site column level because the system will not save the New form without that field completed.
I took this `PreSaveAction` script from another form I have used it with and tried to modify to fix my issue. I installed it as a `script editor web part` and when I went to the edit page, it triggers the alert, but won't save when I actually fill in the field.
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
function PreSaveAction(){
//these look for the display name values in the text field
var textDept1 = $("select[title$='Dept#1']").val();
if(textDept1){
return true;
}
else{
alert("Please insert a Department Number and EOC Code to continue.");
return false;
}
}
</script>
``` | 2017/06/09 | [
"https://sharepoint.stackexchange.com/questions/217810",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/59691/"
] | You can check whether the form is a edit/new/disp form. Accordingly you can set the required field.
For edit form the default url of the list for is editform.aspx, so check if the URL is EditForm.aspx then get the field and make it mandatory. Check if this works for you.
There is other option if you are editing the form in InfoPath, its easy there to set the field as mandatory or not with other validations also. | you have to modify your code like below.
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
function PreSaveAction(){
//these look for the display name values in the text field
var textDept1 = $("select[title$='Dept#1']").val();
if(textDept1 != "" && textDept1 !=undefined ){
return true;
}
else{
alert("Please insert a Department Number and EOC Code to continue.");
return false;
}
}
</script>
``` |
9,096,139 | Can FindFirstFile() be used to move or copy a file from one directory to another? Since it returns a handle, can this handle be used to do it? | 2012/02/01 | [
"https://Stackoverflow.com/questions/9096139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/627760/"
] | The handle it returns is only useful to allow you to call FindNextFile(). Quite handy, lets you pass a wildcard ("*.*" for example) to iterate all the files that match. Don't forget to call FindClose().
The real nugget is the WIN32\_FIND\_DATA.cFileName value it returns. That's the one you need to call MoveFile() to actually move the file. | The [MoveFile()](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365239%28v=vs.85%29.aspx) function just takes in 2 parameters (from file name, to file name) so you wouldn't need to use FindFirstFile to move a file. The [CopyFile()](http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851%28v=vs.85%29.aspx) function is similar. |
11,128,843 | I have a function that returns a value that can be true if the condition is met and false if not, but the function can also return a string message in case of an error.
I need to differentiate between the true/false boolean values under normal conditions without mistaking the string value for either one. My strategy is to use a `parseBoolean()` function that will return a true Boolean-typed true/false value when passed a boolean input, but a "falsy" value that isn't a Boolean-typed `false` when passed a string.
### Example
```
function validate(kkk)
{
//... some check that validates
return true;
//... some check that doesn't validate
return false;
//... failure - return explanation
return 'Error Message jjjjjjjj';
}
function usingit(data)
{
if(parseBoolean(validate(data)) != false)
{
/// the value is Boolean true
}
else
{
if(parseBoolean(validate(data)) === false)
{
/// the value is Boolean false
}
else
{
/// the value is false but not of a Boolean type
/// so we will display it as the error message text.
}
}
}
```
...but I haven't figured out how to create a `parseBoolean()` function that behaves this way. Any ideas? | 2012/06/20 | [
"https://Stackoverflow.com/questions/11128843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848117/"
] | According to this:
>
> @Esailija Why no sense? If it is true return a true, if it is false
> return false, if it is 'somestring' also return false. Get it? –
> Registered User 31 secs ago
>
>
>
You want
```
function parseBoolean(value) {
return typeof value == "boolean" ? value : false;
}
```
But this obviously won't pass the test of doom.
---
This code passes all your tests:
```
function parseBoolean(bool) {
return typeof bool == "boolean" ? bool : 0;
}
if( parseBoolean('anystring') == false ) {
alert("");
}
if( parseBoolean('anystring') !== false ) {
alert("");
}
if( parseBoolean(true) ) {
alert('');
}
if( !parseBoolean(false) ) {
alert('');
}
``` | Is it what you're looking for?
```
var parseBooleanGenerator = function(aPerfectString) {
return function(someStringFromWild) {
return aPerfectString === someStringFromWild
};
};
var goodString = 'FFF';
var badString = 'FfF';
console.log(parseBooleanGenerator('FFF')(goodString)); // true
console.log(parseBooleanGenerator('FFF')(badString)); // false
```
... or ...
```
var checkForFFF = parseBooleanGenerator('FFF');
console.log(checkForFFF(goodString)); // true
console.log(checkForFFF(badString)); // false
``` |
119,597 | I have a multiboot system set up. The system has three drives. Multiboot is configured with Windows XP, Windows 7, and Ubuntu - all on the first drive. I had a lot of unpartitioned space left on the drive and was reserving it for adding other OSes and for storing files there in the future.
One day I went ahead and downloaded Partition Wizard and created a logical NTFS partition from within Windows 7, still some unpartitioned space left over. Everything worked fine, until I rebooted the computer a few days later.
Now I'm getting:
```
error: unknown filesystem.
grub rescue>
```
First of all I was surprised not to find any kind of help command, by trying:
`help`, `?`, `man`, `--help`, `-h`, `bash`, `cmd`, etc.
Now I'm stuck with non-bootable system. I have started researching the issue and finding that people usually recommend to boot to a Live CD and fix the issue from there. Is there a way to fix this issue from within grub rescue without the need for Live CD?
**UPDATE**
By following the steps from [Persist commands typed to GRUB rescue](https://askubuntu.com/questions/90471/persist-commands-typed-to-grub-rescue), I was able to boot to initramfs prompt. But not anywhere further than that.
So far from reading the manual on [grub rescue](https://help.ubuntu.com/community/Grub2#Rescue_Mode_.28.27.27grub_rescue.3E.27.27.29_Booting), I was able to see my drives and partitions using `ls` command. For the first hard drive I see the following:
(hd0) (hd0,msdos6) (hd0,msdos5) (hd0,msdos2) (hd0,msdos1)
I now know that (hd0,msdos6) contains Linux on it, since `ls (hd0,msdos6)/` lists directories. Others will give "error: unknown filesystem."
**UPDATE 2**
After the following commands I am now getting to the boot menu and can boot into Windows 7 and Ubuntu, but upon reboot I have to repeat these steps.
```
ls
ls (hd0,msdos6)/
set root=(hd0,msdos6)
ls /
set prefix=(hd0,msdos6)/boot/grub
insmod /boot/grub/linux.mod
normal
```
**UPDATE 3**
Thanks Shashank Singh, with your instructions I have simplified my steps to the following. I have learned from you that I can replace msdos6 with just a 6 and that I can just do `insmod normal` instead of `insmod /boot/grub/linux.mod`. Now I just need to figure out how to save this settings from within grub itself, without booting into any OS.
```
set root=(hd0,6)
set prefix=(hd0,6)/boot/grub
insmod normal
normal
```
**UPDATE 4**
Well, it seems like it is a requirement to boot into Linux. After booting into Ubuntu I have performed the following steps described in the [manual](https://help.ubuntu.com/community/Grub2#Rescue_Mode_.28.27.27grub_rescue.3E.27.27.29_Booting):
```
sudo update-grub
sudo grub-install /dev/sda
```
This did not resolve the issue. I still get the grub rescue prompt. What do I need to do to permanently fix it?
I have also learned that drive numbers as in hd0 need to be translated to drive letters as in /dev/sda for some commands. hd1 would be sdb, hd2 would be sdc, and so on. Partitions listed in grub as (hd0,msdos6) would be translated to /dev/sda6.
**UPDATE 5**
I could not figure out why the following did not fix grub:
```
sudo update-grub
sudo grub-install /dev/sda
```
So I downloaded [boot-repair](https://help.ubuntu.com/community/Boot-Repair) based on an answer from <https://help.ubuntu.com/community/Boot-Repair> post. That seemed to do the trick after I picked the "Recommended Repair (repairs most frequent problems)" option. | 2012/04/07 | [
"https://askubuntu.com/questions/119597",
"https://askubuntu.com",
"https://askubuntu.com/users/53817/"
] | There is an alternative cause of this problem. In this particular case, GRUB was somehow corrupted and needed to be repaired or reinstalled. However, as shown in [Grub rescue fails with "Boot Repair" with error "unknown file system"](https://askubuntu.com/questions/286837/grub-rescue-fails-with-boot-repair-with-error-unknown-file-system), it's also possible that the root partition on which GRUB is installed could be corrupted. To fix this:
This is a possible solution, but it should not be used likely lest your root partition become further corrupted. Running the command `fsck -t ext4 /dev/sda1`, this program attempts to search and repair errors on a corrupted filesystem. Replace sda1 with your actual root partition. Replace ext4 with the actual filesystem; you have to know the file system or else the partition will be more corrupted. See [Repairing a corrupted filesystem](http://ubuntuforums.org/showthread.php?t=1103061) for more information.
---
Even though this question has an answer, there is an alternative way to fix the problem that worked for me. The steps are explained in the painful video [Grub Rescue - Guide for beginners](http://www.youtube.com/watch?v=ZcbTgMKpVHQ). In short, it will reinstall GRUB 2 altogether instead of repairing it.
Because this video is so painful to watch, I'll list the steps below (as I should regardless of how painful it is to watch the video)
1. Launch a live session of Ubuntu. The video uses a live CD whereas I used a live USB. I made sure that the live USB had the same version of Ubuntu that I had on my harddrive.
2. Find where your root partition was mounted. In the video, the user uses Nautilus to navigate through each drive that was mounted. It was mounted with a long string of numbers and characters. If this is the case, follow the following steps to remount the partition. Else, proceed to step 5.
3. Bring up the terminal with `Ctrl` + `Alt` + `T` and use the `mount` command to find the name of the partition.
4. Mount the partition. Create a new folder in your media folder. `sudo mkdir /media/ubuntu`. Then simply mount your partition to that folder. `sudo mount /dev/sdxx /media/ubuntu` where `xx` of `sdxx` is determined in step 3.
5. Bind the following directories from the root directory of your live CD/USB to that of your root directory on your version of Ubuntu. The directories are the `dev` `proc` and `sys`. Do so with the following commands:
```
sudo mount --bind /dev /media/ubuntu/dev
sudo mount --bind /sys /media/ubuntu/sys
sudo mount --bind /proc /media/ubuntu/proc
```
6. Change the root directory to the one on your Ubuntu partition. `sudo chroot /media/ubuntu/`
7. Having done the above, installing GRUB 2 again will install it to the root directory of your distribution of Ubuntu and not that of the live CD/USB's. So go ahead and run `sudo grub-install /dev/sdx`
And that's how to fix GRUB using a live CD/USB. This method was developed by YouTube user crazytechzone. | **Install Boot-Repair in Ubuntu**
1. Boot your computer on a Ubuntu live-CD or live-USB.
2. Choose "Try Ubuntu"
3. Connect internet
4. Open a new Terminal (`Ctrl`+`Alt`+`T`), then type:
```
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
```
5. Press `Enter`.
6. Then type:
```
sudo apt-get install -y boot-repair && boot-repair
```
7. Press `Enter`.
***Using Boot-Repair***

**Recommended repair**
1. Launch Boot-Repair from either :
a. The Dash (the Ubuntu logo at the top-left of the screen)
b. Or System->Administration->Boot-Repair menu (Ubuntu 10.04 only)
c. Or by typing 'boot-repair' in a terminal
2. Then click the "Recommended repair" button. When repair is finished, note the URL (paste.ubuntu.com/XXXXX) that appeared on a paper, then reboot and check if you recovered access to your OSs.
3. If the repair did not succeed, indicate the URL to people who help you by email or forum. |
446,276 | I just read about the [FastFormat C++ i/o formatting library](http://www.fastformat.org/), and it seems too good to be true: Faster even than printf, typesafe, and with what I consider a pleasing interface:
```
// prints: "This formats the remaining arguments based on their order - in this case we put 1 before zero, followed by 1 again"
fastformat::fmt(std::cout, "This formats the remaining arguments based on their order - in this case we put {1} before {0}, followed by {1} again", "zero", 1);
// prints: "This writes each argument in the order, so first zero followed by 1"
fastformat::write(std::cout, "This writes each argument in the order, so first ", "zero", " followed by ", 1);
```
This looks almost too good to be true. Is there a catch? Have you had good, bad or indifferent experiences with it? | 2009/01/15 | [
"https://Stackoverflow.com/questions/446276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] | >
> Is there a 'catch' with FastFormat?
>
>
>
Last time I checked, there was one annoying catch:
You can only use *either* the narrow string version *or* the wide string version of this library. (The functions for `wchar_t` and `char` are the same -- which type is used is a compile time switch.)
With iostreams, stdio or Boost.Format you can use both. | It looks pretty interesting indeed! Good tip regardless, and +1 for that!
I've been playing with it for a bit. The main drawback I see is that FastFormat supports less formatting options for the output. This is I think a direct consequence of the way the higher typesafety is achieved, and a good tradeoff depending on your circumstances. |
267,021 | When at the command line, I find that I have to type out this command very often:
```
find . -iname "*php" -exec grep -H query {} \;
```
I'd love to set up an alias, script, or shortcut to make it work easier. I would like to do something like:
```
mysearch query ("*php") (.)
```
It would be great if the command could accept three arguments, in reverse order:
```
query string, file name expression, directory
```
If the second two arguments were omitted they would default to not being included, and the current directory.
Finally, the icing on the cake would be that if additional variables were included (4th, 5th, 6th...) they would be injected as additional arguments for the find command (like I could say -type d) at the end.
**Attempted code**
I tried the example below, but I'm still having trouble setting default values. What am I doing wrong?
```
#!/bin/bash
c=${param1+\.}
b=${param2+\*}
a=${param3+test}
find $c -iname $b -exec grep -H $a {} \;
``` | 2011/04/05 | [
"https://superuser.com/questions/267021",
"https://superuser.com",
"https://superuser.com/users/64408/"
] | From [**Firefox Help - Recovering important data from an old profile**](http://support.mozilla.com/en-US/kb/Recovering%20important%20data%20from%20an%20old%20profile#w_passwords):
>
> Your passwords are stored in two different files, both of which are required:
>
>
> * key3.db - This file stores your key database for your passwords. To transfer saved passwords, you must copy this file along with the following file.
> * signons.sqlite - Saved passwords.
>
>
>
Thus, I would try searching your computer for these two files and checking them out for yourself... | [password forensics](https://web.archive.org/web/20150216232057/http://securityxploded.com:80/passwordsecrets.php#Firefox) has an overview and tools for recovery. The latter is a brute force attack on the master password (if you have it, which you should). The security is as good as your password, basically. [This link](https://web.archive.org/web/20150208043249/http://securityxploded.com:80/firepasswordviewer.php#internals_of_firepasswordviewer) has more details (same site). |
18,636,046 | I am making a HTTPPost call using Apache HTTP Client and then I am trying to create an object from the response using Jackson.
Here is my code:
```
private static final Logger log = Logger.getLogger(ReportingAPICall.class);
ObjectMapper mapper = new ObjectMapper();
public void makePublisherApiCall(String jsonRequest)
{
String url = ReaderUtility.readPropertyFile().getProperty("hosturl");
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost(url);
StringEntity entity = new StringEntity(jsonRequest);
postRequest.addHeader("content-type", "application/json");
log.info("pub id :"+ExcelReader.publisherId);
postRequest.addHeader("accountId", ExcelReader.publisherId);
postRequest.setEntity(entity);
HttpResponse postResponse = client.execute(postRequest);
log.info(EntityUtils.toString(postResponse.getEntity()));
// Response<PublisherReportResponse> response = mapper.readValue(postResponse.getEntity().getContent(), Response.class);
// log.info("Reponse "+response.toString());
} catch (UnsupportedEncodingException ex) {
log.error(ex.getMessage());
log.error(ex);
Assert.assertTrue(false, "Exception : UnsupportedEncodingException");
} catch (ClientProtocolException ex) {
log.error(ex.getMessage());
log.error(ex);
Assert.assertTrue(false, "Exception : ClientProtocolException");
} catch (IOException ex) {
log.error(ex.getMessage());
log.error(ex);
Assert.assertTrue(false, "Exception : IOException");
}
```
Method makePublisherApiCall() will be called in a loop which runs for say 100 times.
Basically problem occurs when I uncomment the line:
```
// Response<PublisherReportResponse> response = mapper.readValue(postResponse.getEntity().getContent(), Response.class);
// log.info("Reponse "+response.toString());
```
After uncommenting I am getting exception:
```
Attempted read from closed stream.
17:26:59,384 ERROR com.inmobi.reporting.automation.reportingmanager.ReportingAPICall - java.io.IOException: Attempted read from closed stream.
```
Otherwise it works fine.
Could someone please let me know what I am doing wrong. | 2013/09/05 | [
"https://Stackoverflow.com/questions/18636046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523537/"
] | I found an answer for similar issue with Spring RestTemplate here : <https://www.baeldung.com/spring-rest-template-interceptor>
if we want our interceptor to function as a request/response logger, then we need to read it twice – the first time by the interceptor and the second time by the client.
The default implementation allows us to read the response stream only once. To cater such specific scenarios, Spring provides a special class called BufferingClientHttpRequestFactory. As the name suggests, this class will buffer the request/response in JVM memory for multiple usage.
Here's how the RestTemplate object is initialized using BufferingClientHttpRequestFactory to enable the request/response stream caching:
```
RestTemplate restTemplate = new RestTemplate( new BufferingClientHttpRequestFactory( new SimpleClientHttpRequestFactory() ) );
``` | I had the same problem.
In my case, I need to get the response content via AOP/ |
47,194,063 | Has anyone figured out a way to keep files persisted across sessions in Google's [newly open sourced Colaboratory](https://colab.research.google.com)?
Using the sample notebooks, I'm successfully authenticating and transferring csv files from my Google Drive instance and have stashed them in /tmp, my ~, and ~/datalab. Pandas can read them just fine off of disk too. But once the session times out , it looks like the whole filesystem is wiped and a new VM is spun up, without downloaded files.
I guess this isn't surprising given Google's [Colaboratory Faq](https://research.google.com/colaboratory/faq.html):
>
> Q: Where is my code executed? What happens to my execution state if I close the browser window?
>
>
> A: Code is executed in a virtual machine dedicated to your account. Virtual machines are recycled when idle for a while, and have a maximum lifetime enforced by the system.
>
>
>
Given that, maybe this is a feature (ie "go use Google Cloud Storage, which works fine in Colaboratory")? When I first used the tool, I *was* hoping that any .csv files that were in the **My File/Colab Notebooks** Google Drive folder would be also loaded onto the VM instance that the notebook was running on :/ | 2017/11/09 | [
"https://Stackoverflow.com/questions/47194063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3424705/"
] | Not sure whether this is the best solution, but you can sync your data between Colab and Drive with automated authentication like this: <https://gist.github.com/rdinse/159f5d77f13d03e0183cb8f7154b170a> | As you pointed out, Google Colaboratory's file system is ephemeral. There are workarounds, though there's a network latency penalty and code overhead: e.g. you can use boilerplate code in your notebooks to mount external file systems like GDrive (see their [example notebook](https://colab.research.google.com/notebooks/io.ipynb)).
Alternatively, while this is not supported in Colaboratory, other Jupyter hosting services – like [Jupyo](https://jupyo.com) – provision dedicated VMs with persistent file systems so the data and the notebooks persist across sessions. |
961,833 | Is it possible to disable default gateway in WireGuard VPN client?
I used "allowed IP" to my own subnet, but still whenever I try to connect to VPN server, the client sets default gateway to the WireGuard server IP.
Any other way to disable default gateway in WireGuard? | 2019/04/06 | [
"https://serverfault.com/questions/961833",
"https://serverfault.com",
"https://serverfault.com/users/100156/"
] | Instead of specifying `AllowedIPs = 0.0.0.0/0` specify an ip address.
Ran into this question wondering the same thing. The use case detailed here pointed me in the right direction: <https://emanuelduss.ch/2018/09/wireguard-vpn-road-warrior-setup/> | I used `systemd`. Setting `netdev` here <https://www.freedesktop.org/software/systemd/man/systemd.netdev.html#%5BWireGuard%5D%20Section%20Options> will **not** create route table entry for you. You'll need to manually add it here <https://www.freedesktop.org/software/systemd/man/systemd.network.html#%5BNetwork%5D%20Section%20Options> . I'm allowing all IPs but only route specific traffic to wg interface.
If using `wg-quick`, probably you'll need to change `Table=off` , per <https://manpages.debian.org/unstable/wireguard-tools/wg-quick.8.en.html>
Edit:
As systemd v250 <https://github.com/systemd/systemd/releases> , systemd **will** automatically creates routing for you. To disable so, you need to add `RouteTable=off` under `[WireGuardPeer]` in your `netdev` file. |
444,628 | Would learning to program fractals help think clearly about certain set of programming problems? | 2009/01/14 | [
"https://Stackoverflow.com/questions/444628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1443363/"
] | Fractals got me thinking about complex numbers and [branch-points](http://en.wikipedia.org/wiki/Branch_point). Whether that was a good thing is, I suppose, a matter of opinion. :-) | Great idea! I think coding up fractals makes a great "etude" (study) sized program. It has some nice features this way: generally you won't require much 3rd party code, they can be implemented in a reasonably short amount of time (and complexity) and you get something nice too look at in the end which also verifies your work.
Also there are loads of basic issues in both mathematics and the implementation of numerical algorithms that you will bump into if you do this.
From something as simple as a basic Mandelbrot set generator you can branch out into all sorts of issues as commenters have mentioned. Even sticking with just that, though, you can learn about optimization techniques (why is my generator so slow) and numerical issues (why can't I zoom past here), but also if you want to a bit of color theory (what's L*a*b\* space anyway) and other bits and pieces.
Have fun! |
885,496 | In order to get good test coverage, I want to test the `WriteExternal` and `ReadExternal` methods of `IPortableObject` (as described at [Creating an IPortableObject Implementation (.NET)](http://coherence.oracle.com/display/COH34UG/Configuration+and+Usage+for+.NET+Clients#ConfigurationandUsagefor.NETClients-CreatinganIPortableObjectImplementation%28.NET%29) ).
Here is code similar to what I have in my test method (which I like, and it works).
```
Person person = new Person { Name = "John Doe" };
Person personCopy = CoherenceTestHelper.CopyUsingPofSerialization<Person>(person);
Assert.AreEqual(person, personCopy);
```
But to get this to work, I had do subclass `PofStreamWriter` to override `BeginProperty` and `PofStreamReader` to override `AdvanceTo`. To me this smells a little funny, but I couldn't come up with a better solution. Below is my actual code for my CoherenceTestHelper.
**Question:** Has anybody else unit tested their `IPortableObject` implementation a better way?
```
public static class CoherenceTestHelper
{
public static T CopyUsingPofSerialization<T>(T ipoIn) where T : IPortableObject, new()
{
T ipoOut = new T();
IPofContext context = new SimplePofContext();
using (MemoryStream ms = new MemoryStream())
{
IPofWriter writer = new MyPofStreamWriter(new DataWriter(ms), context);
ipoIn.WriteExternal(writer);
ms.Seek(0, 0);
IPofReader reader = new MyPofStreamReader(new DataReader(ms), context);
ipoOut.ReadExternal(reader);
}
return ipoOut;
}
private class MyPofStreamWriter : PofStreamWriter
{
public MyPofStreamWriter(DataWriter writer, IPofContext context)
: base(writer, context)
{
}
protected override void BeginProperty(int index)
{
}
}
private class MyPofStreamReader : PofStreamReader
{
public MyPofStreamReader(DataReader reader, IPofContext context)
: base(reader, context)
{
}
protected override bool AdvanceTo(int index)
{
return true;
}
}
}
``` | 2009/05/19 | [
"https://Stackoverflow.com/questions/885496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22514/"
] | High level abstraction? I suppose the highest level abstractions in the Bouncy Castle library would include:
* The [BlockCipher](http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BlockCipher.html) interface (for symmetric ciphers)
* The [BufferedBlockCipher](http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BufferedBlockCipher.html) class
* The [AsymmetricBlockCipher](http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/AsymmetricBlockCipher.html) interface
* The [BufferedAsymmetricBlockCipher](http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BufferedAsymmetricBlockCipher.html) class
* The [CipherParameters](http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/CipherParameters.html) interface (for initializing the block ciphers and asymmetric block ciphers)
I am mostly familiar with the Java version of the library. Perhaps this code snippet will offer you a high enough abstraction for your purposes (example is using AES-256 encryption):
```
public byte[] encryptAES256(byte[] input, byte[] key) throws InvalidCipherTextException {
assert key.length == 32; // 32 bytes == 256 bits
CipherParameters cipherParameters = new KeyParameter(key);
/*
* A full list of BlockCiphers can be found at http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BlockCipher.html
*/
BlockCipher blockCipher = new AESEngine();
/*
* Paddings available (http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/paddings/BlockCipherPadding.html):
* - ISO10126d2Padding
* - ISO7816d4Padding
* - PKCS7Padding
* - TBCPadding
* - X923Padding
* - ZeroBytePadding
*/
BlockCipherPadding blockCipherPadding = new ZeroBytePadding();
BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding);
return encrypt(input, bufferedBlockCipher, cipherParameters);
}
public byte[] encrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters) throws InvalidCipherTextException {
boolean forEncryption = true;
return process(input, bufferedBlockCipher, cipherParameters, forEncryption);
}
public byte[] decrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters) throws InvalidCipherTextException {
boolean forEncryption = false;
return process(input, bufferedBlockCipher, cipherParameters, forEncryption);
}
public byte[] process(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters, boolean forEncryption) throws InvalidCipherTextException {
bufferedBlockCipher.init(forEncryption, cipherParameters);
int inputOffset = 0;
int inputLength = input.length;
int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength);
byte[] output = new byte[maximumOutputLength];
int outputOffset = 0;
int outputLength = 0;
int bytesProcessed;
bytesProcessed = bufferedBlockCipher.processBytes(
input, inputOffset, inputLength,
output, outputOffset
);
outputOffset += bytesProcessed;
outputLength += bytesProcessed;
bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset);
outputOffset += bytesProcessed;
outputLength += bytesProcessed;
if (outputLength == output.length) {
return output;
} else {
byte[] truncatedOutput = new byte[outputLength];
System.arraycopy(
output, 0,
truncatedOutput, 0,
outputLength
);
return truncatedOutput;
}
}
```
**Edit**: Whoops, I just read the article you linked to. It sounds like he is talking about even higher level abstractions than I thought (e.g., "send a confidential message"). I am afraid I don't quite understand what he is getting at. | You may use:
```
byte[] process(bool encrypt, byte[] input, byte[] key)
{
var cipher = CipherUtilities.GetCipher("Blowfish");
cipher.Init(false, new KeyParameter(key));
return cipher.DoFinal(input);
}
// Encrypt:
byte[] encrypted = process(true, clear, key);
// Decrypt:
byte[] decrypted = process(false, encrypted, key);
```
See: <https://github.com/wernight/decrypt-toolbox/blob/master/dtDecrypt/Program.cs> |
47,366,956 | [](https://i.stack.imgur.com/Nt0e9.jpg)
I have a division which horizontally fits the screen inside which I have 5 divisons, I want 4 divisions to appear on screen and 1 division to appear when I scroll the division horizontally. And I want the scrollbar to appear inside the div only and not on the browser window.
Below is my non working code which puts the h1 tag in the left, I want it on the top-left then under it all 5 divs
```css
.outer {
overflow-x: scroll;
width: 100%;
}
.inner {
width: 25%;
float: left;
}
```
```html
<div class="outer">
<h1>Header Title</h1>
<div class="inner">
</div>
<div class="inner">
</div>
<div class="inner">
</div>
<div class="inner">
</div>
<div class="inner">
</div>
</div>
``` | 2017/11/18 | [
"https://Stackoverflow.com/questions/47366956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7088483/"
] | You can do it with [Flexbox](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox):
```css
.outer {
display: flex; /* displays flex-items (children) inline */
overflow-x: auto;
}
.inner {
flex: 0 0 25%; /* doesn't grow nor shrink, initial width set to 25% of the parent's */
height: 1em; /* just for demo */
}
```
```html
<div class="outer">
<div class="inner" style="background: red"></div>
<div class="inner" style="background: green"></div>
<div class="inner" style="background: blue"></div>
<div class="inner" style="background: yellow"></div>
<div class="inner" style="background: orange"></div>
</div>
```
Solution with the `h1` element:
```css
.outer {
display: flex;
flex-direction: column;
overflow-x: auto;
}
.middle {
display: flex;
flex: 1;
}
.inner {
flex: 0 0 25%;
height: 1em;
}
```
```html
<div class="outer">
<h1>Header Title</h1>
<div class="middle">
<div class="inner" style="background:red"></div>
<div class="inner" style="background:green"></div>
<div class="inner" style="background:blue"></div>
<div class="inner" style="background:yellow"></div>
<div class="inner" style="background:orange"></div>
</div>
</div>
``` | I'm not sure if I've misunderstood you, but I think that what you want to do is have the H1 over the 5 div, like this:
<https://jsfiddle.net/p78L2bka/>
```css
.outer {
display: flex;
overflow-x: scroll;
}
.middle {
display: flex;
width: 100%;
}
.inner {
flex: 0 0 25%;
height: 100px;
}
```
```html
<h1>Header Title</h1>
<div class="outer">
<div class="middle">
<div class="inner" style="background: red">
1
</div>
<div class="inner" style="background: green">
2
</div>
<div class="inner" style="background: blue">
3
</div>
<div class="inner" style="background: yellow">
4
</div>
<div class="inner" style="background: orange">
5
</div>
</div>
</div>
``` |
2,916,352 | I was just researching some statistics and ran into this problem:
a)If we have two normal bell curves, displaced by one standard deviation, how large is the area of overlap?
b)What is the proportion of the area of overlap to the remaining area of one of the bell curves?
Thank you for any help in advance. | 2018/09/14 | [
"https://math.stackexchange.com/questions/2916352",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/552221/"
] | Not much left to add to the answers you provided in the post, except +1 for a nicely asked question.
* For quick verification, and trusting that the problem has indeed a unique answer regardless of $\,A\,$, consider the degenerate case where $\,A\,$ lies on $\,BC\,$ one unit away from $\,B\,$ towards $\,C\,$. Then $\,AB=1, AC=3\,$ and $\,AB^2+AC^2=1+9=10\,$.
* Or, in a complex plane where $\,B,C\,$ are at $\,\pm2\,$ and $\,A\,$ lies on the unit circle:
$$\require{cancel}
\begin{align}
|a+2|^2 + |a-2|^2 &= (a+2)(\bar a+2) + (a-2)(\bar a-2) \\
&= a \bar a + \cancel{2a} + \bcancel{2 \bar a} + 4+ a \bar a - \cancel{2a} - \bcancel{2 \bar a}+ 4 \\
&= 2 |a|^2 + 8 \\
&= 10
\end{align}
$$ | Apply cosine law to both $\triangle ABM$ and $\triangle ACM$.
Note that the cosine term will cancel each other because $\cos \theta = - \cos (\pi - \theta)$. |
7,000,090 | I have a table with following scehma
```
CREATE TABLE MyTable
(
ID INTEGER DEFAULT(1,1),
FirstIdentifier INTEGER NULL,
SecondIdentifier INTEGER NULL,
--.... some other fields .....
)
```
Now each of FirstIdentifier & SecondIdentifier isunique but NULLable. I want to put a unique constraint on each of this column but cannot do it because its NULLable and can have two rows with NULL values that will fail that unique constraints. Any ideas of how can I address it on schema level? | 2011/08/09 | [
"https://Stackoverflow.com/questions/7000090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712447/"
] | You can use a filtered index as a unique constraint.
```
create unique index ix_FirstIdentifier on MyTable(FirstIdentifier)
where FirstIdentifier is not null
``` | Do a filtered unique index on the fields:
```
CREATE UNIQUE INDEX ix_IndexName ON MyTable (FirstIdentifier, SecondIdentifier)
WHERE FirstIdentifier IS NOT NULL
AND SecondIdentifier IS NOT NULL
```
It will allow `NULL` but still enforce uniqueness. |
65,719 | I'm trying to communicate with a remotely connected FRAM (FM24C04 from Ramtron) by using I2C. This memory is embedded on a board that can be inserted and removed at any time to/from the system (communication is properly terminated before the memory is removed).
The problem is: just after inserting the card that contains the FRAM, **sometimes**, it does not acknowledge the address.
Signals measurements
--------------------
I measured the signals to see what is happening and it seems that the timings are OK in both cases (working and not working).
Correct I2C communication (3 bytes reading):

I2C FRAM address not acknowledged (slave address is correctly sent):

Actions already done in order to solve this issue (without success)
-------------------------------------------------------------------
* Delay added after the card with the embedded FRAM is inserted in order to ensure that the power sequence is respected.
* I2C stop generation after the detection of a slave address not acknowledgement
I2C bus configuration
---------------------
* One master (STM32F205 microcontroller from ST)
* Three slaves (EEPROM 24AA1025 from Microchip, RTC DS1339C from Maxim IC and the remote FRAM FM24C04 from Ramtron
* One I2C level shifter (MAX3373E from Maxim IC) is used to allow communication between the master and the FRAM
* Bus frequency set to 100 kHz
Schematics
----------
The following picture shows a simplified schematic of the I2C bus:

I2C\_SDA and I2C\_SCL signals are directly connected to the microcontroller and FRAM\_SDA and FRAM\_SCL signals are connected to the FRAM. Note that the SDA and SCL signals connected to the FRAM are filtered by using BLM18 ferrites from Murata.
The FRAM is connected as follows:
* NC (pin 1) -> not connected
* A1 (pin 2) -> GND
* A2 (pin 3) -> GND
* VSS (pin 4) -> GND
* SDA (pin 5) -> FRAM\_SDA
* SCL (pin 6) -> FRAM\_SCL
* WP (pin 7) -> GND (not write protected)
* VDD (pin 8) -> +5V
FRAM card description
---------------------
This card is a "ISA like" card that embeds only the FRAM.
Investigations
--------------
### Slowing down the frequency
I ran tests with the SCL frequency set to 50kHz and 10kHz. I measured the SCL signal with an oscilloscope to ensure that it was at the expected frequency.
These modifications didn't solve the problem. I checked the timings and they are within the FRAM datasheet specifications.
### Ensuring power sequence
1. The I2C level shifter is put in three state mode before the card that embeds the FRAM is inserted. FRAM\_SDA and FRAM\_SCL signals are pulled low.
2. After the "FRAM card" is inserted, a delay of 100ms is added in order to ensure that the power supply is stabilized (at least 11ms required before the first start condition according to the datasheet).
3. The I2C level shifter is activated.
4. A delay of 1ms is added in order to ensure that the I2C level shifter is activated and that the lines are pulled up (~4us required by the datasheet). FRAM\_SDA and FRAM\_SCL signals are pulled up.
5. The FRAM is accessed.
FRAM\_SDA and FRAM\_SCL signals have been measured after each step.
The problem still occurs.
### Stop/start condition instead of repeated start
I tried to put a stop before the repeated start during bytes transfer. I measured the byte transfer with the oscilloscope: the STOP condition followed by the START condition is OK.
Unfortunately, this solution doesn't solve the problem.
Thoughts
--------
This issue happens only just after the card embedding the FRAM is connected. I ran a few thousands of successful read access (slave addressing and reading) after the "FRAM card" is inserted and correctly addressed.
It sounds for me more and more like an hardware issue. But I don't know if it could be related to the I2C level-shifter or to the other slaves on the I2C bus.
Do you have any other ideas or suggestions?
---
The problem seems to be resolved
--------------------------------
I replaced the FRAM module connector and find a way to do measurements directly on the FRAM. It seems that all is working well with this new connector.
I'll do more tests in order to be sure that the problem came from a bad connection. | 2013/04/15 | [
"https://electronics.stackexchange.com/questions/65719",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/22628/"
] | 10k seems a bit big for your pullups, and your leading edges look slow. Reduce the resistors to about 3k and see if that helps.
Also, why is the off voltage drifting with time? | Do u hv a 24c04a, b, or c? If its a c04a, it was a robust design. The b part has sensitivity to power supply ramps. What decoupling do u hv on pin8 to gnd? I was gonna say something about signal levels but I see that u use a level translator. You might want to check that u don't get a glitch on SCL that the chip would interpret as an extra clock. |
14,087,893 | I'm trying to create a simple script for logging into various servers via ssh, all keys have been installed and are working but i simply cannot get this script to work for me. Basically there is an option as to which server the user wishes to login to but it keeps throwing up the following error:
```
': not a valid identifier `INPUT
login.sh: line 24: syntax error near unexpected token `elif'
'ogin.sh: line 24: `elif [ $INPUT -eq 2 ] ; then
```
The script layout can be found below with dummy info:
```
#!/bin/bash
echo "What Server would you like to login to?"
echo ""
echo ""
echo "1. Server 1"
echo "2. Server 2"
echo "3. Server 3"
echo "4. Server 4"
echo "5. Exit"
read INPUT
if [ $INPUT -eq 1 ] ; then
echo"Logging in"
echo"..."
ssh root@1.2.3.4 -p 5678
elif [ $INPUT -eq 2 ] ; then
echo"Logging in"
echo"..."
ssh root@1.2.3.4 -p 5678
elif [ $INPUT -eq 3 ] ; then
echo"Logging in"
echo"..."
ssh root@1.2.3.4 -p 5678
elif [ $INPUT -eq 4 ] ; then
echo"Logging in"
echo"..."
ssh root@1.2.3.4 -p 5678
elif [ $INPUT -eq 5 ] ; then
exit 0
else
echo "invalid choice"
return
fi
```
Any help would be greatly appreciated, relatively new to using bash and this is just annoying me now! | 2012/12/30 | [
"https://Stackoverflow.com/questions/14087893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1232678/"
] | This answer is really just a comment, but comments are not suitable for code. You're script could be greatly simplified. Consider something like:
```
#!/bin/bash
servers=( host1 host2 host3 )
ips=( 192.168.1.1 192.168.1.2 192.168.1.3 )
ports=( 123 22 33 )
select server in ${servers[@]}; do
echo "Logging into $server..."
ssh root@${ips[$REPLY]} -p ${ports[$REPLY]}
break
done
```
(Although it's not at all clear why you would want to specify the IP addresses rather than using the hostname!) | I'll throw myself in front of the SO bus by answering the question you didn't ask on this one. Why not use `select`?
```
echo 'Which server would you like to log into?'
select server in 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4; do
printf 'Logging in to server %s...\n' "$server"
ssh "$server" -p "$port"
done
```
If you don't like `select`, then why not at least use `case`?
```
read -p 'Which server do you want? ' input
case "$input" in
whatever)
printf 'Logging in to server %s...\n' "$server"
ssh "$server" -p "$port"
;;
*)
echo 'Invalid option'
;;
esac
``` |
16,287,829 | I started learning WPF few days ago and have been creating some test projects to evaluate my understanding of the materials as I learn them. According to [this article](http://www.codeproject.com/Articles/18270/A-Guided-Tour-of-WPF-Part-3-Data-binding), "a property can only be bound if it is a dependency property." To test this, I used two different patterns:
**1. Using MVVM pattern (sort of)**
I created the `Movie` model:
```
public class MovieModel
{
private string _movieTitle;
private string _rating;
public string MovieTitle
{
get { return _movieTitle; }
set { _movieTitle = value; }
}
public string Rating
{
get { return _rating; }
set { _rating = value; }
}
}
```
and the `MovieViewModel` view model:
```
public class MovieViewModel
{
MovieModel _movie;
public MovieViewModel()
{
_movie = new MovieModel { MovieTitle = "Inception (Default)" };
}
public MovieModel Movie
{
get { return _movie; }
set { _movie = value; }
}
public string MovieTitle
{
get { return Movie.MovieTitle; }
set { Movie.MovieTitle = value; }
}
}
```
And finally in the my main `View`, I set the DataContext to an instance of the `MovieViewModel` class:
```
<Window x:Class="MVVMTestProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMTestProject.ViewModels"
Name="MainWindowElement"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MovieViewModel/>
</Window.DataContext>
<Grid>
<StackPanel Orientation="Vertical">
<TextBox Width="150" Text="{Binding Path=MovieTitle}"></TextBox>
</StackPanel>
</Grid>
```
This works fine, when I run the application I see `Inception (Default)` in the textbox, even though none of the properties in the `Model` or `ViewModel` are `DependencyProperties`. Now the second try was by:
**2. Using a property in the code behind of `MainView`**
In the code behind of my main view, I put:
```
private string _myText;
public MainWindow()
{
InitializeComponent();
MyText = "Some Text";
}
public string MyText
{
get { return _myText; }
set { set _myText = value; }
}
```
And then I changed my view to:
```
<Window x:Class="MVVMTestProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMTestProject.ViewModels"
Name="MainWindowElement"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MovieViewModel/>
</Window.DataContext>
<Grid>
<StackPanel Orientation="Vertical">
<TextBox Width="150" Text="{Binding ElementName=MainWindowElement, Path=MyText}"></TextBox>
</StackPanel>
</Grid>
```
But that didn't work. When I run the application, the textbox is blank. So I changed the property to a dependency property, and oddly enough, it worked. So I don't understand why the properties on the Model and ViewModel can be regular properties, but the code-behind properties have to be dependency properties in order to bind to? Is it because the ViewModel is set to the DataContext of the view and the parser is smart enough to realize this or is there another reason?
Also a not-very-relevant question: I noticed in almost every singe article on WPF people use a local variable and then define a getter and setter for it, even though we all know in .NET 2.5 (I believe?) and above, we can just use the `get; set;` syntax without having to define a local member variable. So is there a specific reason for this?
Thanks in advance. | 2013/04/29 | [
"https://Stackoverflow.com/questions/16287829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1082327/"
] | Picking up a second question tucked in at the end of your post:
>
> Also a not-very-relevant question: I noticed in almost every singe article on WPF people use a local variable and then define a getter and setter for it, even though we all know in .NET 2.5 (I believe?) and above, we can just use the `get; set;` syntax without having to define a local member variable. So is there a specific reason for this?
>
>
>
In your code you gave an example like this:
```
private string _movieTitle;
public string MovieTitle
{
get { return _movieTitle; }
set { _movieTitle = value; }
}
```
That code is exactly what the compiler generates when you write this instead:
```
public string MovieTitle { get; set; }
```
The reason you see something like the first form a lot in WPF, is because we want WPF bindings to react when property values change, and in order to achieve this we need to add change notification via [`INotifyPropertyChanged`](https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx).
There are many ways of doing this, but in modern C# you can write something like this:
```
public class MovieViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _movieTitle;
public string MovieTitle
{
get { return _movieTitle; }
set
{
if (_movieTitle == value)
return;
_movieTitle = value;
OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
In the setter, we raise the `PropertyChanged` event with the string name of the property, `MovieTitle`, which the compiler passes in for us because of the `[CallerMemberName]` attribute, and default value of `null` so we don't have to pass anything when we call it. | Using mvvm light you can bind properties and raise event.
```
/// <summary>
/// The <see cref="SelectedPriority" /> property's name.
/// </summary>
public const string SelectedPriorityPropertyName = "SelectedPriority";
private string _selectedPriority = "normalny";
/// <summary>
/// Sets and gets the SelectedPriority property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string SelectedPriority
{
get
{
return _selectedPriority;
}
set
{
if (_selectedPriority == value)
{
return;
}
RaisePropertyChanging(SelectedPriorityPropertyName);
_selectedPriority = value;
RaisePropertyChanged(SelectedPriorityPropertyName);
}
}
```
this class extends ViewModelBase which has methods RaisePropertyChanged, RaisePropertyChanging. You can download framework from <http://www.galasoft.ch/mvvm/> this site. After you install it you can use snippet to **mvvminpc** to create property that can be binded.
Your other question is answered [Why use INotifyPropertyChanged with bindings in WPF?](https://stackoverflow.com/questions/10475130/why-use-inotifypropertychanged-with-bindings-in-wpf)
To conclude, you need to implement RaisePropertyChanged() method and use this method in set;get to notify view about changing the property.
[Implementing INotifyPropertyChanged - does a better way exist?](https://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist) |
33,109,712 | i tried to center a row of bootstrap custom buttons. It is not working and still is at the left side of the page, no matter what i try. i need some help.
the page got all bootstrap added to the code like it should, but i cant center this buttons. Thank you.
Here is my css and html Code
```
<style type="text/css">
.btn-circle {
width: 130px;
height: 130px;
padding: 10px 0;
font-size: 12px;
border:7px solid #cfd8dc;
line-height: 1.428571429;
border-radius: 130px;
}
.btn-circle.btn-lg {
width: 130px;
height: 130px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 130px;
border:7px solid #cfd8dc;
}
.btn-circle.btn-xl {
width: 130px;
height: 130px;
padding: 10px 16px;
font-size: 24px;
line-height: 1.33;
border-radius: 130px;
border:7px solid #cfd8dc;
}
</style>
<div class="row" style="margin:auto;text-align:center;">
<div class="col-lg-2"><button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
<div class="col-lg-2"><button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
<div class="col-lg-2"> <button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
<div class="col-lg-2"> <button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
</div>
``` | 2015/10/13 | [
"https://Stackoverflow.com/questions/33109712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668330/"
] | Fixed your codes. --
```css
.btn-circle {
width: 130px;
height: 130px;
padding: 10px 0;
font-size: 12px;
border:7px solid #cfd8dc;
line-height: 1.428571429;
border-radius: 130px;
}
.btn-circle.btn-lg {
width: 130px;
height: 130px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 130px;
border:7px solid #cfd8dc;
display:inline-block;
}
.btn-circle.btn-xl {
width: 130px;
height: 130px;
padding: 10px 16px;
font-size: 24px;
line-height: 1.33;
border-radius: 130px;
border:7px solid #cfd8dc;
}
```
```html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row" style="margin:auto;text-align:center;">
<div class="col-lg-2 col-lg-offset-2"><button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
<div class="col-lg-2"><button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
<div class="col-lg-2"> <button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
<div class="col-lg-2"> <button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button></div>
</div>
```
Solution of overlapping problem. --
```css
.btn-circle {
width: 130px;
height: 130px;
padding: 10px 0;
font-size: 12px;
border:7px solid #cfd8dc;
line-height: 1.428571429;
border-radius: 130px;
}
.btn-circle.btn-lg {
width: 130px;
height: 130px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 130px;
border:7px solid #cfd8dc;
display:inline-block;
}
.btn-circle.btn-xl {
width: 130px;
height: 130px;
padding: 10px 16px;
font-size: 24px;
line-height: 1.33;
border-radius: 130px;
border:7px solid #cfd8dc;
}
```
```html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-xs-12" style="text-align:center;">
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
</div>
</div>
``` | Take out the unnecessary div wrap around each button, then the text-align works properly. Check fiddle: <https://jsfiddle.net/bL8vr504/1/>
```
<div class="row" style="margin:auto;text-align:center; width: 100%;">
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
<button type="button" class="btn btn-default btn-circle btn-lg"><span>-</span></button>
</div>
```
final note, apply any needed margin on one of the button classes. |
71,100 | Do police need to have established probable cause before they arrest you, or can your actions later validate the lack of probable cause that they had when they arrested you?
I suspect this may just be one of the many reasons not to talk to the police. | 2021/08/24 | [
"https://law.stackexchange.com/questions/71100",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/5189/"
] | **Can police arrest you to later fish for probable cause?**
Answer for [england-and-wales](/questions/tagged/england-and-wales "show questions tagged 'england-and-wales'") (although presumably there are similar conditions that must be met in the [united-states](/questions/tagged/united-states "show questions tagged 'united-states'")):
This would be an unlawful arrest, potentially aggravated by false imprisonment (and/or kidnapping).
The American phrase "probable cause" is not used in the UK but it (somewhat) equates to the two elements that make a lawful arrest required by [s.24 of the Police and Criminal Evidence Act 1984](https://www.legislation.gov.uk/ukpga/1984/60/section/24?timeline=false):
* Suspicion of an offence, and
* Belief an arrest is necessary (*if not met, then the officer has other options such as giving words of advice for low-level offending, issuing a Fixed Penalty Notice or Traffic Offence Report or releasing the suspect on ["street bail"](https://www.legislation.gov.uk/ukpga/1984/60/section/30A?timeline=false) to appear at police station at a later date*)
The arresting officer **must** reasonably satisfy both elements in his own mind (e.g. not just blindly following orders, or by applying unjustified suspect-profiling) at the time and not later with hindsight or serendipity - especially as the officer [must take the suspect to a police station as soon as practicable](https://www.legislation.gov.uk/ukpga/1984/60/section/30?timeline=false) to justify the arrest to another officer, independent of the investigation, who will or will not authorise the suspect's further detention. This gives little time to come up with a plausible story (although it does happen).
\*(On a scale of 0 to 10 - with 10 being total knowledge and 0 being no opinion at all - suspicion may be as low as 2 or 3 whereas belief starts at 7 or 8.) | In formal English common law, a person cannot be arrested unless they are in commission of a felony and the person or persons arresting them have observed them committing that felony. In all other cases, by formal law, a warrant of arrest would be needed. Note that there is no need to "arrest" someone to charge and prosecute them for a crime and the expectation under English common law is that a person is only arrested if there is need to do so, such as to identify the person. Otherwise, it is expected that if a person is thought to commit a crime, then what should happen is that they should be *indicted*, and then summoned to court where they face trial. None of this requires that the person be "arrested", only that it be known who they are, so that they can be summoned.
Obviously, in the modern world the police and the courts ignore this part of common law principles and arrest people on hearsay evidence after the fact, even for misdemeanors. One reason for this is that most states completely immunize police against being sued for false arrest. For example, in New Hampshire there is the following language:
>
> Any claim arising out of an intentional tort, including assault,
> battery, false imprisonment, **false arrest**, intentional mental
> distress, malicious prosecution, malicious abuse of process, libel,
> slander, misrepresentation, deceit, invasion of privacy, interference
> with advantageous relations, or interference with contractual
> relations, provided that the employee whose conduct gives rise to the
> claim reasonably believes, at the time of the acts or omissions
> complained of, that his conduct was lawful, and provided further that
> the acts complained of were within the scope of official duties of the
> employee for the state.
>
>
>
So, in other words a policeman only has to show that he "reasonably believes" his conduct was lawful to be immune from a lawsuit for false arrest. Furthermore, I believe that New Hampshire's laws against false arrest (that criminalized false arrest) were deleted about 10 years ago.
However, there is a risk for the police in that if they were to engage in false arrest routinely, then there would be a political backlash and the laws against false arrest could be re-instated. For this reason police are cautious about arresting someone unless they have some kind of "reasonable" evidence that the person has committed at least a misdemeanor.
In New Hamsphire, if a person is arrested falsely, the usual course of action is to sue the police for false imprisonment, which is the only law remaining on the books for this kind of action. In some cases, in recent years courts have allowed these civil lawsuits to proceed if the police conduct was particularly egregious. For example, in one case a man was arrested and imprisoned for a long period of time when his drug addict girlfriend trained her 6-year-old daughter to say he raped her. He sued the police for false arrest after his lawyers finally forced the prosecutors to show the girl's record which featured a long list of similar lies against other people. The trial court dismissed the lawsuit, but on appeal the Supreme Court of NH vacated the trial court's ruling and allowed the lawsuit to proceed. |
14,160,683 | I am a c# developer learning/relearning/brushing up on c++
I'm working on database access I have the following code and im having trouble understand what the & does in this case.
```
SQLHENV hEnv = NULL;
if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv) == SQL_ERROR)
{
```
If I remove the & I get this error.
```
'SQLAllocHandle' : cannot convert parameter 3 from 'SQLHENV' to 'SQLHANDLE *'
```
at first I thought it was simply passing this field in as a reference but based on the error it reads more like it is some how allowing it to convert? | 2013/01/04 | [
"https://Stackoverflow.com/questions/14160683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1949093/"
] | `&` is the address operator. It's taking the local hEnv and passing the address of it. Now you have not the type but a pointer to the type you are referring.
so
```
void foo()
{
int i = 1;
int * iptr = &i;
}
```
When you skip the address operator you still have the type, not the pointer to the type. | & does mean to pass by reference. The compiler is just telling you it can't convert from a reference to value type
EDIT: When a function accepts an ADDRESS(pointer), it is called pass by reference. I'm sorry if my answer confused some people, but in this case your function is expecting a REFERENCE to a variable, so you need to pass it the ADDRESS of that variable. |
10,191 | I'm new in Mathematica and I am trying to write numbers from 1 to 10 in txt file. But "Null" is everything that is written in my file. The code is:
```
Export["C:\\Users\\Sealy\\Desktop\\list.txt",
For[k = 1, k <= 10, k++, Print[List[k]]]]
``` | 2012/09/04 | [
"https://mathematica.stackexchange.com/questions/10191",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2200/"
] | Recommendation: Read up on `Table`, `Range` etc. . Press `F1` often!
```
Export[NotebookDirectory[] <> "test.txt", Range[10]]
``` | `Print` is used for it's side effect (which is printing to the screen) but it returns `Null`. Also the `For` loop returns `Null`
Try this:
```
lst = {};
For[k = 1, k <= 10, k++, AppendTo[lst, {k}]]
lst
(* {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}} *)
Export["C:\Users\Sealy\Desktop\list.txt", lst]
``` |
394,068 | I wonder if someone can help me. How will one go about to create a simple circuit simulator? Similar to Multisim, just a lot simpler!
Basically, I only need resistors, capacitors, inductors and voltage sources.
Is there a tutorial I can follow, to create this using C# and Visual Studio? | 2018/09/03 | [
"https://electronics.stackexchange.com/questions/394068",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/187853/"
] | I wrote the simulation engine that powers [CircuitLab](https://www.circuitlab.com/) from scratch: from the sparse matrix library up through component models and simulation modes. My co-founder wrote the front-end. It ended up being an unbelievably huge programming project, but one I'm quite proud of. If you're up for the challenge, writing a circuit simulator may be one of the most rewarding programming projects you'll ever tackle.
At a high level, you just need to:
1. Turn a network of components into a system of equations (non-linear differential equations).
2. Numerically solve the system of equations (using sparse matrix techniques).
I don't know of an online tutorial, but I've tried to document a lot of this as I write the ["Ultimate Electronics" textbook](https://www.circuitlab.com/textbook/), especially in Chapter 2. There are also a number of 1990s-era books on the topic of circuit simulation, though I don't have them handy at the moment.
My suggestion would be to start from only voltage sources and resistors, and continue building from there. Good luck. | I doubt there are online tutorials because it's something pretty specific.
However, one source of information you can definitely use is open source code. One I know of is [SpicePy](https://github.com/giaccone/SpicePy) - it's written in Python, but it's very well documented, although the Python language is very descriptive just by itself. You can use such library in your Python code or though the [Telegram Bot](https://github.com/giaccone/SpicePyBot).
What you'll need is some sort of way to describe the topology of your circuit. One common approach is the use of [netlists](https://en.wikipedia.org/wiki/Netlist), which are essentially text that describe each component in the circuit and how it's connect to the other ones (e.g. through node numbers). You can use this strategy or whatever one seems easier for you to take; parsing it and making it an *actual* graph (i.e. is it meaningful?) out of it might take you some time.
After that, one common way to analyze circuits in simulators is [nodal analysis](https://en.wikipedia.org/wiki/Nodal_analysis); then resort to some linear algebra library to solve the system of equations (which will surely be linear), such as [Math.Net](https://numerics.mathdotnet.com/). |
8,450,561 | Consider the following code:
```
<script>
var i = 0;
function test() {
var _this = this;
// foo and _this.foo are set to the same number
var foo = _this.foo = i++;
function wtf() {
console.log(_this.foo, foo);
}
$("#thediv").click(wtf);
};
test();
test();
test();
</script>
```
It seems that console.log(\_this.foo, foo) should always output equal numbers (i).
But clicking the div outputs 3 lines (for each console.log call):
```
2 0
2 1
2 2
```
It seems that `_this.foo` always refers to last `this.foo`. Why it is so? | 2011/12/09 | [
"https://Stackoverflow.com/questions/8450561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149288/"
] | When test() is run, `this` is a reference to `window` for each of your three test() calls, so you are actually updating `window.foo` when you assign to `_this.foo` and referencing `window.foo` in your `console.log`.
Then, when `wtf()` is invoked, the `_this` variables in each of the `wtf()` closures are the same - they all point to `window`
See this jsfiddle: <http://jsfiddle.net/8cyHm/>
I added some additional parameters to console.log to show what is happening | If you are testing in Chrome you may well be hitting a bug in console.log.
See : [Javascript Funky array mishap](https://stackoverflow.com/questions/8395718/javascript-funky-array-mishap/8396289#8396289)
Try changing to :
```
console.log(_this.foo + ' = ' + foo);
``` |
11,306,587 | i am new to j query, it is cool, but i am glued to the ceiling on how to add width and height to a iframe generated after click, using this code: all suggestions would be great and thanks in advance
Khadija
```
$(document).ready(function () {
$(".fancybox").fancybox();
})
.height = '600px';
``` | 2012/07/03 | [
"https://Stackoverflow.com/questions/11306587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1498036/"
] | To initialize the fancybox popup for the usage of an iframe, limited to a certain width and height, you need at least three parameters:
**jQuery**
```
$(document).ready(function(){
$(".fancybox").fancybox({
'width' : 600, // set the width
'height' : 600, // set the height
'type' : 'iframe' // tell the script to create an iframe
});
});
```
You can read all about the available options at the [FancyBox API Page](http://fancybox.net/api). | **With iframe**
```
$(document).ready(function () {
$(".fancybox").fancybox({
width:600,
height:400,
type: 'iframe',
href : 'url_here'
});
})
```
**Without iframe**
```
$(document).ready(function () {
$(".fancybox").fancybox({
width:600,
height:400,
autoDimensions: false,
});
})
``` |
28,191,305 | I made this application with a button ("descrição") to open a "gray background" with one text box and two buttons:
"salvar" (save button) and "cancelar" (cancel button), you can only save and close it if you type something inside the box or click on "cancelar", for the first time it works perfectly, but when you start again it doesn't open the buttons or the text box, and it stays on the "gray background".
I'm still new to HTML, CSS, and JS.
```js
$('#headerR').on('click', function() {
$('#overlay, #overlay-back').fadeIn(500);
$(".text-hidden").toggleClass("text");
$(".saving").toggleClass("myButton");
$(".canceling").toggleClass("myButton");
});
function validation() {
if (document.getElementById("desc").value == null || document.getElementById("desc").value == "") {
alert("Preencha a Descrição!");
} else {
$(function() {
$("#save").click(function() {
$(".text-hidden").toggleClass("text");
$('#overlay, #overlay-back').fadeOut(500);
});
});
}
}
```
```css
html, body {
width: 100%;
height: 100%;
}
#overlay-back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
opacity: 0.6;
filter: alpha(opacity=60);
z-index: 5;
display: none;
}
#overlay {
position: absolute;
top: 10;
left: 50;
width: 100%;
height: 100%;
z-index: 10;
display: none;
}
.text-hidden {
transform: scaleX(0);
transform-origin: 0% 40%;
transition: all .7s ease;
width: 0px;
height: 0px;
top: 50%;
left: 50%;
}
.saving {
transform: scaleX(0);
transform-origin: 0% 40%;
transition: all .9s ease;
height: 1px;
position: absolute;
top: 90%;
right: 8%;
background: Green;
color: white;
}
.canceling {
transform: scaleX(0);
transform-origin: 0% 40%;
transition: all .9s ease;
height: 1px;
position: absolute;
top: 90%;
left: 5%;
background: Red;
color: white;
}
.text {
transform: scaleX(1);
width: 300px;
height: 150px;
position: absolute;
top: 20%;
left: 37%;
}
.myButton {
transform: scaleX(1);
width: 80px;
height: 80px;
}
```
```html
<p>
<button id="headerR" type="button">Descrição</button>
</p>
<div id="overlay-back"></div>
<div id="overlay">
<span><script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
type="text/javascript">
</script>
<textarea id="desc" type="textarea" class="text-hidden">
</textarea> <button id="save" class="saving" onclick=
"validation();"><span><span>Salvar</span> <button id="cancel"
class="canceling" onclick=
"validation();">Cancelar</button></span></button></span>
</div>
``` | 2015/01/28 | [
"https://Stackoverflow.com/questions/28191305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Have you tried using ng-if instead of ng-show?
ng-if won't render the HTML nodes within if the expression is false. At least with Angular 1.3 or later.
```
<div ng-if="messageAvailable" class="message">
<p ng-bind="message"></p>
</div>
```
In general you should consider ng-if over ng-show/hide, especially when inside an ng-repeat. It will greatly reduce the number of active watches in the digest cycle and speed up the application. | Just hide it with styles
**upd**
```
<style>
.h {display: none;}
.v { display: block}
</style>
<div ng-show="messageAvailable" ng-class="{'v': messageAvailable,'h':!messageAvailable}"
``` |
37,326,068 | So I just updated my app to use ASP.NET Core RC2. I published it using Visual Studio and noticed that my Area is not published:
This snapshot is from `src\MyProject\bin\Release\PublishOutput`:
[](https://i.stack.imgur.com/FjpgY.png)
And here is my Area, named `Admin` in Visual Studio:
[](https://i.stack.imgur.com/VGvdF.png)
Am I missing an step or what? | 2016/05/19 | [
"https://Stackoverflow.com/questions/37326068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5173926/"
] | You need to configure your `publishOptions` section of `project.json` to include the `Areas` folder which is not included in the default template:
ex:
```
"publishOptions": {
"include": [
"wwwroot",
"Views",
"appsettings.json",
"web.config",
"Areas"
],
"exclude": [ "bin" ]
}
```
**Update**
If you want to ensure that your controllers and other .cs files are not included, you can blacklist with the `exclude` property of `publishOptions` like so:
```
"publishOptions": {
"include": [ "wwwroot", "Views", "appsettings.json", "web.config", "Areas" ],
"exclude": [ "**.user", "**.vspscc", "**.cs", "bin" ]
}
```
If you prefer more restrictive security, you can simply whitelist .cshtml files instead of including the entire Areas folder like so:
```
"publishOptions": {
"include": [ "wwwroot", "**.cshtml", "appsettings.json", "web.config" ],
"exclude": [ "bin" ]
}
```
**Note**
Be careful using wildcards like `**.cshtml` as they will include all files in all subdirectories, including the `bin` directory. If you have any views in your `bin` folder from a previous build, they will be duplicated again inside the new build output until the path becomes too long. | Adding Areas will copy everything including the .cs files.
so should add `"Areas/**/Views/**/*.cshtml"` and `"Areas/ * /.cshtml"` under publish options instead of only `"Areas"` |
28,598,308 | On a wordpress site a malformed div tag and a link to thepiratebay.in.ua are being inserted through some kind of attack.
The inserted code is:
`div style="position:absolute;top:-1488px;"><a href="http://thepiratebay.in.ua">torrents,pirate,piratebay,software torrents,porn,porn download</a>`
On a clone of the site, I have switched from the current theme to the default theme and I have also disabled all of the active plugins, but the problem persists.
grep'ing all the site files for 'porn' or 'piratebay' finds nothing and the same is true for searching the database. The insertion happens after the completion of the footer, in the middle of loading the scripts at the bottom of the `<body>` tag.
The attack also seems to have allowed eastern europeaan spammers to send mail as in:
`Tylko spojrzcie jak ten dran zarabia!`
Has anyone seen this? Or have suggestions on next steps for remediating?
Thanks | 2015/02/19 | [
"https://Stackoverflow.com/questions/28598308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111409/"
] | I suffered the exact same problem and just got it solved. Check you index.php
Mine was modified a few days ago and comparing to other wordpress installations I saw it had these extra lines at the beggining:
```
//eAccelerate Caching System
/*ordpr*/
@ini_set('display_errors', '0');
ob_start('__e_accelerate_engine');
register_shutdown_function('ob_end_flush');
function __e_accelerate_engine($output) {if ((substr(trim($_SERVER['REMOTE_ADDR']),0,6)!=='74.125') && !preg_match("/(googlebot|msnbot|yahoo|search|bing|ask|indexer)/i", $_SERVER['HTTP_USER_AGENT'])){
$data=serialize(array('page'=>md5($_SERVER['REQUEST_URI']), 'host'=>$_SERVER['HTTP_HOST'],'ip'=>$_SERVER['REMOTE_ADDR'],'ua'=>$_SERVER["HTTP_USER_AGENT"],'kdg'=>20));$tags=array('</body>');shuffle($tags);foreach($tags as $tg){if(preg_match('!'.$tg.'!', $output)) {$output=preg_replace('!'.$tg.'!', base64_decode('PGRpdiBzdHlsZT0icG9zaXRpb246YWJzb2x1dGU7dG9wOi0xNDg4cHg7Ij48YSBocmVmPSJodHRwOi8vdGhlcGlyYXRlYmF5LmluLnVhIj5waXJhdGViYXkscGlyYXRlIGJheSxwaXJhdGUsYmF5LHRvcnJlbnRzLGZyZWUsZnJlZSBzb2Z0d2FyZSxzb2Z0d2FyZSx0b3JyZW50cyxmcmVlIHRvcnJlbnRzLGZyZWUgcG9ybixwb3JuIHRvcnJlbnRzLHRvcnJlbnQ8L2E+PC9kaXY+').$tg, $output, 1);break;}}}return ((isset($_GET['fccheck']))?('<!--check:'.md5($_GET['fccheck']).'-->'):('')).$output;}
```
To check the last modified files I run:
```
find *.php -mtime -96
```
(96 is for 4 days)
I just removed the lines and the div was gone!
I hope it solves it for you too.
---
Edit: Btw I had big mailing problems last days, I was attacked by a backscatter, sending hundreds of misdirected bounces every hour and my Ip was in 15 blacklists at [MxToolBox](http://mxtoolbox.com/). I don't know if that was the cause but fortunately it's now solved. So If I were you I'd check your Ip there or in a similar page. | First, check the entire WP install to see which were the most recent files updated. That would be where you start looking. Often the code is encrypted, which is why you can't find it using grep. Look for something like:
```
eval(gzinflate(base64_decode(..)));
```
Try grep'ing for "eval" or "base64\_decode".
Often this code is inserted into the functions.php file, or your theme's footer. You can test that by activating another theme. Also, try disabling all the plugins and see if that eventually removes the code.
This is a handy guide for resolving and prevention:
<http://codex.wordpress.org/FAQ_My_site_was_hacked> |
45,647,714 | i'm new to mac. and i installed the netbeans IDE . so i just went to verify it in the terminal. then i'm getting an error while finding out the version ?[this is the screenshot of the terminal.](https://i.stack.imgur.com/nqOsG.png) | 2017/08/12 | [
"https://Stackoverflow.com/questions/45647714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7475005/"
] | According to your question, you can declare a function `is_square(n)` to check a number whether perfect square or not.
Then, you take a number (i.e. `val`) from list `l` using this `for val in l:`. If number (i.e. `val`) is perfect square then it will add to the `sm` otherwise not.
You code will be like following code :
```
l = [1,4,9]
def is_square(n): # function for checking a number whether perfect square or not.
return n**0.5 == int(n**0.5)
sm = 0
for val in l:
if is_square(val): # if number is perfect square then it will add to the sm otherwise not.
sm += val
print(sm)
``` | Try This:
```
import math
a=map(int,input().split())
sum1=0
for i in a:
b=math.sqrt(i)
if math.ceil(b)==math.floor(b):
sum1+=i
print (int(sum1))
``` |
23,775,680 | i want to download file from url. `http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx` - you can try it, it work. My code is next:
```
new DownloadFileFromURL().execute("http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx");
```
DownloadFileFromUrl is
```
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Before starting background thread Show Progress Bar Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PostInfoActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Downloading file in background thread
*/
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/test.docx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
if (pDialog != null) {
pDialog.dismiss();
}
}
}
```
After this a saw new test.docx file in my root folder, but its size is 26 byte and i can not open it. | 2014/05/21 | [
"https://Stackoverflow.com/questions/23775680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2101843/"
] | This happening because your url is in unicoded form so you have to first encode it then try to download
```
URLEncoder.encode(Url, "UTF-8")
```
It works for me. | You can try with this method by calling this method from your doInBackground
```
private void downloader(String urlstr) {
HttpURLConnection c = null;
FileInputStream fis = null;
FileOutputStream fbo = null;
File file = null, file1;
File outputFile = null;
InputStream is = null;
URL url = null;
try {
outputFile = new File(Environment
.getExternalStorageDirectory().toString()
+ "/test.docx");
if(outputFile.exists())
Log.e("File delete",outputFile.delete()+"");
fbo = new FileOutputStream(outputFile, false);
// connect with server where remote file is stored to download it
url = new URL(urlstr);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setConnectTimeout(0);
c.connect();
is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fbo.write(buffer, 0, len1);
Log.e("length", len1+"----");
}
fbo.flush();
} catch (Exception e) {
} finally {
if (c != null)
c.disconnect();
if (fbo != null)
try {
fbo.close();
} catch (IOException e) {
e.printStackTrace();
}
if (is != null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
file = null;
outputFile = null;
}
}
``` |
138,818 | Sometimes when I take a photo I like to share it with friends and family, so I press the button that points up, which then leads to a screen where I can share the photo with facebook, flickr and several other things that I don't use.
Recently I decided to use instagram as a means of sharing photos, since I had noticed some of my friends on facebook doing it.
I installed the instagram app on my iphone and have used it a few times to share photos, but it is missing from the list of things to share with immediately after taking a photo navigated to from the photo gallery.
How can I get instagram to appear in the list of destinations that I see when I decide t share a photo from my phone? | 2014/07/13 | [
"https://apple.stackexchange.com/questions/138818",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/-1/"
] | Sorry but you don't really have any control over this. Some sharing panels offer a "Open In..." option in the bottom-right corner. If you check an application that does offer this option (for example Dropbox) you'll likely find Instagram in that list.
For some reason Apple doesn't provide that "Open In..." option in the Camera or Photos apps.
The Facebook and Flickr options are hard-coded by Apple. They always appear in the sharing list even if you don't have the applications installed. | Re upload the app you missed a step that it asks to access your pictures I did the same thing I have a iOS 6 |
1,462 | I installed Fresh Magento in **Live Server with a subdomain** (shop.example.com)
And It given me error **500 : internal server error**
**But If i delete .htaccess** the site works properly
Without .htaccess file magento project won't be running.
So how to solve this ? | 2013/03/20 | [
"https://magento.stackexchange.com/questions/1462",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/661/"
] | You've clearly got an error in your `.htaccess` file.
If you check your Apache error log, you should see a pointer as to where the error is exactly.
Eg.
```
[Wed Mar 20 12:15:49 2013] [alert] [client 8.8.8.8] /home/chocoloo/public_html/.htaccess: Invalid command 'faulty_line', perhaps misspelled or defined by a module not included in the server configuration
```
There is also a chance the subdomain functionality you are using uses rewrites, in which case try setting
```
RewriteBase /
``` | If you are using CGI mode for PHP (check phpinfo()), you must uncomment first two lines in your .htaccess file:
```
Action php5-cgi /cgi-bin/php5-cgi
AddHandler php5-cgi .php
``` |
45,799,041 | So my problem is I'm creating a UITabBarController without a storyboard and I'm stuck with how to create a UITabBar item without a Viewcontroller. Because what I want to do is the 2nd item of my UITabBarItem is an action not presenting a view controller. | 2017/08/21 | [
"https://Stackoverflow.com/questions/45799041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8495570/"
] | I implement something like this in an app (the close button), though I use storyboards. The close button is a viewController, but I used the following code to get it to act like a regular button:
```
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
// this provides UI feedback that the button has been pressed, even though it leads to the dismissal
if viewController == self.viewControllers![4] {
viewController.tabBarItem.image? = UIImage(named: "TabBarClose")!.imageWithColor(UIColor.red).withRenderingMode(UIImageRenderingMode.alwaysOriginal)
return false
} else {
return true
}
}
override func viewDidDisappear(_ animated: Bool) {
//sets the close button back to original image
self.viewControllers![4].tabBarItem.image = UIImage(named: "TabBarClose")!
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// this is so it never actually goes to the close buttons viewController
currentTab = self.selectedIndex != 4 ? self.selectedIndex:currentTab
saveTabIndexToPreferences(currentTab!)
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
// assign functionality to the close button
if item.tag == 100 {// this is old code, there is probably a better way to reference the tab
dismissTabBar()
} else {
}
}
```
EDIT (for a question that was asked)
```
func selectTabIndexFromPreferences() {
let defaults:UserDefaults = UserDefaults.standard
selectedIndex = defaults.integer(forKey: "songSelectionTabIndex_preference")
}
func saveTabIndexToPreferences(_ index:Int?) {
if index != nil {
let defaults:UserDefaults = UserDefaults.standard
defaults.set(index!, forKey: "songSelectionTabIndex_preference")
}
}
```
[](https://i.stack.imgur.com/ymL7j.jpg) | There is an API conform way to do this.
The `UITabBarControllerDelegate` has a `shouldSelect` method that you can implement: <https://developer.apple.com/documentation/uikit/uitabbarcontrollerdelegate/1621166-tabbarcontroller>
Something along these lines:
```
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
if (viewController == self.centerViewController) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Test" message:@"This is a test" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[tabBarController presentViewController:alert animated:YES completion:nil];
return NO;
}
return YES;
}
``` |
50,603,769 | I have a list which contain lines of files, sample of which is shown.
```
list(c("\"ID\",\"SIGNALINTENSITY\",\"SNR\"", "\"NM_012429\",\"7.19739265676517\",\"0.738130599770152\"",
"\"NM_003980\",\"12.4036181424743\",\"13.753593768862\"", "\"AY044449\",\"8.74973537284918\",\"1.77200602833912\"",
"\"NM_005015\",\"11.3735054810744\",\"6.76079815107347\""), c("\"ID\",\"SIGNALINTENSITY\",\"SNR\"",
"\"NM_012429\",\"7.07699512126353\",\"0.987579612646805\"", "\"NM_003980\",\"11.3172936656653\",\"8.38227473088534\"",
"\"AY044449\",\"9.2865464417786\",\"2.61149606120517\"", "\"NM_005015\",\"10.1228142794354\",\"3.98707517627092\""
), c("ID,SIGNALINTENSITY,SNR", "1,NM_012429,6.44764696592035,0.84120306786724",
"2,NM_003980,9.52604513443066,3.02404186191898", "3,AY044449,9.11930818670925,2.24361163736047",
"4,NM_005015,10.5672879852575,5.29334273442728"))
```
I want to confirm the match when reading lines. I tried to find out which files has content starting with `NM` or `GE` by the following code
```
which(lapply(lines, function(x) any(grepl(paste(c("^NM_","^GE"),collapse = "|"), x, ignore.case = TRUE))) == T)
```
which is supposed to give index of all the three, but it return `integer(0)`. I am not sure what I am missing. | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4467155/"
] | You can use ***`CircleAvatar`*** widget to display the obtained image to make it `circular`.
```
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(new MaterialApp(debugShowCheckedModeBanner: false, home: new MyApp()));
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),
),
body: new Center(
child: _image == null
? new Text('No image selected.')
: new CircleAvatar(backgroundImage: new FileImage(_image), radius: 200.0,),
),
floatingActionButton: new FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: new Icon(Icons.add_a_photo),
),
);
}
}
``` | You can also use [ClipOval](https://api.flutter.dev/flutter/widgets/ClipOval-class.html) to circle the image. Just wrap your file image with `ClipOval`.
```
ClipOval(
child: FileImage(_image)
),
``` |
26,165,160 | In Sublime Text I can arbitrarily select a set of lines and then use `⌘+L` to expand the selection to the full lines. Is there a similar command in PHPStorm / WebStorm? (I'd like to map that command to a keyboard shortcut.)
I know PHPStorm has the option "Select Line at Caret", but that selects only one line. | 2014/10/02 | [
"https://Stackoverflow.com/questions/26165160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373154/"
] | With WebStorm 11 (at least) the multi-caret keyboard shortcut is:
`Ctrl` then `Ctrl`+`Arrow Up` (or click & drag with the middle mouse button/scroll wheel)
then to select the full lines:
`Home` then `Shift`+`End`
which you could even create as a [macro with a keyboard shortcut](https://www.jetbrains.com/help/webstorm/using-macros-in-the-editor.html).
I used to accidentally activate the multi-caret all the time (I scroll with Ctrl+Up/Down), so I knew how to do part of it, but it took me ages to figure out that extra Ctrl tap at the beginning. | This is currently not possible with a selection. However, you can still do that from the keyboard. Instead of doing selections set up a shortcut for `Clone Caret Above` (Alt+Shift+U for me) and `Clone Caret Bellow` (Alt+Shift+D for me). This allows to go up or down a line and add a caret there. So instead of selecting each line, you directly move the caret there and clone it.
I am also coming from Sublime Text and missing that feature, but this worked also pretty well. |
13,925,724 | I want to reuse certain filter for many projects so I want to extract it and use a single jar to just add it to any Web App.
For building I am using Gradle 1.3 and the following `build.gradle` file:
```
apply plugin: 'java'
dependencies {
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.+'
testCompile group:'junit', name:'junit', version:'4.+'
compile group:'org.springframework', name:'spring-web', version:'3.+'
compile group:'org.slf4j', name:'slf4j-log4j12', version:'1.6.+'
compile group:'log4j', name:'log4j', version:'1.2.+'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version:'3.+'
}
repositories {
mavenCentral()
}
```
As you can see, I need the servlet api to compile this filter succesfully so I want to add it like a maven provided dependency.
Anyways, after running `gradle build` I get the following error:
>
> Could not find method providedCompile() for arguments
> [{group=javax.servlet, name=javax.servlet-api, version=3.+}] on root
> project 'hibernate-conversation-context'.
>
>
>
Now, I know that I cannot use providedCompile without the WAR plugin but I need the project to be a simple JAR. Is there another way to do this? | 2012/12/18 | [
"https://Stackoverflow.com/questions/13925724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391333/"
] | There is no such configuration out of the box for the `java` plugin. However you can build it yourself as follows:
```
configurations { providedCompile }
dependencies {
providedCompile "javax.servlet:javax.servlet-api:3.+"
}
sourceSets.main.compileClasspath += configurations.providedCompile
sourceSets.test.compileClasspath += configurations.providedCompile
sourceSets.test.runtimeClasspath += configurations.providedCompile
```
This adds the configuration, and puts all the dependencies in there on the compile classpaths of both your main classes and test classes. You also need to add it to the runtimeClasspath, as that doesn't include the compile classpath according to the gradle DSL documentation. | I wrote a blog post recently which covers exactly this scenario. It also shows you how to get integration with Eclipse set up properly too.
<http://blog.codeaholics.org/2012/emulating-mavens-provided-scope-in-gradle/> |
252,036 | I was looking into thermography which talks about emissivities of metals and other materials. Polished metals which have low emissivity appear to be colder in thermal imaging cameras even if they are actually hot (because they have low emissivity). Refer to the image below:
[](https://i.stack.imgur.com/6emCQ.jpg)
^ Source: <http://www.flir.com/science/blog/details/?ID=71556>
My understanding of thermal radiation says that a material should be radiating when hot. So, a coffee mug made of two materials (ceramic mug with say metal decorative leafs on the outside) should be radiating equally? If they are not radiating equally, then how is metal leafs part moving towards thermal equilibrium?
Thermal radiation is the radiation generated by the thermal motion of charged particles in matter. So if the metal part if actually hot, why is not radiating? If it does radiate, why doesn't it show up in the IR cameras (until you adjust the region of interest and manually enter emissivity of material in camera)? | 2016/04/25 | [
"https://physics.stackexchange.com/questions/252036",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/115460/"
] | A hot material will radiate heat to a colder, that is to say it will radiate
more heat outward than it absorbs from the colder object. The problem is
only that the radiation RATE, as well as the absorption rate, is not
determined by temperature alone, but by the coupling of the material to
light of any given wavelength. Metals are electrically conductive, and
if they haven't any oxide or other nonmetal surface layers, that makes them
reflective. Reflection means the absorption of radiation is very small, and implies that the emission of radiation by a hot metal, while larger
than absorption, can be also very small.
An easily treated case is that of a perfectly absorbing material, a
'black body'. In that case, the material property of absorption
versus wavelength turns into a factor of '1', and simplifies the
equations wonderfully. Such effects as greenhouse warming are
not present in the simple model where all bodies are black, though. | The mug is made up of two materials, ceramic (an insulator) and metal (a conductor). These two types of materials certainly have different heat coupling coefficients, and metals in general both emit and absorb heat faster than insulators. So it definitely makes sense that metals, by virtue of more efficient **radiative** heat transfer with the environment, are almost in a state of thermal equilibrium with the environment in this picture shown. On the other hand, the ceramic has poor thermal coupling with the environment for radiative heat transfer, so the thermal energy cannot be transferred to the environment quickly. This results in the mug *"containing"* more energy and appear hotter in this picture.
It would be interesting to take a time series photographs of this mug from the moment you pour hot liquid into it to the moment where the metal reaches thermal equilibrium with the environment (primarily via radiative lossses). If you wait long enough, you'd also see the ceramic reach thermal equilibrium but it would most likely do this via convection (heat loss to the air through the surface of the liquid rather than radiative losses from the ceramic to the air). <https://en.wikipedia.org/wiki/Heat_transfer>
Hope this helps! |
27,785,572 | I have a TableView with some TextFields in. The values of said TextFields are linked to certain positions in a 2D Array (NSArray of NSMutableArrays).
An initial clean array is defined as so:
```
self.cleanEditContents = @[
[@[@-1,@-1] mutableCopy],
[@[@0,@80] mutableCopy],
[@[@0,@500] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy],
[@[@-1,@-1] mutableCopy]
];
```
This array is supposed to be kept separate from the 'active' array, so that the active array can be reset on a button press.
I use `self.editContents = [self.cleanEditContents copy];` to set the active array both directly after the clean array is populated and on a button press.
There is a problem where even though I reset the array and call reloadData and setNeedsLayout (overkill? probably), the numbers don't reset. I tried outputting the values of the same position in both arrays and it turns out that any changes made to the active array contaminate the clean array. | 2015/01/05 | [
"https://Stackoverflow.com/questions/27785572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1375665/"
] | Assuming that you only need to support [old to recent browsers](http://caniuse.com/#feat=queryselector) (not everything back to IE 4) you can just use [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/document.querySelectorAll):
```
var buttons = document.querySelectorAll('.test-button-set button');
```
Alternatively, if you need to only get the buttons that are a descendent of the *first* `.test-button-set`:
```
var buttons = document.querySelector('.test-button-set').getElementsByTagName('button')
``` | If you want to accomplish the same outcome you're getting with your two lines of code without using querySelector/querySelectorAll (which is a great option but isn't supported in some older browsers), you could just chain your methods together to get them on one line rather than using a variable and breaking them up onto two:
```
document.getElementsByClassName("test-button-set")[0].getElementsByTagName("button")
``` |
32,896,845 | I have managed to create an algorithm to check the rank of a poker hand. It works 100% correctly, but it's very slow. I've been analysing the code, and the check straight function is one of the slowest parts of it.
So my question is, is there a better way of calculating whether a hand make a straight?
Here is some details:
7 cards, 2 from holder, 5 from board. A can be high or low.
Each card is assigned a value:
2 = 2
3 = 3
..
9 = 9
T = 10
J = 11
Q = 12
K = 13
A = 14
The script has an array of all 7 cards:
```
$cards = array(12,5,6,7,4,11,3);
```
So now I need to be able to sort this into an array where it:
* discards duplicates
* orders the card from lowest to highest
* only returns 5 consecutive cards I.e. (3,4,5,6,7)
It needs to be fast; loops and iterations are very costly. This is what I currently use and when it tries to analyse say 15000 hands, it takes its toll on the script.
For the above, I used:
* discard duplicates (use array\_unique)
* order cards from lowest to highest (use sort())
* only return 5 consecutive cards (use a for loop to check the values of cards)
Does anyone have any examples of how I could improve on this? Maybe even in another language that I could perhaps look at and see how it's done? | 2015/10/01 | [
"https://Stackoverflow.com/questions/32896845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3698723/"
] | Instead of working with array deduping and sorting, consider using a bitmask instead, and setting bits to 1 where the card value is set. A bitmask works like a Set datastructure and comes with additional advantages when it comes to detecting contiguous elements.
```
for ($i = 0; $i < count($cards); $i++) {
$card = $cards[$i];
// For each card value, set the bit
if ($card == 14) {
// If card is an ace, also set bit 1 for wheel
$cardBitmask |= 0x2;
}
$cardBitmask |= (1 << $card);
}
// To compare, you simply write a for loop checking for 5 consecutive bits
for($i = 10; $i > 0; $i--)
{
if ($cardBitmask & (0x1F << $i) == (0x1F << $i)) {
// Straight $i high was found!
}
}
``` | Consider the Java implementation at [this link](http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/10/pokerCheck.html). I've included it here:
```
public static boolean isStraight( Card[] h )
{
int i, testRank;
if ( h.length != 5 )
return(false);
sortByRank(h); // Sort the poker hand by the rank of each card
/* ===========================
Check if hand has an Ace
=========================== */
if ( h[4].rank() == 14 )
{
/* =================================
Check straight using an Ace
================================= */
boolean a = h[0].rank() == 2 && h[1].rank() == 3 &&
h[2].rank() == 4 && h[3].rank() == 5 ;
boolean b = h[0].rank() == 10 && h[1].rank() == 11 &&
h[2].rank() == 12 && h[3].rank() == 13 ;
return ( a || b );
}
else
{
/* ===========================================
General case: check for increasing values
=========================================== */
testRank = h[0].rank() + 1;
for ( i = 1; i < 5; i++ )
{
if ( h[i].rank() != testRank )
return(false); // Straight failed...
testRank++; // Next card in hand
}
return(true); // Straight found !
}
}
```
A quick Google search for "check for poker straight `(desired_lang)`" will give you other implementations. |
24,094,158 | In Swift, can someone explain how to override a property on a superclass's with another object subclassed from the original property?
Take this simple example:
```
class Chassis {}
class RacingChassis : Chassis {}
class Car {
let chassis = Chassis()
}
class RaceCar: Car {
override let chassis = RacingChassis() //Error here
}
```
This gives the error:
```
Cannot override with a stored property 'chassis'
```
If I have chassis as 'var' instead, I get the error:
```
Cannot override mutable property 'chassis' of type 'Chassis' with covariant type 'RacingChassis'
```
The only thing I could find in the guide under "Overriding Properties" indicates that we have to override the getter and setter, which may work for changing the value of the property (if it's 'var'), but what about changing the property class? | 2014/06/07 | [
"https://Stackoverflow.com/questions/24094158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559030/"
] | Depending on how you plan on using the property, the simplest way to do this is to use an optional type for your subclass, and override the `didSet {}` method for the super:
```
class Chassis { }
class RacingChassis: Chassis { }
class Car {
// Declare this an optional type, and do your
// due diligence to check that it's initialized
// where applicable
var chassis: Chassis?
}
class RaceCar: Car {
// The subclass is naturally an optional too
var racingChassis: RacingChassis?
override var chassis: Chassis {
didSet {
// using an optional, we try to set the type
racingChassis = chassis as? RacingChassis
}
}
}
```
Obviously you need to spend some time checking to ensure the classes can be initialized this way, but by setting the properties to optional, you protect yourself against situations where casting no longer works. | Simple using generics, e.g.
```
class Chassis {
required init() {}
}
class RacingChassis : Chassis {}
class Car<ChassisType : Chassis> {
var chassis = ChassisType()
}
let car = Car()
let racingCar = Car<RacingChassis>()
let c1 = car.chassis
let c2 = racingCar.chassis
print(c1) // Chassis
print(c2) // RacingChassis
```
Also, Chassis don't even need to be subclasses:
```
protocol Chassis {
init()
}
class CarChassis: Chassis{
required init() {
}
}
class RacingChassis : Chassis {
required init() {
}
}
class Car<ChassisType : Chassis> {
var chassis = ChassisType()
}
``` |
73,881,051 | I have an array of strings, and when the user enters a string with question marks replacing some characters, I want the program to return all words from the array that it could be.
```
possibleWords = ["Animal", "Basket", "Bridge", "Guitar", "Needle", "Office", "Orange"]
#and the user enters "O????e", the program would return "Office" and "Orange"
``` | 2022/09/28 | [
"https://Stackoverflow.com/questions/73881051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10849607/"
] | Try this in one line using list comprehension and `all()`:
```
possibleWords = ["Animal", "Basket", "Bridge", "Guitar", "Needle", "Office", "Orange"]
m = "O????e"
result = [i for i in possibleWords if all(k=='?' or j==k for j,k in zip(i,m))]
```
the output(`result`) will be:
```
In [4]: [i for i in possibleWords if all(k=='?' or j==k for j,k in zip(i,m))]
Out[4]: ['Office', 'Orange']
```
also you can read about `all()` [here](https://www.w3schools.com/python/ref_func_all.asp).
Note that this will not check the length of the words, I assume that the input length is equal to the all of items in the list. but if not, you can use `zip_logest` from `itertools` like this:
```
from itertools import zip_longest
result = [i for i in possibleWords if all(k=='?' or j==k for j,k in zip_longest(i,m))]
``` | The regex character you're looking for is ".", instead of "?". So by simple replacing the question marks with dots, you can use the regex module `re` to get your desired output:
```
import re
possibleWords = ["Animal", "Basket", "Bridge", "Guitar", "Needle", "Office", "Orange"]
entry = "O????e"
pattern = entry.replace("?", ".")
r = re.compile(pattern)
l = list(filter(r.match, possibleWords))
print(l)
```
Out:
```
['Office', 'Orange']
``` |
8,852,939 | I have a list of directories hard coded into my program as such:
```
import os
my_dirs = ["C:\a\foo"
,"C:\b\foo"
,"C:\c\foo"
,"C:\t\foo"
]
```
I later want to perform some operation like `os.path.isfile(my_dirs[3])`. But the string my\_dirs[3] is becoming messed up because `"\t"` is short for tab or something.
I know that a solution to this would be to use this:
```
my_dirs = ["C:\\a\\foo"
,"C:\\b\\foo"
,"C:\\c\\foo"
,"C:\\t\\foo"
]
```
And another solution would be to use forward slashes.
But I like being able to copy directories straight from explorer to my Python code. Is there any way I can tell Python not to turn `"\t"` into a tab or some other solution to my problem? | 2012/01/13 | [
"https://Stackoverflow.com/questions/8852939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/929195/"
] | I agree with Joel - that's how I handle it. A build script minifies the CSS (*and JS*) before each release is FTP'ed to production. I just have a switch in PHP like:
```
if ($config->prod()) {
// incldue the minfied css
} else {
// include all the original files
}
``` | Personnaly, I use an ant build script to make a production version:
1. it "condense" multiple css files in one
2. then it minify them with YUI compressor
3. same for scripts
4. (page recomposition to point to the newly generated files)
this way you divide your http request for those files, and gain some bandwith from 30% to 70% i'd say. depends on gzip also.
in my case, the dev version have:
18 css weighting 178ko
reduced down to 1 css at 96ko in the production version |
20,379,701 | I'm wondering if it's possible to filter logs by properties of passed arguments to a specific function. To be more specific, here's where I'm starting:
```dart
_dispatcher.getLogs(callsTo("dispatchEvent", new isInstanceOf<PinEvent>()));
```
I'd like to further filter this by PinEvent.property = "something"
In pseudo-code, I guess it'd look like this:
```dart
_dispatcher.getLogs(callsTo("dispatchEvent", new isInstanceOf<PinEvent>("property":"something")));
```
Any ideas? I know I can loop through the entire log list, but that seems dirty, and I would think there'd be a better way.
Thanks :-) | 2013/12/04 | [
"https://Stackoverflow.com/questions/20379701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954178/"
] | [This question](https://stackoverflow.com/questions/7343769/sql-server-2008-r2-intellisense-not-working) covers making sure it's enabled, which it sounds like it is (I'm linking it just in case). There also seems to be an installation issue with 2008 and Visual Studio 2010 (also mentioned in that link) sometimes, and [this question](https://dba.stackexchange.com/questions/6145/intellisense-not-working-but-it-is-enabled) covers that. We had the same issue on one of 2008 servers, and post an update, it finally worked (solution 2). | Apart from some very common reasons (which don't apply here, as you say it's not working only for some servers) listed here:
<http://msdn.microsoft.com/en-us/library/ks1ka3t6%28v=vs.90%29.aspx>
... did you happen to instal VS2010 lately? There's a bug that makes IntelliSense stop workingŁ
<http://support.microsoft.com/kb/2531482>
Also try to refresh IntelliSense cache after you connect to new server (SSMS): Edit>IntelliSense>RefreshLocalCache |
6,243,273 | Are there any tools that can generate classes from anonymous types?
I have a complex data structure that I have created using anonymous types. I would like to use this data structure in other places where the anonymous type would be out of scope. That's why I'm looking for such a code generation tool. | 2011/06/05 | [
"https://Stackoverflow.com/questions/6243273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64334/"
] | That's one of the [refactorings](http://www.jetbrains.com/resharper/webhelp/Refactorings__Convert_Anonymous_to_Named_Type.html) supported by [Resharper](http://www.jetbrains.com/resharper/). With nested anonymous types (where one anonymous type has properties of another anonymous type), you'll just have to convert the inner types before you get the option to convert the outer one. | [Resharper - Convert Anonymous to Named Type](https://www.jetbrains.com/resharper/webhelp/Refactorings__Convert_Anonymous_to_Named_Type.html)
>
> The Convert Anonymous to Named Type refactoring converts anonymous
> types to nested or top-level named types in the scope of either the
> current method (locally) or the whole solution (globally). In the
> dialog box that this refactoring provides, you can also specify
> whether ReSharper should generate auto-properties or properties with
> backing fields, and opt to generate equality and formatting method
> overrides.
> 
>
>
> |
221,434 | I'm trying to serve dynamically generated xml pages from a web server, and provide a custom, static, xslt from the same web server, that will offload the processing into the client web browser.
Until recently, I had this working fine in Firefox 2, 3, IE5, 6 and Chrome. Recently, though, something has changed, and Firefox 3 now displays just the text elements in the source.
The page source starts like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<!-- Firefox 2.0 and Internet Explorer 7 use simplistic feed sniffing to override desired presentation behavior for this feed, and thus we are obliged to insert this comment, a bit of a waste of bandwidth, unfortunately. This should ensure that the following stylesheet processing instruction is honored by these new browser versions. For some more background you might want to visit the following bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=338621 -->
<?xml-stylesheet type="text/xsl" href="/WebObjects/SantaPreview.woa/Contents/WebServerResources/Root.xsl"?>
<wrapper xmlns="http://www.bbc.co.uk/ContentInterface/Content" xmlns:cont="http://www.bbc.co.uk/ContentInterface/Content" sceneId="T2a_INDEX" serviceName="DSat_T2">
....
```
Firebug shows that the Root.xsl file is being loaded, and the response headers for it include the line
```
Content-Type text/xml
```
*I've also tried it with application/xml as the content type, but it makes no difference :-(*
The Web Developer Extension shows the correct generated source too, and if you save this and load the page in Firefox, it displays correctly.
The version of Firefox displaying the problem is 3.0.3
Any ideas what I might be doing wrong? | 2008/10/21 | [
"https://Stackoverflow.com/questions/221434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7938/"
] | Displaying just the text elements is the behavior you would get out of an empty XSL stylesheet.
To me, that suggests that something fishy is going on with your xpath expressions, and that the xsl:template/@match attributes do not match the source document.
You do not provide enough information to diagnose further, so this blind guess is all I can offer.
EDIT: It turned out the problem was that IE and Chrome silently accept a nodeset as argument to [string-length](http://www.w3.org/TR/xpath#function-string-length), while FF3 does not. Note that the specification mandates an optional string argument and does not specify behavior with a nodeset argument. | try serving it as application/xml instead of text/xml |
158,871 | This a follow up on the previous post that asked how strong graphene armor would be and the general conclusion is that we have no idea sadly. So in this post I will ask a more relevant question.
If we have made armor with advanced, light-weight carbon and ceramic based materials that can easily stop most bullets like 9mm and 5.56mm calibers that are used in military's and cover the majority of the human body. How does this affect infantry warfare and more specifically guns?
Will guns need to get bigger and stronger to compete, or something else entirely?
And for those who will point out that modern militaries do not cover the entirety of their soldier's body in armor due to weight, heat and comfort issues: Let's just say that the same advancements that made the armor in the first place also allowed the creation of cooling load bearing systems that are simple and rugged enough to be used in the field.
EDIT: I fixed the question and want to clarify on the "entirety" part: What I meant to say was that the soldier has more armor on person than modern militaries to protect the extremities, which is allowed by the lightweight nature of the carbon materials, the cooling capacities and 'minimal; load bearing systems. Meaning that there are gaps in the armour, albeit covered in a cloth that has carbon materials like CNT.
Sorry for any confusion. | 2019/10/20 | [
"https://worldbuilding.stackexchange.com/questions/158871",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/69795/"
] | In general:
* Strong armor/weak ranged weapons means **more close (up to hand-to-hand) combat**, shorter and more active battles, elite troops rules battlefield (less camo, but more colors and honor), relativly less casulties in battles (defeated prefer to run). It also means that **charge is stronger than equal number and quality defence**
* Strong ranged weapons/weak armor (like it is now) means less to no close combat, long (days) "hide-and-seek" battles, with a lot of sittig in trenches and covers, more total casulties (it is useless to run from artilery or bombardmends), constant stalemates (due to defence is times stronger than attack).
(had to mention - there are a lot of "transition states" between this two; more of this - less of that)
Particular in your case guns would become short-ranged but more powerfull. 20+ mm handguns (handcannons?) with explosive (commulative) load and with effective maximum range about 100-200 m (they had to be short to keep it weight low) would become practical.
If you think of bolters and marines from WH40K - you would be wrong. But there would be a lot of parallels. Elite heavy-armored troops with bolter-like cannons to fight each other on close range (*may be* with hand-to-hand weapons), and lot of "infantry" - no-armored, but heavy-armed with large "antitank" rifles to fight those troops from long range (but totaly useless at middle and close range).
War machines would remian almost the same (just less lowcaliber machinguns) - they are already capable to fight heavyarmored troops. | This is just a small partial answer, but in medieval times, a full plate was pretty much impenetrable. The thing is: only knights and nobleman could afford full plates, so most of the people in the battlefield would still be vulnerable to any weapon.
If full body armor capable of protecting against personal projectile weapons are ever developed, be assured that only a handful of very special soldiers would use it, as the cost of having a soldier killer would be likely smaller than the cost of armoring everyone. Those soldiers would be treated like tanks, and would be handled with either heavier mounted weapons, explosives or specially designed weapons, but by no means would make the good old assault rifle obsolete. |
279,569 | I need to delete a "~" folder in my home directory.
I realize now that `rm -R ~` is a bad choice.
Can I safely use `rm -R "~"`? | 2016/04/27 | [
"https://unix.stackexchange.com/questions/279569",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/162496/"
] | In theory yes. In practice usually also yes. If you're calling a shell script or alias that does something weird, then maybe no.
You could use `echo` to see what a particular command would be expanded to by the shell:
```
$ echo rm -R ~
rm -R /home/frostschutz
$ echo rm -R "~"
rm -R ~
```
Note that `echo` removes the `""` so you should not copy-paste what it prints. It just shows that if you give `"~"`, the command literally sees `~` and not the expanded `/home/frostschutz` path.
If you have any doubt about any command, how about starting out with something that is less lethal if it should go wrong? In your case you could start out with renaming instead of deleting it outright.
```
$ mv "~" delete-me
$ ls delete-me
# if everything is in order
$ rm -R delete-me
```
For confusing file names that normally shouldn't even exist (such as `~` and other names starting with `~` or , or containing newlines, etc.), it's better to be safe than sorry.
Also consider using tab completion (type `ls ~<TAB><TAB><TAB>`), most shells try their best to take care of you, this also helps avoid mistyping regular filenames. | In addition to frostschutz's double quotes method, and Andy's simple quote one, there are also the shorter:
```
rm -r \~
```
and the relative path one:
```
rm -rf ./~
``` |
82,389 | I am unable to run an installer with `.packproj` extension. I am unable to find anything via Web search.
Can these files be handled natively by macOS? How do I install a package with this extension? | 2013/02/16 | [
"https://apple.stackexchange.com/questions/82389",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/12543/"
] | `.packproj`-files were files used by developers in the process of application development for OS X 10.2. They contain xml-strings – try editing the file in TextEdit or TextWrangler, you should see an XML-structure, or see [this example](http://code.ohloh.net/file?fid=ntEBCQqv3JoMY44QlWDd6OSq1Ns&cid=w9EXGk1oh00&s=&browser=Default#L0).
It can't really be *run* alone, it's used to tell packaging applications how to pack the application into a real application.
To put it short, it can be used with the application [Iceberg](http://s.sudre.free.fr/Software/Iceberg.html):
>
> (.packproj): Creates a project file for use with Iceberg. This allows you to use Iceberg to edit package options before creating the actual package.
>
>
>
Do note that this is ancient code, and may not work (supposed to work from OS X 10.2 and up). | There is also the [Packages](http://s.sudre.free.fr/Software/Packages/about.html) tool. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.