qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
49,761,972 | Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways.
```
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases. | 2018/04/10 | [
"https://Stackoverflow.com/questions/49761972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191996/"
]
| The key thing to understand is that *the values of string enums are opaque*.
The intended use case for a string enum is that you don't want other code to know or care what the literal string backing `MyKeyType.FOO` is. This means that you won't be able to, say, pass the *literal string* `"bar"` to a function accepting a `MyKeyType` -- you'll have to write `MyKeyType.BAR` instead. | One benefit by using enum instead of string literal is that you can use it also in places that you don't declare the types.
for example -
```
assert.equal(result.keyType, KeyType.FOO)
``` |
49,761,972 | Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways.
```
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases. | 2018/04/10 | [
"https://Stackoverflow.com/questions/49761972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191996/"
]
| Well, there is a **difference** between string enums and literal types in the transpiled code.
Compare the **Typescript** Code
```
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
With the **transpiled JavaScript** Code
```
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
```
What you can see is, there is no generated code for the string literal. Because Typescripts Transpiler is only using for type safety while transpiling. At runtime string literals are "generated to dumb" strings. No references between the definition of the literal and the usages.
So there is a third alternative called **const enum**
Look at this
```
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
// or with a Const String Enum
const enum MyKeyType3 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
var a : MyKeyType1 = "bar"
var b: MyKeyType2 = MyKeyType2.BAR
var c: MyKeyType3 = MyKeyType3.BAR
```
will be transpiled to
```
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
var a = "bar";
var b = MyKeyType2.BAR;
var c = "bar" /* BAR */;
```
**For further playing you can check this [link](http://www.typescriptlang.org/play/index.html#src=%20%20%20%2F%2F%20with%20a%20String%20Literal%20Type%20%0D%0A%20%20%20type%20MyKeyType1%20%3D%20'foo'%20%7C%20'bar'%20%7C%20'baz'%3B%0D%0A%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20enum%20MyKeyType2%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20const%20enum%20MyKeyType3%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%7D%0D%0A%20%20%20%20%0D%0A%0D%0Avar%20a%20%3A%20MyKeyType1%20%3D%20%22bar%22%20%0D%0Avar%20b%3A%20MyKeyType2%20%3D%20MyKeyType2.BAR%0D%0Avar%20c%3A%20MyKeyType3%20%3D%20MyKeyType3.BAR%0D%0A%0D%0A)**
I prefer the const enum case, because of the convenient way of typing Enum.Value. Typescript will do the rest for me to get the highest performance when transpiling. | One benefit for an enum at development time is that you will see the list of options easily via intellisense:
[](https://i.stack.imgur.com/X3IJr.png)
Similarly, you could change an enum value easily using refactoring tools, instead of changing a string everywhere.
Edit: In VS 2017 and TypeScript >=3.2.4, intellisense works with string literal types:
[](https://i.stack.imgur.com/ZeRsx.png) |
49,761,972 | Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways.
```
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases. | 2018/04/10 | [
"https://Stackoverflow.com/questions/49761972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191996/"
]
| One benefit for an enum at development time is that you will see the list of options easily via intellisense:
[](https://i.stack.imgur.com/X3IJr.png)
Similarly, you could change an enum value easily using refactoring tools, instead of changing a string everywhere.
Edit: In VS 2017 and TypeScript >=3.2.4, intellisense works with string literal types:
[](https://i.stack.imgur.com/ZeRsx.png) | A big downside of enum is that if you use number instead of string, the entirely enum is not safety in my opinion: i can always assign any number value to a variable of this kind
```
enum TYPE {MAN = 1, WOMAN = 2, BOY = 3, GIRL = 4};
let foo: TYPE = TYPE.MAN;
foo = 37.14; //no problem for compiler
``` |
49,761,972 | Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways.
```
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases. | 2018/04/10 | [
"https://Stackoverflow.com/questions/49761972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191996/"
]
| One benefit for an enum at development time is that you will see the list of options easily via intellisense:
[](https://i.stack.imgur.com/X3IJr.png)
Similarly, you could change an enum value easily using refactoring tools, instead of changing a string everywhere.
Edit: In VS 2017 and TypeScript >=3.2.4, intellisense works with string literal types:
[](https://i.stack.imgur.com/ZeRsx.png) | One benefit by using enum instead of string literal is that you can use it also in places that you don't declare the types.
for example -
```
assert.equal(result.keyType, KeyType.FOO)
``` |
49,761,972 | Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways.
```
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases. | 2018/04/10 | [
"https://Stackoverflow.com/questions/49761972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191996/"
]
| Well, there is a **difference** between string enums and literal types in the transpiled code.
Compare the **Typescript** Code
```
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
With the **transpiled JavaScript** Code
```
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
```
What you can see is, there is no generated code for the string literal. Because Typescripts Transpiler is only using for type safety while transpiling. At runtime string literals are "generated to dumb" strings. No references between the definition of the literal and the usages.
So there is a third alternative called **const enum**
Look at this
```
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
// or with a Const String Enum
const enum MyKeyType3 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
var a : MyKeyType1 = "bar"
var b: MyKeyType2 = MyKeyType2.BAR
var c: MyKeyType3 = MyKeyType3.BAR
```
will be transpiled to
```
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
var a = "bar";
var b = MyKeyType2.BAR;
var c = "bar" /* BAR */;
```
**For further playing you can check this [link](http://www.typescriptlang.org/play/index.html#src=%20%20%20%2F%2F%20with%20a%20String%20Literal%20Type%20%0D%0A%20%20%20type%20MyKeyType1%20%3D%20'foo'%20%7C%20'bar'%20%7C%20'baz'%3B%0D%0A%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20enum%20MyKeyType2%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20const%20enum%20MyKeyType3%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%7D%0D%0A%20%20%20%20%0D%0A%0D%0Avar%20a%20%3A%20MyKeyType1%20%3D%20%22bar%22%20%0D%0Avar%20b%3A%20MyKeyType2%20%3D%20MyKeyType2.BAR%0D%0Avar%20c%3A%20MyKeyType3%20%3D%20MyKeyType3.BAR%0D%0A%0D%0A)**
I prefer the const enum case, because of the convenient way of typing Enum.Value. Typescript will do the rest for me to get the highest performance when transpiling. | A big downside of enum is that if you use number instead of string, the entirely enum is not safety in my opinion: i can always assign any number value to a variable of this kind
```
enum TYPE {MAN = 1, WOMAN = 2, BOY = 3, GIRL = 4};
let foo: TYPE = TYPE.MAN;
foo = 37.14; //no problem for compiler
``` |
49,761,972 | Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways.
```
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases. | 2018/04/10 | [
"https://Stackoverflow.com/questions/49761972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191996/"
]
| Well, there is a **difference** between string enums and literal types in the transpiled code.
Compare the **Typescript** Code
```
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
```
With the **transpiled JavaScript** Code
```
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
```
What you can see is, there is no generated code for the string literal. Because Typescripts Transpiler is only using for type safety while transpiling. At runtime string literals are "generated to dumb" strings. No references between the definition of the literal and the usages.
So there is a third alternative called **const enum**
Look at this
```
// with a String Literal Type
type MyKeyType1 = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType2 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
// or with a Const String Enum
const enum MyKeyType3 {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
var a : MyKeyType1 = "bar"
var b: MyKeyType2 = MyKeyType2.BAR
var c: MyKeyType3 = MyKeyType3.BAR
```
will be transpiled to
```
// or with a String Enum
var MyKeyType2;
(function (MyKeyType2) {
MyKeyType2["FOO"] = "foo";
MyKeyType2["BAR"] = "bar";
MyKeyType2["BAZ"] = "baz";
})(MyKeyType2 || (MyKeyType2 = {}));
var a = "bar";
var b = MyKeyType2.BAR;
var c = "bar" /* BAR */;
```
**For further playing you can check this [link](http://www.typescriptlang.org/play/index.html#src=%20%20%20%2F%2F%20with%20a%20String%20Literal%20Type%20%0D%0A%20%20%20type%20MyKeyType1%20%3D%20'foo'%20%7C%20'bar'%20%7C%20'baz'%3B%0D%0A%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20enum%20MyKeyType2%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20const%20enum%20MyKeyType3%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%7D%0D%0A%20%20%20%20%0D%0A%0D%0Avar%20a%20%3A%20MyKeyType1%20%3D%20%22bar%22%20%0D%0Avar%20b%3A%20MyKeyType2%20%3D%20MyKeyType2.BAR%0D%0Avar%20c%3A%20MyKeyType3%20%3D%20MyKeyType3.BAR%0D%0A%0D%0A)**
I prefer the const enum case, because of the convenient way of typing Enum.Value. Typescript will do the rest for me to get the highest performance when transpiling. | One benefit by using enum instead of string literal is that you can use it also in places that you don't declare the types.
for example -
```
assert.equal(result.keyType, KeyType.FOO)
``` |
39,722,669 | I have several text files where each line starts with a group code, and each data item is separated by pipe characters. There is a specific group that will sometimes have data, and sometimes have no data, and will therefore only have the group code and pipes. I am trying to remove these groups with no data, while keeping the ones that do have data.
For example, two lines in my file would look like:
```
A01|ABC|123|XYZ|
A05|123456789||
A05|||
A01|DEF|456|UVW|
A05|987654321||
A05|||
A08|SOMEDATA|
```
I want it to look like
```
A01|ABC|123|XYZ|
A05|123456789||
A01|DEF|456|UVW|
A05|987654321||
A08|SOMEDATA|
```
I have tried to use findstr, as below:
```
type MYFILE.txt | findstr /v "A05|||" > MYFILE.txt
```
however this is deleting everything from the file, rather than just lines containing A05||| | 2016/09/27 | [
"https://Stackoverflow.com/questions/39722669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4388475/"
]
| Try using another file:
```
FindStr/RV "^A05||" MyFile.txt>AnotherFile.txt
```
Then if needs be **del**ete **Myfile.txt** & **ren**ame **AnotherFile.txt MyFile.txt** | You are almost there, but there are two issues in your command line:
```
type MYFILE.txt | findstr /v "A05|||" > MYFILE.txt
```
1. The redirection `> MYFILE.txt` is applied to the entire command line, so when redirection is prepared, the (new) empty file `MYFILE.txt` is created first, then the command line is executed. To avoid that, redirect the output to another file and move this onto the original one afterwards.
2. The search string matches only lines beginning with `A05`, but not something like `A06|||`. To match such lines also, change the search string to `|||$` (`$` anchors the match to the end). In case the number of fields may vary, you could use this: `^[^|]*|*$` (meaning any number of characters other than `|` as group code, followed by any number of adjacent `|`; the `^` at the beginning anchors the match to the beginning of the line; together with the `$` that anchors the match to the end, it enforces the entire line to match the given pattern).
Hence the corrected command line looks like this:
```
type "MYFILE.txt" | findstr /V "|||$" > "MYFILE.txt.tmp" & move /Y "MYFILE.txt.tmp" "MYFILE.txt" > nul
```
Or, with the alternative search string for a variable number of fields:
```
type "MYFILE.txt" | findstr /V "^[^|]*|*$" > "MYFILE.txt.tmp" & move /Y "MYFILE.txt.tmp" "MYFILE.txt" > nul
```
The quotation marks around the file path/name are just inserted to yield a more general syntax, which does not fail even in case white-spaces or some other poisonous characters occur. |
63,211 | I am trying to run haproxy in front of tomcat on a Solaris x86 box, but I am getting intermittent failures. At seemingly random intervals, the request just hangs until haproxy times out the connection.
I thought maybe it was my app, but I've been able to reproduce it with the tomcat manager app, and hitting tomcat directly there is no problems at all.
Hitting it repeatedly with curl will cause the error within 10-15 tries
```
curl -ikL http://admin:admin@<my server>:81/manager/status
```
haproxy is running on port 81, tomcat on port 7000. haproxy returns a 504 gateway timeout to the client, and puts this into the log file:
```
Sep 7 21:39:53 localhost haproxy[16887]: xxx.xxx.xxx.xxx:65168 [07/Sep/2009:21:39:23.005] http_proxy http_proxy/tomcat7000 5/0/0/-1/30014 504 194 - - sHNN 0/0/0/0/0 0/0 "GET /manager/status HTTP/1.1"
```
Tomcat shows nothing, no error in the logs and no indication that the request ever makes it to the tomcat server. The request count is not incremented, the manager app only shows activity on one thread, serving up the manager app.
Here are my haproxy and tomcat connector settings, I've been playing with both a good deal trying to chase down the issue, so they may not be ideal, but they definitely don't seem like they should cause this error.
server.xml
```
<Connector
port="7000" protocol="HTTP/1.1"
enableLookups="false" maxKeepAliveRequests="1"
connectionLinger="10"
/>
```
haproxy config
```
global
log loghost local0
chroot /var/haproxy
listen http_proxy :81
mode http
log global
option httplog
option httpclose
clitimeout 150000
srvtimeout 30000
contimeout 3000
balance roundrobin
cookie SERVERID insert
server tomcat7000 127.0.0.1:7000 cookie server00 check inter 2000
``` | 2009/09/08 | [
"https://serverfault.com/questions/63211",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
]
| I suspect that your Tomcat is pausing for a full garbage collection, which is why it is not responding or logging anything. See [here](http://www.infoq.com/news/2010/04/cliff_click_gc_pauses/) for more information on this problem. | If you turn on the haproxy statistics server, the extra information may help you debug
* add "stats enable" to your "listen" section
* browse to [<http://your-proxy:81/haproxy?stats>](http://your-proxy:81/haproxy?stats) |
63,211 | I am trying to run haproxy in front of tomcat on a Solaris x86 box, but I am getting intermittent failures. At seemingly random intervals, the request just hangs until haproxy times out the connection.
I thought maybe it was my app, but I've been able to reproduce it with the tomcat manager app, and hitting tomcat directly there is no problems at all.
Hitting it repeatedly with curl will cause the error within 10-15 tries
```
curl -ikL http://admin:admin@<my server>:81/manager/status
```
haproxy is running on port 81, tomcat on port 7000. haproxy returns a 504 gateway timeout to the client, and puts this into the log file:
```
Sep 7 21:39:53 localhost haproxy[16887]: xxx.xxx.xxx.xxx:65168 [07/Sep/2009:21:39:23.005] http_proxy http_proxy/tomcat7000 5/0/0/-1/30014 504 194 - - sHNN 0/0/0/0/0 0/0 "GET /manager/status HTTP/1.1"
```
Tomcat shows nothing, no error in the logs and no indication that the request ever makes it to the tomcat server. The request count is not incremented, the manager app only shows activity on one thread, serving up the manager app.
Here are my haproxy and tomcat connector settings, I've been playing with both a good deal trying to chase down the issue, so they may not be ideal, but they definitely don't seem like they should cause this error.
server.xml
```
<Connector
port="7000" protocol="HTTP/1.1"
enableLookups="false" maxKeepAliveRequests="1"
connectionLinger="10"
/>
```
haproxy config
```
global
log loghost local0
chroot /var/haproxy
listen http_proxy :81
mode http
log global
option httplog
option httpclose
clitimeout 150000
srvtimeout 30000
contimeout 3000
balance roundrobin
cookie SERVERID insert
server tomcat7000 127.0.0.1:7000 cookie server00 check inter 2000
``` | 2009/09/08 | [
"https://serverfault.com/questions/63211",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
]
| I suspect that your Tomcat is pausing for a full garbage collection, which is why it is not responding or logging anything. See [here](http://www.infoq.com/news/2010/04/cliff_click_gc_pauses/) for more information on this problem. | Well, you should run tcpdump between haproxy and netcat to figure out what's happening. Haproxy says it did not get the response, which may be discuted, but it is clear it has connected and sent the request otherwise it could not be waiting for a header. The fact that tomcat does not see any incoming request is troubling, because at least I could have accepted a bug on haproxy causing it to timeout on responses, but here we're saying that tomcat has no reason to respond because it does not consider it got a request. Either there's a bug on tomcat itself, or something strange on your network (two servers on the same IP ?), because at least it should tell you that it received the connection and the request! Tcpdump will sort that out pretty easily. Also, what version of haproxy are you running on ? versions between 1.3.16 and 1.3.19 had several issues among which a random timeout occurring on the last packet of response (but here tomcat says it has not responded, but anyway it's better to have things fixed).
Willy |
64,873,395 | I have data like this
```
Name valuta price Type Type2
A USD 10 Acc 1
B USD 30 Acc 2
C SGD 20 Acc 3
D SGD 05 Acc 4
A SGD 35 Acc 1
C SGD 05 Acc 3
B USD 50 Rej 2
```
Grouping based on Name, valuta and type. (type2 always have a unique value based on name) and sum the price when have the same group condition, the last step is to order based the highest price followed by same group condition.
And after process (Group & Order), the output should be like this:
```
Name valuta price Type Type2
B USD 50 Rej 2
B USD 30 Acc 2
A SGD 35 Acc 1
A USD 10 Acc 1
C SGD 25 Acc 3
D SGD 05 Acc 4
```
I tried use cte because pipeline process design seems clear to me but the result is wrong.
```
WITH Cte_Process1 AS
(
SELECT
Name,
valuta,
SUM(price) AS price,
Type,
Type2
FROM table1
GROUP BY
Name,
valuta,
price,
Type,
Type2
)
SELECT * FROM Cte_Process1 ORDER BY price
``` | 2020/11/17 | [
"https://Stackoverflow.com/questions/64873395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10766911/"
]
| You can do it with `MAX()` window function in the `ORDER BY` clause:
```
select Name, valuta, sum(price) price, type, type2
from tablename
group by Name, valuta, type, type2
order by max(sum(price)) over (partition by Name) desc,
Name,
sum(price) desc
```
See the [demo](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=d5f1a11b024e3ad4af706cda9f84a8cb).
Results:
```
> Name | valuta | price | type | type2
> :--- | :----- | ----: | :--- | ----:
> B | USD | 50 | Rej | 2
> B | USD | 30 | Acc | 2
> A | SGD | 35 | Acc | 1
> A | USD | 10 | Acc | 1
> C | SGD | 25 | Acc | 3
> D | SGD | 5 | Acc | 4
``` | For the above question, following query will work: (Assume table name - data)
```sql
select Name , valuta , sum(price) as price , Type, Type2
from data
group by 1,2,4,5
order by sum(price) desc ;
``` |
64,873,395 | I have data like this
```
Name valuta price Type Type2
A USD 10 Acc 1
B USD 30 Acc 2
C SGD 20 Acc 3
D SGD 05 Acc 4
A SGD 35 Acc 1
C SGD 05 Acc 3
B USD 50 Rej 2
```
Grouping based on Name, valuta and type. (type2 always have a unique value based on name) and sum the price when have the same group condition, the last step is to order based the highest price followed by same group condition.
And after process (Group & Order), the output should be like this:
```
Name valuta price Type Type2
B USD 50 Rej 2
B USD 30 Acc 2
A SGD 35 Acc 1
A USD 10 Acc 1
C SGD 25 Acc 3
D SGD 05 Acc 4
```
I tried use cte because pipeline process design seems clear to me but the result is wrong.
```
WITH Cte_Process1 AS
(
SELECT
Name,
valuta,
SUM(price) AS price,
Type,
Type2
FROM table1
GROUP BY
Name,
valuta,
price,
Type,
Type2
)
SELECT * FROM Cte_Process1 ORDER BY price
``` | 2020/11/17 | [
"https://Stackoverflow.com/questions/64873395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10766911/"
]
| You can do it with `MAX()` window function in the `ORDER BY` clause:
```
select Name, valuta, sum(price) price, type, type2
from tablename
group by Name, valuta, type, type2
order by max(sum(price)) over (partition by Name) desc,
Name,
sum(price) desc
```
See the [demo](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=d5f1a11b024e3ad4af706cda9f84a8cb).
Results:
```
> Name | valuta | price | type | type2
> :--- | :----- | ----: | :--- | ----:
> B | USD | 50 | Rej | 2
> B | USD | 30 | Acc | 2
> A | SGD | 35 | Acc | 1
> A | USD | 10 | Acc | 1
> C | SGD | 25 | Acc | 3
> D | SGD | 5 | Acc | 4
``` | I know you said Type2 is unique based on Name, but you still need to include it in the GROUP BY (or else use a case statement to derive the value, or JOIN to a lookup table).
The following should give you the correct results.
```
SELECT Name, Valuta, SUM(Price), Type, Type2
FROM Table
GROUP BY Name, Valuta, Type, Type2
``` |
8,161 | I have converted an edge loop to a curve. The edge loop itself was fairly low poly. I want the curve to look smooth so I tried to increase the resolution of it but it looks exactly the same.

Is there a way I can get the curve to be a smooth interpolation of the edge loop?
**[blende file](http://www.pasteall.org/blend/28013)** | 2014/03/29 | [
"https://blender.stackexchange.com/questions/8161",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/1476/"
]
| This is because the converted curve is a *Poly* spline.
To convert it to a smoothly interpolated curve:
1. Convert it to a Bezier or NURBS spline in *3D view > Tool shelf > Curve Tools > Set Spline Type*:

2. Then convert all the Control Vertices to *Auto* (or something besides *vector*) by pressing `A`*> Select all* `V`*> Automatic*.
Now you can adjust the *Resolution* as desired to adjust the "smoothness":
 | After converting the mesh to a curve, go into edit mode, then in the Modeling section of the Tools tab, click on Smooth several times.
 |
18,653,163 | I have a project PROJECT\_A which contains mdf file database.
In the solution of this project I added one new project - PROJECT\_B.
My question is:Can I use .mdf file from PROJECT\_A in PROJECT\_B? | 2013/09/06 | [
"https://Stackoverflow.com/questions/18653163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281755/"
]
| You can add .mdf file as a [Link Reference](http://support.microsoft.com/kb/306234) to project B
Right click project B and then properties > Add Reference > Existing Item > Select the .mdf file and in the add button select `Add As Link` option. | Yes, you can use single .mdf file in multiple projects. However it is not recommended since it may cause 'access denied' error. It is also a bad practice. You should be using per .mdf file per project/application. |
53,924 | Preface this by saying I will be launching this script whether it be applescript or bash script with Alfred.app.
Sorry to be so blunt and unknowledgable but I need to run a couple lines of bash in an applescript. I think a simple bash script is capable but I do not know for sure. Here are the details (note that the commands should probably be different so if you have suggestions, please feel free to state them as they are probably correct):
I want the script to
1. `rm ~/Library/Vidalia/vidalia.conf'`
2. `unzip ~/Library/Vidalia/vidalia.conf.zip'`
3. launch Vidalia.app
Step below I do not believe is possible since the Vidalia.app is not scriptable and I don't want the applescript/bash script to be running until Vidalia quits... but if it's possible to implement without the script needing to stay open:
4) On quit of Vidalia.app `rm ~/Library/Vidalia/vidalia.conf`
Is this possible. I can use bash or applescript whatever is easiest for you guy's & gals to help me with. If I could get the first three steps to run I would be plenty happy! Thanks for your time and sorry for my lack of knowledge. Any tips or pointers are welcome.
Heck, I don't even know if those are the "proper" shell commands to use, they did the job but if they are "sound" I do not know.
Thank you for your time and patience.
**UPDATE - Question: How to move unzipped file into different directory?**
Okay I have one last question. How would I do this same sort of action, but I wanted to keep `vidalia.conf.zip` in another directory?
Say, for example, an external volume named `tor` - I moved into the mounted volume named `tor` with `pushd`, but when I go to extract the file with what I think should work `-d` I get the error that I `cannot create extraction directory`
Which is good because I don't want to replace the directory, just move what get's unzipped into the pre-existing directory. Yeah, I will probably have to remove the file already there depending on what I am doing so what I have looks like this...
```
pushd ~/Library/Vidalia/
rm vidalia.conf
popd
pushd /Volumes/tor
unzip vidalia.conf.zip -d ~/Library/Vidalia/
popd
```
I haven't quite tried this too much once I ran into the error with plain old `-d`. As I was typing this I realized that I had to be navigating directories more with `pushd` and then out with `popd`. Originally I just had lines 4 and 5 but added the top 3 to remove the `.conf` that currently is there ... if ... it is there...
Which bring me to one more question… Is it harmless to tell bash to remove a file that doesn't exist? I would have no idea where to even start with `if then` statements.
Lastly, can anyone recommend a good beginners intro to Bash book? I'd love to actually learn this stuff instead of just having to google and then turn around and bug you all. Thank you again for your help. You solved my earlier problem perfectly, I even learned a lot from the simple example (I think.)
Cheers! | 2012/06/17 | [
"https://apple.stackexchange.com/questions/53924",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/24084/"
]
| As @laaph mentioned, if you just want to run bash commands, use a bash script.
There are, however, a few issues with your commands.
Your script has to look like:
```
#!/bin/sh
pushd ~/Library/Vidalia
rm vidalia.conf
unzip vidalia.conf.zip
popd
open /Applications/Vidalia.app
```
If you didn't change to the correct directory, `unzip` would unzip the file into your home directory, or wherever you launched your script from.
There are ways to look for when an app quits, but in your case this seems useless, you're removing the `.conf` whenever you launch the script anyway. But if you really want that, you could simply do:
```
#!/bin/sh
pushd ~/Library/Vidalia
rm vidalia.conf
unzip vidalia.conf.zip
popd
open -W /Applications/Vidalia.app
pushd ~/Library/Vidalia
rm vidalia.conf
popd
```
(This would make the script wait until you close the app, and then it'd delete the configuration file. Again though, this is useless and redundant if you'll be only launching the app with the script.)
Also, you could try a simpler solution: I assume that what you want is just to have the same vidalia.conf whenever you start the program. If that's the case, try just making the `.conf` read-only. | What you have so far is exactly what you want, and to open a program, use "open", so your script will look like this:
```
rm ~/Library/Vidalia/vidalia.conf
unzip ~/Library/Vidalia/vidalia.conf.zip
open /Applications/Vidallia.app
```
There are all sorts of tricks to monitor if Vidalia is running or not, so if you were willing to leave the script running, you could delete the conf as well, and then have the script exit. And, as you say, this could be done (differently) in Applescript, Automator, or a million other ways. |
703,542 | I've been trying to figure out this integral via use of residues:
$$\int\_{-\infty}^{\infty} \displaystyle \frac{\cos{5x}}{x^4+1}dx$$
The usual semicircle contour wont work for this guy as the integrated is unbounded.
My idea came from a book I was reading on contour integration, where we let
$$f(z) = \displaystyle\frac{e^{(-5iz)}}{2(z^4+1)}+\displaystyle\frac{e^{(5iz)}}{2(z^4+1)}$$
And do the integral in the complex play as follows:
$\gamma\_{1}= \text{The contour taken to be the top half of the circle in the counter clockwise direction}$ This contour uses the second term in $f(z)$
$\gamma\_{2}= \text{The contour taken from $-R$ to $R$ on the real axis}$
$\gamma\_{3}= \text{The contour taken to be the bottom half of the circle in the clockwise direction}$ This uses the first term in $f(z)$.
In the end, the contours $\gamma\_{1}$ and $\gamma\_{3}$ are bounded and will tend to $0$ as $R$ goes to infinity, so that we're left with the two integrals that we want.
My issue now is that when computing residues..everything seems to be cancelling out and I'm getting $0$. Should I take different contour? I'm really not sure what I did wrong. | 2014/03/07 | [
"https://math.stackexchange.com/questions/703542",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/17243/"
]
| I've given the skeleton of my work below. Fill in any missing pieces and check your answer against mine.
Using $\gamma=[-R,R]\cup Re^{i[0,\pi]}$ and the simple poles at $\frac{1+i}{\sqrt2}$ and $\frac{-1+i}{\sqrt2}$ inside $\gamma$
$$
\begin{align}
\int\_{-\infty}^\infty\frac{\cos(5x)}{x^4+1}\mathrm{d}x
&=\mathrm{Re}\left(\int\_\gamma\frac{e^{i5z}}{z^4+1}\mathrm{d}z\right)\\
&=\mathrm{Re}\left(2\pi i\left(\left[\frac{e^{i5z}}{4z^3}\right]\_{z=\frac{1+i}{\sqrt2}}
+\left[\frac{e^{i5z}}{4z^3}\right]\_{z=\frac{-1+i}{\sqrt2}}\right)\right)\\
&=\mathrm{Re}\left(\frac{\pi}{2i}e^{-5/\sqrt2}\left(\frac{1+i}{\sqrt2}e^{i5/\sqrt2}
-\frac{1-i}{\sqrt2}e^{-i5/\sqrt2}
\right)\right)\\
&=\pi e^{-5/\sqrt2}\mathrm{Im}\left(\frac{1+i}{\sqrt2}e^{i5/\sqrt2}\right)\\
&=\pi e^{-5/\sqrt2}\mathrm{Im}\left(e^{i(5/\sqrt2+\pi/4)}\right)\\
&=\pi e^{-5/\sqrt2}\sin\left(\frac5{\sqrt2}+\frac\pi4\right)
\end{align}
$$
Mathematica 8 agrees numerically, but its closed form involves complex functions and looks nothing like what I have above. | No need to compute two different integrals. Note that $\cos 5x = \operatorname{Re} e^{5ix}$. Put
$$ f(z) = \frac{e^{5iz}}{z^4+1} $$
and integrate over the boundary of a half-disc in the upper half-plane. On the semi-circle $C\_R^+$:
$$
\left| \int\_{C\_R^+} \frac{e^{5iz}}{z^4+1} \right| \le \frac{1}{R^4-1} \cdot \pi R \to 0
$$
as $R \to \infty$ since $|e^{5iz}| \le 1$ in the upper half-plane. Compute the relevant residues and finish off by taking the real part. |
293,983 | I am looking for ways to make a mobile power supply for 10 units of MG996R servo motors, each of which can draw up to around 800 mA to 1 A and operate between 4.8 V to 7.2 V.
I have 12 Eneloop AA batteries (BK-3MCCA8BA), and from [Panasonic Eneloop BK-3MCC (4th gen) - where I can find maximum discharge current?](https://electronics.stackexchange.com/questions/123709/panasonic-eneloop-bk-3mcc-4th-gen-where-i-can-find-maximum-discharge-current), I gathered that each of my Eneloop AA battery can discharge up to 6 A, which means that I should be able to power up to 6 MG996R's with a 4 or 6 AA battery pack.
This appears to agree with my setup where I am trying to control the 10 servo motors using the Adafruit 16-channel 12-bit PWM driver with a 1000 uF capacitor.
Once I begin to control over 5 servo motors, I get jitters, which I assume is due to the insufficient current.
However, I also read at [How do I determine the maximum amp output of a battery pack?](https://electronics.stackexchange.com/questions/61939/how-do-i-determine-the-maximum-amp-output-of-a-battery-pack) that I can model the batteries as a Thevenin-equivalent circuit, where the current is V\_Th/R\_Th. If I had 4 1.2 V AA batteries in series and assumed an individual internal resistance of 100 mOhms, I should be getting 4.8 V/ 0.4 ohms= 12 A.
This current should be sufficient for 10 of my servo motors? However, this is not the case.
What am I missing here? Also, could I put 2 packs of 6 AA battery holders in parallel to provide sufficient current? | 2017/03/22 | [
"https://electronics.stackexchange.com/questions/293983",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/142940/"
]
| This one is really clear, surprisingly clear in fact ... downright enlightened. That additional wording that MicroChip put in ... "true ..." makes it a very safe bet that you can perform whatever routing function through that pin you wish to ease your layout. The only caveat is not to put a sensitive net through the pin, since it will add parasitics (a handful of pF) if it matters.
Alternate wordings would be "DNC" for do not connect, which is a command, not a suggestion. or "Reserved" where you must fear for your life if you ever connect that pin incorrectly.
I've been reading data sheets since the '70s and they have not been better or worse across time. This one is very clear.
To convince yourself, put your meter on the highest resistance range to each pin in turn. Checking that it declares over-range. Make sure that you perform each measurement with both polarities of the meter. Most meters use a one-polarity source, often ramping in a triangle, so they read differently each way and a diode will fool you. | NC or 'No connect' usually means 'Not connected', unless the datasheet says otherwise.
DNC or 'DO NOT CONNECT' means do not connect for any reason. (and is could be a factor pin used for manufacturing, or other purposes) |
8,700,063 | This is an interview question: Design a data structure to perform the following operation efficiently: `boolean isPrefix(String s1, String s2)`.
I guess we can create a `multimap`, which maps prefixes to their strings. For instance,
```
strings: "aa", "ab", "abc", "ba", "ca"
multimap: "a" -> ["aa", "ab", "abc"]
"aa" -> ["aa"]
"ab" -> ["ab", "abc"]
"abc" -> ["abc"]
"ba" -> ["ba"]
"ca" -> ["ca"]
```
Which data structure would you propose ? | 2012/01/02 | [
"https://Stackoverflow.com/questions/8700063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521070/"
]
| The trie data structure would seem like an obvious answer, but the problem as stated doesn't require an advanced data structure. A simple string comparison will suffice and would be very fast. Ultimately, if you want to validate that one string is a prefix of another, you will have to compare every character at corresponding positions. No data structure eliminates the need for the character-by-character comparison.
That being said, if you're *searching* for the prefix in a large body of text, there are other techniques such as [Rabin-Karp probablistic string matching](http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm). | The most effective storage for prefix information is probably the [trie](http://en.wikipedia.org/wiki/Trie).
In this, the strings correspond to nodes in a tree where one string has another as a prefix exactly when its node is below the other in the tree. |
58,710,504 | Opencart generates its sitemap on the fly and this is a problem in a big catalogs over 10.000 products. So I have modified the function to generate a static sitemap in an XML file.
When I access to my <http://localhost/index.php?route=extension/feed/google_sitemap> I generate a sitemap-google.xml file without problems and with a unlimited execution time.
I tried to add it in a cron in the development server each 4 hours
```
0 0,4,8,12,16,20 /usr/bin/php /path/to/index.php?route=extension/feed/google_sitemap
```
But I'm receiving a "command not found".
Can I execute on cli the "?params/etc"? | 2019/11/05 | [
"https://Stackoverflow.com/questions/58710504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9417576/"
]
| Reflection is based on the assembly’s *metadata*. What you seem to want would need to involve some kind of *source code* inspection to figure out all the concrete generic types created at runtime. Possible? Yes, the compiler does it, but not with reflection. | This is not what you're after but you could go a level deeper and get all methods of all types and collect all return types and the types of all arguments.
Just to be clear, this is nothing close to code analysis that your task requires. This just gives your a little bit more info. |
69,031,724 | This is the code I usually write:
```
alignas(16) __m128 myBuffer[8];
```
But maybe (since the object-array is 128\*8 bit = 128 byte) I should write:
```
alignas(128) __m128 myBuffer[8];
```
Or, "since the first 16 byte are aligned" in the first example, the rest will be automatically aligned in memory? | 2021/09/02 | [
"https://Stackoverflow.com/questions/69031724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/365251/"
]
| 128-bit SIMD data types must be aligned on 16 bytes. The compiler already knows that, so it's not needed to align `__m128` manually. See for example, [MSVC docs on `__m128`](https://learn.microsoft.com/en-us/cpp/cpp/m128?view=msvc-160):
>
> Variables of type `__m128` are automatically aligned on 16-byte boundaries.
>
>
>
Also, arrays are contiguous. Each array element is naturally aligned the same as the first one. There's no need to multiply the alignment for arrays.
So you need not bother with `alignas` at all:
```
__m128 myBuffer[8];
```
This will just work. | >
> is correct to use alignas(16) for an array[8] of m128?
>
>
>
It's not technically wrong, but according to documentation `__m128` is aligned to 16 bytes, so it's unnecessary to use `alignas`.
>
> But maybe ... I should write: `alignas(128)`
>
>
>
If your goal is to align to 128 bytes, then you can achieve it like that.
>
> Or "since the first 16 byte are aligned" in the first example, the rest will be automatically aligned in memory?
>
>
>
This question confuses me. If the integer is aligned, then the first byte is aligned. Rest of the bytes are offset from the first byte. In case the size is larger than alignment, some of the subsequent bytes would be aligned at offsets equal to the alignment.
---
Note that there is no `__m128` in standard C++. |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| There seems to be a known bug with Android - <http://code.google.com/p/android/issues/detail?id=17535> | According to this:
<http://developer.android.com/reference/android/webkit/WebView.html#loadUrl(java.lang.String>) the method remains.
I think the problem is with the path to the assets... |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| Yes, this is a known bug, even in ICS.
Google don't feel like fixing it.
<http://code.google.com/p/android/issues/detail?id=17535> | According to this:
<http://developer.android.com/reference/android/webkit/WebView.html#loadUrl(java.lang.String>) the method remains.
I think the problem is with the path to the assets... |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| This is a well known bug:
<http://code.google.com/p/android/issues/detail?id=17535>
You can find a workaround for Honeycomb and ICS here:
<http://bricolsoftconsulting.com/fixing-the-broken-honeycomb-and-ics-webview/> | According to this:
<http://developer.android.com/reference/android/webkit/WebView.html#loadUrl(java.lang.String>) the method remains.
I think the problem is with the path to the assets... |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| you have to do like this
```
String data = "<html><body><img src='your source url' width='1000' Height='1000'></body></html>";
wbView.loadData(data, "text/html", null);
```
this solves my problem . I checked it in android 4.0,4.1,4.2 works great, hope it solves your problem . | According to this:
<http://developer.android.com/reference/android/webkit/WebView.html#loadUrl(java.lang.String>) the method remains.
I think the problem is with the path to the assets... |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| Yes, this is a known bug, even in ICS.
Google don't feel like fixing it.
<http://code.google.com/p/android/issues/detail?id=17535> | There seems to be a known bug with Android - <http://code.google.com/p/android/issues/detail?id=17535> |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| Yes, this is a known bug, even in ICS.
Google don't feel like fixing it.
<http://code.google.com/p/android/issues/detail?id=17535> | This is a well known bug:
<http://code.google.com/p/android/issues/detail?id=17535>
You can find a workaround for Honeycomb and ICS here:
<http://bricolsoftconsulting.com/fixing-the-broken-honeycomb-and-ics-webview/> |
8,644,259 | I need to know, in android sdk 4.0
the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc.
```
mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht);
```
Is there any other way to send query string with url in android webview? | 2011/12/27 | [
"https://Stackoverflow.com/questions/8644259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761132/"
]
| Yes, this is a known bug, even in ICS.
Google don't feel like fixing it.
<http://code.google.com/p/android/issues/detail?id=17535> | you have to do like this
```
String data = "<html><body><img src='your source url' width='1000' Height='1000'></body></html>";
wbView.loadData(data, "text/html", null);
```
this solves my problem . I checked it in android 4.0,4.1,4.2 works great, hope it solves your problem . |
17,895,602 | I'm using asp.net web service .asmx to transport json data. I have following code which seems not to be working.
```
$.ajax({
type: "POST",
url: "../../App_Code/jsonWebService/getValue",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (output) {
alert(output);
$(config.captchaQuestion).html(output[0] + " + " + output[1] + " =");
$(config.captchaHidden).val(output[2]);
}
});
```
And my code inside jsonWebService.cs of asmx file is:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for jsonWebService
// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class jsonWebService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Array getValue()
{
Random getRandom = new Random();
int rand1 = getRandom.Next(0, 9);
int rand2 = getRandom.Next(0, 9);
int sum = rand1 + rand2;
int[] jsonObject = new int[3] { rand1, rand2, sum };
return jsonObject;
}
}
```
And I'm getting Forbidden error 403. Thanks in advance. | 2013/07/27 | [
"https://Stackoverflow.com/questions/17895602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1834764/"
]
| you need to convert your text into array first, because what your doing right now includes a `,` in your regexp pattern
```
$stop_ips_masks = file_get_contents('array.txt');
$stop_ips_masks = explode("," $stop_ips_masks);
```
You might also need to do a trim operation and remove the newlines as well. it would be easier if you stick to one record separator. like comma or newline. not both.
If you remove the `,` from your text file then you can do
```
$stop_ips_masks = file('array.txt');
``` | I believe your issue is the quotes and tailing comma. While needed to make a array in php they are invalid when sourced from the file.
```
$stop_ips_masks = file('array.txt', FILE_IGNORE_NEWLINES);
foreach ( $stop_ips_masks as $k=>$v )
{
$v = trim(rtrim($v, ","), '"');
if ( preg_match( '#^'.$v.'$#', $_SERVER['REMOTE_ADDR']) )
echo found;
}
``` |
17,895,602 | I'm using asp.net web service .asmx to transport json data. I have following code which seems not to be working.
```
$.ajax({
type: "POST",
url: "../../App_Code/jsonWebService/getValue",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (output) {
alert(output);
$(config.captchaQuestion).html(output[0] + " + " + output[1] + " =");
$(config.captchaHidden).val(output[2]);
}
});
```
And my code inside jsonWebService.cs of asmx file is:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for jsonWebService
// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class jsonWebService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Array getValue()
{
Random getRandom = new Random();
int rand1 = getRandom.Next(0, 9);
int rand2 = getRandom.Next(0, 9);
int sum = rand1 + rand2;
int[] jsonObject = new int[3] { rand1, rand2, sum };
return jsonObject;
}
}
```
And I'm getting Forbidden error 403. Thanks in advance. | 2013/07/27 | [
"https://Stackoverflow.com/questions/17895602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1834764/"
]
| you need to convert your text into array first, because what your doing right now includes a `,` in your regexp pattern
```
$stop_ips_masks = file_get_contents('array.txt');
$stop_ips_masks = explode("," $stop_ips_masks);
```
You might also need to do a trim operation and remove the newlines as well. it would be easier if you stick to one record separator. like comma or newline. not both.
If you remove the `,` from your text file then you can do
```
$stop_ips_masks = file('array.txt');
``` | Another option is to store your strings "raw" in the file as lines:
```
66\.249\.[6-9][0-9]\.[0-9]+
74\.125\.[0-9]+\.[0-9]+
```
Then read the file, putting each line into the array:
```
$array = file('array.txt');
``` |
17,895,602 | I'm using asp.net web service .asmx to transport json data. I have following code which seems not to be working.
```
$.ajax({
type: "POST",
url: "../../App_Code/jsonWebService/getValue",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (output) {
alert(output);
$(config.captchaQuestion).html(output[0] + " + " + output[1] + " =");
$(config.captchaHidden).val(output[2]);
}
});
```
And my code inside jsonWebService.cs of asmx file is:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for jsonWebService
// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class jsonWebService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Array getValue()
{
Random getRandom = new Random();
int rand1 = getRandom.Next(0, 9);
int rand2 = getRandom.Next(0, 9);
int sum = rand1 + rand2;
int[] jsonObject = new int[3] { rand1, rand2, sum };
return jsonObject;
}
}
```
And I'm getting Forbidden error 403. Thanks in advance. | 2013/07/27 | [
"https://Stackoverflow.com/questions/17895602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1834764/"
]
| you need to convert your text into array first, because what your doing right now includes a `,` in your regexp pattern
```
$stop_ips_masks = file_get_contents('array.txt');
$stop_ips_masks = explode("," $stop_ips_masks);
```
You might also need to do a trim operation and remove the newlines as well. it would be easier if you stick to one record separator. like comma or newline. not both.
If you remove the `,` from your text file then you can do
```
$stop_ips_masks = file('array.txt');
``` | Try something like;
```
<?
$file = file('array.txt');
$stop_ips_masks = explode(",",$file);
foreach ( $stop_ips_masks as $k=>$v )
{
if ( preg_match( '#^'.$v.'$#', $_SERVER['REMOTE_ADDR']) )
echo found;
}
?>
``` |
18,889,688 | I'm trying to test a `HttpServletRequest` and for that I have used [Mockito](http://code.google.com/p/mockito/) as follow:
```
HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
```
now before putting the http-request in `assert` methods I just want to build a simple http header as below without starting a real server:
```
x-real-ip:127.0.0.1
host:example.com
x-forwarded-for:127.0.0.1
accept-language:en-US,en;q=0.8
cookie:JSESSIONID=<session_ID>
```
can some one help how can I build such a test header? thanks. | 2013/09/19 | [
"https://Stackoverflow.com/questions/18889688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277740/"
]
| You can just stub the calls to request.getHeaders etc. or if you can add a dependency, [Spring-test](http://mvnrepository.com/artifact/org.springframework/spring-test/3.2.0.RELEASE) has a `MockHttpServletRequest` that you could use (see [here](http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html#mock-objects-servlet))
```
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("x-real-ip","127.0.0.1");
```
Or you could build your own implementation which allows you to set headers. | The above answer uses `MockHttpServletRequest`.
If one would like to use `Mockito.mock(HttpServletRequest.class)` , then could stub the request as follows.
```
final HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getHeader("host")).thenReturn("stackoverflow.com");
when(request.getHeader("x-real-ip")).thenReturn("127.0.0.1");
``` |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| You should be able to use [holdReady](http://api.jquery.com/jQuery.holdReady/) to do this. As long as it is included before your ready events, you can run your own code and then trigger the other ready events. | You can execute the logging start code in DOMReady and other initialization in load. Or you could make your own initialization manager which calls your logging start code first and then all other initialization callbacks (provided that those are registered with your manager and not jQuery, unless you want to hack jQuery and extract them from there, which I don't advise). |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| `document.ready()` callbacks are called in the order they were registered. If you register your testing callback first, it will be called first.
Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other `document.ready()` callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until `document.ready()`.
Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to `document.ready()` that when passed and set to `true` indicated to call that function first or you could add a new method `document.readyFirst()` that would call your function first. This would involve minor changes to the `document.ready()` processing code in jQuery. | You can execute the logging start code in DOMReady and other initialization in load. Or you could make your own initialization manager which calls your logging start code first and then all other initialization callbacks (provided that those are registered with your manager and not jQuery, unless you want to hack jQuery and extract them from there, which I don't advise). |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| As @jfriend00 mention that `ready callbacks are called in the order they were registered.`
So even if this code block called on the beginning, you can set another callback in it so it'll be executed on endmost.
```js
jQuery(document).ready(function(){
jQuery(document).ready(function(){
// This block will be executed after all ready calls.
});
});
``` | You can execute the logging start code in DOMReady and other initialization in load. Or you could make your own initialization manager which calls your logging start code first and then all other initialization callbacks (provided that those are registered with your manager and not jQuery, unless you want to hack jQuery and extract them from there, which I don't advise). |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| I was trying to do something similar, I was loading a bunch of polyfills that had .ready() functions, but I also had my own .ready()s on page that I needed executed first, though the polyfills were loaded in the header.
I found a nice way around it by having a .ready() very early on (right after jQuery loads) that executes functions from an array. Because it's very early in the source code it's .ready() is executed first. Further down the page I can add functions to the array and, so they all execute before any other .ready()s.
I've wrapped it up in a .beforeReady() function and put it on GitHub as jQuery-Before-Ready for anyone that is interested.
<https://github.com/aim12340/jQuery-Before-Ready> | You can execute the logging start code in DOMReady and other initialization in load. Or you could make your own initialization manager which calls your logging start code first and then all other initialization callbacks (provided that those are registered with your manager and not jQuery, unless you want to hack jQuery and extract them from there, which I don't advise). |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| `document.ready()` callbacks are called in the order they were registered. If you register your testing callback first, it will be called first.
Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other `document.ready()` callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until `document.ready()`.
Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to `document.ready()` that when passed and set to `true` indicated to call that function first or you could add a new method `document.readyFirst()` that would call your function first. This would involve minor changes to the `document.ready()` processing code in jQuery. | You should be able to use [holdReady](http://api.jquery.com/jQuery.holdReady/) to do this. As long as it is included before your ready events, you can run your own code and then trigger the other ready events. |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| As @jfriend00 mention that `ready callbacks are called in the order they were registered.`
So even if this code block called on the beginning, you can set another callback in it so it'll be executed on endmost.
```js
jQuery(document).ready(function(){
jQuery(document).ready(function(){
// This block will be executed after all ready calls.
});
});
``` | You should be able to use [holdReady](http://api.jquery.com/jQuery.holdReady/) to do this. As long as it is included before your ready events, you can run your own code and then trigger the other ready events. |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| You should be able to use [holdReady](http://api.jquery.com/jQuery.holdReady/) to do this. As long as it is included before your ready events, you can run your own code and then trigger the other ready events. | I was trying to do something similar, I was loading a bunch of polyfills that had .ready() functions, but I also had my own .ready()s on page that I needed executed first, though the polyfills were loaded in the header.
I found a nice way around it by having a .ready() very early on (right after jQuery loads) that executes functions from an array. Because it's very early in the source code it's .ready() is executed first. Further down the page I can add functions to the array and, so they all execute before any other .ready()s.
I've wrapped it up in a .beforeReady() function and put it on GitHub as jQuery-Before-Ready for anyone that is interested.
<https://github.com/aim12340/jQuery-Before-Ready> |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| `document.ready()` callbacks are called in the order they were registered. If you register your testing callback first, it will be called first.
Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other `document.ready()` callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until `document.ready()`.
Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to `document.ready()` that when passed and set to `true` indicated to call that function first or you could add a new method `document.readyFirst()` that would call your function first. This would involve minor changes to the `document.ready()` processing code in jQuery. | As @jfriend00 mention that `ready callbacks are called in the order they were registered.`
So even if this code block called on the beginning, you can set another callback in it so it'll be executed on endmost.
```js
jQuery(document).ready(function(){
jQuery(document).ready(function(){
// This block will be executed after all ready calls.
});
});
``` |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| `document.ready()` callbacks are called in the order they were registered. If you register your testing callback first, it will be called first.
Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other `document.ready()` callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until `document.ready()`.
Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to `document.ready()` that when passed and set to `true` indicated to call that function first or you could add a new method `document.readyFirst()` that would call your function first. This would involve minor changes to the `document.ready()` processing code in jQuery. | I was trying to do something similar, I was loading a bunch of polyfills that had .ready() functions, but I also had my own .ready()s on page that I needed executed first, though the polyfills were loaded in the header.
I found a nice way around it by having a .ready() very early on (right after jQuery loads) that executes functions from an array. Because it's very early in the source code it's .ready() is executed first. Further down the page I can add functions to the array and, so they all execute before any other .ready()s.
I've wrapped it up in a .beforeReady() function and put it on GitHub as jQuery-Before-Ready for anyone that is interested.
<https://github.com/aim12340/jQuery-Before-Ready> |
10,883,786 | I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?
Background:
I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803923/"
]
| As @jfriend00 mention that `ready callbacks are called in the order they were registered.`
So even if this code block called on the beginning, you can set another callback in it so it'll be executed on endmost.
```js
jQuery(document).ready(function(){
jQuery(document).ready(function(){
// This block will be executed after all ready calls.
});
});
``` | I was trying to do something similar, I was loading a bunch of polyfills that had .ready() functions, but I also had my own .ready()s on page that I needed executed first, though the polyfills were loaded in the header.
I found a nice way around it by having a .ready() very early on (right after jQuery loads) that executes functions from an array. Because it's very early in the source code it's .ready() is executed first. Further down the page I can add functions to the array and, so they all execute before any other .ready()s.
I've wrapped it up in a .beforeReady() function and put it on GitHub as jQuery-Before-Ready for anyone that is interested.
<https://github.com/aim12340/jQuery-Before-Ready> |
46,619,261 | I want to send a message to websocket from `java` code.
This is configuration class for `websockets`
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private WebSocketHandler handler;
public WebSocketConfig(WebSocketHandler handler) {
this.handler = handler;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(this.handler, "/ws");
}
}
```
This is `websocket` handler
```
@Component
public class WebSocketHandler extends TextWebSocketHandler {
private static final Logger LOGGER = JavaLogUtils.getLogger();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
LOGGER.info(" Server >>>> {}", message);
session.sendMessage(message);
}
}
```
When I send message from `html` page via `javascript` like this
```
$(function(){
var connection = new WebSocket('ws://localhost:8080/ws');
connection.onopen = function () {
console.log('Connected...');
};
connection.onmessage = function(event){
console.log('>>>>> ' + event.data);
var json = JSON.parse(event.data);
$("#output").append("<span><strong>" + json.user + "</strong>: <em>" + json.message +"</em></span><br/>");
};
connection.onclose = function(event){
$("#output").append("<p class=\"text-uppercase\"><strong>CONNECTION: CLOSED</strong></p>");
};
$("#send").click(function(){
var message = {}
message["user"] = $("#user").val();
message["message"] = $("#message").val();
connection.send(JSON.stringify(message));
});
});
```
It works fine. But when I try to send the message from `java client` it fails
```
@SpringBootApplication
@ComponentScan("com.lapots.breed.platform.cloud.boot")
@EnableJpaRepositories("com.lapots.breed.platform.cloud.boot.repository")
@EntityScan("com.lapots.breed.platform.cloud.boot.domain")
@EnableAspectJAutoProxy
@EnableJms
public class JavaCloudSampleApplication {
public static void main(String[] args) {
SpringApplication.run(JavaCloudSampleApplication.class, args);
}
@Bean
public CommandLineRunner welcomeSocketMessage(WebSocketHandler handler) throws URISyntaxException {
return args -> {
StandardWebSocketClient client = new StandardWebSocketClient();
ListenableFuture<WebSocketSession> future = client.doHandshake(handler,
new WebSocketHttpHeaders(),
new URI("ws://localhost:8080/ws"));
WebSocketSession session = future.get();
WebSocketMessage<String> message = new TextMessage("Hello from Spring");
session.sendMessage(message);
};
}
}
```
and I get this error
```
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:272) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:236) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:386) [surefire-booter-2.20.jar:2.20]
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:323) [surefire-booter-2.20.jar:2.20]
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:143) [surefire-booter-2.20.jar:2.20]
Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
... 26 common frames omitted
Caused by: java.util.concurrent.ExecutionException: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:1.8.0_121]
at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[na:1.8.0_121]
at com.lapots.breed.platform.cloud.boot.JavaCloudSampleApplication.lambda$welcomeSocketMessage$4(JavaCloudSampleApplication.java:76) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
... 32 common frames omitted
Caused by: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:395) ~[tomcat-embed-websocket-8.5.16.jar:8.5.16]
at org.springframework.web.socket.client.standard.StandardWebSocketClient$1.call(StandardWebSocketClient.java:150) ~[spring-websocket-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.socket.client.standard.StandardWebSocketClient$1.call(StandardWebSocketClient.java:147) ~[spring-websocket-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_121]
Caused by: java.util.concurrent.ExecutionException: java.io.IOException: The remote computer refused the network connection.
at sun.nio.ch.PendingFuture.get(PendingFuture.java:202) ~[na:1.8.0_121]
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:336) ~[tomcat-embed-websocket-8.5.16.jar:8.5.16]
... 4 common frames omitted
Caused by: java.io.IOException: The remote computer refused the network connection.
at sun.nio.ch.Iocp.translateErrorToIOException(Iocp.java:309) ~[na:1.8.0_121]
at sun.nio.ch.Iocp.access$700(Iocp.java:46) ~[na:1.8.0_121]
at sun.nio.ch.Iocp$EventHandlerTask.run(Iocp.java:399) ~[na:1.8.0_121]
... 1 common frames omitted
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.071 s <<< FAILURE! - in com.lapots.breed.platform.cloud.boot.app.JavaCloudSampleApplicationTests
[ERROR] contextLoads(com.lapots.breed.platform.cloud.boot.app.JavaCloudSampleApplicationTests) Time elapsed: 0 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner
Caused by: java.util.concurrent.ExecutionException: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
Caused by: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
Caused by: java.util.concurrent.ExecutionException:
java.io.IOException: The remote computer refused the network connection.
Caused by: java.io.IOException:
The remote computer refused the network connection.
``` | 2017/10/07 | [
"https://Stackoverflow.com/questions/46619261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432980/"
]
| A bit late but if you're using API 21+, you can set the secondary progress tint to be transparent:
```
android:secondaryProgressTint="@android:color/transparent"
``` | I was facing the same issue too. I figured it out. The drawable at 1 index changes that shadow color. You can set it to the much lighter color of your actual filled star color.
```
RatingBar ratingBar = footer.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(0).setColorFilter(Color.parseColor("#b0b0b0"), PorterDuff.Mode.SRC_ATOP);
stars.getDrawable(1).setColorFilter(Color.parseColor("#fff9ee"), PorterDuff.Mode.SRC_ATOP);// This line changes the color of the shadow under the stars
stars.getDrawable(2).setColorFilter(Color.parseColor("#FEBE55"), PorterDuff.Mode.SRC_ATOP);
ratingBar.setProgressDrawable(stars);
``` |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| Don't forget that aircraft size and link capacity are only loosely related, because it also depends on how many flights there are.
For example in case of Prague, I counted 6 departures to Frakfurt and 7 to Amsterdam a day, while only 2 to Dubai (the Emirates B77W and one SmartWings B738). So while the flights to Frankfurt and Amsterdam are all smaller planes (A319, A320, A321, to AMS some are even just E190), the capacity to both those destination is about double that to Dubai.
For the closer hubs, it makes more sense to fly smaller planes more often, because it can be more easily scaled (e.g. swapping A320 for A321; they don't even have to change the crew for that) and because it allows shorter transfer times, which the passengers obviously prefer.
However Dubai is much further and the small aircraft are less practical for that distance and for long trips, the stopover is smaller fraction of the travel time, so the passengers are more willing to accept it. So Emirates flies just once per day and uses large aircraft. | >
> [C]ouldn't the people living around Bologna take a train to Milan to get to Dubai... ?
>
>
>
Maybe. But even if they can, it's much less convenient. By the time you've factored in taking a train from the outskirts of your city to the centre, waiting for the connection, taking the one-hour train, arriving earlier than you wanted to because of the schedule, and allowing extra time in case the train's late, that can easily be 2hrs actual travelling.
Also, the time of the first train of the day might prevent you from taking morning flights. I used to use my local airport and travel via Amsterdam instead of taking a "75-minute" train to the regional airport and getting a direct flight. Not only was the 75-minute journey more like 135 minutes (because I had to get a local train to the city centre and wait for a connection) but, also, the first train of the day was at 0615, so it was impossible to be at the regional airport before about 0830, so you wouldn't want to take a flight before about 1030.
Yet another problem is that, if my trains had been late, I'd have been at the mercy of my travel insurance company and airline agreeing that I'd made reasonable efforts to get to the airport on time and not charging me to rebook the flight. If the shuttle flight to Amsterdam was late, it was unambiguously the airline's responsibility to get me to my destination.
Finally, Emirates aren't really about people flying *to* Dubai. Rather, they want to be a hub for people flying *via* Dubai. Flying to many different airports makes Dubai a more attractive hub, for example for people flying between Europe and the Asia/Pacific region. You probably don't care what hub you fly through but being able to go from your local airport rather than the regional one can make a big difference. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| Eurostats provides information EU air passengers information, [it details air passengers transport Each of EU countries and their main airport partner.](http://ec.europa.eu/eurostat/help/new-eurostat-website?p_auth=82MXqaAJ&p_p_id=estatsearchportlet_WAR_estatsearchportlet&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&_estatsearchportlet_WAR_estatsearchportlet_action=search&text=avia_par)
Based on the above link, there is the passengers information between Dubai and Newcastle/Prague.
[](https://i.stack.imgur.com/HTfVG.jpg)
[](https://i.stack.imgur.com/btNg6.jpg)
Departure meanes the flights from the cities to dubai, and arrival stands for the flights from dubai to the two cities.
As you can see, the load factor for Newcastle and Prague is around 70%, both are lower than [Emirates 79.6% average](http://content.emirates.com/downloads/ek/pdfs/report/annual_report_2015.pdf). Newcastle are serviced by 2-class B77W while Prague is serviced by 3-class b77w/a388.
Load factor of both cities are from 50% at low season to 80& at high season. Although load factor of Prague route is lower than Newcastle in 2015, please note that at that time [Emirate ran this route by A388 instead of B77W](http://www.routesonline.com/news/29/breaking-news/249703/where-does-the-airbus-a380-fly-july-2015-network-update/?highlight=emirates%20prague).
PS: The nearest airport to Bologna which Emirates serves is Venice, not Milan,although the fastest way between 2 airports and Bologna are almost same. | It's very simple. Emirates is HEAVILY subsidized by the government of UAE. They are privately held by a government investment corporation which means any data on yield, load factors, PRASM, CASM, or profits are not to be trusted. They are trying to flood certain markets with capacity in order to kill competition and gain market share. It's a age old strategy in the aviation world, but it tends to not to work out so well in the long run. Its a great idea until you have a bunch of other airlines trying to do the same thing, then you end up with a HUGE glut of capacity and fares in the dumper! Eithad, Emirates, Saudia, Quatar, and Turkish airlines all seem to be flooding their markets with capacity, we shall see which country has the largest appetite for loss. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| Don't forget that aircraft size and link capacity are only loosely related, because it also depends on how many flights there are.
For example in case of Prague, I counted 6 departures to Frakfurt and 7 to Amsterdam a day, while only 2 to Dubai (the Emirates B77W and one SmartWings B738). So while the flights to Frankfurt and Amsterdam are all smaller planes (A319, A320, A321, to AMS some are even just E190), the capacity to both those destination is about double that to Dubai.
For the closer hubs, it makes more sense to fly smaller planes more often, because it can be more easily scaled (e.g. swapping A320 for A321; they don't even have to change the crew for that) and because it allows shorter transfer times, which the passengers obviously prefer.
However Dubai is much further and the small aircraft are less practical for that distance and for long trips, the stopover is smaller fraction of the travel time, so the passengers are more willing to accept it. So Emirates flies just once per day and uses large aircraft. | It's very simple. Emirates is HEAVILY subsidized by the government of UAE. They are privately held by a government investment corporation which means any data on yield, load factors, PRASM, CASM, or profits are not to be trusted. They are trying to flood certain markets with capacity in order to kill competition and gain market share. It's a age old strategy in the aviation world, but it tends to not to work out so well in the long run. Its a great idea until you have a bunch of other airlines trying to do the same thing, then you end up with a HUGE glut of capacity and fares in the dumper! Eithad, Emirates, Saudia, Quatar, and Turkish airlines all seem to be flooding their markets with capacity, we shall see which country has the largest appetite for loss. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| There are many reasons an airline may fly to a given destination and the economics of air travel are complex to say the least. I would like to fist address your question
>
> couldn't the people living around Bologna take a train to Milan to get
> to Dubai
>
>
>
Sure they could but airlines don't only service locations because of the people that live there they may service them for the very people that don't. I fly both commercially and as a GA pilot to explore new places. I generally fly out of the Philadelphia area which is one of the busiest in the US. From there I head to plenty of tiny airstrips all over the place, none of these airstrips are in towns that are as economically prosperous or busy as Philadelphia but they see my travel because I wish to explore the area. The same goes for foreign airports, simply because a country is less economically prosperous or "busy" than another does not mean it has less to offer culturally and in fact may be a hot bed for tourism.
I have personally been to both Prague and Bologna and they are great cities both with large tourist markets. I can see it being very economical to fly a wide body airliner there full of tourists and maybe only a few locals. While layovers may attract the lower budget fliers there are plenty of people who prefer a direct flight for both the convenience and time savings.
You may be able to find more [stats here](https://www.iata.org/publications/economics/Pages/index.aspx). | I guess one of the reasons for this wide-body use is because this is the primary aircraft for medium-haul routes in the Emirates Network. The 777 for Emirates is the workhorse of the Emirates airline and it has contributed to it's success. But in reality I do agree with you. Many Emirates routes that I have seen on YouTube do not have full aircraft which cannot be economically viable. But I guess this is why Emirates are so careful of assigning the A380 to a route. An example I can think of is Zurich which up till recently was operated by a 777. This is because the A380 is such a huge plane that it is only viable if the flight is packed. The 777 on the other hand is an aircraft that is used for a plethora of routes by Emirates. Reasons for this could be that it is the only widebody aircraft Emirates can use for this route. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| I may try and answer for Bologna which could be a similar case as for other supposedly non busy airports. (I am from Bologna myself!)
I think the reason is that even though the airport is not on the top 30, Bologna itself is one of the busiest economic hubs in Italy. For example from here we have factories like Ferrari, Maserati, Lamborghini and Ducati which are all in the radius of 30 km from the airport.
So if it does not make sense passenger-wise I think it does commercially.
There is also another theory which I have heard from FastJet management (Low cost regional carrier in Tanzania) which serves neighbouring countries. Sometimes you do not have to serve where there is business. The simple fact that you are opening a new route will automatically create business. As an airline YOU are creating the business for many other sectors. This is very true for example for Harare where now, with FastJet there are a lot of people flying into Dar es Salaam to pick up used cars shipped from Japan. This was not happening before but it is now a reality and their flights are fully booked for months from Harare to Dar es Salaam. On the other way (DSM-Harare) there are not many passengers but the pilots are telling me that the plane is fully laden with cargo!
So sometimes it seems that a route is not profitable but probably because no one is doing it. The moment you open it up, BANG! like magic new businesses start to flourish! | I guess one of the reasons for this wide-body use is because this is the primary aircraft for medium-haul routes in the Emirates Network. The 777 for Emirates is the workhorse of the Emirates airline and it has contributed to it's success. But in reality I do agree with you. Many Emirates routes that I have seen on YouTube do not have full aircraft which cannot be economically viable. But I guess this is why Emirates are so careful of assigning the A380 to a route. An example I can think of is Zurich which up till recently was operated by a 777. This is because the A380 is such a huge plane that it is only viable if the flight is packed. The 777 on the other hand is an aircraft that is used for a plethora of routes by Emirates. Reasons for this could be that it is the only widebody aircraft Emirates can use for this route. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| There are many reasons an airline may fly to a given destination and the economics of air travel are complex to say the least. I would like to fist address your question
>
> couldn't the people living around Bologna take a train to Milan to get
> to Dubai
>
>
>
Sure they could but airlines don't only service locations because of the people that live there they may service them for the very people that don't. I fly both commercially and as a GA pilot to explore new places. I generally fly out of the Philadelphia area which is one of the busiest in the US. From there I head to plenty of tiny airstrips all over the place, none of these airstrips are in towns that are as economically prosperous or busy as Philadelphia but they see my travel because I wish to explore the area. The same goes for foreign airports, simply because a country is less economically prosperous or "busy" than another does not mean it has less to offer culturally and in fact may be a hot bed for tourism.
I have personally been to both Prague and Bologna and they are great cities both with large tourist markets. I can see it being very economical to fly a wide body airliner there full of tourists and maybe only a few locals. While layovers may attract the lower budget fliers there are plenty of people who prefer a direct flight for both the convenience and time savings.
You may be able to find more [stats here](https://www.iata.org/publications/economics/Pages/index.aspx). | Don't forget that aircraft size and link capacity are only loosely related, because it also depends on how many flights there are.
For example in case of Prague, I counted 6 departures to Frakfurt and 7 to Amsterdam a day, while only 2 to Dubai (the Emirates B77W and one SmartWings B738). So while the flights to Frankfurt and Amsterdam are all smaller planes (A319, A320, A321, to AMS some are even just E190), the capacity to both those destination is about double that to Dubai.
For the closer hubs, it makes more sense to fly smaller planes more often, because it can be more easily scaled (e.g. swapping A320 for A321; they don't even have to change the crew for that) and because it allows shorter transfer times, which the passengers obviously prefer.
However Dubai is much further and the small aircraft are less practical for that distance and for long trips, the stopover is smaller fraction of the travel time, so the passengers are more willing to accept it. So Emirates flies just once per day and uses large aircraft. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| Eurostats provides information EU air passengers information, [it details air passengers transport Each of EU countries and their main airport partner.](http://ec.europa.eu/eurostat/help/new-eurostat-website?p_auth=82MXqaAJ&p_p_id=estatsearchportlet_WAR_estatsearchportlet&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&_estatsearchportlet_WAR_estatsearchportlet_action=search&text=avia_par)
Based on the above link, there is the passengers information between Dubai and Newcastle/Prague.
[](https://i.stack.imgur.com/HTfVG.jpg)
[](https://i.stack.imgur.com/btNg6.jpg)
Departure meanes the flights from the cities to dubai, and arrival stands for the flights from dubai to the two cities.
As you can see, the load factor for Newcastle and Prague is around 70%, both are lower than [Emirates 79.6% average](http://content.emirates.com/downloads/ek/pdfs/report/annual_report_2015.pdf). Newcastle are serviced by 2-class B77W while Prague is serviced by 3-class b77w/a388.
Load factor of both cities are from 50% at low season to 80& at high season. Although load factor of Prague route is lower than Newcastle in 2015, please note that at that time [Emirate ran this route by A388 instead of B77W](http://www.routesonline.com/news/29/breaking-news/249703/where-does-the-airbus-a380-fly-july-2015-network-update/?highlight=emirates%20prague).
PS: The nearest airport to Bologna which Emirates serves is Venice, not Milan,although the fastest way between 2 airports and Bologna are almost same. | I don't think you have to dig much deeper that the fact that Emirates is exclusively an international carrier; and they have decided to standardize their fleet on the 777 and the A380 - this is actually more economical for them since they are able to get cost savings by only servicing two kinds of airframes.
Overall for them - it makes sense to standardize on these two kinds of aircraft, which means that no matter where they fly - it will either be on a 777 or a A380, no matter what the load ratio is.
This means you have some silly routing - such as flying an A380 from Dubai to Kuwait, a route exclusively serviced by the 737/A320/A321 family by every other carrier. Even Eithad (the UAE's national airline) flies this route on the A320.
For Emirates, when speaking of operations at their scale, it makes sense for them to fly a standard configuration, with a standard crew layout to all destinations. In fact, I would hazard a guess that most airlines would love to do what Emirates is able to, rather than having to service, train for and maintain different kinds of aircraft. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| There are many reasons an airline may fly to a given destination and the economics of air travel are complex to say the least. I would like to fist address your question
>
> couldn't the people living around Bologna take a train to Milan to get
> to Dubai
>
>
>
Sure they could but airlines don't only service locations because of the people that live there they may service them for the very people that don't. I fly both commercially and as a GA pilot to explore new places. I generally fly out of the Philadelphia area which is one of the busiest in the US. From there I head to plenty of tiny airstrips all over the place, none of these airstrips are in towns that are as economically prosperous or busy as Philadelphia but they see my travel because I wish to explore the area. The same goes for foreign airports, simply because a country is less economically prosperous or "busy" than another does not mean it has less to offer culturally and in fact may be a hot bed for tourism.
I have personally been to both Prague and Bologna and they are great cities both with large tourist markets. I can see it being very economical to fly a wide body airliner there full of tourists and maybe only a few locals. While layovers may attract the lower budget fliers there are plenty of people who prefer a direct flight for both the convenience and time savings.
You may be able to find more [stats here](https://www.iata.org/publications/economics/Pages/index.aspx). | It's very simple. Emirates is HEAVILY subsidized by the government of UAE. They are privately held by a government investment corporation which means any data on yield, load factors, PRASM, CASM, or profits are not to be trusted. They are trying to flood certain markets with capacity in order to kill competition and gain market share. It's a age old strategy in the aviation world, but it tends to not to work out so well in the long run. Its a great idea until you have a bunch of other airlines trying to do the same thing, then you end up with a HUGE glut of capacity and fares in the dumper! Eithad, Emirates, Saudia, Quatar, and Turkish airlines all seem to be flooding their markets with capacity, we shall see which country has the largest appetite for loss. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| Eurostats provides information EU air passengers information, [it details air passengers transport Each of EU countries and their main airport partner.](http://ec.europa.eu/eurostat/help/new-eurostat-website?p_auth=82MXqaAJ&p_p_id=estatsearchportlet_WAR_estatsearchportlet&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&_estatsearchportlet_WAR_estatsearchportlet_action=search&text=avia_par)
Based on the above link, there is the passengers information between Dubai and Newcastle/Prague.
[](https://i.stack.imgur.com/HTfVG.jpg)
[](https://i.stack.imgur.com/btNg6.jpg)
Departure meanes the flights from the cities to dubai, and arrival stands for the flights from dubai to the two cities.
As you can see, the load factor for Newcastle and Prague is around 70%, both are lower than [Emirates 79.6% average](http://content.emirates.com/downloads/ek/pdfs/report/annual_report_2015.pdf). Newcastle are serviced by 2-class B77W while Prague is serviced by 3-class b77w/a388.
Load factor of both cities are from 50% at low season to 80& at high season. Although load factor of Prague route is lower than Newcastle in 2015, please note that at that time [Emirate ran this route by A388 instead of B77W](http://www.routesonline.com/news/29/breaking-news/249703/where-does-the-airbus-a380-fly-july-2015-network-update/?highlight=emirates%20prague).
PS: The nearest airport to Bologna which Emirates serves is Venice, not Milan,although the fastest way between 2 airports and Bologna are almost same. | I guess one of the reasons for this wide-body use is because this is the primary aircraft for medium-haul routes in the Emirates Network. The 777 for Emirates is the workhorse of the Emirates airline and it has contributed to it's success. But in reality I do agree with you. Many Emirates routes that I have seen on YouTube do not have full aircraft which cannot be economically viable. But I guess this is why Emirates are so careful of assigning the A380 to a route. An example I can think of is Zurich which up till recently was operated by a 777. This is because the A380 is such a huge plane that it is only viable if the flight is packed. The 777 on the other hand is an aircraft that is used for a plethora of routes by Emirates. Reasons for this could be that it is the only widebody aircraft Emirates can use for this route. |
23,239 | This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is.
Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are:
* Newcastle upon Tyne (NCL)
* Prague (PRG)
* Bologna (BLQ)
* Harare (HRE)
and so forth.
**My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)? | 2015/11/28 | [
"https://aviation.stackexchange.com/questions/23239",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11885/"
]
| Don't forget that aircraft size and link capacity are only loosely related, because it also depends on how many flights there are.
For example in case of Prague, I counted 6 departures to Frakfurt and 7 to Amsterdam a day, while only 2 to Dubai (the Emirates B77W and one SmartWings B738). So while the flights to Frankfurt and Amsterdam are all smaller planes (A319, A320, A321, to AMS some are even just E190), the capacity to both those destination is about double that to Dubai.
For the closer hubs, it makes more sense to fly smaller planes more often, because it can be more easily scaled (e.g. swapping A320 for A321; they don't even have to change the crew for that) and because it allows shorter transfer times, which the passengers obviously prefer.
However Dubai is much further and the small aircraft are less practical for that distance and for long trips, the stopover is smaller fraction of the travel time, so the passengers are more willing to accept it. So Emirates flies just once per day and uses large aircraft. | I guess one of the reasons for this wide-body use is because this is the primary aircraft for medium-haul routes in the Emirates Network. The 777 for Emirates is the workhorse of the Emirates airline and it has contributed to it's success. But in reality I do agree with you. Many Emirates routes that I have seen on YouTube do not have full aircraft which cannot be economically viable. But I guess this is why Emirates are so careful of assigning the A380 to a route. An example I can think of is Zurich which up till recently was operated by a 777. This is because the A380 is such a huge plane that it is only viable if the flight is packed. The 777 on the other hand is an aircraft that is used for a plethora of routes by Emirates. Reasons for this could be that it is the only widebody aircraft Emirates can use for this route. |
42,309,571 | I've got this fragment of automatically-generated HTML:
```
<label><input type="radio" name="question24_answer" value="A">A)
H<sub>0</sub>: p = 0.0016<br/>H<sub>1</sub>: p < 0.0016</label>
```
This produces the following:
[](https://i.stack.imgur.com/bSbPx.png)
I'd like the two lines of the label to align vertically so they look good:
[](https://i.stack.imgur.com/uRnV8.png)
If necessary, the `A)` can be omitted, though I'd prefer not to:
[](https://i.stack.imgur.com/uAOQy.png) | 2017/02/18 | [
"https://Stackoverflow.com/questions/42309571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3063736/"
]
| >
> Any solution needs to be something that can be done automatically.
>
>
>
I believe that would rule out a pure HTML solution to which is the only tag your question has. So at the risk of ignoring the fact there's no CSS or JavaScript tag, I'll suggest JavaScript right off and a little bit of CSS.
1. `.querySelectorAll()` collects every `<br/>` that's a child of a `<label>` into a NodeList
2. `Array.prototype.map.call()`executes a function on each item of the NodeList and return a new array
3. `insertAdjacentHTML()` inserts a `<span>` after every `<br>` in the NodeList
4. This `<span>`'s width is 6.4ch; ch is a unit of measure equal to the width of a zero.
5. Use a monospaced font and make sure that `<input>` inherits font. These steps help normalize variances that fonts may cause.
6. To make it perfect, use a combination of `vertical-align` and `line-height` so the radio button is aligned properly.
**SNIPPET**
```js
var br = document.querySelectorAll('label br');
Array.prototype.map.call(br, function(obj) {
return obj.insertAdjacentHTML('afterend', "<span class='ch'><span>")
});
```
```css
body {
font: 400 16px/1.5 Consolas;
}
input {
vertical-align: -10%;
line-height: 1;
font: inherit;
}
.ch {
display:inline-block;
width: 6.4ch;
}
```
```html
<label><input type="radio" name="question24_answer" value="A">A)
H<sub>0</sub>: p = 0.0016<br/>H<sub>1</sub>: p < 0.0016</label>
<br/>
<label><input type="radio" name="question24_answer" value="B">B)
H<sub>26</sub>: p = 0.04096<br/>CH<sub>2</sub>: p < 0.096</label>
<br/>
<label><input type="radio" name="question24_answer" value="C">C)
H<sub>89</sub>: p = 0.00248966652<br/>H<sub>1</sub>: p < 0.0016</label>
<br/>
<label><input type="radio" name="question24_answer" value="D">D)
H<sub>0</sub>: p = 0.1<br/>H<sub>652</sub>: p < 0.0016</label>
``` | Ideally, any visual changes you would like to make should be done with CSS.
However if this must be done with just html with no in-line styling, you can simply add some non-breaking spaces (` `) to achieve this effect, along with an additional `<br>` tag.
```
<label><input type="radio" name="question24_answer" value="A">A)<br>
H<sub>0</sub>: p = 0.0016<br/> H<sub>1</sub>: p < 0.0016</label>
```
Which should give you this:
[](https://i.stack.imgur.com/rBJb5.png)
Alternatively if you want to use some in-line styling you could make use of the `float` property and place the second set of information in a `<div>` tag (or any semantic tag you deem fit):
```
<label style="float: left"><input type="radio" name="question24_answer" value="A">A)
<div style="float: right;">H<sub>0</sub>: p = 0.0016<br/>H<sub>1</sub>: p < 0.0016</div></label>
```
Which should give you this:
[](https://i.stack.imgur.com/YyG9v.png) |
42,309,571 | I've got this fragment of automatically-generated HTML:
```
<label><input type="radio" name="question24_answer" value="A">A)
H<sub>0</sub>: p = 0.0016<br/>H<sub>1</sub>: p < 0.0016</label>
```
This produces the following:
[](https://i.stack.imgur.com/bSbPx.png)
I'd like the two lines of the label to align vertically so they look good:
[](https://i.stack.imgur.com/uRnV8.png)
If necessary, the `A)` can be omitted, though I'd prefer not to:
[](https://i.stack.imgur.com/uAOQy.png) | 2017/02/18 | [
"https://Stackoverflow.com/questions/42309571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3063736/"
]
| >
> Any solution needs to be something that can be done automatically.
>
>
>
I believe that would rule out a pure HTML solution to which is the only tag your question has. So at the risk of ignoring the fact there's no CSS or JavaScript tag, I'll suggest JavaScript right off and a little bit of CSS.
1. `.querySelectorAll()` collects every `<br/>` that's a child of a `<label>` into a NodeList
2. `Array.prototype.map.call()`executes a function on each item of the NodeList and return a new array
3. `insertAdjacentHTML()` inserts a `<span>` after every `<br>` in the NodeList
4. This `<span>`'s width is 6.4ch; ch is a unit of measure equal to the width of a zero.
5. Use a monospaced font and make sure that `<input>` inherits font. These steps help normalize variances that fonts may cause.
6. To make it perfect, use a combination of `vertical-align` and `line-height` so the radio button is aligned properly.
**SNIPPET**
```js
var br = document.querySelectorAll('label br');
Array.prototype.map.call(br, function(obj) {
return obj.insertAdjacentHTML('afterend', "<span class='ch'><span>")
});
```
```css
body {
font: 400 16px/1.5 Consolas;
}
input {
vertical-align: -10%;
line-height: 1;
font: inherit;
}
.ch {
display:inline-block;
width: 6.4ch;
}
```
```html
<label><input type="radio" name="question24_answer" value="A">A)
H<sub>0</sub>: p = 0.0016<br/>H<sub>1</sub>: p < 0.0016</label>
<br/>
<label><input type="radio" name="question24_answer" value="B">B)
H<sub>26</sub>: p = 0.04096<br/>CH<sub>2</sub>: p < 0.096</label>
<br/>
<label><input type="radio" name="question24_answer" value="C">C)
H<sub>89</sub>: p = 0.00248966652<br/>H<sub>1</sub>: p < 0.0016</label>
<br/>
<label><input type="radio" name="question24_answer" value="D">D)
H<sub>0</sub>: p = 0.1<br/>H<sub>652</sub>: p < 0.0016</label>
``` | Maybe with a list?
```html
<label><input type="radio" name="question24_answer" value="A">A)
<ul style="list-style: none; margin-top: 0;"><li>H<sub>0</sub>: p = 0.0016</li><li>H<sub>1</sub>: p < 0.0016</li></label>
``` |
65,027,547 | I'm using using this data to fill a FlatList, each item contains a LinearGradient
```
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
firstColor: "#f472a7",
secondColor: "#d84351"
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
firstColor: "#50be71",
secondColor: "#50be71"
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
firstColor: "#e2bd4f",
secondColor: "#e49074"
}
];
```
I added two properties called "firstColor" and "secondColor", to fill the LinearGradient colors, but I'm having some issues doing that. I'm receiving this error:
```
TypeError: undefined is not an object (evaluating '_ref3.secondColor')
```
Code:
```
const Item = ({ title }, { firstColor }, { secondColor }) => (
<LinearGradient
colors={[{firstColor}, {secondColor} ]}
style={styles.item}
>
<Text style={styles.title}>{title}</Text>
</LinearGradient>
);
const renderItem = ({ item }) => (
<Item title={item.title} />
);
...
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
``` | 2020/11/26 | [
"https://Stackoverflow.com/questions/65027547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596416/"
]
| Since Python 3.7, keys in dict are ordered.
-------------------------------------------
You can use enumerate in order to keep track of the position of the element in the dict while iterating over it. Then, you use the `i` as an index on each row of the 2d list, convert each value to int and do a sum of the result.
```py
List2d = [['1', '55', '32', '667' ],
['43', '76', '55', '100'],
['23', '70', '15', '300']]
dictionary = {'New York':0, "London": 0, "Tokyo": 0, "Toronto": 0 }
for i, city in enumerate(dictionary.keys()):
dictionary[city] = sum(int(row[i]) for row in List2d)
print(dictionary)
# {'New York': 67, 'London': 201, 'Tokyo': 102, 'Toronto': 1067}
``` | Use pandas
```
#!pip install pandas
import pandas as pd
pd.DataFrame(List2d, columns=dictionary.keys()).astype(int).sum(axis=0).to_dict()
```
output:
```
{'New York': 67, 'London': 201, 'Tokyo': 102, 'Toronto': 1067}
``` |
65,462,499 | I am trying to use grep with the `pwd` command.
So, if i enter `pwd`, it shows me something like:
```
/home/hrq/my-project/
```
But, for purposes of a script i am making, i need to use it with grep, so it only prints what is after `hrq/`, so i need to hide my home folder always (the `/home/hrq/`) excerpt, and show only what is onwards (like, in this case, only `my-project`).
Is it possible?
I tried something like
`pwd | grep -ov 'home'`, since i saw that the "-v" flag would be equivalent to the NOT operator, and combine it with the "-o" only matching flag. But it didn't work. | 2020/12/27 | [
"https://Stackoverflow.com/questions/65462499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10113447/"
]
| Given:
```
$ pwd
/home/foo/tmp
$ echo "$PWD"
/home/foo/tmp
```
Depending on what it is you really want to do, either of these is probably what you really should be using rather than trying to use grep:
```
$ basename "$PWD"
tmp
$ echo "${PWD#/home/foo/}"
tmp
``` | Use `grep -Po 'hrq/\K.*'`, for example:
```
grep -Po 'hrq/\K.*' <<< '/home/hrq/my-project/'
my-project/
```
Here, `grep` uses the following options:
`-P` : Use Perl regexes.
`-o` : Print the matches only (1 match per line), not the entire lines.
`\K` : Cause the regex engine to "keep" everything it had matched prior to the `\K` and not include it in the match. Specifically, ignore the preceding part of the regex when printing the match.
**SEE ALSO:**
[`grep` manual](https://www.gnu.org/software/grep/manual/grep.html)
[perlre - Perl regular expressions](https://perldoc.perl.org/perlre) |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| What makes your problem a little bit tricky is that you want to match inside of a multiline string. You need to use the `re.MULTILINE` flag to make that work.
Then, you need to match some groups inside your source string, and use those groups in the final output. Here is code that works to solve your problem:
```
import re
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
def mksub(m):
return '<replace name="%s">%s</replace>' % m.groups()
s_output = re.sub(pat, mksub, s_input)
```
The only tricky part is the regular expression pattern. Let's look at it in detail.
`^` matches the start of a string. With `re.MULTILINE`, this matches the start of a line within a multiline string; in other words, it matches right after a newline in the string.
`\s*` matches optional whitespace.
`REPLACE` matches the literal string "REPLACE".
`\(` matches the literal string "(".
`(` begins a "match group".
`[^)]` means "match any character but a ")".
`+` means "match one or more of the preceding pattern.
`)` closes a "match group".
`\)` matches the literal string ")"
`(.*)` is another match group containing ".\*".
`$` matches the end of a string. With `re.MULTILINE`, this matches the end of a line within a multiline string; in other words, it matches a newline character in the string.
`.` matches any character, and `*` means to match zero or more of the preceding pattern. Thus `.*` matches anything, up to the end of the line.
So, our pattern has two "match groups". When you run `re.sub()` it will make a "match object" which will be passed to `mksub()`. The match object has a method, `.groups()`, that returns the matched substrings as a tuple, and that gets substituted in to make the replacement text.
EDIT: You actually don't need to use a replacement function. You can put the special string `\1` inside the replacement text, and it will be replaced by the contents of match group 1. (Match groups count from 1; the special match group 0 corresponds the the entire string matched by the pattern.) The only tricky part of the `\1` string is that `\` is special in strings. In a normal string, to get a `\`, you need to put two backslashes in a row, like so: `"\\1"` But you can use a Python "raw string" to conveniently write the replacement pattern. Doing so you get this:
import re
```
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_repl = r'<replace name="\1">\2</replace>'
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
s_output = re.sub(pat, s_repl, s_input)
``` | Maybe like this ?
```
import re
mystr = """Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
prog = re.compile(r'REPLACE\((.*?)\)\s(.*)')
for line in mystr.split("\n"):
print prog.sub(r'< replace name="\1" > \2',line)
``` |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| Here is an [excellent tutorial](http://www.amk.ca/python/howto/regex/) on how to write regular expressions in Python. | Here is a solution using pyparsing. I know you specifically asked about a regex solution, but if your requirements change, you might find it easier to expand a pyparsing parser. Or a pyparsing prototype solution might give you a little more insight into the problem leading toward a regex or other final implementation.
```
src = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
"""
from pyparsing import Suppress, Word, alphas, alphanums, restOfLine
LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas, alphanums)
replExpr = "REPLACE" + LPAR + ident("name") + RPAR + restOfLine("body")
replExpr.setParseAction(
lambda toks : '<replace name="%(name)s">%(body)s </replace>' % toks
)
print replExpr.transformString(src)
```
In this case, you create the expression to be matched with pyparsing, define a parse action to do the text conversion, and then call transformString to scan through the input source to find all the matches, apply the parse action to each match, and return the resulting output. The parse action serves a similar function to mksub in @steveha's solution.
In addition to the parse action, pyparsing also supports naming individual elements of the expression - I used "name" and "body" to label the two parts of interest, which are represented in the re solution as groups 1 and 2. You *can* name groups in an re, the corresponding re would look like:
```
s_pat = "^\s*REPLACE\((?P<name>[^)]+)\)(?P<body>.*)$"
```
Unfortunately, to access these groups by name, you have to invoke the `group()` method on the re match object, you can't directly do the named string interpolation as in my lambda parse action. But this is Python, right? We can wrap that callable with a class that will give us dict-like access to the groups by name:
```
class CallableDict(object):
def __init__(self,fn):
self.fn = fn
def __getitem__(self,name):
return self.fn(name)
def mksub(m):
return '<replace name="%(name)s">%(body)s</replace>' % CallableDict(m.group)
s_output = re.sub(pat, mksub, s_input)
```
Using `CallableDict`, the string interpolation in mksub can now call m.group for each field, by making it look like we are retrieving the ['name'] and ['body'] elements of a dict. |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| Here is a solution using pyparsing. I know you specifically asked about a regex solution, but if your requirements change, you might find it easier to expand a pyparsing parser. Or a pyparsing prototype solution might give you a little more insight into the problem leading toward a regex or other final implementation.
```
src = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
"""
from pyparsing import Suppress, Word, alphas, alphanums, restOfLine
LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas, alphanums)
replExpr = "REPLACE" + LPAR + ident("name") + RPAR + restOfLine("body")
replExpr.setParseAction(
lambda toks : '<replace name="%(name)s">%(body)s </replace>' % toks
)
print replExpr.transformString(src)
```
In this case, you create the expression to be matched with pyparsing, define a parse action to do the text conversion, and then call transformString to scan through the input source to find all the matches, apply the parse action to each match, and return the resulting output. The parse action serves a similar function to mksub in @steveha's solution.
In addition to the parse action, pyparsing also supports naming individual elements of the expression - I used "name" and "body" to label the two parts of interest, which are represented in the re solution as groups 1 and 2. You *can* name groups in an re, the corresponding re would look like:
```
s_pat = "^\s*REPLACE\((?P<name>[^)]+)\)(?P<body>.*)$"
```
Unfortunately, to access these groups by name, you have to invoke the `group()` method on the re match object, you can't directly do the named string interpolation as in my lambda parse action. But this is Python, right? We can wrap that callable with a class that will give us dict-like access to the groups by name:
```
class CallableDict(object):
def __init__(self,fn):
self.fn = fn
def __getitem__(self,name):
return self.fn(name)
def mksub(m):
return '<replace name="%(name)s">%(body)s</replace>' % CallableDict(m.group)
s_output = re.sub(pat, mksub, s_input)
```
Using `CallableDict`, the string interpolation in mksub can now call m.group for each field, by making it look like we are retrieving the ['name'] and ['body'] elements of a dict. | Something like this should work:
```
import re,sys
f = open( sys.argv[1], 'r' )
for i in f:
g = re.match( r'REPLACE\((.*)\)(.*)', i )
if g is None:
print i
else:
print '<replace name=\"%s\">%s</replace>' % (g.group(1),g.group(2))
f.close()
``` |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| What makes your problem a little bit tricky is that you want to match inside of a multiline string. You need to use the `re.MULTILINE` flag to make that work.
Then, you need to match some groups inside your source string, and use those groups in the final output. Here is code that works to solve your problem:
```
import re
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
def mksub(m):
return '<replace name="%s">%s</replace>' % m.groups()
s_output = re.sub(pat, mksub, s_input)
```
The only tricky part is the regular expression pattern. Let's look at it in detail.
`^` matches the start of a string. With `re.MULTILINE`, this matches the start of a line within a multiline string; in other words, it matches right after a newline in the string.
`\s*` matches optional whitespace.
`REPLACE` matches the literal string "REPLACE".
`\(` matches the literal string "(".
`(` begins a "match group".
`[^)]` means "match any character but a ")".
`+` means "match one or more of the preceding pattern.
`)` closes a "match group".
`\)` matches the literal string ")"
`(.*)` is another match group containing ".\*".
`$` matches the end of a string. With `re.MULTILINE`, this matches the end of a line within a multiline string; in other words, it matches a newline character in the string.
`.` matches any character, and `*` means to match zero or more of the preceding pattern. Thus `.*` matches anything, up to the end of the line.
So, our pattern has two "match groups". When you run `re.sub()` it will make a "match object" which will be passed to `mksub()`. The match object has a method, `.groups()`, that returns the matched substrings as a tuple, and that gets substituted in to make the replacement text.
EDIT: You actually don't need to use a replacement function. You can put the special string `\1` inside the replacement text, and it will be replaced by the contents of match group 1. (Match groups count from 1; the special match group 0 corresponds the the entire string matched by the pattern.) The only tricky part of the `\1` string is that `\` is special in strings. In a normal string, to get a `\`, you need to put two backslashes in a row, like so: `"\\1"` But you can use a Python "raw string" to conveniently write the replacement pattern. Doing so you get this:
import re
```
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_repl = r'<replace name="\1">\2</replace>'
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
s_output = re.sub(pat, s_repl, s_input)
``` | ```
import re
a="""Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
regex = re.compile(r"^REPLACE\(([^)]+)\)\s+(.*)$", re.MULTILINE)
b=re.sub(regex, r'< replace name="\1" > \2 < /replace >', a)
print b
```
will do the replace in one line. |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| What makes your problem a little bit tricky is that you want to match inside of a multiline string. You need to use the `re.MULTILINE` flag to make that work.
Then, you need to match some groups inside your source string, and use those groups in the final output. Here is code that works to solve your problem:
```
import re
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
def mksub(m):
return '<replace name="%s">%s</replace>' % m.groups()
s_output = re.sub(pat, mksub, s_input)
```
The only tricky part is the regular expression pattern. Let's look at it in detail.
`^` matches the start of a string. With `re.MULTILINE`, this matches the start of a line within a multiline string; in other words, it matches right after a newline in the string.
`\s*` matches optional whitespace.
`REPLACE` matches the literal string "REPLACE".
`\(` matches the literal string "(".
`(` begins a "match group".
`[^)]` means "match any character but a ")".
`+` means "match one or more of the preceding pattern.
`)` closes a "match group".
`\)` matches the literal string ")"
`(.*)` is another match group containing ".\*".
`$` matches the end of a string. With `re.MULTILINE`, this matches the end of a line within a multiline string; in other words, it matches a newline character in the string.
`.` matches any character, and `*` means to match zero or more of the preceding pattern. Thus `.*` matches anything, up to the end of the line.
So, our pattern has two "match groups". When you run `re.sub()` it will make a "match object" which will be passed to `mksub()`. The match object has a method, `.groups()`, that returns the matched substrings as a tuple, and that gets substituted in to make the replacement text.
EDIT: You actually don't need to use a replacement function. You can put the special string `\1` inside the replacement text, and it will be replaced by the contents of match group 1. (Match groups count from 1; the special match group 0 corresponds the the entire string matched by the pattern.) The only tricky part of the `\1` string is that `\` is special in strings. In a normal string, to get a `\`, you need to put two backslashes in a row, like so: `"\\1"` But you can use a Python "raw string" to conveniently write the replacement pattern. Doing so you get this:
import re
```
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_repl = r'<replace name="\1">\2</replace>'
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
s_output = re.sub(pat, s_repl, s_input)
``` | Something like this should work:
```
import re,sys
f = open( sys.argv[1], 'r' )
for i in f:
g = re.match( r'REPLACE\((.*)\)(.*)', i )
if g is None:
print i
else:
print '<replace name=\"%s\">%s</replace>' % (g.group(1),g.group(2))
f.close()
``` |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| What makes your problem a little bit tricky is that you want to match inside of a multiline string. You need to use the `re.MULTILINE` flag to make that work.
Then, you need to match some groups inside your source string, and use those groups in the final output. Here is code that works to solve your problem:
```
import re
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
def mksub(m):
return '<replace name="%s">%s</replace>' % m.groups()
s_output = re.sub(pat, mksub, s_input)
```
The only tricky part is the regular expression pattern. Let's look at it in detail.
`^` matches the start of a string. With `re.MULTILINE`, this matches the start of a line within a multiline string; in other words, it matches right after a newline in the string.
`\s*` matches optional whitespace.
`REPLACE` matches the literal string "REPLACE".
`\(` matches the literal string "(".
`(` begins a "match group".
`[^)]` means "match any character but a ")".
`+` means "match one or more of the preceding pattern.
`)` closes a "match group".
`\)` matches the literal string ")"
`(.*)` is another match group containing ".\*".
`$` matches the end of a string. With `re.MULTILINE`, this matches the end of a line within a multiline string; in other words, it matches a newline character in the string.
`.` matches any character, and `*` means to match zero or more of the preceding pattern. Thus `.*` matches anything, up to the end of the line.
So, our pattern has two "match groups". When you run `re.sub()` it will make a "match object" which will be passed to `mksub()`. The match object has a method, `.groups()`, that returns the matched substrings as a tuple, and that gets substituted in to make the replacement text.
EDIT: You actually don't need to use a replacement function. You can put the special string `\1` inside the replacement text, and it will be replaced by the contents of match group 1. (Match groups count from 1; the special match group 0 corresponds the the entire string matched by the pattern.) The only tricky part of the `\1` string is that `\` is special in strings. In a normal string, to get a `\`, you need to put two backslashes in a row, like so: `"\\1"` But you can use a Python "raw string" to conveniently write the replacement pattern. Doing so you get this:
import re
```
s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$"
pat = re.compile(s_pat, re.MULTILINE)
s_repl = r'<replace name="\1">\2</replace>'
s_input = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
s_output = re.sub(pat, s_repl, s_input)
``` | Here is a solution using pyparsing. I know you specifically asked about a regex solution, but if your requirements change, you might find it easier to expand a pyparsing parser. Or a pyparsing prototype solution might give you a little more insight into the problem leading toward a regex or other final implementation.
```
src = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
"""
from pyparsing import Suppress, Word, alphas, alphanums, restOfLine
LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas, alphanums)
replExpr = "REPLACE" + LPAR + ident("name") + RPAR + restOfLine("body")
replExpr.setParseAction(
lambda toks : '<replace name="%(name)s">%(body)s </replace>' % toks
)
print replExpr.transformString(src)
```
In this case, you create the expression to be matched with pyparsing, define a parse action to do the text conversion, and then call transformString to scan through the input source to find all the matches, apply the parse action to each match, and return the resulting output. The parse action serves a similar function to mksub in @steveha's solution.
In addition to the parse action, pyparsing also supports naming individual elements of the expression - I used "name" and "body" to label the two parts of interest, which are represented in the re solution as groups 1 and 2. You *can* name groups in an re, the corresponding re would look like:
```
s_pat = "^\s*REPLACE\((?P<name>[^)]+)\)(?P<body>.*)$"
```
Unfortunately, to access these groups by name, you have to invoke the `group()` method on the re match object, you can't directly do the named string interpolation as in my lambda parse action. But this is Python, right? We can wrap that callable with a class that will give us dict-like access to the groups by name:
```
class CallableDict(object):
def __init__(self,fn):
self.fn = fn
def __getitem__(self,name):
return self.fn(name)
def mksub(m):
return '<replace name="%(name)s">%(body)s</replace>' % CallableDict(m.group)
s_output = re.sub(pat, mksub, s_input)
```
Using `CallableDict`, the string interpolation in mksub can now call m.group for each field, by making it look like we are retrieving the ['name'] and ['body'] elements of a dict. |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| Here is an [excellent tutorial](http://www.amk.ca/python/howto/regex/) on how to write regular expressions in Python. | Something like this should work:
```
import re,sys
f = open( sys.argv[1], 'r' )
for i in f:
g = re.match( r'REPLACE\((.*)\)(.*)', i )
if g is None:
print i
else:
print '<replace name=\"%s\">%s</replace>' % (g.group(1),g.group(2))
f.close()
``` |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| Here is a solution using pyparsing. I know you specifically asked about a regex solution, but if your requirements change, you might find it easier to expand a pyparsing parser. Or a pyparsing prototype solution might give you a little more insight into the problem leading toward a regex or other final implementation.
```
src = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
"""
from pyparsing import Suppress, Word, alphas, alphanums, restOfLine
LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas, alphanums)
replExpr = "REPLACE" + LPAR + ident("name") + RPAR + restOfLine("body")
replExpr.setParseAction(
lambda toks : '<replace name="%(name)s">%(body)s </replace>' % toks
)
print replExpr.transformString(src)
```
In this case, you create the expression to be matched with pyparsing, define a parse action to do the text conversion, and then call transformString to scan through the input source to find all the matches, apply the parse action to each match, and return the resulting output. The parse action serves a similar function to mksub in @steveha's solution.
In addition to the parse action, pyparsing also supports naming individual elements of the expression - I used "name" and "body" to label the two parts of interest, which are represented in the re solution as groups 1 and 2. You *can* name groups in an re, the corresponding re would look like:
```
s_pat = "^\s*REPLACE\((?P<name>[^)]+)\)(?P<body>.*)$"
```
Unfortunately, to access these groups by name, you have to invoke the `group()` method on the re match object, you can't directly do the named string interpolation as in my lambda parse action. But this is Python, right? We can wrap that callable with a class that will give us dict-like access to the groups by name:
```
class CallableDict(object):
def __init__(self,fn):
self.fn = fn
def __getitem__(self,name):
return self.fn(name)
def mksub(m):
return '<replace name="%(name)s">%(body)s</replace>' % CallableDict(m.group)
s_output = re.sub(pat, mksub, s_input)
```
Using `CallableDict`, the string interpolation in mksub can now call m.group for each field, by making it look like we are retrieving the ['name'] and ['body'] elements of a dict. | Maybe like this ?
```
import re
mystr = """Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
prog = re.compile(r'REPLACE\((.*?)\)\s(.*)')
for line in mystr.split("\n"):
print prog.sub(r'< replace name="\1" > \2',line)
``` |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| Here is an [excellent tutorial](http://www.amk.ca/python/howto/regex/) on how to write regular expressions in Python. | ```
import re
a="""Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
regex = re.compile(r"^REPLACE\(([^)]+)\)\s+(.*)$", re.MULTILINE)
b=re.sub(regex, r'< replace name="\1" > \2 < /replace >', a)
print b
```
will do the replace in one line. |
1,842,608 | I'm using Python to write a regular expression for replacing parts of the string with a XML node.
The source string looks like:
```
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
```
And the result string should be like:
```
Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>
```
Can anyone help me? | 2009/12/03 | [
"https://Stackoverflow.com/questions/1842608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
]
| Here is a solution using pyparsing. I know you specifically asked about a regex solution, but if your requirements change, you might find it easier to expand a pyparsing parser. Or a pyparsing prototype solution might give you a little more insight into the problem leading toward a regex or other final implementation.
```
src = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
"""
from pyparsing import Suppress, Word, alphas, alphanums, restOfLine
LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas, alphanums)
replExpr = "REPLACE" + LPAR + ident("name") + RPAR + restOfLine("body")
replExpr.setParseAction(
lambda toks : '<replace name="%(name)s">%(body)s </replace>' % toks
)
print replExpr.transformString(src)
```
In this case, you create the expression to be matched with pyparsing, define a parse action to do the text conversion, and then call transformString to scan through the input source to find all the matches, apply the parse action to each match, and return the resulting output. The parse action serves a similar function to mksub in @steveha's solution.
In addition to the parse action, pyparsing also supports naming individual elements of the expression - I used "name" and "body" to label the two parts of interest, which are represented in the re solution as groups 1 and 2. You *can* name groups in an re, the corresponding re would look like:
```
s_pat = "^\s*REPLACE\((?P<name>[^)]+)\)(?P<body>.*)$"
```
Unfortunately, to access these groups by name, you have to invoke the `group()` method on the re match object, you can't directly do the named string interpolation as in my lambda parse action. But this is Python, right? We can wrap that callable with a class that will give us dict-like access to the groups by name:
```
class CallableDict(object):
def __init__(self,fn):
self.fn = fn
def __getitem__(self,name):
return self.fn(name)
def mksub(m):
return '<replace name="%(name)s">%(body)s</replace>' % CallableDict(m.group)
s_output = re.sub(pat, mksub, s_input)
```
Using `CallableDict`, the string interpolation in mksub can now call m.group for each field, by making it look like we are retrieving the ['name'] and ['body'] elements of a dict. | ```
import re
a="""Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""
regex = re.compile(r"^REPLACE\(([^)]+)\)\s+(.*)$", re.MULTILINE)
b=re.sub(regex, r'< replace name="\1" > \2 < /replace >', a)
print b
```
will do the replace in one line. |
117,371 | I'm an intern in an industrial company in Brazil and it happens that I'm using excel a lot. I just started playing with VBA couple of days ago, and I'm amused of how many things it can do for me!
I don't have a strong programming background, so I'm learning by doing. The code is working fine and it takes less than 15 seconds from start to finish. I'm not that concerned with the time, but if it could be improved that'd be great.
My main goal is to keep the code simple and efficient. I'll be leaving the company in the next months and I'd like it to be easy to maintain and use. What I'm asking is a better way to write readable code, with performance as a secondary concern.
My code delete 4 sheets of content in my current workbook, and then copies the updated data from 4 other closed workbooks. Then it closes everything. The data is about the daily production and their names are in Portuguese, sorry about that.
```
Sub CopiarBase()
'
' Atalho do teclado: Ctrl+q
'
' Variables
Dim MyCurrentWB As Workbook
Dim BMalharia As Worksheet
Dim BBeneficiamento As Worksheet
Dim BEmbalagem As Worksheet
Dim BDikla As Worksheet
Set MyCurrentWB = ThisWorkbook
Set BMalharia = MyCurrentWB.Worksheets("B-Malharia")
Set BBeneficiamento = MyCurrentWB.Worksheets("B-Beneficiamento")
Set BEmbalagem = MyCurrentWB.Worksheets("B-Embalagem")
Set BDikla = MyCurrentWB.Worksheets("B-Dikla")
'Clean all the cells - Workbook 1
Dim Malharia_rng As Range
Set Malharia_rng = BMalharia.Range("A2:CN" & BMalharia.Cells(Rows.Count, 1).End(xlUp).Row)
Malharia_rng.ClearContents
Dim Ben_rng As Range
Set Ben_rng = BBeneficiamento.Range("A2:CY" & BBeneficiamento.Cells(Rows.Count, 1).End(xlUp).Row)
Ben_rng.ClearContents
Dim Emb_rng As Range
Set Emb_rng = BEmbalagem.Range("A2:CT" & BEmbalagem.Cells(Rows.Count, 1).End(xlUp).Row)
Emb_rng.ClearContents
Dim Dikla_rng As Range
Set Dikla_rng = BDikla.Range("A2:AV" & BDikla.Cells(Rows.Count, 1).End(xlUp).Row)
Dikla_rng.ClearContents
'Copy from Malharia Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Malharia Base.xls"
LastRowMB = Workbooks("Malharia Base.xls").Worksheets("Malharia Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Malha_base As Range
Set Malha_base = Workbooks("Malharia Base.xls").Worksheets("Malharia Base").Range("A2:CN" & LastRowMB)
MyCurrentWB.Worksheets("B-Malharia").Range("A2:CN" & LastRowMB).Value = Malha_base.Value
Workbooks("Malharia Base.xls").Close
'Copy from Beneficiamento Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Beneficiamento Base.xls"
LastRowBB = Workbooks("Beneficiamento Base.xls").Worksheets("Beneficiamento Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Ben_base As Range
Set Ben_base = Workbooks("Beneficiamento Base.xls").Worksheets("Beneficiamento Base").Range("A2:CY" & LastRowBB)
MyCurrentWB.Worksheets("B-Beneficiamento").Range("A2:CY" & LastRowBB).Value = Ben_base.Value
Workbooks("Beneficiamento Base.xls").Close
'Copy from Embalagem Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Embalagem Base.xls"
LastRowEB = Workbooks("Embalagem Base.xls").Worksheets("Embalagem Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Emb_base As Range
Set Emb_base = Workbooks("Embalagem Base.xls").Worksheets("Embalagem Base").Range("A2:CT" & LastRowEB)
MyCurrentWB.Worksheets("B-Embalagem").Range("A2:CT" & LastRowEB).Value = Emb_base.Value
Workbooks("Embalagem Base.xls").Close
'Copy from Dikla Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Diklatex Base.xls"
LastRowDB = Workbooks("Diklatex Base.xls").Worksheets("Diklatex Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Dikla_base As Range
Set Dikla_base = Workbooks("Diklatex Base.xls").Worksheets("Diklatex Base").Range("A2:AV" & LastRowDB)
MyCurrentWB.Worksheets("B-Dikla").Range("A2:AV" & LastRowDB).Value = Dikla_base.Value
Workbooks("Diklatex Base.xls").Close
End Sub
``` | 2016/01/20 | [
"https://codereview.stackexchange.com/questions/117371",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/95263/"
]
| An idea for you:
Right now, your code is assuming all sorts of things about worksheets in **other** workbooks including, but not limited to:
* The names of the other workbooks' worksheets
* The location of the data within those sheets
If any of those workbooks change you'll have to go through every macro that interacts with them and change all the details. This is a huge source of errors and data corruption.
Instead, each of your (other) workbooks should have an internal Macro to export sheet data. That way, if something in your other workbooks changes, you can change the code there, and every other workbook that needs the data won't need to be re-written.
As an example, this is some code from my last VBA project with example usage:
---
From any other workbook that wants the data:
--------------------------------------------
```
Sub test()
Dim wbTarget as Workbook
Set wbTarget = [Workbook Ref]
Dim targetCodeName As String
wbTarget.GetSubsheetCodeNames newClientCodename:=targetCodeName
Dim arr As Variant
arr = wbTarget.GetDataArrayFromSheetByCodename(targetCodeName)
End Sub
```
---
**In the workbook containing the data:**
----------------------------------------
```
Option Explicit
Public Const ADVISER_HEADER As String = "Adviser"
Public Sub GetSubsheetCodeNames( _
Optional ByRef newClientCodename As String _
, Optional ByRef existingClientCodename As String _
, Optional ByRef otherInitialCodename As String _
, Optional ByRef groupSchemesCodename As String _
, Optional ByRef clientWithdrawalsCodename As String)
newClientCodename = wsNewClient.CodeName
existingClientCodename = wsExistingClient.CodeName
otherInitialCodename = wsOtherInitial.CodeName
groupSchemesCodename = wsGroupSchemes.CodeName
clientWithdrawalsCodename = wsClientWithdrawals.CodeName
End Sub
Public Function GetDataArrayFromSheetByCodename(ByVal wsCodename As String) As Variant
'/ returns the dataArray, or an error if could not find worksheet
Dim dataArray As Variant
dataArray = Array()
Dim wsWasFound As Boolean
Dim wsTarget As Worksheet, ws As Worksheet
wsWasFound = False
For Each ws In ThisWorkbook.Worksheets
If ws.CodeName = wsCodename Then
Set wsTarget = ws
wsWasFound = True
Exit For
End If
Next ws
Dim topLeftCellText As String
topLeftCellText = GetWsTopLeftCellText(wsTarget)
Dim tableRange As Range
If wsWasFound Then
dataArray = GetWsDataArray(ThisWorkbook, wsTarget, topLeftCellText, useCurrentRegion:=False)
GetDataArrayFromSheetByCodename = dataArray
Else
GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error
End If
End Function
Private Function GetWsTopLeftCellText(ByRef ws As Worksheet) As String
Dim topLeftCellText As String
Select Case ws.CodeName
Case Is = "wsNewClient"
topLeftCellText = ADVISER_HEADER
Case Is = "wsExistingClient"
topLeftCellText = ADVISER_HEADER
Case Is = "wsOtherInitial"
topLeftCellText = ADVISER_HEADER
Case Is = "wsGroupSchemes"
topLeftCellText = ADVISER_HEADER
Case Is = "wsClientWithdrawals"
topLeftCellText = ADVISER_HEADER
Case Else
'/ TODO: Add Error handling
Stop
End Select
GetWsTopLeftCellText = topLeftCellText
End Function
```
---
```
Public Function GetWsDataArray(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
, Optional ByVal searchStartRow As Long = 1, Optional ByVal searchStartColumn As Long = 1 _
, Optional ByVal searchEndRow As Long = 10, Optional ByVal searchEndColumn As Long = 10) As Variant
'/ 10x10 is arbitrary search range that should cover almost all typical worksheets
Dim dataArray As Variant
dataArray = Array()
dataArray = GetWsDataRange(wbTarget, wsTarget, topLeftCellText, useCurrentRegion, searchStartRow, searchStartColumn, searchEndRow, searchEndColumn)
GetWsDataArray = dataArray
End Function
Public Function GetWsDataRange(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
, ByVal searchStartRow As Long, ByVal searchStartColumn As Long _
, ByVal searchEndRow As Long, ByVal searchEndColumn As Long) As Range
Dim wbSource As Workbook, wsSource As Worksheet
Set wbSource = ActiveWorkbook
Set wsSource = ActiveSheet
wbTarget.Activate
wsTarget.Activate
ShowAllWsCells wsTarget
Dim topLeftCell As Range, searchRange As Range, dataRange As Range
Set searchRange = wsTarget.Range(Cells(searchStartRow, searchStartColumn), Cells(searchEndRow, searchEndColumn))
Set topLeftCell = CellContainingStringInRange(searchRange, topLeftCellText)
Dim lastRow As Long, lastCol As Long
If useCurrentRegion Then
Set dataRange = topLeftCell.CurrentRegion
Else
lastRow = Cells(Rows.Count, topLeftCell.Column).End(xlUp).Row
lastCol = Cells(topLeftCell.Row, Columns.Count).End(xlToLeft).Column
Set dataRange = wsTarget.Range(topLeftCell, Cells(lastRow, lastCol))
End If
Set GetWsDataRange = dataRange
wbSource.Activate
wsSource.Activate
End Function
Public Function CellContainingStringInRange(ByRef rngSearch As Range, ByVal strSearch As String) As Range
Dim errorMessage As String
Set CellContainingStringInRange = rngSearch.Find(strSearch, LookIn:=xlValues)
If CellContainingStringInRange Is Nothing _
Then
errorMessage = "Couldn't find cell """ & strSearch & """ in " & rngSearch.Worksheet.name
PrintErrorMessage errorMessage, stopExecution:=True
End If
End Function
Public Sub ShowAllWsCells(ByRef ws As Worksheet)
ws.Rows.Hidden = False
ws.Columns.Hidden = False
ws.AutoFilterMode = False
End Sub
```
---
As you can see, the workbook containing the data knows all sorts of information about how to locate the data that the other workbooks **do not need to know**.
If it changes, you only have to change the information **in the workbook that changed**.
Any other workbook that wants the data can just ask for it, **and let the target handle the details**.
Also,
---
Codenames
---------
Codenames are big and clever. Every worksheet and workbook has a "name" that the user can see and change.
`MyCurrentWB.Worksheets("B-Dikla")`
is referencing a sheet name.
A Codename on the other hand is a secret name that can **only** be set/changed in the IDE.
[](https://i.stack.imgur.com/6u86p.png)
the name in brackets is the "name". The name not in brackets is the "codename". It is set in the properties window.
[](https://i.stack.imgur.com/KqNBN.png)
If you give a sheet a codename (E.G. "wsBDikla") then the user can change the name as much as they like, all you have to do is use
`wsBDikla.ClearContents`
in your code and it will keep running. | >
> My main goal is to keep the code simple and efficient. I'll be leaving the company in the next months and I'd like it to be easy to maintain and use. What I'm asking is a better way to write readable code, with performance as a secondary concern.
>
>
>
In all manner of repeated processes with minimal variations of a few names and/or addresses, loops and arrays are your friend. You are essentially using three (well... two and a file extension) parameters for each nearly identical process. By loading these into an array and cycling through the array your code becomes significantly more localized; greatly reducing the actual number of code lines. The added benefit is that even minor modifications need only be performed once and mistakes are not multiplied by copying and pasting sections of code. The only detriment to this method is if you get paid by the code line.
There simply isn't enough attention paid to the benefits of implementing nested [With ... End With](https://msdn.microsoft.com/en-us/library/wc500chb.aspx) statements to provide parentage to cells and worksheets. Not only does it (to my eye) make code easier to read by reducing clutter but it speeds up code execution by retaining a parent reference and not reestablishing it line-after-line.
```
Sub CopiarBase()
' Atalho do teclado: Ctrl+q
' Variables
Dim fp As String, w As Long, vWSs As Variant, vTMP As Variant
fp = "C:\Users\marco.henrique\Desktop\Bases\"
vWSs = Array("B-Malharia", "Malharia Base.xls", "Malharia Base", _
"B-Beneficiamento", "Beneficiamento Base.xls", "Beneficiamento Base", _
"B-Embalagem", "Embalagem Base.xls", "Embalagem Base", _
"B-Dikla", "Diklatex Base.xls", "Diklatex Base")
With ThisWorkbook
For w = LBound(vWSs) To UBound(vWSs) Step 3
With .Worksheets(vWSs(w))
'Clean all the cells
With .Cells(1, 1).CurrentRegion
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearContents
End With
'open the matching workbook
With Workbooks.Open(Filename:=fp & vWSs(w + 1), ReadOnly:=True)
'put all the cells' values into an array
With .Worksheets(vWSs(w + 2)).CurrentRegion
vTMP = .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).Value
End With
.Close SaveChanges:=False
End With
'pass the stored values back
.Cells(2, 1).Resize(UBound(vTMP, 1), UBound(vTMP, 2)) = vTMP
End With
Next w
End With
End Sub
```
I've used the [Range.CurrentRegion property](https://msdn.microsoft.com/en-us/library/office/ff196678.aspx) to isolate the block or 'island' of cells that radiates out from A1. This is a bit of a guess as you had them referred to in slightly different range sizes (e.g. A:CN, A:CY, A:CT and A:AV). This would have to be reworked if there actually were completely blank columns or rows.
If these workbooks are reasonably large (e.g. >25K rows) you would see an appreciable decrease in file size (and subsequent load-time) if you could create them as **[Binary Workbooks (\*.xlsb)](https://support.office.com/en-us/article/file-formats-that-are-supported-in-excel-a28ae1d3-6d19-4180-9209-5a950d51b719)**. The .xls extension suggests to me that they are created by an older outside process but a binary workbook format should remain a future consideration. Small filesize (typically 30% of a similar .xlsx or .xlsm) means faster load times and (marginally) faster calculation. |
117,371 | I'm an intern in an industrial company in Brazil and it happens that I'm using excel a lot. I just started playing with VBA couple of days ago, and I'm amused of how many things it can do for me!
I don't have a strong programming background, so I'm learning by doing. The code is working fine and it takes less than 15 seconds from start to finish. I'm not that concerned with the time, but if it could be improved that'd be great.
My main goal is to keep the code simple and efficient. I'll be leaving the company in the next months and I'd like it to be easy to maintain and use. What I'm asking is a better way to write readable code, with performance as a secondary concern.
My code delete 4 sheets of content in my current workbook, and then copies the updated data from 4 other closed workbooks. Then it closes everything. The data is about the daily production and their names are in Portuguese, sorry about that.
```
Sub CopiarBase()
'
' Atalho do teclado: Ctrl+q
'
' Variables
Dim MyCurrentWB As Workbook
Dim BMalharia As Worksheet
Dim BBeneficiamento As Worksheet
Dim BEmbalagem As Worksheet
Dim BDikla As Worksheet
Set MyCurrentWB = ThisWorkbook
Set BMalharia = MyCurrentWB.Worksheets("B-Malharia")
Set BBeneficiamento = MyCurrentWB.Worksheets("B-Beneficiamento")
Set BEmbalagem = MyCurrentWB.Worksheets("B-Embalagem")
Set BDikla = MyCurrentWB.Worksheets("B-Dikla")
'Clean all the cells - Workbook 1
Dim Malharia_rng As Range
Set Malharia_rng = BMalharia.Range("A2:CN" & BMalharia.Cells(Rows.Count, 1).End(xlUp).Row)
Malharia_rng.ClearContents
Dim Ben_rng As Range
Set Ben_rng = BBeneficiamento.Range("A2:CY" & BBeneficiamento.Cells(Rows.Count, 1).End(xlUp).Row)
Ben_rng.ClearContents
Dim Emb_rng As Range
Set Emb_rng = BEmbalagem.Range("A2:CT" & BEmbalagem.Cells(Rows.Count, 1).End(xlUp).Row)
Emb_rng.ClearContents
Dim Dikla_rng As Range
Set Dikla_rng = BDikla.Range("A2:AV" & BDikla.Cells(Rows.Count, 1).End(xlUp).Row)
Dikla_rng.ClearContents
'Copy from Malharia Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Malharia Base.xls"
LastRowMB = Workbooks("Malharia Base.xls").Worksheets("Malharia Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Malha_base As Range
Set Malha_base = Workbooks("Malharia Base.xls").Worksheets("Malharia Base").Range("A2:CN" & LastRowMB)
MyCurrentWB.Worksheets("B-Malharia").Range("A2:CN" & LastRowMB).Value = Malha_base.Value
Workbooks("Malharia Base.xls").Close
'Copy from Beneficiamento Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Beneficiamento Base.xls"
LastRowBB = Workbooks("Beneficiamento Base.xls").Worksheets("Beneficiamento Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Ben_base As Range
Set Ben_base = Workbooks("Beneficiamento Base.xls").Worksheets("Beneficiamento Base").Range("A2:CY" & LastRowBB)
MyCurrentWB.Worksheets("B-Beneficiamento").Range("A2:CY" & LastRowBB).Value = Ben_base.Value
Workbooks("Beneficiamento Base.xls").Close
'Copy from Embalagem Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Embalagem Base.xls"
LastRowEB = Workbooks("Embalagem Base.xls").Worksheets("Embalagem Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Emb_base As Range
Set Emb_base = Workbooks("Embalagem Base.xls").Worksheets("Embalagem Base").Range("A2:CT" & LastRowEB)
MyCurrentWB.Worksheets("B-Embalagem").Range("A2:CT" & LastRowEB).Value = Emb_base.Value
Workbooks("Embalagem Base.xls").Close
'Copy from Dikla Workbook
Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Diklatex Base.xls"
LastRowDB = Workbooks("Diklatex Base.xls").Worksheets("Diklatex Base").Cells(Rows.Count, 1).End(xlUp).Row
Dim Dikla_base As Range
Set Dikla_base = Workbooks("Diklatex Base.xls").Worksheets("Diklatex Base").Range("A2:AV" & LastRowDB)
MyCurrentWB.Worksheets("B-Dikla").Range("A2:AV" & LastRowDB).Value = Dikla_base.Value
Workbooks("Diklatex Base.xls").Close
End Sub
``` | 2016/01/20 | [
"https://codereview.stackexchange.com/questions/117371",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/95263/"
]
| An idea for you:
Right now, your code is assuming all sorts of things about worksheets in **other** workbooks including, but not limited to:
* The names of the other workbooks' worksheets
* The location of the data within those sheets
If any of those workbooks change you'll have to go through every macro that interacts with them and change all the details. This is a huge source of errors and data corruption.
Instead, each of your (other) workbooks should have an internal Macro to export sheet data. That way, if something in your other workbooks changes, you can change the code there, and every other workbook that needs the data won't need to be re-written.
As an example, this is some code from my last VBA project with example usage:
---
From any other workbook that wants the data:
--------------------------------------------
```
Sub test()
Dim wbTarget as Workbook
Set wbTarget = [Workbook Ref]
Dim targetCodeName As String
wbTarget.GetSubsheetCodeNames newClientCodename:=targetCodeName
Dim arr As Variant
arr = wbTarget.GetDataArrayFromSheetByCodename(targetCodeName)
End Sub
```
---
**In the workbook containing the data:**
----------------------------------------
```
Option Explicit
Public Const ADVISER_HEADER As String = "Adviser"
Public Sub GetSubsheetCodeNames( _
Optional ByRef newClientCodename As String _
, Optional ByRef existingClientCodename As String _
, Optional ByRef otherInitialCodename As String _
, Optional ByRef groupSchemesCodename As String _
, Optional ByRef clientWithdrawalsCodename As String)
newClientCodename = wsNewClient.CodeName
existingClientCodename = wsExistingClient.CodeName
otherInitialCodename = wsOtherInitial.CodeName
groupSchemesCodename = wsGroupSchemes.CodeName
clientWithdrawalsCodename = wsClientWithdrawals.CodeName
End Sub
Public Function GetDataArrayFromSheetByCodename(ByVal wsCodename As String) As Variant
'/ returns the dataArray, or an error if could not find worksheet
Dim dataArray As Variant
dataArray = Array()
Dim wsWasFound As Boolean
Dim wsTarget As Worksheet, ws As Worksheet
wsWasFound = False
For Each ws In ThisWorkbook.Worksheets
If ws.CodeName = wsCodename Then
Set wsTarget = ws
wsWasFound = True
Exit For
End If
Next ws
Dim topLeftCellText As String
topLeftCellText = GetWsTopLeftCellText(wsTarget)
Dim tableRange As Range
If wsWasFound Then
dataArray = GetWsDataArray(ThisWorkbook, wsTarget, topLeftCellText, useCurrentRegion:=False)
GetDataArrayFromSheetByCodename = dataArray
Else
GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error
End If
End Function
Private Function GetWsTopLeftCellText(ByRef ws As Worksheet) As String
Dim topLeftCellText As String
Select Case ws.CodeName
Case Is = "wsNewClient"
topLeftCellText = ADVISER_HEADER
Case Is = "wsExistingClient"
topLeftCellText = ADVISER_HEADER
Case Is = "wsOtherInitial"
topLeftCellText = ADVISER_HEADER
Case Is = "wsGroupSchemes"
topLeftCellText = ADVISER_HEADER
Case Is = "wsClientWithdrawals"
topLeftCellText = ADVISER_HEADER
Case Else
'/ TODO: Add Error handling
Stop
End Select
GetWsTopLeftCellText = topLeftCellText
End Function
```
---
```
Public Function GetWsDataArray(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
, Optional ByVal searchStartRow As Long = 1, Optional ByVal searchStartColumn As Long = 1 _
, Optional ByVal searchEndRow As Long = 10, Optional ByVal searchEndColumn As Long = 10) As Variant
'/ 10x10 is arbitrary search range that should cover almost all typical worksheets
Dim dataArray As Variant
dataArray = Array()
dataArray = GetWsDataRange(wbTarget, wsTarget, topLeftCellText, useCurrentRegion, searchStartRow, searchStartColumn, searchEndRow, searchEndColumn)
GetWsDataArray = dataArray
End Function
Public Function GetWsDataRange(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
, ByVal searchStartRow As Long, ByVal searchStartColumn As Long _
, ByVal searchEndRow As Long, ByVal searchEndColumn As Long) As Range
Dim wbSource As Workbook, wsSource As Worksheet
Set wbSource = ActiveWorkbook
Set wsSource = ActiveSheet
wbTarget.Activate
wsTarget.Activate
ShowAllWsCells wsTarget
Dim topLeftCell As Range, searchRange As Range, dataRange As Range
Set searchRange = wsTarget.Range(Cells(searchStartRow, searchStartColumn), Cells(searchEndRow, searchEndColumn))
Set topLeftCell = CellContainingStringInRange(searchRange, topLeftCellText)
Dim lastRow As Long, lastCol As Long
If useCurrentRegion Then
Set dataRange = topLeftCell.CurrentRegion
Else
lastRow = Cells(Rows.Count, topLeftCell.Column).End(xlUp).Row
lastCol = Cells(topLeftCell.Row, Columns.Count).End(xlToLeft).Column
Set dataRange = wsTarget.Range(topLeftCell, Cells(lastRow, lastCol))
End If
Set GetWsDataRange = dataRange
wbSource.Activate
wsSource.Activate
End Function
Public Function CellContainingStringInRange(ByRef rngSearch As Range, ByVal strSearch As String) As Range
Dim errorMessage As String
Set CellContainingStringInRange = rngSearch.Find(strSearch, LookIn:=xlValues)
If CellContainingStringInRange Is Nothing _
Then
errorMessage = "Couldn't find cell """ & strSearch & """ in " & rngSearch.Worksheet.name
PrintErrorMessage errorMessage, stopExecution:=True
End If
End Function
Public Sub ShowAllWsCells(ByRef ws As Worksheet)
ws.Rows.Hidden = False
ws.Columns.Hidden = False
ws.AutoFilterMode = False
End Sub
```
---
As you can see, the workbook containing the data knows all sorts of information about how to locate the data that the other workbooks **do not need to know**.
If it changes, you only have to change the information **in the workbook that changed**.
Any other workbook that wants the data can just ask for it, **and let the target handle the details**.
Also,
---
Codenames
---------
Codenames are big and clever. Every worksheet and workbook has a "name" that the user can see and change.
`MyCurrentWB.Worksheets("B-Dikla")`
is referencing a sheet name.
A Codename on the other hand is a secret name that can **only** be set/changed in the IDE.
[](https://i.stack.imgur.com/6u86p.png)
the name in brackets is the "name". The name not in brackets is the "codename". It is set in the properties window.
[](https://i.stack.imgur.com/KqNBN.png)
If you give a sheet a codename (E.G. "wsBDikla") then the user can change the name as much as they like, all you have to do is use
`wsBDikla.ClearContents`
in your code and it will keep running. | So, here's the deal with getting data from closed workbooks... *you don't actually have to open them*.
Add a reference to the ADODB library and use it to *query* the workbooks as data sources. A bit of searching "use ADODB to query Excel worksheet" should put you onto a much faster solution. The hard part will be getting the connection strings right, and learning the funky Excel/SQL syntax for querying.
This is faster because the workbook never has to be loaded into an instance of Excel. It's read directly from file. |
23,081,395 | I am facing issue to start my tomcat server in netbeans. I am getting error when I click on start button
```
"Starting of tomact failed, check whether the /Application/NetBeans/apache-tomcat-7.0.52/bin/catalina/sh and related scripts are executable."
```
For more details please check screenshot
 | 2014/04/15 | [
"https://Stackoverflow.com/questions/23081395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331568/"
]
| You should run from the command line / shell if you can though I realize you want to run from Netbeans in this case.
Also make sure that all your `.sh` scripts are executable (do a `chmod`) because otherwise they cannot be called.
Lastly, make sure you have the right permissions to run the scripts.
Once you are beyond these checks, you'll possibly get other error messages e.g. your `JAVA_HOME` or your `CATALINA_HOME` are not set. These will be easy to fix.
### EDIT
To run Tomcat from the terminal,
* go to your Tomcat folder (either `TOMCAT_HOME` or `TOMCAT_HOME/bin`).
* Make sure all `.sh` scripts are executable (`chmod a+x *.sh`)
* run `startup.sh`: .`/startup.sh` or `bin/startup.sh` (depending on whether you are inside `TOMCAT_HOME` or inside `TOMCAT_HOME/bin`) | You can make `catalina.sh` runnable by executing following command in terminal
```
chmod 755 <your tomcat location>/bin/catalina.sh
``` |
21,339,759 | I have an situation where I need to save a hibernate object, but I am not sure whether an ID would be assigned by calling app (using special logic with in a range - unique) or not.
If the ID is not assigned, I need hibernate to generate an ID higher than the possible ID range which the app would input (i know the range). Else should go with what using app inputs.
I am working on MySQL - checking to see if I can custom generator like below
```
public class MyDOIdGenerator extends IdentityGenerator{
@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
if ((((MyDO) obj).getId()) == null) {
Serializable id = super.generate(session, obj) ;
return id;
} else {
return ((MyDO) obj).getId();
}
}
}
```
But my problem is, I dont know how the super.generate would behave in a clustered environment. Would it maintain the ID synchronization across servers? How do I specify the number to start from? (Because I need to exclude the app using id range when having hibernate generate it)
Please help
Thanks | 2014/01/24 | [
"https://Stackoverflow.com/questions/21339759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3233126/"
]
| Actually you will still need to do some stuff with your Models in your controller. Use Repository Pattern do to so, which is pretty similar of querying your models in your controller, but being less verbose:
```
public function serve($company)
{
return View::make('layouts.singlereview')->withReview(with(new Review)->getCompanyData($company));
}
```
And put the whole logic in your repository:
```
class Review extends Eloquent {
public function getCompanyData($company)
{
return static::select('head', 'body', 'logo', 'name')
->where('company', '=', $company)
->firstOrFail();
}
}
``` | Also, while you are on the subject of creating good code, you might as well check out Eloquent relationships. They may require database restructuring for certain occurrences, but most of the time you should be good.
With the code you have provided, I can assume that review and company are in a one-to-one relationship, so once this is defined, you can simply retrieve a company object, then do,
```
$review = $company->review;
``` |
84,249 | When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort? | 2017/12/27 | [
"https://movies.stackexchange.com/questions/84249",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/60426/"
]
| From my interpretation, DJ seemed to be bored before he encountered Finn and crew. He had a very relaxed demeanor, indicating that he wasn't stressed out about where he was at all because, as we find out, he could leave at any time.
I think he was probably captured after breaking in somewhere, possibly stealing something, and was locked up and possibly awaiting further processing. He also quite possibly could have been waiting for particular events to happen (changing of guards, casino slowing down for the night, etc.) before making his escape, and finding Finn and Rose accelerated his plans. | DJ has a strange gait, way of talking, and general attitude, so what happens later throws this into question a bit, but I got the very distinct impression that he was thrown in there as a drunk and was sleeping off the alcohol. Finn and Rose being noisy woke him up, so he decided it was time to go. |
84,249 | When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort? | 2017/12/27 | [
"https://movies.stackexchange.com/questions/84249",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/60426/"
]
| From my interpretation, DJ seemed to be bored before he encountered Finn and crew. He had a very relaxed demeanor, indicating that he wasn't stressed out about where he was at all because, as we find out, he could leave at any time.
I think he was probably captured after breaking in somewhere, possibly stealing something, and was locked up and possibly awaiting further processing. He also quite possibly could have been waiting for particular events to happen (changing of guards, casino slowing down for the night, etc.) before making his escape, and finding Finn and Rose accelerated his plans. | Well DJ is not actually the character's real name, but is an abreviation for the philosophy of what DJ believes in: **Don't Join**.
>
> The Star Wars The Last Jedi The Visual Dictionary reveals "DJ" aren't
> his initials but actually stands for "Don't Join." Indeed, his cap
> bears a tin plate with the motto "don't join" stamped on it.
>
>
> DJ is a cynical, opportunistic survivor who **sees society as imbalanced
> in favor of the wealthy and holds little regard for the First Order,
> the Resistance, or the New Republic. "He thinks larger causes are for
> fools, since society is just a machine looking to turn everyone into a
> cog,"** according to the book.
> <http://www.ign.com/articles/2017/12/17/star-wars-the-last-jedi-why-benicio-del-toros-character-is-named-dj>
>
>
>
So although this does not explain this potential DJ "set-up" (juxtaposition to "Old Wookiee Prisoner Trick"), **it may shed some light on where his mind is.**
With the idea of being an anarchist, he may be willing to turn on anyone in order to achieve some goal of wealth-equality. On the other hand, "not joining" is another way to say, "doesn't belong to" and therefor there is an irony in that 'every man for himself' usually does not equivicate a better society, so DJ almost seems like a lost cause at this point...
Obvioiusly though, this is speculative and does not explain to what end DJ is working towards, which would give us a better reason why he was in the cell and if he was in fact waiting for Finn/Rose or any other "criminal" bystander. Perhaps the novelization, which is out in April may shed more light on this. Also there is a Canto Bight Novella, but I have not read it. |
84,249 | When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort? | 2017/12/27 | [
"https://movies.stackexchange.com/questions/84249",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/60426/"
]
| He got himself arrested so the police would stop bothering him.
===============================================================
Taken from p. 65 of *The Last Jedi Visual Dictionary*:
>
> Already known to local authorities, **DJ purposely arranges his own arrest** for a petty crime. The jail is the only place he can grab some sleep with the assurance that he won't be pestered by the Canto Bight Police Department.
>
>
> | From my interpretation, DJ seemed to be bored before he encountered Finn and crew. He had a very relaxed demeanor, indicating that he wasn't stressed out about where he was at all because, as we find out, he could leave at any time.
I think he was probably captured after breaking in somewhere, possibly stealing something, and was locked up and possibly awaiting further processing. He also quite possibly could have been waiting for particular events to happen (changing of guards, casino slowing down for the night, etc.) before making his escape, and finding Finn and Rose accelerated his plans. |
84,249 | When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort? | 2017/12/27 | [
"https://movies.stackexchange.com/questions/84249",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/60426/"
]
| Well DJ is not actually the character's real name, but is an abreviation for the philosophy of what DJ believes in: **Don't Join**.
>
> The Star Wars The Last Jedi The Visual Dictionary reveals "DJ" aren't
> his initials but actually stands for "Don't Join." Indeed, his cap
> bears a tin plate with the motto "don't join" stamped on it.
>
>
> DJ is a cynical, opportunistic survivor who **sees society as imbalanced
> in favor of the wealthy and holds little regard for the First Order,
> the Resistance, or the New Republic. "He thinks larger causes are for
> fools, since society is just a machine looking to turn everyone into a
> cog,"** according to the book.
> <http://www.ign.com/articles/2017/12/17/star-wars-the-last-jedi-why-benicio-del-toros-character-is-named-dj>
>
>
>
So although this does not explain this potential DJ "set-up" (juxtaposition to "Old Wookiee Prisoner Trick"), **it may shed some light on where his mind is.**
With the idea of being an anarchist, he may be willing to turn on anyone in order to achieve some goal of wealth-equality. On the other hand, "not joining" is another way to say, "doesn't belong to" and therefor there is an irony in that 'every man for himself' usually does not equivicate a better society, so DJ almost seems like a lost cause at this point...
Obvioiusly though, this is speculative and does not explain to what end DJ is working towards, which would give us a better reason why he was in the cell and if he was in fact waiting for Finn/Rose or any other "criminal" bystander. Perhaps the novelization, which is out in April may shed more light on this. Also there is a Canto Bight Novella, but I have not read it. | DJ has a strange gait, way of talking, and general attitude, so what happens later throws this into question a bit, but I got the very distinct impression that he was thrown in there as a drunk and was sleeping off the alcohol. Finn and Rose being noisy woke him up, so he decided it was time to go. |
84,249 | When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort? | 2017/12/27 | [
"https://movies.stackexchange.com/questions/84249",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/60426/"
]
| He got himself arrested so the police would stop bothering him.
===============================================================
Taken from p. 65 of *The Last Jedi Visual Dictionary*:
>
> Already known to local authorities, **DJ purposely arranges his own arrest** for a petty crime. The jail is the only place he can grab some sleep with the assurance that he won't be pestered by the Canto Bight Police Department.
>
>
> | DJ has a strange gait, way of talking, and general attitude, so what happens later throws this into question a bit, but I got the very distinct impression that he was thrown in there as a drunk and was sleeping off the alcohol. Finn and Rose being noisy woke him up, so he decided it was time to go. |
84,249 | When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort? | 2017/12/27 | [
"https://movies.stackexchange.com/questions/84249",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/60426/"
]
| He got himself arrested so the police would stop bothering him.
===============================================================
Taken from p. 65 of *The Last Jedi Visual Dictionary*:
>
> Already known to local authorities, **DJ purposely arranges his own arrest** for a petty crime. The jail is the only place he can grab some sleep with the assurance that he won't be pestered by the Canto Bight Police Department.
>
>
> | Well DJ is not actually the character's real name, but is an abreviation for the philosophy of what DJ believes in: **Don't Join**.
>
> The Star Wars The Last Jedi The Visual Dictionary reveals "DJ" aren't
> his initials but actually stands for "Don't Join." Indeed, his cap
> bears a tin plate with the motto "don't join" stamped on it.
>
>
> DJ is a cynical, opportunistic survivor who **sees society as imbalanced
> in favor of the wealthy and holds little regard for the First Order,
> the Resistance, or the New Republic. "He thinks larger causes are for
> fools, since society is just a machine looking to turn everyone into a
> cog,"** according to the book.
> <http://www.ign.com/articles/2017/12/17/star-wars-the-last-jedi-why-benicio-del-toros-character-is-named-dj>
>
>
>
So although this does not explain this potential DJ "set-up" (juxtaposition to "Old Wookiee Prisoner Trick"), **it may shed some light on where his mind is.**
With the idea of being an anarchist, he may be willing to turn on anyone in order to achieve some goal of wealth-equality. On the other hand, "not joining" is another way to say, "doesn't belong to" and therefor there is an irony in that 'every man for himself' usually does not equivicate a better society, so DJ almost seems like a lost cause at this point...
Obvioiusly though, this is speculative and does not explain to what end DJ is working towards, which would give us a better reason why he was in the cell and if he was in fact waiting for Finn/Rose or any other "criminal" bystander. Perhaps the novelization, which is out in April may shed more light on this. Also there is a Canto Bight Novella, but I have not read it. |
26,236,662 | How can I create a script that checks if a process is running, and when it is not running executes a line of codes? And let the script check every minute?
I was thinking of something like this:
```
#! /bin/bash
case "$(pidof Program.exe | wc -w)" in
0) echo "Restarting Program: $(date)" >> /var/log/ProgramLog.txt
(mono-runtime Program.exe -option1 yes -option2 no -option3 6; 1) &
;;
1) # all ok
;;
*) echo "Removed double Program: $(date)" >> /var/log/ProgramLog.txt
kill $(pidof Program.exe | awk '{print $1}')
;;
esac
```
0: If no process is found execute the code
1: If process is found do nothing
\*: If there is more than 1 process found stop the last one
there are 2 codes to execute:
mono-runtime Program.exe -option1 yes -option2 no -option3 6
and behind the semicolon: 1
Is this a correct way to do that?:
(mono-runtime Program.exe -option1 yes -option2 no -option3 6; 1) & | 2014/10/07 | [
"https://Stackoverflow.com/questions/26236662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3572440/"
]
| The monit (small software) will do all this job for you:
Please look here:
```
https://mmonit.com/monit/documentation/
``` | IIUC you're trying to make sure there's always one instance of your program running on the machine. Have you considered adding this program to `/etc/inittab`? With this file you can configure your init system to run the program for you and restart whenever it exits (crashes).
Some more information: <http://unixhelp.ed.ac.uk/CGI/man-cgi?inittab+5> |
12,664 | I am using a Microsoft template for adding Training and Courses for people to register for. Everything is working fine, but I want to add a field to the Courses list. I want to add a field to indicate what type of staff this course is for, eg HR, Health & Safety, Admin, etc.
So I have searched all over for answers to this, the documentation on SharePoint is shocking, and I did the following:
* Settings > Create Column on the Courses page.
* Entered all necessary details
* On DispForm, EditForm and NewForm (.aspx) added `@fStaffType, Staff Type;` to `DataFields` section. (`Staff Type` is the name of the field`)
* On DispForm added a new row to display the data:
```
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<H3 class="ms-standardheader">
<nobr>Staff Type</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<xsl:value-of select="@fStaffType"/>
</td>
</tr>
```
* On EditForm and NewForm added a new row to edit/enter data:
```
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<H3 class="ms-standardheader">
<nobr>Staff Type</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<SharePoint:FormField runat="server" id="ff12{$Pos}" ControlMode="New" FieldName="fStaffType" __designer:bind="{ddwrt:DataBind('i',concat('ff12',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@fStaffType')}"/>
<SharePoint:FieldDescription runat="server" id="ff12description{$Pos}" FieldName="fStaffType" ControlMode="New"/>
</td>
</tr>
```
On EditForm and NewForm I get the error:
>
> Error Rendering Control -
> ff12description\_1
>
>
> An unhandled exception has occured.
> Object reference not set to an
> instance of an object.
>
>
>
If I comment out the description it will show the first `td` (Field Name) but the second `td` is just empty.
Any help would be greatly appreciated!
EDIT: A related problem, don't know if I should create a new question or not. But Marc D Anderson answered below and I was able to add and display a new field. However, I can add a new Course perfectly but if I edit one, and change the Staff Type field, a new Course will be created at the current day and time. But if other fields are edited they edit correctly.
Any ideas? | 2011/05/13 | [
"https://sharepoint.stackexchange.com/questions/12664",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3393/"
]
| Looks like ff12 is already defined somewhere else in the page and it's probably re-writing with \_1 at the end.
1. Can you just try drag and drop the field from the Data Source and let the designer figure out the field names?
OR
1. Can you try adding the "Custom Edit Form" in another page and then copy the FieldDescription? | I may have not read or got good grasp of your needs. Why not implement Content Type? You could have feature for your custom fields (aka columns) and set attribute like diplay on edit form=true, show on view = true (etc.) |
12,664 | I am using a Microsoft template for adding Training and Courses for people to register for. Everything is working fine, but I want to add a field to the Courses list. I want to add a field to indicate what type of staff this course is for, eg HR, Health & Safety, Admin, etc.
So I have searched all over for answers to this, the documentation on SharePoint is shocking, and I did the following:
* Settings > Create Column on the Courses page.
* Entered all necessary details
* On DispForm, EditForm and NewForm (.aspx) added `@fStaffType, Staff Type;` to `DataFields` section. (`Staff Type` is the name of the field`)
* On DispForm added a new row to display the data:
```
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<H3 class="ms-standardheader">
<nobr>Staff Type</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<xsl:value-of select="@fStaffType"/>
</td>
</tr>
```
* On EditForm and NewForm added a new row to edit/enter data:
```
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<H3 class="ms-standardheader">
<nobr>Staff Type</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<SharePoint:FormField runat="server" id="ff12{$Pos}" ControlMode="New" FieldName="fStaffType" __designer:bind="{ddwrt:DataBind('i',concat('ff12',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@fStaffType')}"/>
<SharePoint:FieldDescription runat="server" id="ff12description{$Pos}" FieldName="fStaffType" ControlMode="New"/>
</td>
</tr>
```
On EditForm and NewForm I get the error:
>
> Error Rendering Control -
> ff12description\_1
>
>
> An unhandled exception has occured.
> Object reference not set to an
> instance of an object.
>
>
>
If I comment out the description it will show the first `td` (Field Name) but the second `td` is just empty.
Any help would be greatly appreciated!
EDIT: A related problem, don't know if I should create a new question or not. But Marc D Anderson answered below and I was able to add and display a new field. However, I can add a new Course perfectly but if I edit one, and change the Staff Type field, a new Course will be created at the current day and time. But if other fields are edited they edit correctly.
Any ideas? | 2011/05/13 | [
"https://sharepoint.stackexchange.com/questions/12664",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3393/"
]
| Many of the ["Fabulous 40" templates](http://technet.microsoft.com/en-us/windowsserver/sharepoint/bb407286.aspx) have customized forms. (You'll probably debate the fabulous part of the name at this point.)
It looks like you are doing roughly the right things in the forms, but it's a little hard to tell where it's going south on you.
When you created the new column, did you give it a name of "fStaffType"? If not, that's the issue. If you named it "Staff Type", then the internal name (or StaticName) for the column is "Staff\_x0020\_Type". (The space in the name will be encoded.) EDIT: You can find the StaticName for a column by going into list settings and editing that column. The StaticName will be at the end of the URL as a Query String parameter. Depending on which characters you have used, it may bedouble encoded, like Staff%5Fx0020%5FType.
You don't need to add the column DisplayName and StaticName to the DiataFields section -- it doesn't really serve any obvious purpose, frankly. You'll just need to make sure that the column name in the SharePoint:FormField and SharePoint:FieldDescription matches the StaticName for the column name you've added.
The trailing "\_1" in the error is part of the unique name that SharePoint gives each instance of that column in the page (you could be allowing edits to multiple items in the same form) by appending the value of the $Pos variable. | Looks like ff12 is already defined somewhere else in the page and it's probably re-writing with \_1 at the end.
1. Can you just try drag and drop the field from the Data Source and let the designer figure out the field names?
OR
1. Can you try adding the "Custom Edit Form" in another page and then copy the FieldDescription? |
12,664 | I am using a Microsoft template for adding Training and Courses for people to register for. Everything is working fine, but I want to add a field to the Courses list. I want to add a field to indicate what type of staff this course is for, eg HR, Health & Safety, Admin, etc.
So I have searched all over for answers to this, the documentation on SharePoint is shocking, and I did the following:
* Settings > Create Column on the Courses page.
* Entered all necessary details
* On DispForm, EditForm and NewForm (.aspx) added `@fStaffType, Staff Type;` to `DataFields` section. (`Staff Type` is the name of the field`)
* On DispForm added a new row to display the data:
```
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<H3 class="ms-standardheader">
<nobr>Staff Type</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<xsl:value-of select="@fStaffType"/>
</td>
</tr>
```
* On EditForm and NewForm added a new row to edit/enter data:
```
<tr>
<td width="190px" valign="top" class="ms-formlabel">
<H3 class="ms-standardheader">
<nobr>Staff Type</nobr>
</H3>
</td>
<td width="400px" valign="top" class="ms-formbody">
<SharePoint:FormField runat="server" id="ff12{$Pos}" ControlMode="New" FieldName="fStaffType" __designer:bind="{ddwrt:DataBind('i',concat('ff12',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@fStaffType')}"/>
<SharePoint:FieldDescription runat="server" id="ff12description{$Pos}" FieldName="fStaffType" ControlMode="New"/>
</td>
</tr>
```
On EditForm and NewForm I get the error:
>
> Error Rendering Control -
> ff12description\_1
>
>
> An unhandled exception has occured.
> Object reference not set to an
> instance of an object.
>
>
>
If I comment out the description it will show the first `td` (Field Name) but the second `td` is just empty.
Any help would be greatly appreciated!
EDIT: A related problem, don't know if I should create a new question or not. But Marc D Anderson answered below and I was able to add and display a new field. However, I can add a new Course perfectly but if I edit one, and change the Staff Type field, a new Course will be created at the current day and time. But if other fields are edited they edit correctly.
Any ideas? | 2011/05/13 | [
"https://sharepoint.stackexchange.com/questions/12664",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3393/"
]
| Many of the ["Fabulous 40" templates](http://technet.microsoft.com/en-us/windowsserver/sharepoint/bb407286.aspx) have customized forms. (You'll probably debate the fabulous part of the name at this point.)
It looks like you are doing roughly the right things in the forms, but it's a little hard to tell where it's going south on you.
When you created the new column, did you give it a name of "fStaffType"? If not, that's the issue. If you named it "Staff Type", then the internal name (or StaticName) for the column is "Staff\_x0020\_Type". (The space in the name will be encoded.) EDIT: You can find the StaticName for a column by going into list settings and editing that column. The StaticName will be at the end of the URL as a Query String parameter. Depending on which characters you have used, it may bedouble encoded, like Staff%5Fx0020%5FType.
You don't need to add the column DisplayName and StaticName to the DiataFields section -- it doesn't really serve any obvious purpose, frankly. You'll just need to make sure that the column name in the SharePoint:FormField and SharePoint:FieldDescription matches the StaticName for the column name you've added.
The trailing "\_1" in the error is part of the unique name that SharePoint gives each instance of that column in the page (you could be allowing edits to multiple items in the same form) by appending the value of the $Pos variable. | I may have not read or got good grasp of your needs. Why not implement Content Type? You could have feature for your custom fields (aka columns) and set attribute like diplay on edit form=true, show on view = true (etc.) |
787,992 | Let $G$ be a reductive group and $B$ a Borel subgroup. The Bruhat decomposition allows us to write (where $W$ is the Weyl group):
$$ G/B = \coprod\_{w\in W} BwB$$
Why is this form the same as looking at the $G$-orbit decomposition ($G$ acting diagonally):
$$ (G/B)^2 = \coprod\_{w\in W} G\cdot (eB,wB)$$
I believe this generalizes. If $P\_1,...,P\_n$ are parabolic subgroups, then looking at the orbits of the diagonal $G$ action on $G/P\_1\times ... \times G/P\_n$ is the same as the orbit structure of the $P\_1$ action on $G/P\_2 \times ... \times G/P\_n$. | 2014/05/09 | [
"https://math.stackexchange.com/questions/787992",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/130769/"
]
| So, suppose
$$G/B = \coprod\_{w \in W} B w B.$$
Then, pick $(gB, hB) \in (G/B)^{2}.$ We can find $w$ such that $g^{-1}h \in BwB$. Say $g^{-1}hB = bwB$. Then, $b^{-1}g^{-1}h \in wB$ and hence,
$$(gB, hB) = gb(eB, b^{-1}g^{-1}hB) = gb(eB, wB).$$
Hence, $(G/B)^{2} \subseteq \coprod\_{w \in W} G\cdot (eB, wB)$, and the reverse inclusion is obvious.
Now, suppose
$$(G/B)^{2} \subseteq \coprod\_{w \in W} G \cdot (eB, wB).$$
Pick $gB \in G/B$. Then, for some $w \in W$, and $g \in G$,
$$(eB, gB) = (g'B, g'wB)$$
and hence $g' \in B$ and hence $gB \in BwB.$ Hence, $G/B \subseteq \coprod\_{w \in W} BwB$ and the reverse inclusion is trivial. | This is just an instance of the following general fact. Suppose a group $G$ acts *transitively* on two sets $X,Y$. Choose any $x\_0\in X$ and $y\_0\in Y$, and put $\def\Stab{\operatorname{Stab}\_G}H\_x=\Stab(x\_0)$ and $H\_y=\Stab(y\_0)$. Then there is a bijection between on one hand the orbits of $G$ acting componentwise on $X\times Y$, and on the other hand the set of double cosets $H\_x\backslash G/H\_y$: the orbit of $(x,y)$ corresponds to the double coset $H\_xg\_1^{-1}g\_2H\_y$ where $g\_1,g\_2$ are any group elements with $g\_1\cdot x\_0=x$ and $g\_2\cdot y\_0=y$. Since the elements $g\_1,g\_2$ are determined up to right multiplication by $H\_x$ respectively by $H\_y$, the double coset associated to $(x,y)$ is well defined, and it does not change if $(x,y)$ is replaced by another point $(g\cdot x,g\cdot y)$ in its orbit. Moreover
any double coset $H\_xgH\_y$ corresponds to some orbit, namely that of the point $(x\_0,g\cdot y\_0)$, so the correspondence is surjective, and its injectivity is also easily checked.
Now in the case of the question one can take $X=Y$ the set $\def\B{\mathcal B}\B$ of Borel subgroups; since these Borel subgroups are their own normalisers, $\B$ is in bijection with $G/B$ once the particular Borel subgroup $B$ is chosen (via $gBg^{-1}\mapsto gB$), and one chooses $x\_0=y\_0=B$ as base point, for which $H\_x=H\_y=B$. Now the Bruhat decomposition says that $W$ provides a set of double coset representatives for $B\backslash G/B$, and by the general correspondence I indicated this also means that $\{\,(x\_0,w\cdot y\_0)\mid w\in W\,\}$ is a set of representatives for the diagonal $B$-orbits on $\B\times\B$. The element $(x\_0,w\cdot y\_0)$ is actually $(B,wBw^{-1})$ in $\B\times\B$, or under the map $\B\to G/B$ it is $(eB,wB)$ in $(G/B)^2$. |
60,231,231 | I'm trying to make a regex to identify a comment. It has to start with // and end with a new line or a \*) pattern. | 2020/02/14 | [
"https://Stackoverflow.com/questions/60231231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12899942/"
]
| Set `closeOnSelect` to `false`
```
<ng-select [items]="items"
bindLabel="name"
bindValue="id"
[multiple]="true"
[closeOnSelect]="false"
placeholder="Select categories"
[(ngModel)]="selectedCategories">
</ng-select>
``` | Try using the `isOpen` property:
```
<ng-select [items]="items"
[isOpen]="true" // <--- This one
bindLabel="name"
bindValue="id"
[multiple]="true"
placeholder="Select categories"
[(ngModel)]="selectedCategories">
</ng-select>
``` |
14,888,843 | I have my two log files in my django root dir called `apache.error.log` and `django.log`. In my `app/static` folder I have the HTML file `mylog.html`. Now I want to view those log files inside that HTML page.
Is this possible? I want to view the last 20 lines of both files. basically something like `tail -f`, but inside the browser so that I can have my one tab always open for debugging. | 2013/02/15 | [
"https://Stackoverflow.com/questions/14888843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024264/"
]
| If you're using Class Based Views:
```
class LogTemplateView(TemplateView):
template_name = "mylog.html"
apache_log_file = "apache.error.log"
django_log_file = "django.log"
def get_context_data(self, **kwargs):
"""
This has been overriden to give the template access to the log files.
i.e. {{ apache_log_file }} and {{ django_log_file }}
"""
context = super(LogTemplateView, self).get_context_data(**kwargs)
context["apache_log_file"] = self.tail(open(self.apache_log_file, "r"), 20)
context["django_log_file"] = self.tail(open(self.django_log_file, "r"), 20)
return context
# Credit: Armin Ronacher - http://stackoverflow.com/a/692616/1428653
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
``` | Create a new view in Django
in the controller, `import os`
use `lastLines = os.popen("tail /path/to/logFile").read()`
show these `listLines` in the view |
62,116,031 | I have a `SerialPort` object. I have put an event handler on this to monitor disposal, exceptions and received data events:
```
mySp.DataReceived += sp_DataReceived;
mySp.ErrorReceived += sp_ErrorReceived;
mySp.Disposed += sp_Disposed;
```
After a few minutes I stop receiving data, but I have good reason to believe this is not an issue with the sender of the serial messages.
I've had issues in this app before with GC disposing things I needed (`Threading.Timer` objects), so I want to make sure this `SerialPort` is not being disposed. I attached a `Disposed` handler, but I've just read GC would not invoke `Dispose` - so how can I tell if it's GC or an issue elsewhere? | 2020/05/31 | [
"https://Stackoverflow.com/questions/62116031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12683473/"
]
| With the GC we can never say if it is or when it is collected - only if it **CAN** be collected. The rule is "the GC can collect everything that does not have a chain of strong references to a application root." If you got that, the GC will not touch it. If you do not have it the GC may touch it - eventually.
Running the GC is expensive. While it collects, all other threads *must pause*. Accordingly the Framework is lazy at running it. If it only runs once - on application closure - that is the ideal case. Before that only some rare scenarios can get it into action:
* The danger of a OOM Exception. Before those happen, the GC will have collected everything it can.
* Manually calling it
* various optimsiations. Like trying to collect everything you created inside the function you just finished.
* any alternate GC strategy, like the one optimized for servers
As for your problem:
**As long as you keep a strong reference to something, it can not be collected**.
If you got a strong reference, the GC has to assume you are working on it and it is not supposed to remove it. It may still do other background stuff with it (like moving it around in memory), but those changes are usually invisible for you.
The only way to cause a memory leak with a GC like this, is to forgetting to remove all strong references to something. Mostly it is people forgetting to remove it from a Collection.
Event handlers by design do not count as "a unbroken chain of strong references". GUI Automatics already have a strong reference chain to everything that is displayed (and the stuff that is only hidden, not undisplayed).
I think you are doing some wierd way of multitasking like this:
* you create a instance
* you register events
* you do not keep a strong reference
This will not work. You need to use a proper way of multitasking - ideally using some blocking or polling code - to process them. That would also allow you to get Exceptions out of the SerialPorts. | To answer the question "how do I know if my objects are collected":
1. Inspect the code. Ensure that you keep a reference to the object in question.
2. You can wrap the object and add a [finalizer](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/destructors) to the wrapper. If you reach the finalizer you know your object is about to be collected.
3. Use a memory profiler. This lets you capture a snapshot and search for the number of objects in memory. That way you can see if whatever object you use exists or not. I'm not aware of any competent free alternative, but there are often trial versions of the commercial systems.
Other things to keep in mind:
1. Ensure you watch for any exceptions and other faults that occur. Some APIs have events or other extension points where you can listen for problems. This might reveal if there is some internal problem causing the messages to stop.
2. Not sure what you are using for serial communication, but some libraries or even drivers can be unreliable. It might be an idea to switch versions or even hardware to see if this avoids the problem. |
40,889,351 | Can you please advise how i can implement this sql query:
```
select * from products where (category, category2, category3) in (2, 138, 136, 125)
```
Error:
```
#1241 - Operand should contain 3 column(s)
``` | 2016/11/30 | [
"https://Stackoverflow.com/questions/40889351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7230953/"
]
| 1) input variable : continuous / output variable : categorical
C4.5 algorithm solve this situation.
[C4.5](https://en.wikipedia.org/wiki/C4.5_algorithm)
In order to handle continuous attributes, C4.5 creates a threshold and then splits the list into those whose attribute value is above the threshold and those that are less than or equal to it.
2) input variable : continuous / output variable : continuous
CART(classification and regression trees) algorithm solves this situation. [CART](https://en.wikipedia.org/wiki/Decision_tree_learning)
Case 2 is the regression problem. You should enumerate the attribute `j`, and enumerate the values `s` in that attribute, and then splits the list into those whose attribute value is above the threshold and those that are less than or equal to it. Then you get two areas
[](https://i.stack.imgur.com/oecME.png)
Find the best attribute `j` and the best split value `s`, which
[](https://i.stack.imgur.com/PIAH0.png)
`c_1` and `c_2` and be solved as follows:
[](https://i.stack.imgur.com/CBCGj.png)
Then when do regression,
[](https://i.stack.imgur.com/y19cp.png)
where
[](https://i.stack.imgur.com/sga1c.png) | I can explain the concept at a very high level.
The main goal of the algorithm is to find an attribute that we will use for the first split. We can use various impurity metrics to evaluate the most significant attribute. Those impurity metrics can be Information Gain, Entropy, Gain Ratio, etc. But, if the decision variable is a continuous type variable, then we usually use another impurity metric 'standard deviation reduction'. But, whatever metric you use, depending on your algorithm (i.e. ID3, C4.5, etc) you actually find an attribute that will be used for splitting.
When you have a continuous type attribute, then things get a little tricky. You need to find a threshold value for an attribute that will give you the highest impurity (Entropy, Gain Ratio, Information Gain ... whatever). Then, you find which attribute's threshold value gives that highest impurity, and then chose an attribute accordingly, right?
Now, if the attribute is a continuous type and decision variable is also continuous type, then you can simply combine the above two concepts and generate the Regression Tree.
That means, as the decision variable is continuous type, you will use the metric (like Variance reduction) and chose the attribute which will give you the highest value of the chosen metric (i.e. variance reduction) for the threshold value of all attributes.
You can visualize such a regression tree using a Decision Tree Machine Learning software like [SpiceLogic Decision Tree Software](https://www.spicelogic.com/Products/decision-tree-software-27)
Say, you have a data table like this:
[](https://i.stack.imgur.com/jMpds.png)
The software will generate the Regression tree like this:
[](https://i.stack.imgur.com/tusIs.png) |
49,819,295 | In Xamarin.Android, to load an image using FFImageLoading, a ImageViewAsync must be used instead of a standard ImageView.
I couldn't find what I can use if I wanna load my image into an ImageButton. Didn't find an "ImageButtonAsync". | 2018/04/13 | [
"https://Stackoverflow.com/questions/49819295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Dont know if this is relevant or not. I gave my svg a tap gesture to get it working like a button.
first reference the FFImageLoading.Svg.Forms in your xaml
```
namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
```
second add the svgImage with a tap gesture
```
<ffimageloadingsvg:SvgCachedImage Source="YourImageSource" >
<ffimageloadingsvg:SvgCachedImage.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding YourCommand}"/>
</ffimageloadingsvg:SvgCachedImage.GestureRecognizers>
</ffimageloadingsvg:SvgCachedImage>
```
You will call this in the constructor of your ViewModel to initialize the command
```
YourCommand= new DelegateCommand(async () => await ExecuteYourCommandAsync());
```
Create the properties that bind to the xaml file
```
public ICommand YourCommand
{
get => yourCommand;
set => SetProperty(ref yourCommand, value);
}
private ICommand yourCommand;
```
The await ExecuteYourCommandAsync is a method that you create. and in there you will put your logic of what you actually want the tap gesture to do.
You can also pass through object with the command. let met know if this makes sense | AFAIK there is no particular `ImageButton` to use with FFImageLoading but you can use directly an `ImageViewAsync` set it as `android:clickable="true"` and add the click event.
And as stated [here](https://stackoverflow.com/questions/5847136/difference-between-a-clickable-imageview-and-imagebutton?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) an `ImageButton` is just an `ImageView` that has a non-null background by default and also, ImageButton.onSetAlpha() method always returns false, scaleType is set to center and it's always inflated as focusable. So if you need that behaviour you can add it.
Another way would be you to create your custom `ImageButton` that can handle FFImageLoading image loading. For that you can inherit from `ImageViewAsync` and add the behaviours explained in the paragraph before. So that you can use the FFImageLoading API directly as this custom controls inherits `ImageViewAsync`.
Instead of that you can also add your custom loading logic as explained [here](https://github.com/luberda-molinet/FFImageLoading/wiki/Advanced-Usage) inheriting from `ImageLoaderTask` and call it like `ImageService.Instance.LoadImage(customImageTask)`
Finally another way (but hackish and non-performant) would be to create an `ImageViewAsync` just to hold the result of the FFImageLoading and on the Success callback set the Drawable in the `ImageButton`:
```
var myImageButton = myView.FindViewById<ImageButton>(Resource.Id.my_image_button);
var myImageView = new ImageViewAsync(this); // this is the context
ImageService.Instance.LoadUrl(this.Source[position].LogoImagePath)
.Success(() => myImageButton.SetImageDrawable(myImageView.Drawable))
.Into(myImageView);
```
HIH and if you need any help let me know |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| I believe you´re making a common mistake. You forgot to close the stream after using it!
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
``` | Your first line:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
```
gave me pause, as the values are not guaranteed to be `Serializable` and thus may not be written out correctly. You should really define the object as a `HashMap<String, Serializable>` (or if you prefer, simpy `Map<String, Serializable>`).
I would also consider serializing the Map in a simple text format such as JSON since you are doing a simple `String -> List<String>` mapping. |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| I believe you´re making a common mistake. You forgot to close the stream after using it!
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
``` | I believe you're getting what you're saving. Have you inspected the map before you save it? In `HashMap`:
```
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
```
e.g. the default `HashMap` will start off with 16 `null`s. You use one of the buckets, so you only have 15 `null`s left when you save, which is what you get when you load.
Try inspecting `fileObj.keySet()`, `.entrySet()` or `.values()` to see what you expect.
`HashMap`s are designed to be fast while trading off memory. See [Wikipedia's Hash table](http://en.wikipedia.org/wiki/Hash_table) entry for more details. |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
```
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
``` | I believe you´re making a common mistake. You forgot to close the stream after using it!
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
``` |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
```
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
``` | Your first line:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
```
gave me pause, as the values are not guaranteed to be `Serializable` and thus may not be written out correctly. You should really define the object as a `HashMap<String, Serializable>` (or if you prefer, simpy `Map<String, Serializable>`).
I would also consider serializing the Map in a simple text format such as JSON since you are doing a simple `String -> List<String>` mapping. |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| you can also use JSON file to read and write MAP object.
>
> To write map object into JSON file
>
>
>
```
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Suson");
map.put("age", 26);
// write JSON to a file
mapper.writeValue(new File("c:\\myData.json"), map);
```
>
> To read map object from JSON file
>
>
>
```
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\\myData.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
```
and import ObjectMapper from com.fasterxml.jackson and put code in try catch block | Your first line:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
```
gave me pause, as the values are not guaranteed to be `Serializable` and thus may not be written out correctly. You should really define the object as a `HashMap<String, Serializable>` (or if you prefer, simpy `Map<String, Serializable>`).
I would also consider serializing the Map in a simple text format such as JSON since you are doing a simple `String -> List<String>` mapping. |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
```
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
``` | I believe you're getting what you're saving. Have you inspected the map before you save it? In `HashMap`:
```
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
```
e.g. the default `HashMap` will start off with 16 `null`s. You use one of the buckets, so you only have 15 `null`s left when you save, which is what you get when you load.
Try inspecting `fileObj.keySet()`, `.entrySet()` or `.values()` to see what you expect.
`HashMap`s are designed to be fast while trading off memory. See [Wikipedia's Hash table](http://en.wikipedia.org/wiki/Hash_table) entry for more details. |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| you can also use JSON file to read and write MAP object.
>
> To write map object into JSON file
>
>
>
```
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Suson");
map.put("age", 26);
// write JSON to a file
mapper.writeValue(new File("c:\\myData.json"), map);
```
>
> To read map object from JSON file
>
>
>
```
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\\myData.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
```
and import ObjectMapper from com.fasterxml.jackson and put code in try catch block | I believe you're getting what you're saving. Have you inspected the map before you save it? In `HashMap`:
```
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
```
e.g. the default `HashMap` will start off with 16 `null`s. You use one of the buckets, so you only have 15 `null`s left when you save, which is what you get when you load.
Try inspecting `fileObj.keySet()`, `.entrySet()` or `.values()` to see what you expect.
`HashMap`s are designed to be fast while trading off memory. See [Wikipedia's Hash table](http://en.wikipedia.org/wiki/Hash_table) entry for more details. |
3,347,504 | I have the following **HashMap**:
```
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
```
I write it to a file as follows:
```
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
```
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
```
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
```
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
**ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.**
*In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).*
Thanks, | 2010/07/27 | [
"https://Stackoverflow.com/questions/3347504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403828/"
]
| You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
```
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
``` | you can also use JSON file to read and write MAP object.
>
> To write map object into JSON file
>
>
>
```
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Suson");
map.put("age", 26);
// write JSON to a file
mapper.writeValue(new File("c:\\myData.json"), map);
```
>
> To read map object from JSON file
>
>
>
```
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\\myData.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
```
and import ObjectMapper from com.fasterxml.jackson and put code in try catch block |
14,996,632 | There are some `C#` console applications that started by **Windows scheduler**.
How can I gather work progress from any of them (using internal data available only in concrete console application)?
In other words, I want to show some data from running console application on my asp.net webforms website.
How can i do this? | 2013/02/21 | [
"https://Stackoverflow.com/questions/14996632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083527/"
]
| Host a http server inside the console app that the website can communicate with. I already kind of do this using self host signal r inside a tray application and it works a treat.
<https://github.com/SignalR/SignalR/wiki/Self-host> | I would preferred old good [.NET Remouting](http://msdn.microsoft.com/en-us/library/kwdt6w2k%28v=vs.100%29.aspx) for this (check out [simple example for it](http://www.codeproject.com/Articles/10045/NET-Remoting-Sample)). But you can use WCF with NetNamedPipesBinding or NetTcpBinding binding. |
25,409,822 | In my package, before I perform a query on my database I check if some of the params provided are valid:
```
//check
if(!$this->checkId($id)) //error
//do the query
$user = User::find($id);
```
What's the best way to handle this in a laravel package?
Throw an error? If so, which kind? Do an app abort? | 2014/08/20 | [
"https://Stackoverflow.com/questions/25409822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013512/"
]
| Using findOrFail()
------------------
There is a pretty good method that Laravel provides just for this case called `findOrFail()`.
What you can do is use that and then catch the exception.
```
try {
$user = User::findOrFail($queryParam);
} catch(ModelNotFoundException $e) {
// Do things that should happen here if your query parameter does not exist.
}
```
If you do not wish to catch it here, you can setup a listener for this exception. You can place it anywhere you wish as long as it's being autoloaded.
```
use Illuminate\Database\Eloquent\ModelNotFoundException;
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
```
Throwing an exception
---------------------
If all you want to do is throw an error if a query param isn't available, you can throw any of the exceptions found here... <https://github.com/symfony/symfony/tree/master/src/Symfony/Component/HttpKernel/Exception>
If none suit you, you can create your own and just extend `Symfony\Component\HttpKernel\Exception\HttpException` and `throw new YourCustomException($statusCode, $message);`. Just follow what they've done in the other exception classes and it should be fairly easy.
Then you can modify the the "exception listener" to catch `YourCustomException`.
Here is a tutorial I found... <http://fideloper.com/laravel4-error-handling> | I would use Event Listeners for the most control.
Create an `events.php` in your `app` directory and include it in `app/start/global.php`
Or, you can register anywhere in your package.
Create a listener:
```
Event::listen('paramCheck.noId', function($id)
{
// do some logic, log something, return something, throw an error...
});
```
Then fire the event from whenever you need to:
```
if(!$this->checkId($id))
$returnFromEvent = Event::fire('paramCheck.noId', array($id));
``` |
34,726,185 | Imagine I'm building a blog system where a user can upload images for a blog post. I have a problem mapping the uploaded images with user and their blog post.
Here's the flow :
1. User uploaded some pictures, it's saved to the server.
2. I store the image name in the related table, means later I can
retrieve images by blog's post\_id.
But what if the user upload images that has the same file name? | 2016/01/11 | [
"https://Stackoverflow.com/questions/34726185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5485528/"
]
| You can do the fading with just css transitions all you need to do is use jquery toggleClass function when the window reaches 150px.
Try the following:
```
$(window).on( "scroll", function() {
$('#secondNav').toggleClass('scrolled', $(this).scrollTop() > 150);
});
```
and the css
```
#secondNav.navbar-default{
background: #000;
transition: background-color 0.5s ease;
}
#secondNav.scrolled {
background: rgba(0,0,0,0.5);
}
```
The transition property is what will give you the fade in and out and then you can change the background of the navbar-default to whatever you want it to be. When it reaches 150px it will toggle the scrolled class and change the background. | Are you using jQuery? if so, maybe something like this?
```
$('#div').click(() => {
$('#div').fadeOut();
$('#div')
.css('background-color', 'green')
.fadeIn();
});
```
<https://jsfiddle.net/53n2o76g/> |
34,726,185 | Imagine I'm building a blog system where a user can upload images for a blog post. I have a problem mapping the uploaded images with user and their blog post.
Here's the flow :
1. User uploaded some pictures, it's saved to the server.
2. I store the image name in the related table, means later I can
retrieve images by blog's post\_id.
But what if the user upload images that has the same file name? | 2016/01/11 | [
"https://Stackoverflow.com/questions/34726185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5485528/"
]
| I have a difficult solution. You can create two `navbar`. second `nav` should be hidden. when you `scroll` more than `150px`, then it should be `fade in` with fixed position. Below my jQuery code is
```
$(window).scroll(function(){
var scrolled = $(window).scrollTop();
if(scrolled>149){
$('#second_nav').fadeIn();
}
else{
$('#second_nav').fadeOut();
}
});
```
Below the code is first nav.
```
<nav class="navbar navbar-default">
```
And below the code is second nav.
```
<nav class="navbar navbar-default navbar-fixed-top" id="second_nav">
```
Check my live demo on [jsfiddle](https://jsfiddle.net/sarowerj/64s99gad/) | Are you using jQuery? if so, maybe something like this?
```
$('#div').click(() => {
$('#div').fadeOut();
$('#div')
.css('background-color', 'green')
.fadeIn();
});
```
<https://jsfiddle.net/53n2o76g/> |
34,726,185 | Imagine I'm building a blog system where a user can upload images for a blog post. I have a problem mapping the uploaded images with user and their blog post.
Here's the flow :
1. User uploaded some pictures, it's saved to the server.
2. I store the image name in the related table, means later I can
retrieve images by blog's post\_id.
But what if the user upload images that has the same file name? | 2016/01/11 | [
"https://Stackoverflow.com/questions/34726185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5485528/"
]
| You can do the fading with just css transitions all you need to do is use jquery toggleClass function when the window reaches 150px.
Try the following:
```
$(window).on( "scroll", function() {
$('#secondNav').toggleClass('scrolled', $(this).scrollTop() > 150);
});
```
and the css
```
#secondNav.navbar-default{
background: #000;
transition: background-color 0.5s ease;
}
#secondNav.scrolled {
background: rgba(0,0,0,0.5);
}
```
The transition property is what will give you the fade in and out and then you can change the background of the navbar-default to whatever you want it to be. When it reaches 150px it will toggle the scrolled class and change the background. | I have a difficult solution. You can create two `navbar`. second `nav` should be hidden. when you `scroll` more than `150px`, then it should be `fade in` with fixed position. Below my jQuery code is
```
$(window).scroll(function(){
var scrolled = $(window).scrollTop();
if(scrolled>149){
$('#second_nav').fadeIn();
}
else{
$('#second_nav').fadeOut();
}
});
```
Below the code is first nav.
```
<nav class="navbar navbar-default">
```
And below the code is second nav.
```
<nav class="navbar navbar-default navbar-fixed-top" id="second_nav">
```
Check my live demo on [jsfiddle](https://jsfiddle.net/sarowerj/64s99gad/) |
90,189 | I tried to sync the blockchain and, though I have ample free disk space (>500 GB on my computer, the chain is ~265) I've been having a hard time. So, how can I use an SPV node to send transactions and/or view the blockchain?
NOTE: don't do this if you don't have to because the blockchain needs nodes to ensure adequate distribution. | 2019/09/03 | [
"https://bitcoin.stackexchange.com/questions/90189",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/96148/"
]
| Try Electrum. Exact details on how to install depend on Linux distribution used.
Also Wasabi Wallet could be good choice, easy to setup. | Since your constraint is the blockchain size, it seems you would be fine with running bitcoind with `--prune` enabled to something like 2gb or similar. This is technically not an SPV solution, but you would have access to the bitcoin-qt gui ( if that's the version of bitcoind you have installed ) and you'd be able to run with your minimal constraints. |
324,562 | ```
telnet www.ietf.org 80
GET /rfc.html HTTP/1.1
Host: www.ietf.org
```
This sequence of commands starts up a telnet (i.e., TCP) connection to port 80 on
IETF’s Web server, www.ietf.org. Then comes the GET command naming the
path of the URL and the protocol. Try servers and URLs of your choosing. The
next line is the mandatory Host header.
1. Can we use `ssh` instead of `telnet`, something like
```
ssh www.ietf.org 80
GET /rfc.html HTTP/1.1
Host: www.ietf.org
```
?
2. What **other programs** besides `ssh` can be used in place of `telnet` in the above
example to establish a connection from a local host to a remote http
server, so that we can send a http request to the http server and
receive a http response from it?
What **kind of programs** can be used in place of `telent` in the above example?
Thanks. | 2016/11/19 | [
"https://unix.stackexchange.com/questions/324562",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/674/"
]
| To reconfigure the keyboard in Debian, run (as `root`, or using `sudo`):
```
dpkg-reconfigure keyboard-configuration
```
Link to official Debian documentation [here](https://wiki.debian.org/Keyboard).
If your keys are "random" (I have been there, not fun!), try to find the characters needed to execute the command above. | If you have access to another computer you can `ssh` to your Pi and reset the keyboard that way.
I cannot give you a recommended keyboard layout for a direct console connection because that varies from keyboard to keyboard and I don't have a Mac keyboard to test against. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.