qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
55,119,643 | How find sum of all value in that object? In object included array with another object with value and may be "next" array with similar structure object.
```
{
value: 4,
next: [
{
value: 3,
next: [...]
},
{
value: 3,
next: [...]
},
...
]
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55119643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6289878/"
] | You would need recursion to deal with the arbitrary nesting of your object:
```js
const nestedSum = o => (o.next || []).reduce((acc, o) => acc + nestedSum(o), o.value);
// Demo
const data = {
value: 4,
next: [{
value: 3,
next: [{value: 5}]
}, {
value: 3,
next: []
},
]
};
console.log(nestedSum(data));
``` | The structure of your object is called tree [Tree (data structure)](https://en.wikipedia.org/wiki/Tree_(data_structure)).
You can use [breadth-first](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search) or [depth-first](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search) approach to [traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) and gather the sum along the way.
Other answers say you have to go recursively but you can do it iteratively with the breadth-first approach, I show you both approaches down in the code snippet.
I've expanded your data sample adding null values where there is supposedely no next values (you could use any kind of check really).
```js
let data = {
value: 4,
next: [
{
value: 3,
next: [
{
value: 5,
next: null
},
{
value: 6,
next: null
}
]
},
{
value: 2,
next: [
{
value: 2,
next: null
},
{
value: 3,
next: [
{
value: 7,
next: null
},
{
value: 8,
next: null
}
]
}
]
}
]
}
// iterative approach
function breadthFirst(node){
let sum = 0
let q = [node]
while(q.length > 0){
let node = q.pop()
sum += node.value
if (node.next !== null) {
for (let other of node.next){
q.push(other)
}
}
}
return sum
}
console.log('breadthFirst sum (iterative):', breadthFirst(data))
// recursive apporach
function depthFirst(node){
let sum = 0
function recursion(node){
sum += node.value
if (node.next !== null) {
for (let other of node.next){
recursion(other)
}
}
}
recursion(node)
return sum
}
console.log('depthFirst sum (recursive):', depthFirst(data))
``` |
55,119,643 | How find sum of all value in that object? In object included array with another object with value and may be "next" array with similar structure object.
```
{
value: 4,
next: [
{
value: 3,
next: [...]
},
{
value: 3,
next: [...]
},
...
]
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55119643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6289878/"
] | Use [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) and [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) to sum the values recursively:
```js
const obj = {
value: 4,
next: [{
value: 3,
next: [{ value: 1 }]
}, {
value: 3,
next: [{ value: 2, next: [] }]
}]
};
const sum = (obj) =>
Object.entries(obj).reduce((acc, [k, v]) => acc + (
k === 'next'
? v.map(sum).reduce((s, x) => s + x, 0)
: k === 'value' ? v : 0)
, 0);
console.log(sum(obj));
``` | You need a recursive function and check if the value of a key is a number then add with the variable , else if it is an array like `next` then iterate through it and again call the same function with a new object
```js
let data = {
value: 4,
next: [{
value: 3,
next: [{
value: 4
}, {
value: 5
}]
},
{
value: 3,
next: [{
value: 2
}]
}
]
}
let sum = 0;
function findSum(obj) {
for (let keys in obj) {
if (typeof obj[keys] === 'number') {
sum += obj[keys];
} else if (Array.isArray(obj[keys]) && obj[keys].length > 0) {
obj[keys].forEach(function(item) {
findSum(item)
})
}
}
}
findSum(data);
console.log(sum)
``` |
55,119,643 | How find sum of all value in that object? In object included array with another object with value and may be "next" array with similar structure object.
```
{
value: 4,
next: [
{
value: 3,
next: [...]
},
{
value: 3,
next: [...]
},
...
]
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55119643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6289878/"
] | ```js
function sum(obj, current = 0) {
const nextSum = (obj.next || []).reduce((nextSum, obj) => nextSum + sum(obj, current), 0)
return current + nextSum + obj.value
}
const example = {
value: 4,
next: [
{
value: 3,
next: [{
value: 7
}]
},
{
value: 3
}
]
}
console.log(sum(example)) // must be 17
``` | You need a recursive function and check if the value of a key is a number then add with the variable , else if it is an array like `next` then iterate through it and again call the same function with a new object
```js
let data = {
value: 4,
next: [{
value: 3,
next: [{
value: 4
}, {
value: 5
}]
},
{
value: 3,
next: [{
value: 2
}]
}
]
}
let sum = 0;
function findSum(obj) {
for (let keys in obj) {
if (typeof obj[keys] === 'number') {
sum += obj[keys];
} else if (Array.isArray(obj[keys]) && obj[keys].length > 0) {
obj[keys].forEach(function(item) {
findSum(item)
})
}
}
}
findSum(data);
console.log(sum)
``` |
55,119,643 | How find sum of all value in that object? In object included array with another object with value and may be "next" array with similar structure object.
```
{
value: 4,
next: [
{
value: 3,
next: [...]
},
{
value: 3,
next: [...]
},
...
]
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55119643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6289878/"
] | The structure of your object is called tree [Tree (data structure)](https://en.wikipedia.org/wiki/Tree_(data_structure)).
You can use [breadth-first](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search) or [depth-first](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search) approach to [traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) and gather the sum along the way.
Other answers say you have to go recursively but you can do it iteratively with the breadth-first approach, I show you both approaches down in the code snippet.
I've expanded your data sample adding null values where there is supposedely no next values (you could use any kind of check really).
```js
let data = {
value: 4,
next: [
{
value: 3,
next: [
{
value: 5,
next: null
},
{
value: 6,
next: null
}
]
},
{
value: 2,
next: [
{
value: 2,
next: null
},
{
value: 3,
next: [
{
value: 7,
next: null
},
{
value: 8,
next: null
}
]
}
]
}
]
}
// iterative approach
function breadthFirst(node){
let sum = 0
let q = [node]
while(q.length > 0){
let node = q.pop()
sum += node.value
if (node.next !== null) {
for (let other of node.next){
q.push(other)
}
}
}
return sum
}
console.log('breadthFirst sum (iterative):', breadthFirst(data))
// recursive apporach
function depthFirst(node){
let sum = 0
function recursion(node){
sum += node.value
if (node.next !== null) {
for (let other of node.next){
recursion(other)
}
}
}
recursion(node)
return sum
}
console.log('depthFirst sum (recursive):', depthFirst(data))
``` | You need a recursive function and check if the value of a key is a number then add with the variable , else if it is an array like `next` then iterate through it and again call the same function with a new object
```js
let data = {
value: 4,
next: [{
value: 3,
next: [{
value: 4
}, {
value: 5
}]
},
{
value: 3,
next: [{
value: 2
}]
}
]
}
let sum = 0;
function findSum(obj) {
for (let keys in obj) {
if (typeof obj[keys] === 'number') {
sum += obj[keys];
} else if (Array.isArray(obj[keys]) && obj[keys].length > 0) {
obj[keys].forEach(function(item) {
findSum(item)
})
}
}
}
findSum(data);
console.log(sum)
``` |
55,119,643 | How find sum of all value in that object? In object included array with another object with value and may be "next" array with similar structure object.
```
{
value: 4,
next: [
{
value: 3,
next: [...]
},
{
value: 3,
next: [...]
},
...
]
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55119643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6289878/"
] | Use [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) and [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) to sum the values recursively:
```js
const obj = {
value: 4,
next: [{
value: 3,
next: [{ value: 1 }]
}, {
value: 3,
next: [{ value: 2, next: [] }]
}]
};
const sum = (obj) =>
Object.entries(obj).reduce((acc, [k, v]) => acc + (
k === 'next'
? v.map(sum).reduce((s, x) => s + x, 0)
: k === 'value' ? v : 0)
, 0);
console.log(sum(obj));
``` | The structure of your object is called tree [Tree (data structure)](https://en.wikipedia.org/wiki/Tree_(data_structure)).
You can use [breadth-first](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search) or [depth-first](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search) approach to [traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) and gather the sum along the way.
Other answers say you have to go recursively but you can do it iteratively with the breadth-first approach, I show you both approaches down in the code snippet.
I've expanded your data sample adding null values where there is supposedely no next values (you could use any kind of check really).
```js
let data = {
value: 4,
next: [
{
value: 3,
next: [
{
value: 5,
next: null
},
{
value: 6,
next: null
}
]
},
{
value: 2,
next: [
{
value: 2,
next: null
},
{
value: 3,
next: [
{
value: 7,
next: null
},
{
value: 8,
next: null
}
]
}
]
}
]
}
// iterative approach
function breadthFirst(node){
let sum = 0
let q = [node]
while(q.length > 0){
let node = q.pop()
sum += node.value
if (node.next !== null) {
for (let other of node.next){
q.push(other)
}
}
}
return sum
}
console.log('breadthFirst sum (iterative):', breadthFirst(data))
// recursive apporach
function depthFirst(node){
let sum = 0
function recursion(node){
sum += node.value
if (node.next !== null) {
for (let other of node.next){
recursion(other)
}
}
}
recursion(node)
return sum
}
console.log('depthFirst sum (recursive):', depthFirst(data))
``` |
55,119,643 | How find sum of all value in that object? In object included array with another object with value and may be "next" array with similar structure object.
```
{
value: 4,
next: [
{
value: 3,
next: [...]
},
{
value: 3,
next: [...]
},
...
]
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55119643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6289878/"
] | ```js
function sum(obj, current = 0) {
const nextSum = (obj.next || []).reduce((nextSum, obj) => nextSum + sum(obj, current), 0)
return current + nextSum + obj.value
}
const example = {
value: 4,
next: [
{
value: 3,
next: [{
value: 7
}]
},
{
value: 3
}
]
}
console.log(sum(example)) // must be 17
``` | The structure of your object is called tree [Tree (data structure)](https://en.wikipedia.org/wiki/Tree_(data_structure)).
You can use [breadth-first](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search) or [depth-first](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search) approach to [traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) and gather the sum along the way.
Other answers say you have to go recursively but you can do it iteratively with the breadth-first approach, I show you both approaches down in the code snippet.
I've expanded your data sample adding null values where there is supposedely no next values (you could use any kind of check really).
```js
let data = {
value: 4,
next: [
{
value: 3,
next: [
{
value: 5,
next: null
},
{
value: 6,
next: null
}
]
},
{
value: 2,
next: [
{
value: 2,
next: null
},
{
value: 3,
next: [
{
value: 7,
next: null
},
{
value: 8,
next: null
}
]
}
]
}
]
}
// iterative approach
function breadthFirst(node){
let sum = 0
let q = [node]
while(q.length > 0){
let node = q.pop()
sum += node.value
if (node.next !== null) {
for (let other of node.next){
q.push(other)
}
}
}
return sum
}
console.log('breadthFirst sum (iterative):', breadthFirst(data))
// recursive apporach
function depthFirst(node){
let sum = 0
function recursion(node){
sum += node.value
if (node.next !== null) {
for (let other of node.next){
recursion(other)
}
}
}
recursion(node)
return sum
}
console.log('depthFirst sum (recursive):', depthFirst(data))
``` |
31,602 | I've been working on creating my first decentralized application, and I'm currently working on [this tutorial](https://www.safaribooksonline.com/library/view/decentralized-applications/9781491924532/ch03.html) which attempts to create a decentralized version of Twitter.
I want to integrate an IPFS to store data from users, but another guide that I took a look at used Solidity as the language before compilation.
In fact, this tutorial just distributes the code as a go file.
I'm confused as to how this might be compiled and distributed to the EVMs on the network, and how the process of compiling this application would go. And also - what are the differences between Golang and Solidity in terms of writing decentralized applications? | 2017/11/25 | [
"https://ethereum.stackexchange.com/questions/31602",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/23675/"
] | 1. `geth --rpc` starts the rpc interface. The rpc interface is required to be able to connect with clients (websites, for example) that want to access the Ethereum blockchain. Use options `--rpcaddress` and `--rpcport` to set address and port of the rpc interface. With `--rpcapi` you can limit access via rpc to certain apis. Also, `--rpccorsdomain` has to be set in many cases such that the calling domain is allowed, if you set it to `"*"` you allow every domain.
2. geth logs every action it does, so you always know about the sync state, connection issues with peers, and transactions that are sent to your node.
3. syncing means that you bring your local copy of the blockchain up to date. This is required to be able to participate in the blockchain. When syncing, information on the state of the blockchain and on prior transactions are copied to your node.
4. if you have geth running, open a different shell and run `geth attach`. geth then connects to the already running geth process and starts the geth console. Enter `eth` on the geth console and look for the `syncing` entry. If your node is syncing, the entry shows `true`.
5. you can interrupt and restart the sync any time, it will resume where it was stopped before. Note that if you stop a geth node that is in sync, it will have to sync again after you restart it, since the blockchain continues to evolve while your node is turned off. | --rpc has been replaced with --http. You can find more details here <https://stackoverflow.com/questions/69463898/flag-provided-but-not-defined-rpc/69643321#69643321> |
59,352,742 | Tl;dr: I'm getting a `require is not defined` error in the Chrome JS console, despite having installed node.js and requrejs.
---
I am trying to access API keys in an external JSON file using the following code in `main.js`:
```js
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
readTextFile("../secrets.json", function(text){
var data = JSON.parse(text);
apiKey = data.api_key;
username = data.username;
});
```
and since I use an XMLHttpRequest to the API later, which has an http:// scheme, I am looking to use CORS to work around the same-origin policy.
I put these lines at the beginning of `main.js`:
```js
var cors = require('cors')
var app = express()
app.use(cors());
```
and my directory structure looks like this:
```html
/project
index.html
secrets.json
/scripts
main.js
require.js
```
In the JS console on Chrome I get a `require is not defined` error. Where have I gone wrong? | 2019/12/16 | [
"https://Stackoverflow.com/questions/59352742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10768444/"
] | This code:
```
var cors = require('cors')
var app = express()
app.use(cors());
```
Belongs in a node.js server. It is not to be run inside of Chrome. It's purpose is to help you create an http server that can ACCEPT cross origin http requests from a browser.
A browser will only allow a cross origin XMLHttpRequest if the server itself that you are trying to make the request from specifically allows that cross origin request. So, it would be whatever server that supports the URL you are trying to make the XMLHttpRequest to allows cross origin requests (typically by supporting CORS). If the server does not already support your cross origin call, you would have to either modify that server's code or make the request through some sort of proxy that you do have access to that will get the data for you and relay it back to the browser.
>
> Where have I gone wrong?
>
>
>
Well, the `require('cors')` along with the other two lines of code you show below it are not meant to run in a browser. They run in a node.js environment and would be used to create an http server that you could then connect to from some outside agent (like a browser's web page).
From the browser, you can't do anything to MAKE a server accept cross origin requests if the server isn't already configured to do so. Your only two options are to change the target server or to use a proxy. | `require()` is NodeJS feature, see the [link](https://nodejs.org/en/knowledge/getting-started/what-is-require/) for more details.
Could You please share the command You start the app? |
41,124,388 | I have `@Controller` with method with signature like this:
```
@PostMapping
@ResponseBody
public ResponseEntity<Result> uploadFileAndReturnJson(@RequestParam("file") MultipartFile file) {}
```
I want to construct multipart request without physically creating any file. I tried doing it like this:
```
private MultiPartSpecification getMultiPart() {
return new MultiPartSpecBuilder("111,222")
.mimeType(MimeTypeUtils.MULTIPART_FORM_DATA.toString())
.controlName("file")
.fileName("file")
.build();
}
Response response = RestAssured.given(this.spec)
.auth().basic("admin", "admin")
.multiPart(getMultiPart())
.when().post(URL);
```
Unfortunately I received response:
>
> Required request part 'file' is not present
>
>
>
I tried looking at RestAssured unit tests and it seems I'm doing it correctly. If I try to pass byte[] or InputStream instead of String, an exception is thrown:
>
> Cannot retry request with a non-repeatable request entity.
>
>
>
Thanks for help. | 2016/12/13 | [
"https://Stackoverflow.com/questions/41124388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678184/"
] | Your code looks fine and it should work with byte[]. You can use `MultiPartSpecBuilder(byte[] content)` like below.
```
private MultiPartSpecification getMultiPart() {
return new MultiPartSpecBuilder("Test-Content-In-File".getBytes()).
fileName("book.txt").
controlName("file").
mimeType("text/plain").
build();
}
```
The details for error you are getting with byte[] is available at <https://github.com/rest-assured/rest-assured/issues/507>. According to this you should try with preemptive basic auth like below.
```
.auth().preemptive.basic("admin", "admin")
``` | ```
try {
RestAssured.given()
.header(new Header("content-type", "multipart/form-data"))
.multiPart("file",new File( "./src/main/resources/test.txt"))
.formParam("description", "This is my doc")
.auth().preemptive().basic(loginModel.getUsername(), loginModel.getPassword())
.when()
.post(URL)
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("schemas/members/member-document.json"));
}
catch(Exception e) {
Assert.assertEquals(false, true);
logger.error(e.getMessage(), e);
}
``` |
41,124,388 | I have `@Controller` with method with signature like this:
```
@PostMapping
@ResponseBody
public ResponseEntity<Result> uploadFileAndReturnJson(@RequestParam("file") MultipartFile file) {}
```
I want to construct multipart request without physically creating any file. I tried doing it like this:
```
private MultiPartSpecification getMultiPart() {
return new MultiPartSpecBuilder("111,222")
.mimeType(MimeTypeUtils.MULTIPART_FORM_DATA.toString())
.controlName("file")
.fileName("file")
.build();
}
Response response = RestAssured.given(this.spec)
.auth().basic("admin", "admin")
.multiPart(getMultiPart())
.when().post(URL);
```
Unfortunately I received response:
>
> Required request part 'file' is not present
>
>
>
I tried looking at RestAssured unit tests and it seems I'm doing it correctly. If I try to pass byte[] or InputStream instead of String, an exception is thrown:
>
> Cannot retry request with a non-repeatable request entity.
>
>
>
Thanks for help. | 2016/12/13 | [
"https://Stackoverflow.com/questions/41124388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678184/"
] | Your code looks fine and it should work with byte[]. You can use `MultiPartSpecBuilder(byte[] content)` like below.
```
private MultiPartSpecification getMultiPart() {
return new MultiPartSpecBuilder("Test-Content-In-File".getBytes()).
fileName("book.txt").
controlName("file").
mimeType("text/plain").
build();
}
```
The details for error you are getting with byte[] is available at <https://github.com/rest-assured/rest-assured/issues/507>. According to this you should try with preemptive basic auth like below.
```
.auth().preemptive.basic("admin", "admin")
``` | I needed to send multiple request with files and json data , i solve it like that
```
public static Response Post(JSONObject body, String URL, String file1, String file2) {
try {
return RestAssured.given().baseUri(URL).urlEncodingEnabled(false)
.accept("application/json, text/plain, */*")
.multiPart("data",body,"application/json")
.multiPart("file[0]", new File(file1),"multipart/form-data")
.multiPart("file[1]", new File(file2),"multipart/form-data")
.relaxedHTTPSValidation().when().post();
} catch (Exception e) {
System.out.println(e);
return null;
}
}
``` |
41,124,388 | I have `@Controller` with method with signature like this:
```
@PostMapping
@ResponseBody
public ResponseEntity<Result> uploadFileAndReturnJson(@RequestParam("file") MultipartFile file) {}
```
I want to construct multipart request without physically creating any file. I tried doing it like this:
```
private MultiPartSpecification getMultiPart() {
return new MultiPartSpecBuilder("111,222")
.mimeType(MimeTypeUtils.MULTIPART_FORM_DATA.toString())
.controlName("file")
.fileName("file")
.build();
}
Response response = RestAssured.given(this.spec)
.auth().basic("admin", "admin")
.multiPart(getMultiPart())
.when().post(URL);
```
Unfortunately I received response:
>
> Required request part 'file' is not present
>
>
>
I tried looking at RestAssured unit tests and it seems I'm doing it correctly. If I try to pass byte[] or InputStream instead of String, an exception is thrown:
>
> Cannot retry request with a non-repeatable request entity.
>
>
>
Thanks for help. | 2016/12/13 | [
"https://Stackoverflow.com/questions/41124388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678184/"
] | ```
try {
RestAssured.given()
.header(new Header("content-type", "multipart/form-data"))
.multiPart("file",new File( "./src/main/resources/test.txt"))
.formParam("description", "This is my doc")
.auth().preemptive().basic(loginModel.getUsername(), loginModel.getPassword())
.when()
.post(URL)
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("schemas/members/member-document.json"));
}
catch(Exception e) {
Assert.assertEquals(false, true);
logger.error(e.getMessage(), e);
}
``` | I needed to send multiple request with files and json data , i solve it like that
```
public static Response Post(JSONObject body, String URL, String file1, String file2) {
try {
return RestAssured.given().baseUri(URL).urlEncodingEnabled(false)
.accept("application/json, text/plain, */*")
.multiPart("data",body,"application/json")
.multiPart("file[0]", new File(file1),"multipart/form-data")
.multiPart("file[1]", new File(file2),"multipart/form-data")
.relaxedHTTPSValidation().when().post();
} catch (Exception e) {
System.out.println(e);
return null;
}
}
``` |
161,425 | I'm developing a social network and to my knowledge, the best way of storing between pages which user is logged on is using cookies. So, suppose I'm storing a cookie of the user ID which is logged in.
Anyway, what's stopping the user from changing the cookie's value in order to trick the website into thinking they're logged in as someone else? | 2017/06/07 | [
"https://security.stackexchange.com/questions/161425",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/150347/"
] | >
> So, suppose I'm storing a cookie of the user ID which is logged in.
>
>
>
That's not how session cookies work. The cookie shoudn't just contain the ID of the current user since that would obviously allow an attacker to tamper with the value.
Instead, a common approach is that the web application issues a sufficiently long, random session ID to the user and internally associates this session ID with the actual user account. Since a user is then assigned a new session ID after each login, it won't be feasible to predict the session IDs of other users or manipulate user-specific values by modifying the cookie.
Generally, you shouldn't have to invent your own session management scheme. If you think about how to store a user ID in a cookie, you're probably doing it wrong. Many frameworks already provide abstractions for cookie-based sessions. E.g., PHP has built-in support for [session handling](https://secure.php.net/manual/en/book.session.php). Also have a look at the OWASP [Session Management Cheat Sheet](https://www.owasp.org/index.php/Session_Management_Cheat_Sheet) to learn about security considerations. | If you authenticate a user based on a plaintext cookie with a username then you can't ensure whoever has the cookie is the person they say they are. Anyone can create a cookie with whatever username they want. It's up to you to ensure that they are who they say they are.
If I knew someone's username I could create a cookie with their username and bypass the login of the application and be whoever I wanted to be if there were no server side checks.
Instead of authenticating a user using a cookie I would suggest using a server side session, and pass an identifier of this session to the user to store as a cookie. Then when they request your page you can identify who the user is using their server-side session variables. The issue with this method is if your session identifier is easily guessable another user's session could be hijacked, but at least in this case the session could be cleared on the server. |
161,425 | I'm developing a social network and to my knowledge, the best way of storing between pages which user is logged on is using cookies. So, suppose I'm storing a cookie of the user ID which is logged in.
Anyway, what's stopping the user from changing the cookie's value in order to trick the website into thinking they're logged in as someone else? | 2017/06/07 | [
"https://security.stackexchange.com/questions/161425",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/150347/"
] | It is possible to store information in cookies and prevent users from tampetering with the data in the cookies. The way to do this is to create a HMAC of the cookie value and store that along with the cookie. Then whenever you receive a cookie value, check if it has the correct HMAC. Since HMACs need a secret key to create which only the server has, you know for sure that the cookie value was created by the server.
Some frameworks have this built in ([expressjs](https://stackoverflow.com/questions/11897965/what-are-signed-cookies-in-connect-expressjs), [rails](http://blog.bigbinary.com/2013/03/19/cookies-on-rails.html)). [This question](https://security.stackexchange.com/questions/7398/secure-session-cookies) discusses the concept of signed cookies some more. | If you authenticate a user based on a plaintext cookie with a username then you can't ensure whoever has the cookie is the person they say they are. Anyone can create a cookie with whatever username they want. It's up to you to ensure that they are who they say they are.
If I knew someone's username I could create a cookie with their username and bypass the login of the application and be whoever I wanted to be if there were no server side checks.
Instead of authenticating a user using a cookie I would suggest using a server side session, and pass an identifier of this session to the user to store as a cookie. Then when they request your page you can identify who the user is using their server-side session variables. The issue with this method is if your session identifier is easily guessable another user's session could be hijacked, but at least in this case the session could be cleared on the server. |
161,425 | I'm developing a social network and to my knowledge, the best way of storing between pages which user is logged on is using cookies. So, suppose I'm storing a cookie of the user ID which is logged in.
Anyway, what's stopping the user from changing the cookie's value in order to trick the website into thinking they're logged in as someone else? | 2017/06/07 | [
"https://security.stackexchange.com/questions/161425",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/150347/"
] | >
> So, suppose I'm storing a cookie of the user ID which is logged in.
>
>
>
That's not how session cookies work. The cookie shoudn't just contain the ID of the current user since that would obviously allow an attacker to tamper with the value.
Instead, a common approach is that the web application issues a sufficiently long, random session ID to the user and internally associates this session ID with the actual user account. Since a user is then assigned a new session ID after each login, it won't be feasible to predict the session IDs of other users or manipulate user-specific values by modifying the cookie.
Generally, you shouldn't have to invent your own session management scheme. If you think about how to store a user ID in a cookie, you're probably doing it wrong. Many frameworks already provide abstractions for cookie-based sessions. E.g., PHP has built-in support for [session handling](https://secure.php.net/manual/en/book.session.php). Also have a look at the OWASP [Session Management Cheat Sheet](https://www.owasp.org/index.php/Session_Management_Cheat_Sheet) to learn about security considerations. | It is possible to store information in cookies and prevent users from tampetering with the data in the cookies. The way to do this is to create a HMAC of the cookie value and store that along with the cookie. Then whenever you receive a cookie value, check if it has the correct HMAC. Since HMACs need a secret key to create which only the server has, you know for sure that the cookie value was created by the server.
Some frameworks have this built in ([expressjs](https://stackoverflow.com/questions/11897965/what-are-signed-cookies-in-connect-expressjs), [rails](http://blog.bigbinary.com/2013/03/19/cookies-on-rails.html)). [This question](https://security.stackexchange.com/questions/7398/secure-session-cookies) discusses the concept of signed cookies some more. |
66,351,081 | Guys I'm trying to put two buttons from two different forms on the same line.
I tried to put an id on both buttons so that I can manage them in css.
In particular, what I want to do is put the "delete" button next to the "update" button.
This is what I tried to do but it doesn't work because the "delete" button stays under the "update" button.
```js
//First form
<form action="../updatecustdet" method="post">
<pre>
<c:forEach var="customer" items="${listCustomer}">
<input type="hidden" name="id" value="${customer.id}" />
.
.
.
.
<input type="submit" id="up" value="Update" />
</c:forEach>
</pre>
</form>
//Second form
<form action="../deletefromdetailslist" method="POST">
<input id="cust" name="customer" type="hidden" value="${customer.id}"/>
<input type="submit" id="de" value="Delete"/>
</c:forEach>
</form>
```
```css
#up {
padding:5px 15px;
background:#ccc;
border:0 none;
cursor:pointer;
-webkit-border-radius: 5px;
border-radius: 5px;
display:inline-block;
}
#de {
padding:5px 15px;
background:#ccc;
border:0 none;
cursor:pointer;
-webkit-border-radius: 5px;
border-radius: 5px;
top:-43px;
}
```
Heartfelt thanks to those who will help me | 2021/02/24 | [
"https://Stackoverflow.com/questions/66351081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15051230/"
] | There are [two](https://github.com/mongoosastic/mongoosastic/issues/441) [issues](https://github.com/mongoosastic/mongoosastic/issues/380) closed without a solution in the mongoosastic repository, suggesting that this is very likely a bug in the library that may not have a solution in user code.
What those issues and yours have in common is the use of subdocuments, and a quick glance at the library's source code suggests that it may be indeed related to an improper handling of that case.
A look at the test suite of the library also does not show any tests covering this scenario, further suggesting that it may simply not be supported. | It's not immediately clear [from the source code](https://github.com/mongoosastic/mongoosastic/blob/558ba1a486ae1efdb0a48dba279d69118679d3c5/lib/mongoosastic.js#L385) why the `modelName` would be `undefined`...
In any event, each `mongoosastic` model constructor [accepts an `index` parameter](https://github.com/mongoosastic/mongoosastic/blob/master/docs/README.md#modelpluginmongoosastic-options) so I'd declare it when I'm registering the plugin:
```js
...
orderLineItemSchema.plugin(mtastic, {
esClient: esClient,
index: 'orders-index` // <---
});
let OrderLineItem = mongodb.model('OrderLineItem', orderLineItemSchema);
...
``` |
64,786,477 | I am trying to create a function that will query times in a table and then return the correct time based on the site.
The times in the table being queried have the opening and closing times of the branch. I am not sure if I should be using CASE or IF.
When I use `CASE`, I get this error:
>
> Msg 444, Level 16, State 2, Procedure WorkTime, Line 33
>
> Select statements included within a function cannot return data to a client.
>
>
>
When I print to screen it works fine.
/*added this for the site times open and close*/
```
DECLARE @WorkStart TIME
SET @WorkStart = '09:00'
SELECT
CASE
WHEN [Location Code] = 'OF' THEN [OpenTime]
WHEN [Location Code] = 'MP' THEN [OpenTime]
WHEN [Location Code] = 'GP' THEN [OpenTime]
WHEN [Location Code] = 'EC' THEN [OpenTime]
WHEN [Location Code] = 'WP' THEN [OpenTime]
WHEN [Location Code] = 'ZN' THEN [OpenTime]
END
FROM
[dbo].[OperationHours]
--PRINT @WorkStart
--GO
``` | 2020/11/11 | [
"https://Stackoverflow.com/questions/64786477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14619192/"
] | First of all I think you didn't specify all requirements.
I expect that you pass the location code to the function.
your function could have a look like
```
CREATE FUNCTION YourFunction
(
@locationCode varchar(2)
)
RETURNS TIME
AS
BEGIN
DECLARE @OpenTime TIME
DECLARE @WorkStart TIME
SET @WorkStart = '09:00'
SELECT @OpenTime = [OpenTime]
FROM [dbo].[OperationHours]
where @locationCode = [Location Code]
RETURN ISNULL(@OpenTime, @WorkStart)
END
``` | "Select statements included within a function cannot return data to a client"
To clarify the error message: you must assign your result to a variable and return the variable. A SELECT as shown in your question, will return a dataset to the client. As noted in the error message, that is not allowed for a function. Returning a dataset works for a stored procedure, but not a function.
Fix: Assign the result of your SELECT to a variable.
The answer by @Illia above should work. |
12,268,913 | I recently modify the "include\_path" var in my php.ini file. Before you ask, I restarted the apache service. The change work for every pages we access from a web browser.
The problem is the cron jobs doesn't seems to consider that change. When I do a phpinfo() inside the cron job, it uses the same php.ini file than the web server and it is the one I changed, but the value beside "include\_path" is the old one.
So is there a way to "restart" crontab?
Or maybe there is another problem? | 2012/09/04 | [
"https://Stackoverflow.com/questions/12268913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738638/"
] | Several systems use a separate php.ini file for web and CLI. You will need to make changes in that one as well: [How to find the php.ini file used by the command line?](https://stackoverflow.com/questions/2750580/how-to-find-the-php-ini-file-used-by-the-command-line)
The easiest way to find this file is to run this at the command line: **php --ini** which will result in output like this:
```
user@computer:~$ php --ini
Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File: /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
```
What you see as "Loaded Configuration File:" is where you need to add your changes.
**EDIT:** Another option, is in your CRON script use [set\_include\_path()](http://php.net/manual/en/function.set-include-path.php) to make the change at runtime. | PHP generally has two .ini files. One for in-webserver (SAPI) and one for command-line (CLI) usage. If you modified only the SAPI one, then anything running from CLI (e.g. cron jobs) will not see the change.
do a `php -i` at the command line to see where PHP is looking for its ini file while in that mode. |
50,703,782 | I'm having some issues writing a simple for loop with conditions in r.
I've got this array:
```
Temp <- c("A", "A", "B", "A", "C", "C", "A", "B")
```
I want to count the couples in this array, by using two indexes which are incremented during the loop.It's mandatory to follow the order of the sequence.
The final result for this array should be:
```
CountAA = 1
CountAB = 2
CountAC = 1
CountBA = 1
CountBB = 0
CountBC = 0
CountCA = 1
CountCB = 0
CountCC = 1
```
I've tried with this code, but it gives me an error
```
"Error in if (Temp[i] == "A" & Temp[j] == "A") { :
argument is of length zero"
```
Code
```
CountAA = 0
CountAB = 0
CountAC = 0
CountBA = 0
CountBB = 0
CountBC = 0
CountCA = 0
CountCB = 0
CountCC = 0
i = 1
j = 2
for (j in 1:length(Temp)-1){
if (Temp[i]=="A" & Temp[j]=="A"){
CountAA = CountAA + 1
i = i + 1
j = j + 1
}
if (Temp[i]=="A" & Temp[j]=="B"){
CountAB = CountAB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="A" & Temp[j]=="C"){
CountAC = CountAC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="A"){
CountBA = CountBA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="B"){
CountBB = CountBB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="C"){
CountBC = CountBC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="A"){
CountCA = CountCA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="B"){
CountCB = CountCB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="C"){
CountCC = CountCC + 1
i = i + 1
j = j + 1
}
}
``` | 2018/06/05 | [
"https://Stackoverflow.com/questions/50703782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4433862/"
] | in base `R`:
```
# unique letter values
ut <- unique(Temp)
# expand to get a data.frame with all combinations
expnd <- data.frame(pair=do.call(paste0,expand.grid(ut,ut)),stringsAsFactors = FALSE)
# merge it with the table containing counts of all pair combinations
out <- merge(expnd, table(pair=paste0(head(Temp,-1),tail(Temp,-1))), all=TRUE)
# turn NAs into zeroes
out$Freq[is.na(out$Freq)] <- 0
# pair Freq
# 1 AA 1
# 2 AB 2
# 3 AC 1
# 4 BA 1
# 5 BB 0
# 6 BC 0
# 7 CA 1
# 8 CB 0
# 9 CC 1
```
with library `tidyverse`
```
library(tidyverse)
tibble(x=head(Temp,-1),y=tail(Temp,-1)) %>%
count(x,y) %>% # count combinations
complete(x,y) %>% # add missing combinations
replace_na(list(n=0)) %>% # make them zero
unite(pair,x,y,sep='') %>% # turn 2 columns into 1
arrange(pair) # sort
# # A tibble: 9 x 2
# pair n
# <chr> <dbl>
# 1 AA 1
# 2 AB 2
# 3 AC 1
# 4 BA 1
# 5 BB 0
# 6 BC 0
# 7 CA 1
# 8 CB 0
# 9 CC 1
``` | You can try
```
library(tidyverse)
b <- table(sapply(seq_along(Temp), function(x) paste0(Temp[x], Temp[x+1]))[-length(Temp)])
expand.grid(unique(Temp), unique(Temp)) %>%
unite(Var1, Var1, Var2, sep = "") %>%
left_join(as.data.frame(b,stringsAsFactors = F)) %>%
mutate(Freq=ifelse(is.na(Freq), 0, Freq))
Var Freq
1 AA 1
2 BA 1
3 CA 1
4 AB 2
5 BB 0
6 CB 0
7 AC 1
8 BC 0
9 CC 1
``` |
50,703,782 | I'm having some issues writing a simple for loop with conditions in r.
I've got this array:
```
Temp <- c("A", "A", "B", "A", "C", "C", "A", "B")
```
I want to count the couples in this array, by using two indexes which are incremented during the loop.It's mandatory to follow the order of the sequence.
The final result for this array should be:
```
CountAA = 1
CountAB = 2
CountAC = 1
CountBA = 1
CountBB = 0
CountBC = 0
CountCA = 1
CountCB = 0
CountCC = 1
```
I've tried with this code, but it gives me an error
```
"Error in if (Temp[i] == "A" & Temp[j] == "A") { :
argument is of length zero"
```
Code
```
CountAA = 0
CountAB = 0
CountAC = 0
CountBA = 0
CountBB = 0
CountBC = 0
CountCA = 0
CountCB = 0
CountCC = 0
i = 1
j = 2
for (j in 1:length(Temp)-1){
if (Temp[i]=="A" & Temp[j]=="A"){
CountAA = CountAA + 1
i = i + 1
j = j + 1
}
if (Temp[i]=="A" & Temp[j]=="B"){
CountAB = CountAB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="A" & Temp[j]=="C"){
CountAC = CountAC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="A"){
CountBA = CountBA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="B"){
CountBB = CountBB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="C"){
CountBC = CountBC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="A"){
CountCA = CountCA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="B"){
CountCB = CountCB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="C"){
CountCC = CountCC + 1
i = i + 1
j = j + 1
}
}
``` | 2018/06/05 | [
"https://Stackoverflow.com/questions/50703782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4433862/"
] | in base `R`:
```
# unique letter values
ut <- unique(Temp)
# expand to get a data.frame with all combinations
expnd <- data.frame(pair=do.call(paste0,expand.grid(ut,ut)),stringsAsFactors = FALSE)
# merge it with the table containing counts of all pair combinations
out <- merge(expnd, table(pair=paste0(head(Temp,-1),tail(Temp,-1))), all=TRUE)
# turn NAs into zeroes
out$Freq[is.na(out$Freq)] <- 0
# pair Freq
# 1 AA 1
# 2 AB 2
# 3 AC 1
# 4 BA 1
# 5 BB 0
# 6 BC 0
# 7 CA 1
# 8 CB 0
# 9 CC 1
```
with library `tidyverse`
```
library(tidyverse)
tibble(x=head(Temp,-1),y=tail(Temp,-1)) %>%
count(x,y) %>% # count combinations
complete(x,y) %>% # add missing combinations
replace_na(list(n=0)) %>% # make them zero
unite(pair,x,y,sep='') %>% # turn 2 columns into 1
arrange(pair) # sort
# # A tibble: 9 x 2
# pair n
# <chr> <dbl>
# 1 AA 1
# 2 AB 2
# 3 AC 1
# 4 BA 1
# 5 BB 0
# 6 BC 0
# 7 CA 1
# 8 CB 0
# 9 CC 1
``` | ```
library(magrittr)
n <- length(Temp)
sapply(1:(n-1),function(i) paste(Temp[i:(i+1)], collapse = "")) %>%
factor(levels = paste0(rep(LETTERS[1:3], each = 3), LETTERS[1:3])) %>%
table()
AA AB AC BA BB BC CA CB CC
1 2 1 1 0 0 1 0 1
``` |
50,703,782 | I'm having some issues writing a simple for loop with conditions in r.
I've got this array:
```
Temp <- c("A", "A", "B", "A", "C", "C", "A", "B")
```
I want to count the couples in this array, by using two indexes which are incremented during the loop.It's mandatory to follow the order of the sequence.
The final result for this array should be:
```
CountAA = 1
CountAB = 2
CountAC = 1
CountBA = 1
CountBB = 0
CountBC = 0
CountCA = 1
CountCB = 0
CountCC = 1
```
I've tried with this code, but it gives me an error
```
"Error in if (Temp[i] == "A" & Temp[j] == "A") { :
argument is of length zero"
```
Code
```
CountAA = 0
CountAB = 0
CountAC = 0
CountBA = 0
CountBB = 0
CountBC = 0
CountCA = 0
CountCB = 0
CountCC = 0
i = 1
j = 2
for (j in 1:length(Temp)-1){
if (Temp[i]=="A" & Temp[j]=="A"){
CountAA = CountAA + 1
i = i + 1
j = j + 1
}
if (Temp[i]=="A" & Temp[j]=="B"){
CountAB = CountAB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="A" & Temp[j]=="C"){
CountAC = CountAC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="A"){
CountBA = CountBA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="B"){
CountBB = CountBB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="C"){
CountBC = CountBC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="A"){
CountCA = CountCA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="B"){
CountCB = CountCB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="C"){
CountCC = CountCC + 1
i = i + 1
j = j + 1
}
}
``` | 2018/06/05 | [
"https://Stackoverflow.com/questions/50703782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4433862/"
] | Here is a simple base solution:
```
table(sapply(1:(length(Temp) - 1), function(x) paste(Temp[x:(x+1)], collapse = "")))
AA AB AC BA CA CC
1 2 1 1 1 1
```
If you really want to see all possible permutations you can use any package that will generate permutations with repetition. Below we use `gtools`.
```
library(gtools)
## Same as above
vec <- table(sapply(1:(length(Temp) - 1), function(x) paste(Temp[x:(x+1)], collapse = "")))
## Generate all permutations
myNames <- apply(permutations(3, 2, unique(Temp), repeats.allowed = TRUE), 1, paste, collapse = "")
## Initialize return vector
res <- integer(length(myNames))
## Add names
names(res) <- myNames
## Subset on names
res[names(res) %in% names(vec)] <- vec
res
AA AB AC BA BB BC CA CB CC
1 2 1 1 0 0 1 0 1
``` | in base `R`:
```
# unique letter values
ut <- unique(Temp)
# expand to get a data.frame with all combinations
expnd <- data.frame(pair=do.call(paste0,expand.grid(ut,ut)),stringsAsFactors = FALSE)
# merge it with the table containing counts of all pair combinations
out <- merge(expnd, table(pair=paste0(head(Temp,-1),tail(Temp,-1))), all=TRUE)
# turn NAs into zeroes
out$Freq[is.na(out$Freq)] <- 0
# pair Freq
# 1 AA 1
# 2 AB 2
# 3 AC 1
# 4 BA 1
# 5 BB 0
# 6 BC 0
# 7 CA 1
# 8 CB 0
# 9 CC 1
```
with library `tidyverse`
```
library(tidyverse)
tibble(x=head(Temp,-1),y=tail(Temp,-1)) %>%
count(x,y) %>% # count combinations
complete(x,y) %>% # add missing combinations
replace_na(list(n=0)) %>% # make them zero
unite(pair,x,y,sep='') %>% # turn 2 columns into 1
arrange(pair) # sort
# # A tibble: 9 x 2
# pair n
# <chr> <dbl>
# 1 AA 1
# 2 AB 2
# 3 AC 1
# 4 BA 1
# 5 BB 0
# 6 BC 0
# 7 CA 1
# 8 CB 0
# 9 CC 1
``` |
50,703,782 | I'm having some issues writing a simple for loop with conditions in r.
I've got this array:
```
Temp <- c("A", "A", "B", "A", "C", "C", "A", "B")
```
I want to count the couples in this array, by using two indexes which are incremented during the loop.It's mandatory to follow the order of the sequence.
The final result for this array should be:
```
CountAA = 1
CountAB = 2
CountAC = 1
CountBA = 1
CountBB = 0
CountBC = 0
CountCA = 1
CountCB = 0
CountCC = 1
```
I've tried with this code, but it gives me an error
```
"Error in if (Temp[i] == "A" & Temp[j] == "A") { :
argument is of length zero"
```
Code
```
CountAA = 0
CountAB = 0
CountAC = 0
CountBA = 0
CountBB = 0
CountBC = 0
CountCA = 0
CountCB = 0
CountCC = 0
i = 1
j = 2
for (j in 1:length(Temp)-1){
if (Temp[i]=="A" & Temp[j]=="A"){
CountAA = CountAA + 1
i = i + 1
j = j + 1
}
if (Temp[i]=="A" & Temp[j]=="B"){
CountAB = CountAB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="A" & Temp[j]=="C"){
CountAC = CountAC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="A"){
CountBA = CountBA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="B"){
CountBB = CountBB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="C"){
CountBC = CountBC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="A"){
CountCA = CountCA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="B"){
CountCB = CountCB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="C"){
CountCC = CountCC + 1
i = i + 1
j = j + 1
}
}
``` | 2018/06/05 | [
"https://Stackoverflow.com/questions/50703782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4433862/"
] | Here is a simple base solution:
```
table(sapply(1:(length(Temp) - 1), function(x) paste(Temp[x:(x+1)], collapse = "")))
AA AB AC BA CA CC
1 2 1 1 1 1
```
If you really want to see all possible permutations you can use any package that will generate permutations with repetition. Below we use `gtools`.
```
library(gtools)
## Same as above
vec <- table(sapply(1:(length(Temp) - 1), function(x) paste(Temp[x:(x+1)], collapse = "")))
## Generate all permutations
myNames <- apply(permutations(3, 2, unique(Temp), repeats.allowed = TRUE), 1, paste, collapse = "")
## Initialize return vector
res <- integer(length(myNames))
## Add names
names(res) <- myNames
## Subset on names
res[names(res) %in% names(vec)] <- vec
res
AA AB AC BA BB BC CA CB CC
1 2 1 1 0 0 1 0 1
``` | You can try
```
library(tidyverse)
b <- table(sapply(seq_along(Temp), function(x) paste0(Temp[x], Temp[x+1]))[-length(Temp)])
expand.grid(unique(Temp), unique(Temp)) %>%
unite(Var1, Var1, Var2, sep = "") %>%
left_join(as.data.frame(b,stringsAsFactors = F)) %>%
mutate(Freq=ifelse(is.na(Freq), 0, Freq))
Var Freq
1 AA 1
2 BA 1
3 CA 1
4 AB 2
5 BB 0
6 CB 0
7 AC 1
8 BC 0
9 CC 1
``` |
50,703,782 | I'm having some issues writing a simple for loop with conditions in r.
I've got this array:
```
Temp <- c("A", "A", "B", "A", "C", "C", "A", "B")
```
I want to count the couples in this array, by using two indexes which are incremented during the loop.It's mandatory to follow the order of the sequence.
The final result for this array should be:
```
CountAA = 1
CountAB = 2
CountAC = 1
CountBA = 1
CountBB = 0
CountBC = 0
CountCA = 1
CountCB = 0
CountCC = 1
```
I've tried with this code, but it gives me an error
```
"Error in if (Temp[i] == "A" & Temp[j] == "A") { :
argument is of length zero"
```
Code
```
CountAA = 0
CountAB = 0
CountAC = 0
CountBA = 0
CountBB = 0
CountBC = 0
CountCA = 0
CountCB = 0
CountCC = 0
i = 1
j = 2
for (j in 1:length(Temp)-1){
if (Temp[i]=="A" & Temp[j]=="A"){
CountAA = CountAA + 1
i = i + 1
j = j + 1
}
if (Temp[i]=="A" & Temp[j]=="B"){
CountAB = CountAB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="A" & Temp[j]=="C"){
CountAC = CountAC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="A"){
CountBA = CountBA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="B"){
CountBB = CountBB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="B" & Temp[j]=="C"){
CountBC = CountBC + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="A"){
CountCA = CountCA + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="B"){
CountCB = CountCB + 1
i = i + 1
j = j + 1
}
if(Temp[i]=="C" & Temp[j]=="C"){
CountCC = CountCC + 1
i = i + 1
j = j + 1
}
}
``` | 2018/06/05 | [
"https://Stackoverflow.com/questions/50703782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4433862/"
] | Here is a simple base solution:
```
table(sapply(1:(length(Temp) - 1), function(x) paste(Temp[x:(x+1)], collapse = "")))
AA AB AC BA CA CC
1 2 1 1 1 1
```
If you really want to see all possible permutations you can use any package that will generate permutations with repetition. Below we use `gtools`.
```
library(gtools)
## Same as above
vec <- table(sapply(1:(length(Temp) - 1), function(x) paste(Temp[x:(x+1)], collapse = "")))
## Generate all permutations
myNames <- apply(permutations(3, 2, unique(Temp), repeats.allowed = TRUE), 1, paste, collapse = "")
## Initialize return vector
res <- integer(length(myNames))
## Add names
names(res) <- myNames
## Subset on names
res[names(res) %in% names(vec)] <- vec
res
AA AB AC BA BB BC CA CB CC
1 2 1 1 0 0 1 0 1
``` | ```
library(magrittr)
n <- length(Temp)
sapply(1:(n-1),function(i) paste(Temp[i:(i+1)], collapse = "")) %>%
factor(levels = paste0(rep(LETTERS[1:3], each = 3), LETTERS[1:3])) %>%
table()
AA AB AC BA BB BC CA CB CC
1 2 1 1 0 0 1 0 1
``` |
36,557,058 | I have a text file (textfile.txt) in a folder called DOT and I am trying to convert that file to an Excel file (Excelfile.xls) using Python code. I am not familiar with Python but from other comments I wrote the code below. The code does not work. Could anyone help me get the correct syntax?
```
book = xlwt.Workbook()
import xlwt
import xlrd
f = open('/DOT/textfile.txt', 'r+')
book.save('/DOT/Excelfile' + '.xls')
``` | 2016/04/11 | [
"https://Stackoverflow.com/questions/36557058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6099978/"
] | This is based on documentation from: <https://pypi.python.org/pypi/xlwt>
You will need to read the file line by line, format it and write it to the xls file.
```
import xlwt
import xlrd
book = xlwt.Workbook()
ws = book.add_sheet('First Sheet') # Add a sheet
f = open('/DOT/textfile.txt', 'r+')
data = f.readlines() # read all lines at once
for i in range(len(data)):
row = data[i].split() # This will return a line of string data, you may need to convert to other formats depending on your use case
for j in range(len(row)):
ws.write(i, j, row[j]) # Write to cell i, j
book.save('/DOT/Excelfile' + '.xls')
f.close()
```
Here, the data is being read, all the rows at once. Then, each line is being split into a list of data points, and added to a new row in the spreadsheet.
This is not the best/optimal solution but should get you started. Let me know in case there is a bug. | I had a similar problem. The txt file’s content was actually separated by “Tab” blanks (get to know this when importing data in Excel).
Searched and tried some answers, but only got this working fine with mine.
<https://mail.python.org/pipermail/tutor/2011-May/083411.html> |
45,194,284 | I'm working on a linux server right now and have a list of servers I would like to do control using salt-stack(a DSC tool) While working on my linux+ I came across a really neat command -- xargs I've been using it to simplify a lot of my linux administration life, however I cam into an issue with it and I'm wondering if there is an easy fix for this
I'm tracking down some ntp issues across our enviornment, but the problem is the list of servers I have do not have the FQDN attached in the data set. Unfortunately salt needs the fqdn in order to see the device, otherwise it errors out every time. Now I could drop the list into notepad++ and tack on the .servers.fakefqdn.com that way but I'm wondering if there is a way to do this in the command itself
Here is my current command:
```
cat servers | xargs -I % sudo salt % cmd.run 'date'
```
Is it possible to do something like:
```
cat servers | xargs -I % sudo salt %+.servers.fakefqdn.com cmd.run 'date'
```
so if my list of servers where:
```
Bobsburgers
SouthPark
RickAndMorty
```
end goal of the xargs command would run these commands:
```
salt Bobsburgers.servers.fakefqdn.com cmd.run 'date'
salt SouthPark.servers.fakefqdn.com cmd.run 'date'
salt RickAndMorty.servers.fakefqdn.com cmd.run 'date'
``` | 2017/07/19 | [
"https://Stackoverflow.com/questions/45194284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8021878/"
] | ```
for server in $(< servers); do echo salt ${server}.servers.fakefqdn.com cmd.run 'date'; done
``` | Using xargs, this should work as you want:
```
cat servers | xargs -I % sudo salt %.servers.fakefqdn.com cmd.run 'date'
``` |
16,192,991 | How can I do a parse of Metar information in Java programming?
I'v searched in the Internet and ther's a lot of complex things, I want something more simple.
I don't know how to use Regex or something like that...
example of Metar Info :<http://weather.noaa.gov/pub/data/observations/metar/stations/ABBN.TXT>
>
> 2011/03/16 05:30 ABBN 160530Z 23004KT 9999 NSC 02/M05 Q1029
> R14R/CLRD60 NOSIG RMK G/O QFE696
>
>
>
Note that Metar report can have variations:
<http://en.wikipedia.org/wiki/METAR> | 2013/04/24 | [
"https://Stackoverflow.com/questions/16192991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1837447/"
] | I found a solution, there's the code (it can be useful for somebody):
```
for (int i=0; i<httpGet.length(); i++) {
char c = httpGet.charAt(i);
if(c=='M' && Character.isDigit(httpGet.charAt(i+1)) &&
Character.isDigit(httpGet.charAt(i+2)) &&
httpGet.charAt(i+3)== '/' &&
Character.isDigit(httpGet.charAt(i+4))&&
Character.isDigit(httpGet.charAt(i+5))&&
httpGet.charAt(i+6)==' ' &&
Character.isLetter(httpGet.charAt(i+7))){
temp="-"+httpGet.substring(i+1,i+3);
dewP=httpGet.substring(i+4,i+6);
break;
}
else if(c=='M' && Character.isDigit(httpGet.charAt(i+1)) &&
Character.isDigit(httpGet.charAt(i+2)) &&
httpGet.charAt(i+3)== '/' &&
httpGet.charAt(i+4)== 'M' &&
Character.isDigit(httpGet.charAt(i+5))&&
Character.isDigit(httpGet.charAt(i+6))&&
httpGet.charAt(i+7)==' ' &&
Character.isLetter(httpGet.charAt(i+8))){
temp="-"+httpGet.substring(i+1,i+3);
dewP="-"+httpGet.substring(i+5,i+7);
break;
}
else if(Character.isDigit(httpGet.charAt(i)) &&
Character.isDigit(httpGet.charAt(i+1)) &&
httpGet.charAt(i+2)== '/' &&
httpGet.charAt(i+3)== 'M' &&
Character.isDigit(httpGet.charAt(i+4))&&
Character.isDigit(httpGet.charAt(i+5))&&
httpGet.charAt(i+6)==' ' &&
Character.isLetter(httpGet.charAt(i+7))){
temp=httpGet.substring(i,i+2);
dewP="-"+httpGet.substring(i+4,i+6);
break;
}
else if(Character.isDigit(c) && Character.isDigit(httpGet.charAt(i+1))
&& httpGet.charAt(i+2)=='/' &&
Character.isDigit(httpGet.charAt(i+3)) &&
Character.isDigit(httpGet.charAt(i+4)) &&
httpGet.charAt(i+5)==' ' &&
Character.isLetter(httpGet.charAt(i+6))){
temp=httpGet.substring(i,i+2);
dewP=httpGet.substring(i+3,i+5);
break;
}
}
``` | Regex is almost certainly what your gonna want, yes is daunting but you will use it over and over again. The RMK section is going to be the hardest, it's the most free form. The only alternative is to go through character by character with a lot of if's or case statements. |
16,192,991 | How can I do a parse of Metar information in Java programming?
I'v searched in the Internet and ther's a lot of complex things, I want something more simple.
I don't know how to use Regex or something like that...
example of Metar Info :<http://weather.noaa.gov/pub/data/observations/metar/stations/ABBN.TXT>
>
> 2011/03/16 05:30 ABBN 160530Z 23004KT 9999 NSC 02/M05 Q1029
> R14R/CLRD60 NOSIG RMK G/O QFE696
>
>
>
Note that Metar report can have variations:
<http://en.wikipedia.org/wiki/METAR> | 2013/04/24 | [
"https://Stackoverflow.com/questions/16192991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1837447/"
] | I found a solution, there's the code (it can be useful for somebody):
```
for (int i=0; i<httpGet.length(); i++) {
char c = httpGet.charAt(i);
if(c=='M' && Character.isDigit(httpGet.charAt(i+1)) &&
Character.isDigit(httpGet.charAt(i+2)) &&
httpGet.charAt(i+3)== '/' &&
Character.isDigit(httpGet.charAt(i+4))&&
Character.isDigit(httpGet.charAt(i+5))&&
httpGet.charAt(i+6)==' ' &&
Character.isLetter(httpGet.charAt(i+7))){
temp="-"+httpGet.substring(i+1,i+3);
dewP=httpGet.substring(i+4,i+6);
break;
}
else if(c=='M' && Character.isDigit(httpGet.charAt(i+1)) &&
Character.isDigit(httpGet.charAt(i+2)) &&
httpGet.charAt(i+3)== '/' &&
httpGet.charAt(i+4)== 'M' &&
Character.isDigit(httpGet.charAt(i+5))&&
Character.isDigit(httpGet.charAt(i+6))&&
httpGet.charAt(i+7)==' ' &&
Character.isLetter(httpGet.charAt(i+8))){
temp="-"+httpGet.substring(i+1,i+3);
dewP="-"+httpGet.substring(i+5,i+7);
break;
}
else if(Character.isDigit(httpGet.charAt(i)) &&
Character.isDigit(httpGet.charAt(i+1)) &&
httpGet.charAt(i+2)== '/' &&
httpGet.charAt(i+3)== 'M' &&
Character.isDigit(httpGet.charAt(i+4))&&
Character.isDigit(httpGet.charAt(i+5))&&
httpGet.charAt(i+6)==' ' &&
Character.isLetter(httpGet.charAt(i+7))){
temp=httpGet.substring(i,i+2);
dewP="-"+httpGet.substring(i+4,i+6);
break;
}
else if(Character.isDigit(c) && Character.isDigit(httpGet.charAt(i+1))
&& httpGet.charAt(i+2)=='/' &&
Character.isDigit(httpGet.charAt(i+3)) &&
Character.isDigit(httpGet.charAt(i+4)) &&
httpGet.charAt(i+5)==' ' &&
Character.isLetter(httpGet.charAt(i+6))){
temp=httpGet.substring(i,i+2);
dewP=httpGet.substring(i+3,i+5);
break;
}
}
``` | This looks promising, I googled java METAR parse :-)
<http://jfall-javafx.googlecode.com/svn-history/r6/WeatherFX/src/com/feldt/metar/Metar.java> |
15,836,423 | I'm trying to figure out how to set some environment variable which would make g++ to link to correct versions of the libraries.
I have some old boost libraries in /usr/lib64 (linking against these will fail) and new libraries in /v/users/regel/lib. So the linker should link against the new libraries.
Command:
```
$ g++ test.cpp -lboost_system -L/v/users/regel/lib
```
links the program correctly. However, I wish to set this as the number 1 search directory for the linker so that I don't have to specify '-L' every time I link.
The following environment variables do not seem to do the trick:
```
$ LIBRARY_PATH=/v/users/regel/lib g++ test.cpp -lboost_system
/tmp/regel/cc4SmBtI.o: In function `main':
test.cpp:(.text+0x5): undefined reference to `boost::system::system_category()'
collect2: error: ld returned 1 exit status
```
and
```
$ LD_LIBRARY_PATH=/v/users/regel/lib:$LD_LIBRARY_PATH g++ test.cpp -lboost_system
/tmp/regel/ccUreBZy.o: In function `main':
test.cpp:(.text+0x5): undefined reference to `boost::system::system_category()'
collect2: error: ld returned 1 exit status
```
Despite reading numerous articles and posts on similar subjects, I have not found a solution yet. | 2013/04/05 | [
"https://Stackoverflow.com/questions/15836423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738107/"
] | As the GCC manual [says](https://gcc.gnu.org/onlinedocs/gcc/Environment-Variables.html#Environment-Variables), `LIBRARY_PATH` is the correct environment variable to add directories to the library search path.
If you add `-v` to the `g++` command you should see the `LIBRARY_PATH` that it uses, and you should see it includes the directory you have specified, and that it gets added to the `collect2` command as `-L`, but you will see it gets added *after* the standard directories such as `-L/usr/lib` etc.
I don't know any way to make the directories in `LIBRARY_PATH` come first, I think you have to use `-L` for that. | Try specifying the library path in a .conf file in /etc/ld.so.conf.d/
The linker looks at paths specified in files in /etc/ld.so.conf.d/ while linking.
Make sure you run 'ldconfig' once you create the file, that will force it to update its cache. |
13,691,562 | I have this line:
`[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)`
How do i split it from the **3rd ]** and have 2 parts:
```
[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc]
```
and
```
I'm Sure [he/she] is leading CORN @types (countyfair)
``` | 2012/12/03 | [
"https://Stackoverflow.com/questions/13691562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060070/"
] | This one skips three `]`s:
```
use strict;
use warnings;
while (<>) {
if (my ($p1, $p2) = (/([^]]+][^]]+][^]]+])\s*(.*)/)) {
print "$p1 : $p2\n";
}
}
```
Using an array:
```
my @a;
while (<>) {
if (@a = (/([^]]+][^]]+][^]]+])\s*(.*)/)) {
print join(",", @a), "\n";
}
}
``` | I got interested in a generic function, so here it is:
```
#!/usr/bin/env perl
use strict;
use warnings;
my $str = q{[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)}; #'# fix highlight
my ($first, $second) = split_after_nth( qr/]/, $str, 3 );
$second =~ s/^\s*//; #/# fix highlight
print "$first\n$second\n";
sub split_after_nth {
my ($qr, $str, $num) = @_;
my @parts = split /($qr)/, $str, ++$num;
my $second = pop @parts;
my $first = join '', @parts;
return ($first, $second);
}
``` |
13,691,562 | I have this line:
`[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)`
How do i split it from the **3rd ]** and have 2 parts:
```
[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc]
```
and
```
I'm Sure [he/she] is leading CORN @types (countyfair)
``` | 2012/12/03 | [
"https://Stackoverflow.com/questions/13691562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060070/"
] | This one skips three `]`s:
```
use strict;
use warnings;
while (<>) {
if (my ($p1, $p2) = (/([^]]+][^]]+][^]]+])\s*(.*)/)) {
print "$p1 : $p2\n";
}
}
```
Using an array:
```
my @a;
while (<>) {
if (@a = (/([^]]+][^]]+][^]]+])\s*(.*)/)) {
print join(",", @a), "\n";
}
}
``` | A look-behind for three strings each terminated by `]` will do the trick. You didn't mention what you wanted to do with the whitespace after the third `]` so I've left it there.
```
use strict;
use warnings;
my $s = q{[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)};
my @pair = split /(?:[^]]*\]){3}\K/, $s;
print "$_\n" for @pair;
```
**output**
```
[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc]
I'm Sure [he/she] is leading CORN @types (countyfair)
``` |
13,691,562 | I have this line:
`[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)`
How do i split it from the **3rd ]** and have 2 parts:
```
[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc]
```
and
```
I'm Sure [he/she] is leading CORN @types (countyfair)
``` | 2012/12/03 | [
"https://Stackoverflow.com/questions/13691562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060070/"
] | A look-behind for three strings each terminated by `]` will do the trick. You didn't mention what you wanted to do with the whitespace after the third `]` so I've left it there.
```
use strict;
use warnings;
my $s = q{[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)};
my @pair = split /(?:[^]]*\]){3}\K/, $s;
print "$_\n" for @pair;
```
**output**
```
[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc]
I'm Sure [he/she] is leading CORN @types (countyfair)
``` | I got interested in a generic function, so here it is:
```
#!/usr/bin/env perl
use strict;
use warnings;
my $str = q{[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)}; #'# fix highlight
my ($first, $second) = split_after_nth( qr/]/, $str, 3 );
$second =~ s/^\s*//; #/# fix highlight
print "$first\n$second\n";
sub split_after_nth {
my ($qr, $str, $num) = @_;
my @parts = split /($qr)/, $str, ++$num;
my $second = pop @parts;
my $first = join '', @parts;
return ($first, $second);
}
``` |
36,614,034 | I'm running out of ideas on how to uncompress an array (request array A[] to response array B[])
Here are my definitions
**A** is a request class.
```
class A
{
public string Date { get; set; }
public decimal Price { get; set; }
}
```
Below is my array of requests of class A with its initalization.
```
var request = new A[]
{
new A { Date = "14-04-2016", Price = 100 },
new A { Date = "15-04-2016", Price = 100 },
new A { Date = "16-04-2016", Price = 0 },
new A { Date = "17-04-2016", Price = 100 },
new A { Date = "18-04-2016", Price = 100 }
};
```
**B** is a respond class.
```
class B
{
public string Start { get; set; }
public string End { get; set; }
public decimal Price { get; set; }
}
```
The above requests needs to be converted to an array of `B`. Something like this
```
var response = new B[]
{
new B { Start = "14-04-2016", End = "16-04-2016", Price = 100 },
new B { Start = "16-04-2016", End = "17-04-2016", Price = 0 },
new B { Start = "17-04-2016", End = "18-04-2016", Price = 100 }
};
```
The response is grouped based on the Price and order by date. Its more of like, I need to uncompress the request array A[] into response array B[].
How can I achieve this? | 2016/04/14 | [
"https://Stackoverflow.com/questions/36614034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210896/"
] | You could do this using `GroupBy` linq extension, following query returns `List<B>`objects.
```
var results = request.Select(s=>
new
{
Price = s.Price,
Date = DateTime.ParseExact(s.Date, "dd-MM-yyyy", null) // convert to Date.
})
.GroupBy(g=>g.Price)
.Select(s=>
new B()
{
Start = s.Min(c=>c.Date).ToString("dd-MM-yyyy"),
End = s.Max(c=>c.Date).ToString("dd-MM-yyyy"),
Price = s.Key
})
.ToList() ;
```
**Update :**
As per comments, you don't really require grouping on price. What you need is grouping *adjacent* items whose price is matching .
We could achieve this with slight modification to above `Linq` query.
```
int grp = 0;
decimal prevprice=response.First().Price;
var results = request.Select((s, i)=>
{
grp = s.Price == prevprice? grp : ++grp;
prevprice = s.Price;
return new
{
grp,
Price = s.Price,
Date = DateTime.ParseExact(s.Date, "dd-MM-yyyy", null)
};
})
.GroupBy(g=>g.grp)
.Select(s=>
new B()
{
Start = s.Min(c=>c.Date).ToString("dd-MM-yyyy"),
End = s.Max(c=>c.Date).ToString("dd-MM-yyyy"),
Price = s.First().Price
});
```
**Output**
```
14-04-2016,15-04-2016 ,100
16-04-2016,16-04-2016 ,0
17-04-2016,18-04-2016 ,100
```
Working [`Example`](https://dotnetfiddle.net/KPiNdN) | Pseudocode (assumes request is ordered by date - if not you can sort it easily):
```
int lastPrice = -1;
//count the distinct price ranges
int responseSize = 0;
foreach (A requestObj in request) {
if (requestObj.price != lastPrice) {
responseSize++;
lastPrice = requestObj.price;
}
}
//set the initial element
B[] response = new B[responseSize];
response[0].start = request[0].date;
response[0].price = request[0].price;
int responseindex = 0;
//parse the result
foreach (A requestObj in request) {
if (requestObj.price != response[responseindex].price) {
response[responseindex].end = requestObj.date;
responseIndex++;
response[responseindex].price = requestObj.price;
response[responseindex].start= requestObj.date;
}
}
//set the end date of the final object
response[response.length - 1].end = request[request.length - 1].date;
``` |
36,614,034 | I'm running out of ideas on how to uncompress an array (request array A[] to response array B[])
Here are my definitions
**A** is a request class.
```
class A
{
public string Date { get; set; }
public decimal Price { get; set; }
}
```
Below is my array of requests of class A with its initalization.
```
var request = new A[]
{
new A { Date = "14-04-2016", Price = 100 },
new A { Date = "15-04-2016", Price = 100 },
new A { Date = "16-04-2016", Price = 0 },
new A { Date = "17-04-2016", Price = 100 },
new A { Date = "18-04-2016", Price = 100 }
};
```
**B** is a respond class.
```
class B
{
public string Start { get; set; }
public string End { get; set; }
public decimal Price { get; set; }
}
```
The above requests needs to be converted to an array of `B`. Something like this
```
var response = new B[]
{
new B { Start = "14-04-2016", End = "16-04-2016", Price = 100 },
new B { Start = "16-04-2016", End = "17-04-2016", Price = 0 },
new B { Start = "17-04-2016", End = "18-04-2016", Price = 100 }
};
```
The response is grouped based on the Price and order by date. Its more of like, I need to uncompress the request array A[] into response array B[].
How can I achieve this? | 2016/04/14 | [
"https://Stackoverflow.com/questions/36614034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210896/"
] | You could do this using `GroupBy` linq extension, following query returns `List<B>`objects.
```
var results = request.Select(s=>
new
{
Price = s.Price,
Date = DateTime.ParseExact(s.Date, "dd-MM-yyyy", null) // convert to Date.
})
.GroupBy(g=>g.Price)
.Select(s=>
new B()
{
Start = s.Min(c=>c.Date).ToString("dd-MM-yyyy"),
End = s.Max(c=>c.Date).ToString("dd-MM-yyyy"),
Price = s.Key
})
.ToList() ;
```
**Update :**
As per comments, you don't really require grouping on price. What you need is grouping *adjacent* items whose price is matching .
We could achieve this with slight modification to above `Linq` query.
```
int grp = 0;
decimal prevprice=response.First().Price;
var results = request.Select((s, i)=>
{
grp = s.Price == prevprice? grp : ++grp;
prevprice = s.Price;
return new
{
grp,
Price = s.Price,
Date = DateTime.ParseExact(s.Date, "dd-MM-yyyy", null)
};
})
.GroupBy(g=>g.grp)
.Select(s=>
new B()
{
Start = s.Min(c=>c.Date).ToString("dd-MM-yyyy"),
End = s.Max(c=>c.Date).ToString("dd-MM-yyyy"),
Price = s.First().Price
});
```
**Output**
```
14-04-2016,15-04-2016 ,100
16-04-2016,16-04-2016 ,0
17-04-2016,18-04-2016 ,100
```
Working [`Example`](https://dotnetfiddle.net/KPiNdN) | This can also be done with the following:
```
var response = from reqItem in request
group reqItem by reqItem.Price into g
select new B()
{
Start = g.Min(m => DateTime.Parse(m.Date)).ToString("dd-MM-yyyy"),
End = g.Max(m => DateTime.Parse(m.Date)).ToString("dd-MM-yyyy"),
Price = g.Key
};
``` |
36,614,034 | I'm running out of ideas on how to uncompress an array (request array A[] to response array B[])
Here are my definitions
**A** is a request class.
```
class A
{
public string Date { get; set; }
public decimal Price { get; set; }
}
```
Below is my array of requests of class A with its initalization.
```
var request = new A[]
{
new A { Date = "14-04-2016", Price = 100 },
new A { Date = "15-04-2016", Price = 100 },
new A { Date = "16-04-2016", Price = 0 },
new A { Date = "17-04-2016", Price = 100 },
new A { Date = "18-04-2016", Price = 100 }
};
```
**B** is a respond class.
```
class B
{
public string Start { get; set; }
public string End { get; set; }
public decimal Price { get; set; }
}
```
The above requests needs to be converted to an array of `B`. Something like this
```
var response = new B[]
{
new B { Start = "14-04-2016", End = "16-04-2016", Price = 100 },
new B { Start = "16-04-2016", End = "17-04-2016", Price = 0 },
new B { Start = "17-04-2016", End = "18-04-2016", Price = 100 }
};
```
The response is grouped based on the Price and order by date. Its more of like, I need to uncompress the request array A[] into response array B[].
How can I achieve this? | 2016/04/14 | [
"https://Stackoverflow.com/questions/36614034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210896/"
] | Pseudocode (assumes request is ordered by date - if not you can sort it easily):
```
int lastPrice = -1;
//count the distinct price ranges
int responseSize = 0;
foreach (A requestObj in request) {
if (requestObj.price != lastPrice) {
responseSize++;
lastPrice = requestObj.price;
}
}
//set the initial element
B[] response = new B[responseSize];
response[0].start = request[0].date;
response[0].price = request[0].price;
int responseindex = 0;
//parse the result
foreach (A requestObj in request) {
if (requestObj.price != response[responseindex].price) {
response[responseindex].end = requestObj.date;
responseIndex++;
response[responseindex].price = requestObj.price;
response[responseindex].start= requestObj.date;
}
}
//set the end date of the final object
response[response.length - 1].end = request[request.length - 1].date;
``` | This can also be done with the following:
```
var response = from reqItem in request
group reqItem by reqItem.Price into g
select new B()
{
Start = g.Min(m => DateTime.Parse(m.Date)).ToString("dd-MM-yyyy"),
End = g.Max(m => DateTime.Parse(m.Date)).ToString("dd-MM-yyyy"),
Price = g.Key
};
``` |
27,731,015 | i want to create an android application,
the apk has a text box and one button perhaps.
in the text box the user will input their HTML codes/strings.
and by clicking the button it will show the output of the codes they type from the textbox. | 2015/01/01 | [
"https://Stackoverflow.com/questions/27731015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410140/"
] | you can do it like this
```
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
WebView wv = (WebView) findViewById(R.id.WebView01);
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = "<br /><br />Read the handouts please for tomorrow.<br /><br /><!--homework help homework" +
"help help with homework homework assignments elementary school high school middle school" +
"// --><font color='#60c000' size='4'><strong>Please!</strong></font>" +
"<img src='http://www.homeworknow.com/hwnow/upload/images/tn_star300.gif' />";
wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
}
}
```
add this in the menifest
```
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
``` | call this line:
```
wv.loadData(yourHtmlData, "text/html", "UTF-8");
``` |
17,152,150 | Here is a line of code that I have:
```
public class ReminderHandler() {
if (edittext.containsReminderWords()){
test.setText("Do you want me to remind you to " + sharedPref.getString(toremember, toremember) + "?");
}
}
```
I want the program to wait for either a yes or a no answer from the edittext after this specific line of command.
I have no idea how though.
How can I achieve this? | 2013/06/17 | [
"https://Stackoverflow.com/questions/17152150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2491252/"
] | You better use [AlertDialog](http://developer.android.com/reference/android/app/AlertDialog.html). Check [this link](http://developer.android.com/guide/topics/ui/dialogs.html) to know more about android Dialogs | you would do this with an event:
* a button near the text input that say something like "do it"/"save"/"done", etc.
* an event, like focus changed, touch up,etc. see: <http://developer.android.com/guide/topics/ui/ui-events.html> |
17,152,150 | Here is a line of code that I have:
```
public class ReminderHandler() {
if (edittext.containsReminderWords()){
test.setText("Do you want me to remind you to " + sharedPref.getString(toremember, toremember) + "?");
}
}
```
I want the program to wait for either a yes or a no answer from the edittext after this specific line of command.
I have no idea how though.
How can I achieve this? | 2013/06/17 | [
"https://Stackoverflow.com/questions/17152150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2491252/"
] | JOptionPane has plenty of options for you to use.
```
JOptionPane.showConfirmDialog(null, "Do you want to do something?")
```
See [here](http://docs.oracle.com/javase/6/docs/api/javax/swing/JOptionPane.html#showConfirmDialog%28java.awt.Component,%20java.lang.Object%29) for the documentation | you would do this with an event:
* a button near the text input that say something like "do it"/"save"/"done", etc.
* an event, like focus changed, touch up,etc. see: <http://developer.android.com/guide/topics/ui/ui-events.html> |
17,152,150 | Here is a line of code that I have:
```
public class ReminderHandler() {
if (edittext.containsReminderWords()){
test.setText("Do you want me to remind you to " + sharedPref.getString(toremember, toremember) + "?");
}
}
```
I want the program to wait for either a yes or a no answer from the edittext after this specific line of command.
I have no idea how though.
How can I achieve this? | 2013/06/17 | [
"https://Stackoverflow.com/questions/17152150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2491252/"
] | You better use [AlertDialog](http://developer.android.com/reference/android/app/AlertDialog.html). Check [this link](http://developer.android.com/guide/topics/ui/dialogs.html) to know more about android Dialogs | JOptionPane has plenty of options for you to use.
```
JOptionPane.showConfirmDialog(null, "Do you want to do something?")
```
See [here](http://docs.oracle.com/javase/6/docs/api/javax/swing/JOptionPane.html#showConfirmDialog%28java.awt.Component,%20java.lang.Object%29) for the documentation |
11,465,067 | I have 3 text boxes where user will enter some value inside it. Then user will click on done button which then it will redirect user to another page and the page will show user what data entered by them before in label before they hit save button to be saved in db. I would like to use session in this case but the i dont know how. Can someone tell me how? Thank you. | 2012/07/13 | [
"https://Stackoverflow.com/questions/11465067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220691/"
] | When you use `Scanner.nextInt()`, it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a `Scanner.nextLine()`. You can discard the result instead of assigning it to `a`:
```
int a = in.nextInt();
in.nextLine();
```
It's for this reason that I suggest *always* using `nextLine` (or `BufferedReader.readLine()`) and doing the parsing after using `Integer.parseInt()`. | Instead of
```
s = in.nextLine();
```
try
```
in.nextLine();
s = in.nextLine();
```
The call to nextInt() still leaves a trailing newline.
Calling in.nextLine() actually goes to the next line. Then in.nextLine will get your actual result. |
11,465,067 | I have 3 text boxes where user will enter some value inside it. Then user will click on done button which then it will redirect user to another page and the page will show user what data entered by them before in label before they hit save button to be saved in db. I would like to use session in this case but the i dont know how. Can someone tell me how? Thank you. | 2012/07/13 | [
"https://Stackoverflow.com/questions/11465067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220691/"
] | Instead of
```
s = in.nextLine();
```
try
```
in.nextLine();
s = in.nextLine();
```
The call to nextInt() still leaves a trailing newline.
Calling in.nextLine() actually goes to the next line. Then in.nextLine will get your actual result. | Try it like this :D
```
import java.util.Scanner;
public class Hello {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a;
String s = null;
System.out.print("Enter int: ");
a = in.nextInt();
while ((s = in.nextLine()).trim().isEmpty()) {
System.out.print("Enter String: ");
}
System.out.println("int : " + a + "\nString : " + s);
}
}
``` |
11,465,067 | I have 3 text boxes where user will enter some value inside it. Then user will click on done button which then it will redirect user to another page and the page will show user what data entered by them before in label before they hit save button to be saved in db. I would like to use session in this case but the i dont know how. Can someone tell me how? Thank you. | 2012/07/13 | [
"https://Stackoverflow.com/questions/11465067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220691/"
] | Instead of
```
s = in.nextLine();
```
try
```
in.nextLine();
s = in.nextLine();
```
The call to nextInt() still leaves a trailing newline.
Calling in.nextLine() actually goes to the next line. Then in.nextLine will get your actual result. | ```
import java.util.Scanner;
public class Hello{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int a;
String s;
System.out.println("Enter int : ");
a = in.nextInt();
System.out.println("Enter String : ");
s = in.next();
System.out.println("int : "+a+"\nString : "+s);
}
}
``` |
11,465,067 | I have 3 text boxes where user will enter some value inside it. Then user will click on done button which then it will redirect user to another page and the page will show user what data entered by them before in label before they hit save button to be saved in db. I would like to use session in this case but the i dont know how. Can someone tell me how? Thank you. | 2012/07/13 | [
"https://Stackoverflow.com/questions/11465067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220691/"
] | When you use `Scanner.nextInt()`, it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a `Scanner.nextLine()`. You can discard the result instead of assigning it to `a`:
```
int a = in.nextInt();
in.nextLine();
```
It's for this reason that I suggest *always* using `nextLine` (or `BufferedReader.readLine()`) and doing the parsing after using `Integer.parseInt()`. | Try it like this :D
```
import java.util.Scanner;
public class Hello {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a;
String s = null;
System.out.print("Enter int: ");
a = in.nextInt();
while ((s = in.nextLine()).trim().isEmpty()) {
System.out.print("Enter String: ");
}
System.out.println("int : " + a + "\nString : " + s);
}
}
``` |
11,465,067 | I have 3 text boxes where user will enter some value inside it. Then user will click on done button which then it will redirect user to another page and the page will show user what data entered by them before in label before they hit save button to be saved in db. I would like to use session in this case but the i dont know how. Can someone tell me how? Thank you. | 2012/07/13 | [
"https://Stackoverflow.com/questions/11465067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220691/"
] | When you use `Scanner.nextInt()`, it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a `Scanner.nextLine()`. You can discard the result instead of assigning it to `a`:
```
int a = in.nextInt();
in.nextLine();
```
It's for this reason that I suggest *always* using `nextLine` (or `BufferedReader.readLine()`) and doing the parsing after using `Integer.parseInt()`. | ```
import java.util.Scanner;
public class Hello{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int a;
String s;
System.out.println("Enter int : ");
a = in.nextInt();
System.out.println("Enter String : ");
s = in.next();
System.out.println("int : "+a+"\nString : "+s);
}
}
``` |
69,986,583 | I'd like to create several plots by looping ggplot. I created a small df (*plothelp\_df*) for deriving the plot object names and variable names during the loop. But I am struggling with naming the plot objects dynamically when trying to derive the names from *plothelp\_df*.
Here the code:
```
### Creating df which loop is based on
pltnames_scat <- c("plt_test2_blu","plt_test2_grn", "plt_test2_red", "plt_test2_re1", "plt_test2_re2", "plt_test2_re3", "plt_test2_bnr", "plt_test2_nir", "plt_test2_sw1", "plt_test2_sw2")
band_vnames <- c("BLUE", "GREEN", "RED", "REDEDGE1", "REDEDGE2", "REDEDGE3", "BROADNIR", "NIR", "SWIR1", "SWIR2")
band_appndx <- c("blu","grn", "red", "re1", "re2", "re3", "bnr", "nir", "sw1", "sw2")
plothelp_df <- data.frame(cbind(pltnames_scat, band_vnames, band_appndx))
### Principally I'd like to run a loop, but I am struggling with naming the plots dynamically
### Therefore the loop lines as comments and the indices in the plot section are set to 1
# for (o in 1:nrow(plothelp_df)){
noquote(plothelp_df$pltnames_scat[1]) <- ggplot(loopsubset_created_S02, aes_string(x = plothelp_df$band_vnames[1] , y = "PdKeyT")) +
geom_point() +
geom_point(mapping = aes(color = Class_Derived))
# }
plt_test2_blu
```
`unquote(plothelp_df$pltnames_scat[1])` should assign the name *plt\_test2\_blu* to the plot, but ends in:
`Error in noquote(plothelp_df$pltnames_scat[1]) <- ggplot( loopsubset_created_S02,:could not find function "noquote<-"`.
I tried also with`as.name` (instead of `unquote`). But the same error.
If I insert the index-1 plot object name (= *plt\_test2\_blu*) manually the plot object will be created as intended. So, the error seems at least not to be caused by the rest of the code.
```
plt_test2_blu <- ggplot(loopsubset_created_S02, aes_string(x = plothelp_df$band_vnames[1] , y = "PdKeyT")) +
geom_point() +
geom_point(mapping = aes(color = Class_Derived))
```
Somehow R seems to not to accept functions at the beginning of a line. But I don't know how to solve this. I am quite new to R.
May anybody show me the right approach to get the plots named dynamically?
(At the end you'll find a `dput` of the `loopsubset_created_S02`-df)
Here the data:
```
> dput(loopsubset_created_S02)
structure(list(Site_ID = c("A", "A", "A", "A", "A", "A", "A",
"A", "A", "A", "A", "A", "A"), Spot_Nr = c("1", "1", "1", "1",
"1", "1", "1", "1", "1", "1", "1", "1", "1"), Transkt_Nr = c("2",
"2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2"),
Point_Nr = c("13", "13", "13", "13", "13", "13", "13", "13",
"13", "13", "13", "13", "13"), nobs = c(3L, 22L, 22L, 22L,
22L, 22L, 22L, 22L, 22L, 22L, 22L, 22L, 2L), rank = c(3L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 15L), Tile = c("1008",
"1008", "1008", "1008", "1008", "1008", "1008", "1008", "1008",
"1008", "1008", "1008", "1008"), Date = c(20191023L, 20190506L,
20190603L, 20190625L, 20190630L, 20190710L, 20190725L, 20190809L,
20190817L, 20190903L, 20190913L, 20190921L, 20190524L), id = c("31",
"31", "31", "31", "31", "31", "31", "31", "31", "31", "31",
"31", "31"), Point_ID = c("1031", "1031", "1031", "1031",
"1031", "1031", "1031", "1031", "1031", "1031", "1031", "1031",
"1031"), Site_Nr = c("1", "1", "1", "1", "1", "1", "1", "1",
"1", "1", "1", "1", "1"), Point_x = c(356040.781, 356040.781,
356040.781, 356040.781, 356040.781, 356040.781, 356040.781,
356040.781, 356040.781, 356040.781, 356040.781, 356040.781,
356040.781), Point_y = c(5132780.701, 5132780.701, 5132780.701,
5132780.701, 5132780.701, 5132780.701, 5132780.701, 5132780.701,
5132780.701, 5132780.701, 5132780.701, 5132780.701, 5132780.701
), Classification = c(7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
2), Class_Derived = c("WW", "WF", "WF", "WF", "WF", "WF",
"WF", "WF", "WF", "WF", "WF", "WF", "NW"), BLUE = c(963,
2422, 2524, 1798, 1830, 1886, 1548, 1775, 2055, 1613, 1566,
1650, 2542), GREEN = c(1166, 2528, 2717, 2084, 2073, 2058,
1787, 1962, 2323, 1858, 1810, 1880, 2736), RED = c(1034,
2355, 2477, 2064, 2166, 2161, 1756, 2108, 2348, 1840, 1765,
1958, 2663), REDEDGE1 = c(1170, 2199, 2427, 2052, 2317, 2365,
1774, 2154, 2213, 1702, 1723, 2096, 2728), REDEDGE2 = c(917,
1670, 2077, 1880, 2087, 2163, 1879, 1972, 1986, 1409, 1435,
1943, 2450), REDEDGE3 = c(948, 1637, 2113, 1975, 2179, 2192,
1965, 2008, 2007, 1461, 1516, 1964, 2530), BROADNIR = c(826,
1727, 1990, 2047, 2048, 1983, 2203, 2004, 2133, 1574, 1554,
1823, 2303), NIR = c(918, 1590, 2036, 1910, 2172, 2098, 2029,
1987, 2008, 1437, 1486, 1899, 2451), SWIR1 = c(922, 1423,
2093, 1808, 2266, 2258, 1759, 2027, 2014, 1456, 1432, 1940,
2326), SWIR2 = c(709, 1080, 1468, 1362, 1565, 1600, 1295,
1416, 1523, 1104, 1077, 1395, 1648), Quality.assurance.information = c(8192,
8208, 8192, 8256, 8192, 8192, 8256, 8192, 8192, 8192, 8192,
8192, 8192), Q00_VAL = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0), Q01_CS1 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
Q02_CS2 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Q03_CSH = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Q04_SNO = c(0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Q05_WAT = c(0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0), Q06_AR1 = c(0, 0, 0, 1, 0, 0, 1,
0, 0, 0, 0, 0, 0), Q07_AR2 = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0), Q08_SBZ = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0), Q09_SAT = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
Q10_ZEN = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Q11_IL1 = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Q12_IL2 = c(0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Q13_SLO = c(1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1), Q14_VAP = c(0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0), Q15_WDC = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0), PdMax = c(5L, 57L, 44L, 18L, 13L, 16L, 13L,
9L, 7L, 11L, 9L, 2L, 47L), PdMin = c(0L, 47L, 37L, 14L, 9L,
9L, 9L, 5L, 3L, 2L, 5L, -3L, 36L), PdKeyT = c(3L, 53L, 43L,
15L, 13L, 13L, 10L, 7L, 6L, 6L, 9L, 2L, 40L)), row.names = c(50L,
66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 81L), class = "data.frame")
``` | 2021/11/16 | [
"https://Stackoverflow.com/questions/69986583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16918018/"
] | Instead of storing your plots as single objects I would suggest to store them in a (named) list, which in general is the recommend way to do. Additionally I would suggest to create your plots via e.g. `lapply` instead of using a `for` loop. Finally, if `aes_string` works you also make use of the `.data` pronoun from `rlang` if you want to access a column via a character string.
```
library(ggplot2)
pltnames_scat <- c("plt_test2_blu","plt_test2_grn", "plt_test2_red", "plt_test2_re1", "plt_test2_re2", "plt_test2_re3", "plt_test2_bnr", "plt_test2_nir", "plt_test2_sw1", "plt_test2_sw2")
band_vnames <- c("BLUE", "GREEN", "RED", "REDEDGE1", "REDEDGE2", "REDEDGE3", "BROADNIR", "NIR", "SWIR1", "SWIR2")
# Set the names for the vector to loop over.
# This will automatically return a named list with the plot names
names(band_vnames) <- pltnames_scat
plot_list <- lapply(band_vnames, function(vname) {
ggplot(loopsubset_created_S02, aes(x = .data[[vname]], y = PdKeyT)) +
geom_point() +
geom_point(mapping = aes(color = Class_Derived))
})
plot_list$plt_test2_blu
```
[](https://i.stack.imgur.com/8wkNT.png) | This can also be done simply with `assign()` and `paste0()` in the `for` loop putting plots individually in the R environment.
```
library(ggplot2)
# Using mtcars dataset
cylinder <- unique(mtcars$cyl)
for(i in 1:length(cylinder)){
data <- mtcars[which(mtcars$cyl == cylinder[i]),]
plot <-
ggplot(data = data, aes(x = disp, y = hp))+
geom_point(aes(colour = gear))+
labs(title = paste0(cylinder[i]," Cylinder")) # Not necessary but can also be dynamic
assign(paste0("plot", i), plot)
}
plot1
plot2
plot3
``` |
11,908,579 | I seriously hope someone here can help me with this one... eventhough it's somewhat complicated to explain what I'm searching for.
Basically I'm looking for a "countdown/countup" javascript - *sounding pretty straight forward, right?*
I have found lots of variations of this sort of script but none of them meets the following requirements.
What I specifically need, is a script which on page load starts counting down from 36000 sec. and when reaching 0 sec. immediately starts counting back up to 36000 sec.
Meanwhile, I have these two div's which ought to both effect and be effected by the script:
```
<style>
.indicator {
width: 20px;
height: 8px;
}
</style>
<div class="percent">100%</div>
<div class="indicator"></div>
```
As you can see, the innerHTML of the first div starts out being 100% and should be reduced by 1 when the script has counted past every 360th sec.
*(e.g.: when counted past the 3600th sec. the innerHTML should be 90%)*
The second div has a width of 20px which should be reduced by 1px when the script has counted past every 1800th sec.
*(e.g.: when counted past the 3600th sec. the width should be 18px)*
* 36000 sec. = 100% = 20px
* 18000 sec. = 50% = 10px
* 3600 sec. = 10% = 2px
* 1800 sec. = 5% = 1px
* 360 sec. = 1% = 0px
As mentioned before, the script should start counting back upwards when it has reached 0 sec.
When this happens, the className of the second div should change from **indicator** to **charging** and the innerHTML of the first div should increase appropriately according to the sec's counted past.
*(exactly as when the script was counting downwards)*
However, when the countup reaches the 36000th sec. it isn't supposed to just start counting back down again, but rather pause there and change the className of the second div from **charging** to **charged**.
Needless to say, the innerHTML of the first div should at this point be 100%.
From here on, the script is only to commence countdown if the second div is clicked, in which case the className of the second div should change from **charged** back to **indicator**.
Furthermore, the countdown/countup is to be reversed whenever the second div is clicked, simultaniously changing of its className.
* **Countdown**: `<div class="indicator"></div>`
* **Countup**: `<div class="charging"></div>`
I apologize for the long explanation and my poor english grammar...
Hope somebody is able to make sence of this :) | 2012/08/10 | [
"https://Stackoverflow.com/questions/11908579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289669/"
] | You can use for the "Done" button click callback something like
```
if (!$("#AddCustomerDialog form").valid())
return false;
var postUrl = $("#AddCustomerDialog form").attr('action');
$.post(postUrl, $(containerSelector + ' form').serialize(),
function (result) {
$("#AddCustomerDialog").dialog("close");
var addedCustomerId = result.Id;
});
```
Also AddCustomer action (for post request) should return added customer in Json format. | declare a variable in your html page script, now in the return data from your php code add an echo script with the variable name and set here the id you want
in your script: var foo;
in your php code
```
echo 'data for insert in div';
echo '<script>foo=id_you_want</script>';
exit();
```
with this you set the foo var in the html page with the id of the new customer and can use it |
23,445 | Can an employer force an employee to donate to a charity and is it legal that they know how much an employee contributes? This is in the U.S. with a large global corporation. | 2017/10/19 | [
"https://law.stackexchange.com/questions/23445",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/3645/"
] | "Probable cause" and "reasonable suspicion" are things that apply to law enforcement, not private authority.
Your school may also have conditions of entry that include, or be in a jurisdiction with laws that specifically allow, search of student persons and their property under some given circumstances. This may or may not involve police to ensure a search is conducted appropriately. Your consent is not required in such cases.
Finally, your parents may consent on your behalf, especially if you are defined as a child or young person over whom they have this authority. For students considered legal adults, this is like to not be a factor. | It is not illegal for someone to search my bag or even my person if I give consent. As a child (which you are until 18), consent given by your parents is consent given by you. |
23,445 | Can an employer force an employee to donate to a charity and is it legal that they know how much an employee contributes? This is in the U.S. with a large global corporation. | 2017/10/19 | [
"https://law.stackexchange.com/questions/23445",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/3645/"
] | The school admins likely did not even need to call the parents to obtain permission to search the bag. School admins only need *reasonable grounds* to believe there is evidence of a crime. This lower bar is due to [inherent nature of the school environment](https://www.law.cornell.edu/supremecourt/text/469/325) and what it takes to manage it:
>
> How, then, should we strike the balance between the schoolchild's legitimate expectations of privacy and the school's equally legitimate need to maintain an environment in which learning can take place? It is evident that the school setting requires some easing of the restrictions to which searches by public authorities are ordinarily subject. The warrant requirement, in particular, is unsuited to the school environment: requiring a teacher to obtain a warrant before searching a child suspected of an infraction of school rules (or of the criminal law) would unduly interfere with the maintenance of the swift and informal disciplinary procedures needed in the schools. Just as we have in other cases dispensed with the warrant requirement when "the burden of obtaining a warrant is likely to frustrate the governmental purpose behind the search," Camara v. Municipal Court, 387 U.S. at 532-533, we hold today that school officials need not obtain a warrant before searching a student who is under their authority.
>
>
>
*New Jersey v. TLO 469 US 325 (1985).*
School searches are upheld when they are reasonable. To be reasonable, the search must
(a) offer a *moderate chance of finding evidence*,
(b) the way the search was conducted was *reasonably related* to the search's objectives, and
(c) with respect to the age and sex of the child and the nature of the rule the child violated, the such must not be *excessively intrusive*.
*New Jersey v. TLO.*
---
Conducting a search that reasonably relates to the search's objectives means if you suspect someone of shoplifting a TV, a full body search may be considered excessive. while a flat-handed patdown to check for weapons when approaching someone as a police officer is almost always found appropriate.
--- | It is not illegal for someone to search my bag or even my person if I give consent. As a child (which you are until 18), consent given by your parents is consent given by you. |
23,445 | Can an employer force an employee to donate to a charity and is it legal that they know how much an employee contributes? This is in the U.S. with a large global corporation. | 2017/10/19 | [
"https://law.stackexchange.com/questions/23445",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/3645/"
] | The school admins likely did not even need to call the parents to obtain permission to search the bag. School admins only need *reasonable grounds* to believe there is evidence of a crime. This lower bar is due to [inherent nature of the school environment](https://www.law.cornell.edu/supremecourt/text/469/325) and what it takes to manage it:
>
> How, then, should we strike the balance between the schoolchild's legitimate expectations of privacy and the school's equally legitimate need to maintain an environment in which learning can take place? It is evident that the school setting requires some easing of the restrictions to which searches by public authorities are ordinarily subject. The warrant requirement, in particular, is unsuited to the school environment: requiring a teacher to obtain a warrant before searching a child suspected of an infraction of school rules (or of the criminal law) would unduly interfere with the maintenance of the swift and informal disciplinary procedures needed in the schools. Just as we have in other cases dispensed with the warrant requirement when "the burden of obtaining a warrant is likely to frustrate the governmental purpose behind the search," Camara v. Municipal Court, 387 U.S. at 532-533, we hold today that school officials need not obtain a warrant before searching a student who is under their authority.
>
>
>
*New Jersey v. TLO 469 US 325 (1985).*
School searches are upheld when they are reasonable. To be reasonable, the search must
(a) offer a *moderate chance of finding evidence*,
(b) the way the search was conducted was *reasonably related* to the search's objectives, and
(c) with respect to the age and sex of the child and the nature of the rule the child violated, the such must not be *excessively intrusive*.
*New Jersey v. TLO.*
---
Conducting a search that reasonably relates to the search's objectives means if you suspect someone of shoplifting a TV, a full body search may be considered excessive. while a flat-handed patdown to check for weapons when approaching someone as a police officer is almost always found appropriate.
--- | "Probable cause" and "reasonable suspicion" are things that apply to law enforcement, not private authority.
Your school may also have conditions of entry that include, or be in a jurisdiction with laws that specifically allow, search of student persons and their property under some given circumstances. This may or may not involve police to ensure a search is conducted appropriately. Your consent is not required in such cases.
Finally, your parents may consent on your behalf, especially if you are defined as a child or young person over whom they have this authority. For students considered legal adults, this is like to not be a factor. |
64,051 | The display of maps and data within an interactive framework is becoming more prevalent online. I'm thinking beyond merely the ability to pan/zoom/control layers, but more along the lines of displaying spatial and non-spatial data, together, in a unique format (e.g. animated charts).
For example, [this website](http://www.watershed-watch.org/fraser-basin-livemap/) goes beyond mapping and presents spatial data as a learning and exploration tool with graphical data summaries, text summaries, animations, etc.
What are some good examples of well-designed interactive maps using modern technologies, and what are the advantages/disadvantages of these tools?
What technologies should be avoided? | 2013/06/20 | [
"https://gis.stackexchange.com/questions/64051",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2114/"
] | >
> This question has been converted to Community Wiki and wiki locked
> because it is an example of a question that seeks a list of answers
> and appears to be popular enough to protect it from closure. It
> should be treated as a special case and should not be viewed as the
> type of question that is encouraged on this, or any Stack Exchange
> site, but if you wish to contribute more content to it then feel free
> to do so by editing this answer.
>
>
>
---
This is a very dynamic and exciting period for interactive data and map applications on the Web. This great dynamism is driven (but to some extent also drives) by the numerous innovations and trends that are currently undergoing within the complex Web scenario (users, industry, standards, innovation...). Very briefly:
1. Browsers are getting more and more capable, with JavaScript interpreters becoming faster and [HTML5 technologies](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5) getting more widely adopted.
2. To some extent, different browser vendors are finally converging more towards a wide adoption of Web Standards. A relevant example for data and mapping visualizations is SVG that, although around as a Web standard since 1999, lacked until recently wide adoption, because of Internet Explorer not supporting it until version 9.
The consequences of this are that JavaScript is becoming central to building today's Web applications and functionality is moving from the server to the client wilts the 2 are becoming more decoupled with the rise of REST interfaces. This is well exemplified, for example, in the rise of so many JavaScript MVC frameworks or even more by the huge proliferation of Open Source JavaScript libraries and projects on well known code repository sites such as [GitHub](https://github.com/) or [BitBucket](https://bitbucket.org/).
If JavaSript (and HTML5) is the big winner, Flash is the loser. You can still find Flash applications around the Web (your example is a beautifully designed interactive Flash application), but its technology is clearly PAST.
### Companies that are doing some serious JavaScript data-map Web visualizations:
* [vizzuality](http://vizzuality.com/). These guys from Spain are amazing. There interactive visualizations are stunning. They also have a Web product called [cartodb](http://cartodb.com/) that lets you upload data to a PostGIS server and create awesome visualizations. And look out also their [HTML5 mapping experiments](http://vizzuality.github.io/HTML5-experiments/), to have an idea of where the technology is heading.
* [MapBox](http://www.mapbox.com/) is another awesome company that drives a lot of innovation in the Web mapping-data visualization field. [Tilemill](http://www.mapbox.com/tilemill/), in particular, based on [mapnik](http://mapnik.org/) and JavaScript and Web technologies, is something ESRI would have never had the creativity to invent.
* [Stamen](http://maps.stamen.com/), not my personal favorite, but still very good and full of innovative ideas.
### About and around d3.js:
* [d3.js](http://d3js.org/) is by far the best example of a JavaScript library built for data and map interactive visualizations. The links could be endless here.
* [Map gallery list](https://github.com/mbostock/d3/wiki/Gallery#maps)
* [Mike Bostock](http://bost.ocks.org/mike/) Web page.
* [Jason Davies](http://www.jasondavies.com/)
* [Geo-Projections](https://github.com/mbostock/d3/wiki/Geo-Projections)
* [topojson](https://github.com/mbostock/topojson)
### Other great JavaScript technologies:
* [Kartograph](http://kartograph.org/). Simply beautiful maps and visualizations.
* [OpenLayers](http://openlayers.org/). Years ago, when flash was still strong, it opened the road to Open Source JavaScript mapping.
* [Leaflet](http://leafletjs.com/). One cannot avoid mentioning this library for its huge following among today's Web designers and programmers.
### And Web examples:
* [protectedplanet](http://protectedplanet.net/), an original and nice way of making use of google maps.
* [remittances](http://remittances.herokuapp.com/?en), a nice d3 example from the above gallery.
* [MapMaker Interactive](http://education.nationalgeographic.com/education/mapping/interactive-map/?ar_a=1). I love the idea behind this, but the implementation is far from perfect. | A List of 'OpenSource' GIS & **WebMap Servers**
<http://en.wikipedia.org/wiki/List_of_geographic_information_systems_software>
Recommend Geoserver 2.1
<http://geoserver.org/display/GEOS/Stable> |
53,317,899 | I'm trying to call **chrome.exe** inside a **C#** program by using **System.Diagnostics.Process** namespace.
my **chrome.exe** is located inside path **C:\Program Files (x86)\Google\Chrome\Application**
if I call **RunProc** function by passing bellow parameters - (keep absolute path of the exe and keep WorkingDirectory empty)
(**"C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe" , "<https://www.google.com>", ""**) it works just fine.
But, with parameters -
(**"Chrome.exe , "<https://www.google.com>", "C:\Program Files (x86)\Google\Chrome\Application"**) it gives exception at step **proc.Start();** stating - *The system cannot find the file specified.*
I also tried writing **WorkingDirectory = workingDir** while initializing StartInfo but still looking for solutions.
```
class Program
{
static void Main(string[] args)
{
RunProc(@"chrome.exe", @"https://www.google.com", @"C:\Program Files (x86)\Google\Chrome\Application");
}
static bool RunProc(string exe, string args, string workingDir)
{
Process proc = new Process
{
StartInfo =
{
FileName = exe,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
//WorkingDirectory = workingDir
}
};
if (!string.IsNullOrEmpty(workingDir))
{
proc.StartInfo.WorkingDirectory = workingDir;
}
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
``` | 2018/11/15 | [
"https://Stackoverflow.com/questions/53317899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10299461/"
] | The only way for this to work is for you to change *your* working directory to the passed in working directory before attempting to start the other process. The `WorkingDirectory` property is just that, and doesn't in any way get involved in locating the executable to run. That just relies on your working directory and your `PATH` environment variable, if you fail to provide a fully-qualified name.
```
static bool RunProc(string exe, string args, string workingDir)
{
var prevWorking = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = workingDir;
Process proc = new Process
{
StartInfo =
{
FileName = exe,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
}
};
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
finally
{
Environment.CurrentDirectory = prevWorking;
}
}
``` | Why not just call the .exe from the path where it is located directly ?
```
Process.Start(@"C:\new\folder\abcd.exe");
```
Or just put
```
proc.StartInfo.WorkingDirectory = @"c:\new\folder";
```
before proc.start(); |
53,317,899 | I'm trying to call **chrome.exe** inside a **C#** program by using **System.Diagnostics.Process** namespace.
my **chrome.exe** is located inside path **C:\Program Files (x86)\Google\Chrome\Application**
if I call **RunProc** function by passing bellow parameters - (keep absolute path of the exe and keep WorkingDirectory empty)
(**"C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe" , "<https://www.google.com>", ""**) it works just fine.
But, with parameters -
(**"Chrome.exe , "<https://www.google.com>", "C:\Program Files (x86)\Google\Chrome\Application"**) it gives exception at step **proc.Start();** stating - *The system cannot find the file specified.*
I also tried writing **WorkingDirectory = workingDir** while initializing StartInfo but still looking for solutions.
```
class Program
{
static void Main(string[] args)
{
RunProc(@"chrome.exe", @"https://www.google.com", @"C:\Program Files (x86)\Google\Chrome\Application");
}
static bool RunProc(string exe, string args, string workingDir)
{
Process proc = new Process
{
StartInfo =
{
FileName = exe,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
//WorkingDirectory = workingDir
}
};
if (!string.IsNullOrEmpty(workingDir))
{
proc.StartInfo.WorkingDirectory = workingDir;
}
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
``` | 2018/11/15 | [
"https://Stackoverflow.com/questions/53317899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10299461/"
] | Why not just call the .exe from the path where it is located directly ?
```
Process.Start(@"C:\new\folder\abcd.exe");
```
Or just put
```
proc.StartInfo.WorkingDirectory = @"c:\new\folder";
```
before proc.start(); | What do you think about combining the absolute path of the .exe within your static method and check if the path exists before you call the Process start:
```c
using System.Diagnostics;
using System.IO;
namespace RunProc
{
class Program
{
static void Main(string[] args)
{
RunProc(@"chrome.exe", @"https://www.google.com", @"C:\Program Files (x86)\Google\Chrome\Application");
}
static bool RunProc(string exe, string args, string workingDir)
{
string filePath = workingDir + "\"" + exe;
if (!File.Exists(filePath))
return false;
Process proc = new Process
{
StartInfo =
{
FileName = filePath,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
}
};
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
}
```
Maybe, the method `RunProc` is a bit clearer with [DirectoryInfo](https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo?view=netcore-3.1) and [FileInfo](https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netcore-3.1)
```c
using System.Diagnostics;
using System.IO;
namespace RunProc
{
class Program
{
static void Main(string[] args)
{
FileInfo myRelativeFileExe = new FileInfo(@"chrome.exe");
DirectoryInfo myAbsoluteFileDir = new DirectoryInfo(@"C:\Program Files (x86)\Google\Chrome\Application");
RunProc(myRelativeFileExe, myAbsoluteFileDir, @"https://www.google.com");
}
static bool RunProc(FileInfo exe, DirectoryInfo workingDir, string args)
{
FileInfo myAbsoluteFilePath = new FileInfo(Path.Combine(workingDir.ToString(), exe.ToString()));
if (!myAbsoluteFilePath.Exists)
return false;
Process proc = new Process
{
StartInfo =
{
FileName = myAbsoluteFilePath.FullName,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
}
};
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
}
``` |
53,317,899 | I'm trying to call **chrome.exe** inside a **C#** program by using **System.Diagnostics.Process** namespace.
my **chrome.exe** is located inside path **C:\Program Files (x86)\Google\Chrome\Application**
if I call **RunProc** function by passing bellow parameters - (keep absolute path of the exe and keep WorkingDirectory empty)
(**"C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe" , "<https://www.google.com>", ""**) it works just fine.
But, with parameters -
(**"Chrome.exe , "<https://www.google.com>", "C:\Program Files (x86)\Google\Chrome\Application"**) it gives exception at step **proc.Start();** stating - *The system cannot find the file specified.*
I also tried writing **WorkingDirectory = workingDir** while initializing StartInfo but still looking for solutions.
```
class Program
{
static void Main(string[] args)
{
RunProc(@"chrome.exe", @"https://www.google.com", @"C:\Program Files (x86)\Google\Chrome\Application");
}
static bool RunProc(string exe, string args, string workingDir)
{
Process proc = new Process
{
StartInfo =
{
FileName = exe,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
//WorkingDirectory = workingDir
}
};
if (!string.IsNullOrEmpty(workingDir))
{
proc.StartInfo.WorkingDirectory = workingDir;
}
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
``` | 2018/11/15 | [
"https://Stackoverflow.com/questions/53317899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10299461/"
] | The only way for this to work is for you to change *your* working directory to the passed in working directory before attempting to start the other process. The `WorkingDirectory` property is just that, and doesn't in any way get involved in locating the executable to run. That just relies on your working directory and your `PATH` environment variable, if you fail to provide a fully-qualified name.
```
static bool RunProc(string exe, string args, string workingDir)
{
var prevWorking = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = workingDir;
Process proc = new Process
{
StartInfo =
{
FileName = exe,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
}
};
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
finally
{
Environment.CurrentDirectory = prevWorking;
}
}
``` | What do you think about combining the absolute path of the .exe within your static method and check if the path exists before you call the Process start:
```c
using System.Diagnostics;
using System.IO;
namespace RunProc
{
class Program
{
static void Main(string[] args)
{
RunProc(@"chrome.exe", @"https://www.google.com", @"C:\Program Files (x86)\Google\Chrome\Application");
}
static bool RunProc(string exe, string args, string workingDir)
{
string filePath = workingDir + "\"" + exe;
if (!File.Exists(filePath))
return false;
Process proc = new Process
{
StartInfo =
{
FileName = filePath,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
}
};
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
}
```
Maybe, the method `RunProc` is a bit clearer with [DirectoryInfo](https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo?view=netcore-3.1) and [FileInfo](https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netcore-3.1)
```c
using System.Diagnostics;
using System.IO;
namespace RunProc
{
class Program
{
static void Main(string[] args)
{
FileInfo myRelativeFileExe = new FileInfo(@"chrome.exe");
DirectoryInfo myAbsoluteFileDir = new DirectoryInfo(@"C:\Program Files (x86)\Google\Chrome\Application");
RunProc(myRelativeFileExe, myAbsoluteFileDir, @"https://www.google.com");
}
static bool RunProc(FileInfo exe, DirectoryInfo workingDir, string args)
{
FileInfo myAbsoluteFilePath = new FileInfo(Path.Combine(workingDir.ToString(), exe.ToString()));
if (!myAbsoluteFilePath.Exists)
return false;
Process proc = new Process
{
StartInfo =
{
FileName = myAbsoluteFilePath.FullName,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
}
};
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
}
``` |
7,365,405 | If I pass a number of selectors to jQuery, how can I differentiate the selector that fires the event, and return that selector as a string? For example:
```
$('#selector-a, #selector-b, #selector-c').click(function(){
console.log( $(this).selector ); // logs an empty string
});
``` | 2011/09/09 | [
"https://Stackoverflow.com/questions/7365405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62983/"
] | Obviously the URL is wrong. See my answer to this related question:
* [Reading an image in Netbeans](https://stackoverflow.com/questions/7014123/reading-an-image-in-netbeans/7014177#7014177)
As for your second question, it is possible to combine multiple layout managers, although each container is limited to *exactly one*. For more information, see [Laying Out Components Within a Container](http://download.oracle.com/javase/tutorial/uiswing/layout/index.html).
And what exactly do you want to set in the top right corner? I'm sure this can be done using a single layout manager.
As for placing the image in the top-right corner of the container, there are *many ways* to achieve this. One way is to simply use a `JLabel` as seen in the answer provided by [@camickr](https://stackoverflow.com/users/131872/camickr) in [this](https://stackoverflow.com/questions/5850949/how-to-place-jlabel-on-top-right-corner-just-below-the-title-bar) question. | The package isn't named "res", but "resources" as we can see from your snapshot.
```
Image cima = ImageIO.read(YourClass.class.getResource("/resources/cross.png"));
```
---
Change the catch body to this:
```
} catch (IOException ex){
System.out.println("ERROR");
ex.printStackTrace();
}
```
And tell us what exception you've got. |
9,407,654 | I am using ExtJs4.
```
new Ext.Window({
id: token + '_window',
animateTarget: token + '_taskbar', //Button id
height: 300,
width: 300,
title: name,
maximizable: true,
minimizable: true,
iconCls: 'basketball-small-icon',
html: 'This is the <b>' + name + '</b> window',
listeners: {
'beforeclose': onWindowClose,
'minimize': function(){ this.hide(); }
}
```
Note the button to which the animate target is associated.
Here the onWindowClose is defined as
```
function onWindowClose(t){
var token = t.id.split('_')[0];
var taskBarItemId = token + '_taskbar';
Ext.getCmp(taskBarItemId).destroy(); //Destroying the button
t.destroy(); //Destroying the window
}
```
Here I want to remove the window and the associated button.
Everytime I close the window, I have two choices as below
* I can destroy both the button and the window but sometimes I can't open the window again. I think this has something to do with the fact that the button is linked to window's 'animateTarget'. Because when I remove this property, this works fine.
* I can use t.close() instead of t.destroy(), but it becomes recursive. How can I call the base close method?
Is it a good idea to destroy the window everytime and create using 'new' whenever the icon is clicked?
What is difference between close() and destroy() methods? | 2012/02/23 | [
"https://Stackoverflow.com/questions/9407654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213885/"
] | If I understand well, you want to reuse the window, with a different content.
So, you should create only one window, that you reuse by updating the html content and calling show() on this window.
To perform that, you need to add the property `closeAction:'hide'`. This way, your window won't be destroyed when clicking on the close button.
```
test = new Ext.Window({
id: token + '_window',
animateTarget: token + '_taskbar',
height: 300,
width: 300,
title: name,
maximizable: true,
minimizable: true,
closeAction: 'hide',
iconCls: 'basketball-small-icon',
html: 'This is the <b> imad </b> window',
listeners:{
'beforehide':function(win){
Ext.getCmp(win.animateTarget).hide();
}
}
});
```
Then, you add this listener to your buttons :
```
listeners:{
'click':function(){
var token = t.id.split('_')[0];
var targetWindow = Ext.getCmp('token + '_window);
targetWindow.body.dom.innerHtml = 'Your new html !';
targetWindow.show();
}
}
``` | You don't have to call destroy() since once the window is closed, it is automatically destroyed.
See api of [Ext.Window](http://docs.sencha.com/ext-js/4-0/#!/api/Ext.window.Window-method-close).
And do not call close() in your beforeclose handler since it's already about to close.
I think you can use 'new' whenever you want to create a window and close it either click on the close header tool(top right) or call its close() method. Don't worry about destroy. Ext will do it.
The main difference between close() and destroy() is close fires 'beforeclose' event and decide whether to close the window or hide it based on config option 'closeAction'. If it decides to close, destroy() will be called.
**EDIT:**
try the following
```
function onWindowClose(t){
var token = t.id.split('_')[0];
var taskBarItemId = token + '_taskbar';
Ext.getCmp(taskBarItemId).destroy(); //Destroying the button
//t.destroy(); //Remove this statement.
return true;
}
```
**EDIT2:** Remove minimize listener
```
listeners: {
'beforeclose': onWindowClose//,
//'minimize': function(){ this.hide(); }
}
``` |
5,829,059 | I have written a script which stores digital signatures in binaries and script files. This question is only regarding scripts: Currently, all these signatures get stored in one single line (a comment) such as:
```
#!/usr/bin/perl
print "Hello"
print " World\n"
#Signature:ASDASG13412sdflsal4sf etc........
```
The example is Perl, but this is done for all scripting languages (Perl, Python, shell scripts etc.)
So now my question is: Can I get into trouble if the length of the line containing the signature is too long? How do interpreter handle this? If so, what is the max. line length I can use? | 2011/04/29 | [
"https://Stackoverflow.com/questions/5829059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669602/"
] | Most scripting languages will have long enough limits, if indeed they have a formal limit on the length of lines. POSIX recommends 2048 minimum.
How long are your signatures? Most likely, not more than 1024...in which case, I really wouldn't worry. If it doesn't work for some language, you should report the bug rather than anything else. | In Python, you should not have any problem with line length as long as you have sufficient memory. In PHP, you may be limited by the amount of memory PHP interpreter is allowed to use (set in php.ini) |
5,829,059 | I have written a script which stores digital signatures in binaries and script files. This question is only regarding scripts: Currently, all these signatures get stored in one single line (a comment) such as:
```
#!/usr/bin/perl
print "Hello"
print " World\n"
#Signature:ASDASG13412sdflsal4sf etc........
```
The example is Perl, but this is done for all scripting languages (Perl, Python, shell scripts etc.)
So now my question is: Can I get into trouble if the length of the line containing the signature is too long? How do interpreter handle this? If so, what is the max. line length I can use? | 2011/04/29 | [
"https://Stackoverflow.com/questions/5829059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669602/"
] | Most scripting languages will have long enough limits, if indeed they have a formal limit on the length of lines. POSIX recommends 2048 minimum.
How long are your signatures? Most likely, not more than 1024...in which case, I really wouldn't worry. If it doesn't work for some language, you should report the bug rather than anything else. | Perl also has no fixed maximum line length, other than imposed by memory usage. |
3,863,754 | I want to find out common `days/dates` between `two periods`.
For example
```
period1: 25-10-2010 to 25-11-2010
period2: 10-11-2010 to 10-12-2010
```
Here `15 days`, `10-11` to `25-11` are common. How can I find it in PHP or Zend Framework. | 2010/10/05 | [
"https://Stackoverflow.com/questions/3863754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765545/"
] | ```
In [33]: hash?
```
>
> Return a hash value for the object. Two objects with the same
> value have the same hash value. **The reverse is not necessarily true, but
> likely**.
>
>
>
Why not just use the tuple (ida,idb) as the key?
```
import pprint
class SomeClass(object):
def __init__(self,ida,idb):
self.ida=ida
self.idb=idb
obj1 = SomeClass(ida=5223372036854775807, idb=2)
obj2 = SomeClass(ida=2, idb=5223372036854775807)
obj3 = SomeClass(ida=5223372036854775807, idb=2)
d={}
for obj in (obj1,obj2,obj3):
d[obj.ida,obj.idb]=obj
pprint.pprint(d)
# {(2, 5223372036854775807L): <__main__.SomeClass object at 0xb78839ec>,
(5223372036854775807L, 2): <__main__.SomeClass object at 0xb7883a0c>}
``` | There are only 2\*\*<word size> possible hashes, so you would have to run a 128-bit version of Python to even store all (2\*\*64)\*\*2 possible hashes in the first place. And yes, it could *still* be possible to have collisions. Use a `set` if you need to store unique objects; just define `__hash__()` and `__eq__()` in a sane manner. |
3,863,754 | I want to find out common `days/dates` between `two periods`.
For example
```
period1: 25-10-2010 to 25-11-2010
period2: 10-11-2010 to 10-12-2010
```
Here `15 days`, `10-11` to `25-11` are common. How can I find it in PHP or Zend Framework. | 2010/10/05 | [
"https://Stackoverflow.com/questions/3863754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765545/"
] | Like Ignacio said, you can have hash collisions. Why don't you just use the tuple itself? Tuples are immutable and it looks like your ida and idb are (immutable) integers. | There are only 2\*\*<word size> possible hashes, so you would have to run a 128-bit version of Python to even store all (2\*\*64)\*\*2 possible hashes in the first place. And yes, it could *still* be possible to have collisions. Use a `set` if you need to store unique objects; just define `__hash__()` and `__eq__()` in a sane manner. |
3,863,754 | I want to find out common `days/dates` between `two periods`.
For example
```
period1: 25-10-2010 to 25-11-2010
period2: 10-11-2010 to 10-12-2010
```
Here `15 days`, `10-11` to `25-11` are common. How can I find it in PHP or Zend Framework. | 2010/10/05 | [
"https://Stackoverflow.com/questions/3863754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765545/"
] | ```
In [33]: hash?
```
>
> Return a hash value for the object. Two objects with the same
> value have the same hash value. **The reverse is not necessarily true, but
> likely**.
>
>
>
Why not just use the tuple (ida,idb) as the key?
```
import pprint
class SomeClass(object):
def __init__(self,ida,idb):
self.ida=ida
self.idb=idb
obj1 = SomeClass(ida=5223372036854775807, idb=2)
obj2 = SomeClass(ida=2, idb=5223372036854775807)
obj3 = SomeClass(ida=5223372036854775807, idb=2)
d={}
for obj in (obj1,obj2,obj3):
d[obj.ida,obj.idb]=obj
pprint.pprint(d)
# {(2, 5223372036854775807L): <__main__.SomeClass object at 0xb78839ec>,
(5223372036854775807L, 2): <__main__.SomeClass object at 0xb7883a0c>}
``` | Like Ignacio said, you can have hash collisions. Why don't you just use the tuple itself? Tuples are immutable and it looks like your ida and idb are (immutable) integers. |
2,439,139 | Hey I have a general recurrence relation as follows, and I want to find a general sum formula in terms of the variable.
$U\_1=DE$
$U\_n=(U\_{n-1} + D)E$
$D$ and $E$ are real positive numbers, can there be a sum formula for $n$ terms in terms of $D$ and $E$? | 2017/09/21 | [
"https://math.stackexchange.com/questions/2439139",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/448452/"
] | Hint:
$$U\_2=EU\_1+U\_1=(E+1)U\_1$$
$$U\_3 = EU\_2+U\_1=(E^2+E)U\_1+U\_1=(E^2+E+1)U\_1$$
$$U\_4 = EU\_3+U\_1=(E^3+E^2+E)U\_1+U\_1=(E^3+E^2+E+1)U\_1$$
Do you see a pattern? Use also $1+E+E^2+...+E^{n-1}=\frac{1-E^{n}}{1-E}$.
If you found the candidate for the formula you can plug it into the recurrence equation and test if it is right or use induction. | Notice the recurrence relation can be rewritten as
$$U\_{n+1} = (U\_n + D)E = U\_n E + \frac{DE}{1-E}(1-E) \implies
U\_{n+1} - \frac{DE}{1-E} = \left(U\_n - \frac{DE}{1-E}\right)E$$
After the offset $-\frac{DE}{1-E}$, each term is a multiple of $E$ of previous term. For general $n$, this leads to
$$U\_n - \frac{DE}{1-E} = \left(U\_1 - \frac{DE}{1-E}\right)E^{n-1}
= \left(DE - \frac{DE}{1-E}\right)E^{n-1} = -\frac{DE}{1-E} E^n\\
\implies U\_n = \frac{DE}{1-E}(1-E^n)$$ |
2,439,139 | Hey I have a general recurrence relation as follows, and I want to find a general sum formula in terms of the variable.
$U\_1=DE$
$U\_n=(U\_{n-1} + D)E$
$D$ and $E$ are real positive numbers, can there be a sum formula for $n$ terms in terms of $D$ and $E$? | 2017/09/21 | [
"https://math.stackexchange.com/questions/2439139",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/448452/"
] | Hint:
$$U\_2=EU\_1+U\_1=(E+1)U\_1$$
$$U\_3 = EU\_2+U\_1=(E^2+E)U\_1+U\_1=(E^2+E+1)U\_1$$
$$U\_4 = EU\_3+U\_1=(E^3+E^2+E)U\_1+U\_1=(E^3+E^2+E+1)U\_1$$
Do you see a pattern? Use also $1+E+E^2+...+E^{n-1}=\frac{1-E^{n}}{1-E}$.
If you found the candidate for the formula you can plug it into the recurrence equation and test if it is right or use induction. | $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
\newcommand{\dd}{\mathrm{d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
\newcommand{\ic}{\mathrm{i}}
\newcommand{\mc}[1]{\mathcal{#1}}
\newcommand{\mrm}[1]{\mathrm{#1}}
\newcommand{\pars}[1]{\left(\,{#1}\,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
\newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
>
> With $\ds{U\_{1} = DE}$:
>
>
>
\begin{align}
U\_{n} & = \pars{U\_{n - 1} + D}E \implies
U\_{n} - {DE \over 1 - E} = \pars{U\_{n - 1} - {DE \over 1 - E}}E =
\pars{U\_{n - 2} - {DE \over 1 - E}}E^{2}
\\[5mm] & =
\pars{U\_{n - 3} - {DE \over 1 - E}}E^{3} = \cdots =
\pars{U\_{1} - {DE \over 1 - E}}E^{n - 1} =
\pars{DE - {DE \over 1 - E}}E^{n - 1}
\\[5mm] & = {D \over E - 1}\,E^{n + 1} \implies
U\_{n} = {DE \over 1 - E} + {D \over E - 1}\,E^{n + 1} =
\bbx{DE\,{E^{n} - 1 \over E - 1}}
\end{align} |
2,439,139 | Hey I have a general recurrence relation as follows, and I want to find a general sum formula in terms of the variable.
$U\_1=DE$
$U\_n=(U\_{n-1} + D)E$
$D$ and $E$ are real positive numbers, can there be a sum formula for $n$ terms in terms of $D$ and $E$? | 2017/09/21 | [
"https://math.stackexchange.com/questions/2439139",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/448452/"
] | Hint:
$$U\_2=EU\_1+U\_1=(E+1)U\_1$$
$$U\_3 = EU\_2+U\_1=(E^2+E)U\_1+U\_1=(E^2+E+1)U\_1$$
$$U\_4 = EU\_3+U\_1=(E^3+E^2+E)U\_1+U\_1=(E^3+E^2+E+1)U\_1$$
Do you see a pattern? Use also $1+E+E^2+...+E^{n-1}=\frac{1-E^{n}}{1-E}$.
If you found the candidate for the formula you can plug it into the recurrence equation and test if it is right or use induction. | WLOG, $D=1$ (see why ?)
Then as there is this factor $E$, consider $U\_n=V\_nE^n$.
The recurrence becomes
$$V\_1E=E,$$ and $$V\_nE^n=(V\_{n-1}E^{n-1}+1)E$$ or
$$V\_n=V\_{n-1}+E^{-n},$$ which is the summation of a geometric series.
$$V\_n=\frac{1-E^{-n}}{1-E^{-1}},$$ and
$$U\_n=\frac{E^n-1}{1-E^{-1}}.$$
Now the summation of the $U\_n$ is that of another geometric series and a constant term.
$$\sum\_{k=1}^n U\_k=\frac{\dfrac{E^{n+1}-1}{E-1}-n}{1-E^{-1}}.$$
(Or the same times $D$.) |
2,439,139 | Hey I have a general recurrence relation as follows, and I want to find a general sum formula in terms of the variable.
$U\_1=DE$
$U\_n=(U\_{n-1} + D)E$
$D$ and $E$ are real positive numbers, can there be a sum formula for $n$ terms in terms of $D$ and $E$? | 2017/09/21 | [
"https://math.stackexchange.com/questions/2439139",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/448452/"
] | Hint:
$$U\_2=EU\_1+U\_1=(E+1)U\_1$$
$$U\_3 = EU\_2+U\_1=(E^2+E)U\_1+U\_1=(E^2+E+1)U\_1$$
$$U\_4 = EU\_3+U\_1=(E^3+E^2+E)U\_1+U\_1=(E^3+E^2+E+1)U\_1$$
Do you see a pattern? Use also $1+E+E^2+...+E^{n-1}=\frac{1-E^{n}}{1-E}$.
If you found the candidate for the formula you can plug it into the recurrence equation and test if it is right or use induction. | I'm always a fan of the generating function approach.
The given recurrence can be defined as $u\_0=0$ and $u\_n=(u\_{n-1}+d)e$.
\begin{align}
U(x) &= \sum\_{j=0}^{\infty}u\_jx^j\\
&= \sum\_{j=1}^{\infty}u\_jx^j\\
&= \sum\_{j=1}^{\infty}(u\_{j-1}+d)ex^j\\
&= \sum\_{j=0}^{\infty}(u\_{j-1}+d)ex^{j+1}\\
&= ex\sum\_{j=0}^{\infty}(u\_{j-1}+d)x^j\\
&= ex\left(U(x)+\frac{d}{1-x}\right)\\
U(x) &= \frac{dex}{(1-x)(1-ex)}\\
\end{align}
If we set $\frac{dex}{(1-x)(1-ex)}=\frac{A}{1-x} + \frac{B}{1-ex}$ and solve for $A$ and $B$, we get that $A=\frac{de}{1-e}$ and $B=\frac{-de}{1-e}$.
\begin{align}
U(x) &= \frac{de}{(1-e)(1-x)} + \frac{-de}{(1-e)(1-ex)}\\
&= \frac{de}{1-e}\left(\sum\_{j=0}^{\infty}x^j - \sum\_{j=0}^{\infty}e^jx^j\right)\\
&= \frac{de}{1-e}\sum\_{j=0}^{\infty}(1-e^j)x^j\\
\end{align}
The coefficient of $x^j$ is then the $j^{th}$ term in the sequence.
$$u\_0=\frac{de}{1-e}(1-e^0)=0$$
$$u\_1=\frac{de}{1-e}(1-e^1)=de$$
$$u\_j=\frac{de}{1-e}(1-e^j)$$ |
2,439,139 | Hey I have a general recurrence relation as follows, and I want to find a general sum formula in terms of the variable.
$U\_1=DE$
$U\_n=(U\_{n-1} + D)E$
$D$ and $E$ are real positive numbers, can there be a sum formula for $n$ terms in terms of $D$ and $E$? | 2017/09/21 | [
"https://math.stackexchange.com/questions/2439139",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/448452/"
] | Hint:
$$U\_2=EU\_1+U\_1=(E+1)U\_1$$
$$U\_3 = EU\_2+U\_1=(E^2+E)U\_1+U\_1=(E^2+E+1)U\_1$$
$$U\_4 = EU\_3+U\_1=(E^3+E^2+E)U\_1+U\_1=(E^3+E^2+E+1)U\_1$$
Do you see a pattern? Use also $1+E+E^2+...+E^{n-1}=\frac{1-E^{n}}{1-E}$.
If you found the candidate for the formula you can plug it into the recurrence equation and test if it is right or use induction. | I have previously shown [here](https://math.stackexchange.com/questions/2400524/solving-simple-linear-recurrences-with-generating-functions/2402627#2402627), that $f\_n=Af\_{n-1}+B$, which I call a *short* Fibonacci sequence, has the general solution
$$f\_n=\frac{[(A-1)f\_0+B]A^n-B}{A-1},\quad n\ge0$$
This gives us a solution, once and for all such *short* Fibonacci sequences. In the present case, we have $A=E,~B=DE$, and $u\_1=DE$ so that
$$u\_n= \frac{DE \left(E^n-1\right)}{E-1}\quad n\ge1$$ |
71,039,912 | I have a file with tons of lines using a semicolon (`;`) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line
`20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff`
I want the end result to look like
`2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff`
I have tried the solution [How Do I add Multiple characters using SED?](https://stackoverflow.com/questions/70946004/how-do-i-add-multiple-characters-using-sed) (My first Poorly Made question) and [change date format from DD/MM/YYYY to YYYY-MM-DD with sed](https://stackoverflow.com/questions/54729814/change-date-format-from-dd-mm-yyyy-to-yyyy-mm-dd-with-sed) doesn't make sense to me.
```
sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
-e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
< input > output
```
This solution makes sense, but affects the rest of the line. | 2022/02/08 | [
"https://Stackoverflow.com/questions/71039912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7845766/"
] | Use capture-groups with fixed number of digits.
```sh
sed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1-\2-\3 \4:\5:\6/g' input > output
``` | Using awk:
```
$ awk -v FS=";" '
function process_date(date)
{
# 20211119000751 -> 2021-11-19 00:07:51
new_date = substr(date, 1, 4) \
"-" \
substr(date, 5, 2) \
"-" \
substr(date, 7, 2) \
" " \
substr(date, 9, 2) \
":" substr(date, 11, 2) \
":" substr(date, 13, 2)
return new_date
}
BEGIN { OFS=FS }
{ $1 = process_date($1); $2 = process_date($2); print $0}' input
``` |
71,039,912 | I have a file with tons of lines using a semicolon (`;`) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line
`20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff`
I want the end result to look like
`2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff`
I have tried the solution [How Do I add Multiple characters using SED?](https://stackoverflow.com/questions/70946004/how-do-i-add-multiple-characters-using-sed) (My first Poorly Made question) and [change date format from DD/MM/YYYY to YYYY-MM-DD with sed](https://stackoverflow.com/questions/54729814/change-date-format-from-dd-mm-yyyy-to-yyyy-mm-dd-with-sed) doesn't make sense to me.
```
sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
-e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
< input > output
```
This solution makes sense, but affects the rest of the line. | 2022/02/08 | [
"https://Stackoverflow.com/questions/71039912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7845766/"
] | Use capture-groups with fixed number of digits.
```sh
sed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1-\2-\3 \4:\5:\6/g' input > output
``` | Crappy but working solution (each line add a character at a given position
`/./` select any char
the n number at the end is the number of repetition of the selected pattern, so `/4` repeat `/./` 4 times
& is the selected motif, plus a character, sor for example :
`s/./&-/4' take any first 4 character, and replace them by & ("Re-add" the pattern itself) plus a character.
Everything of that piped into another sed.
I usually use python for date formatting, plus the easy csv parsing, if it's a possible solution for you.
```
sed 's/./&-/4' < input.csv | \
sed 's/./&-/7' | \
sed 's/./&\ /10' | \
sed 's/./&:/13' | \
sed 's/./&:/16' | \
sed 's/./&-/24' | \
sed 's/./&-/27' | \
sed 's/./&\ /30' | \
sed 's/./&\:/33' | \
sed 's/./&\:/36' >> output.csv
``` |
71,039,912 | I have a file with tons of lines using a semicolon (`;`) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line
`20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff`
I want the end result to look like
`2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff`
I have tried the solution [How Do I add Multiple characters using SED?](https://stackoverflow.com/questions/70946004/how-do-i-add-multiple-characters-using-sed) (My first Poorly Made question) and [change date format from DD/MM/YYYY to YYYY-MM-DD with sed](https://stackoverflow.com/questions/54729814/change-date-format-from-dd-mm-yyyy-to-yyyy-mm-dd-with-sed) doesn't make sense to me.
```
sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
-e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
< input > output
```
This solution makes sense, but affects the rest of the line. | 2022/02/08 | [
"https://Stackoverflow.com/questions/71039912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7845766/"
] | Use capture-groups with fixed number of digits.
```sh
sed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1-\2-\3 \4:\5:\6/g' input > output
``` | Since only `bash` is tagged, here's a solution using bash's string indexing:
```sh
while IFS=\; read -r x y z
do printf '%s;%s;%s\n' \
"${x::4}-${x:4:2}-${x:6:2} ${x:8:2}:${x:10:2}:${x:12:2}" \
"${y::4}-${y:4:2}-${y:6:2} ${y:8:2}:${y:10:2}:${y:12:2}" \
"$z"
done
``` |
16,463,152 | ```
sub open_files {
my @files = @_;
my @lines;
foreach (@files){
print "$_\[1\]\n";
}
foreach my $f (@files){
print "$f\[2\]\n";
open(my $fh,'<',$f) or die " '$f' $!";
print "$fh\[3\]\n";
push(@lines,<$fh>);
close($fh);
}
return @lines;
}
```
Hi i am having problems with opening files whose absolute path are stored in an array.
What i want to do is go through the array and open each file and then store their data inside `@lines` array and then close the file handle.
However i am able to open the `.html` files which are stored in the first child directory `.e.g /a/abc.html or /b/bcd.html` however it is not opening (or parsing ) the files which are in sub-child directories such as `/a/aa/abc.html or /b/bb/bcd.html`
I have put in some extra `print statements` in my script and numbered their output for the different print lines e.g. `[1] [2] [3]`.
This is the result of executing the above code:
The full code is : [pastebin Full code](http://pastebin.com/DFsU1RUZ)
```
/mnt/hgfs/PERL/assignment/test/a/aa/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/a/aa/1 - Copy - Copy (2).htm[2]
GLOB(0x898ad20)[3]
/mnt/hgfs/PERL/assignment/test/b/bb/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/b/bb/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
/mnt/hgfs/PERL/assignment/test/a/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/b/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/c/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/a/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
/mnt/hgfs/PERL/assignment/test/b/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
/mnt/hgfs/PERL/assignment/test/c/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
```
If you guys need the full code here it is : [pastebin Full code](http://pastebin.com/DFsU1RUZ) | 2013/05/09 | [
"https://Stackoverflow.com/questions/16463152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016977/"
] | ```
use warnings;
use strict;
die "Usage: $0 (abs path to dir) " if @ARGV != 1;
my $dir = shift @ARGV;
our @html_files = ();
file_find($dir);
print "html files: @html_files\n";
sub file_find {
my $dir = shift;
opendir my $dh, $dir or warn "$dir: $!";
my @files = grep { $_ !~ /^\.{1,2}$/ } readdir $dh;
closedir $dh;
for my $file ( @files ) {
my $path = "$dir/$file";
push @html_files, $file if $file =~ /\.html$/;
file_find($path) if -d $path;
}
}
``` | The short answer is that [`glob`](http://perldoc.perl.org/functions/glob.html) does not recurse into sub-directories.
Instead, use [`File::Find`](https://metacpan.org/module/File%3a%3aFind):
```
use strict;
use warnings;
use feature 'say';
use File::Find 'find';
my @files;
find( sub { push @files, $File::Find::name if /\.html?$/ }, 'base_dir' );
say for @files;
``` |
36,512,337 | I'd like to create a form field. And then display two variables (already assigned with values) inside it when the page loads itself. I know I can use "`<input id="formField" value="John Smith"/>` but I'd like to use `document.getElementById` to do this. What is wrong with my code?
The form field loads, but it is empty.
I'm very new to JS....
```
<!doctype html>
<html>
<body>
<input type="number" id="formField"/>
<script>
var one = "John";
var two = "Smith";
function concat() {
var x = one.value;
var y = two.value;
var z = one + "" + two;
document.getElementById("formField").innerHTML = z;
//Why doesn't this work?
}
concat();
</script>
</body>
</html>
``` | 2016/04/09 | [
"https://Stackoverflow.com/questions/36512337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6179680/"
] | `input` elements do not have an `innerHTML` property. You want to set the `value` property, like so:
`document.getElementById("formField").value = z;`
Other things to note:
* You're setting `x` equal to `one` and `y` equal to `two`, then just using `one` and `two` directly. No point in having `x` and `y`.
* `one` and `two` don't really have a `value` property - they're just strings.
* Don't forget a space between those strings. It seems like what you want is `one + " " + two` (note the space between the quotes) otherwise your ouput will be `JohnSmith` | <http://jsbin.com/buroxaciba/edit?html,output>
innerHTML is normally used for div, span, p and similar elements.
input type number -> text |
36,512,337 | I'd like to create a form field. And then display two variables (already assigned with values) inside it when the page loads itself. I know I can use "`<input id="formField" value="John Smith"/>` but I'd like to use `document.getElementById` to do this. What is wrong with my code?
The form field loads, but it is empty.
I'm very new to JS....
```
<!doctype html>
<html>
<body>
<input type="number" id="formField"/>
<script>
var one = "John";
var two = "Smith";
function concat() {
var x = one.value;
var y = two.value;
var z = one + "" + two;
document.getElementById("formField").innerHTML = z;
//Why doesn't this work?
}
concat();
</script>
</body>
</html>
``` | 2016/04/09 | [
"https://Stackoverflow.com/questions/36512337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6179680/"
] | There are couple of issues in your code
1. `input type = "number"` but you are trying to put a string to its value. Which will not work. So change input type to text
2. `one` & `two` are variables, so there is no `one.value` and `two.value`. Simply `one + two` will work
3. You have to use `.value` instead of `innerHTML` to put the value back in input
**HTML**
```
<input type="text" id="formFieldText" value=""/>
```
**JS**
```
var one = "John";
var two = "Smith";
function concat() {
var x = one;
var y = two;
var z = one + " " + two;
console.log(z)
document.getElementById("formFieldText").value = z;
}
concat();
```
[Click here for demo](https://jsfiddle.net/hL4xdb5c/) | `input` elements do not have an `innerHTML` property. You want to set the `value` property, like so:
`document.getElementById("formField").value = z;`
Other things to note:
* You're setting `x` equal to `one` and `y` equal to `two`, then just using `one` and `two` directly. No point in having `x` and `y`.
* `one` and `two` don't really have a `value` property - they're just strings.
* Don't forget a space between those strings. It seems like what you want is `one + " " + two` (note the space between the quotes) otherwise your ouput will be `JohnSmith` |
36,512,337 | I'd like to create a form field. And then display two variables (already assigned with values) inside it when the page loads itself. I know I can use "`<input id="formField" value="John Smith"/>` but I'd like to use `document.getElementById` to do this. What is wrong with my code?
The form field loads, but it is empty.
I'm very new to JS....
```
<!doctype html>
<html>
<body>
<input type="number" id="formField"/>
<script>
var one = "John";
var two = "Smith";
function concat() {
var x = one.value;
var y = two.value;
var z = one + "" + two;
document.getElementById("formField").innerHTML = z;
//Why doesn't this work?
}
concat();
</script>
</body>
</html>
``` | 2016/04/09 | [
"https://Stackoverflow.com/questions/36512337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6179680/"
] | There are couple of issues in your code
1. `input type = "number"` but you are trying to put a string to its value. Which will not work. So change input type to text
2. `one` & `two` are variables, so there is no `one.value` and `two.value`. Simply `one + two` will work
3. You have to use `.value` instead of `innerHTML` to put the value back in input
**HTML**
```
<input type="text" id="formFieldText" value=""/>
```
**JS**
```
var one = "John";
var two = "Smith";
function concat() {
var x = one;
var y = two;
var z = one + " " + two;
console.log(z)
document.getElementById("formFieldText").value = z;
}
concat();
```
[Click here for demo](https://jsfiddle.net/hL4xdb5c/) | <http://jsbin.com/buroxaciba/edit?html,output>
innerHTML is normally used for div, span, p and similar elements.
input type number -> text |
66,964,028 | (*VSCode*)
When I Disunite the event from jsx code. (at. class Component)
Like This⬇
```
handleSubmit = e => { ...}
render(){
return (
<>
<form onSubmit={this.handelSubmit}>
<input
ref={this.onRefInput}
type='number'
value={this.state.value}
onChange={this.onChange}
/>
<button>입력!</button>
</form>
</>
);}
```
Usually When others raise the cursor on the "onSubmit"
tsc say
>
> "React.DOMAttributes< HTMLFormElement >onSubmit?***:(event:
> React.FormEvent< HTMLFormElement >)=> void) | undefined*** "
>
>
>
[enter image description here](https://i.stack.imgur.com/Wrcug.png)
So, We can directly know about event object's type! (event: React.FormEvent< HTMLFormElement >)
✅ Problem is that my code doesn't announces as above.
My tsc say
>
> " React.DOMAttributes< HTMLFormElement >.onSubmit?:
> ***React.FormEventHandler< HTMLFormElement > | undefined***"
>
>
>
So, ***I can't directly know about event object's type!***
I know that there are many other ways to know about event object's type.
But I want to **directly know about event object's type**! by Type inference.
How can I **directly know about event object's type**! by Type inference? | 2021/04/06 | [
"https://Stackoverflow.com/questions/66964028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12796086/"
] | You can assign a type to either to the function itself or to the arguments of the function, which is the event.
---
```
React.FormEventHandler<HTMLFormElement>
```
This is the type for the function. If you use it like this:
```
handleSubmit: React.FormEventHandler<HTMLFormElement> = e => {
}
```
Then the type for the variable `e` will be inferred as `React.FormEvent<HTMLFormElement>` automatically. So you don't actually need to know the event type because you can apply a type to the function itself and get the correct type.
---
Or you can assign the type to the event argument `e`.
```
handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
}
```
Now the type for the `handleSubmit` property is inferred as `(e: React.FormEvent<HTMLFormElement>) => void`. | In advance, sorry for that This answer is not a complete solution
I had the same problem, and I searched a lot, and try to change all settings.json about typescript.inlayHints.
unfortunately, nothing works
So I go to the implementation of onSubmit
[](https://i.stack.imgur.com/Mp2HT.png)
If you hover over onSubmit with command key (maybe ctrl key another OS)
you can go to index.d.ts
then you can see
```
onSubmit?: FormEventHandler<T> | undefined;
```
so I changed it as
```
onSubmit?: (event: FormEvent<T>) => void | undefined;
```
and now I can get what you want
[](https://i.stack.imgur.com/aOtU4.png)
I think, the new version of node\_modules/@types/react/index.d.ts results in like the first image.
Using Eventhandler type is also a good solution, If you hover over `e` parameter, you can see the Event Object
[](https://i.stack.imgur.com/Caqw2.png) |
2,848,522 | As in c # to create and then call the function? In C + + do so:
```
int func (int value)
{
value +=2;
}
```
But as is done in c #? | 2010/05/17 | [
"https://Stackoverflow.com/questions/2848522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312900/"
] | Here's the same function translated in C#:
```
public void Func(ref int value)
{
// Parameter is passed by reference so any modification
// to the value will propagate to the caller
value +=2;
}
```
And call it like this:
```
int value = 5;
Func(ref value); // value is now 7
```
---
UPDATE:
If as an alternative you don't want to reflect the modifications made to the `value` parameter outside the function you could declare it like this:
```
public void Func(int value)
{
// Parameter is passed by value so any modification
// to the value will not propagate to the caller
value +=2;
}
```
And call like this:
```
int value = 5;
Func(value); // value is still 5
``` | Considering your example is wrong... well, anyway.
```
public void func(ref int value)
{
value+=2;
}
``` |
35,378,833 | When I try to execute my app in the simulator or in my iPhone I get the next error:
```
App installation failed
This application or a bundle it contains has the same bundle identifier as this application or another bundle that it contains. Bundle identifiers must be unique.
```
[](https://i.stack.imgur.com/F2kBB.png)
When I look in the device's log I get thi detailed error message:
For the iPhone:
```
Feb 13 10:28:36 iPhone-de-P streaming_zip_conduit[240] <Warning>: __dispatch_source_read_socket_block_invoke:274:
Failed to install application at file:///var/mobile/Media/PublicStaging/MyApp.app/ :
Error Domain=LaunchServicesError Code=0 "(null)" UserInfo={Error=DuplicateIdentifier,
ErrorDescription=Found bundle at /private/var/mobile/Library/Caches/com.apple.mobile.installd.staging/temp.3L3YM3/extracted/MyApp.app/Frameworks/SlideMenuControllerSwift.framework
with the same identifier ($(PRODUCT_BUNDLE_IDENTIFIER)) as bundle at /private/var/mobile/Library/Caches/com.apple.mobile.installd.staging/temp.3L3YM3/extracted/MyApp.app/Frameworks/Serialize.framework}
```
For the Simulator:
```
12/2/16 20:40:34,408 com.apple.CoreSimulator.CoreSimulatorService[2426]:
Error Domain=LaunchServicesError Code=0 "(null)" UserInfo={Error=DuplicateIdentifier,
ErrorDescription=Found bundle at /Users/myUserName/Library/Developer/CoreSimulator/Devices/78CD18E0-B8E1-4A95-9224-2EF3ABDE5585/data/Library/Caches/com.apple.mobile.installd.staging/temp.s9Kecf/extracted/MyApp.app/Frameworks/SlideMenuControllerSwift.framework
with the same identifier ($(PRODUCT_BUNDLE_IDENTIFIER)) as bundle at
/Users/myUserName/Library/Developer/CoreSimulator/Devices/78CD18E0-B8E1-4A95-9224-2EF3ABDE5585/data/Library/Caches/com.apple.mobile.installd.staging/temp.s9Kecf/extracted/MyApp.app/Frameworks/Serialize.framework}
```
It's the same error in both devices: 2 frameworks with the same bundle ID
Normally I solved this error by doing a "pod update" or "pod install" before each compilation, but this solution it's not working anymore.
My project contains 5 pods, and this is my podfile:
```
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire'
pod 'MBProgressHUD', '~> 0.9.1'
pod 'swift-serialize'
pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
pod 'SlideMenuControllerSwift'
end
target 'MyApp' do
end
target 'MyApp' do
end
```
I have not set any pods bundle IDs manually.
All configuration of the pods are those that are set by default when you make a "pod install"
In addition, the two pods that give me the problem are configured with the following bundle:
SlideMenu Pod:
[](https://i.stack.imgur.com/jOMhb.png)
Serialize Pod:
[](https://i.stack.imgur.com/l9Mni.png)
And this is my project bundle configuration:
[](https://i.stack.imgur.com/qUoZG.png)
I tried every posted solution: reset simulator, delete derived data, product clean, clean build folder, delete simulator and re-install it...
I searched in the cocoapods forums, GitHub and Google but I can't find any reference to this error with the bundle ID of the pods frameworks.
I really do not know why this error occurs...so any help will be appreciated mates. | 2016/02/13 | [
"https://Stackoverflow.com/questions/35378833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1259245/"
] | Finally the error was the PRODUCT\_BUNDLE\_IDENTIFIER field in the info.plist of each pod. Changing it to "org.cocoapods.${PRODUCT\_NAME:rfc1034identifier}" solved the problem (previously was "$(PRODUCT\_BUNDLE\_IDENTIFIER)"). | For me selecting Product > Clean in Xcode from menu and running again worked! |
54,140,661 | I have created a MySQL deployment in kubernetes and exposed it as nodes-port.
***What I can do:***
Access it from inside the cluster using
`kubectl run -it --rm --image=mysql:5.6 --restart=Never mysql-client -- mysql -h mysql -ppassword`
**What I want to do:**
Access the MySQL server from outside the cluster(like accessing a normal MySQL server).
Kubernetes v1.13 in DigitalOcean Cloud.
Guide me, please. | 2019/01/11 | [
"https://Stackoverflow.com/questions/54140661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123139/"
] | You can access it by `mysql -u {username} -p {password} -h {any kubernetes worker ip} -P {nodePort}`. After you start mysql container and expose it ad node port through a service. | You need to specify the MYSQL\_ROOT\_PASSWORD while bringing up the pod. How were you able to bring it up in Docker without it? |
318,230 | I wanted to make a little script involving messages on my Mac and after some research I discovered it was indeed possible. The only problem is that the "AppleScript handler" option in Messages>Preferences>General is missing for me. [This very option is listed right on the Apple website under the High Sierra heading.](https://support.apple.com/guide/messages/general-preferences-icht20001/mac)
This is what I'm expecting:
[](https://i.stack.imgur.com/q9eDm.jpg)
But this is all I see:
[](https://i.stack.imgur.com/4Fc2k.png)
For what it's worth I'm running **10.13.4 Beta (17E160e)**. Is it possible that this feature has been removed? | 2018/03/15 | [
"https://apple.stackexchange.com/questions/318230",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/280065/"
] | Yes, Apple DID remove that feature in 10.13.4. I actually opened a case on this with Apple Support (I even referenced this page) and they got back to me today and informed me that it really has been removed from Messages. The Apple representative suggested going to <http://www.apple.com/feedback/> if I wanted to express my displeasure, but that was all he could do. | I have spoken with apple tech support senior advisor and they called me back and confirmed that the applescript handler option in messages has been removed in the latest operating system update 10.13.4. If you would like to send them feedback go to Apple.com/feedback and let them know your thoughts and that we would like the option back. |
194,382 | I would like to pull a from another phtml to my, how can I do this?
I would like to use the same div that appears for the desktop cart for the mobile cart.
**My Phtml**
```
<div class="carrinho-cheio-mobile" style="display: none;">Itens in cart!</div>
```
**Magento PHTML**
```
<?php $_items = $this->getRecentItems(); ?>
<?php if (count($_items)): ?>
<div id="header-cart" class="mini-cart-content dropdown-content left-hand skip-content skip-content- -style block-cart block">
<div class="">
<?php if ($tmpHtml = $this->getChildHtml('block_mini_cart_above_products')): ?>
<div class="block_mini_cart_above_products"><?php echo $tmpHtml; ?></div>
<?php endif; ?>
<div class="block-subtitle"><?php echo $this->__('Recently added item(s)') ?></div>
<ol id="cart-sidebar" class="mini-products-list clearer">
<?php foreach($_items as $_item): ?>
<?php echo $this->getItemHtml($_item) ?>
<?php endforeach; ?>
</ol>
<script type="text/javascript">decorateList('cart-sidebar', 'none-recursive')</script>
<div class="subtotal">
<?php if ($canApplyMsrp): ?>
<span class="map-cart-sidebar-total"><?php echo $this->__('ORDER TOTAL WILL BE DISPLAYED BEFORE YOU SUBMIT THE ORDER'); ?></span>
<?php else: ?>
<span class="label"><?php echo $this->__('Cart Subtotal:') ?></span> <?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal()) ?>
<?php if ($_subtotalInclTax = $this->getSubtotalInclTax()): ?>
<br />
<span class="incl-tax">(<?php echo Mage::helper('checkout')->formatPrice($_subtotalInclTax) ?> <?php echo Mage::helper('tax')->getIncExcText(true) ?>)</span>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="actions clearer">
<button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('View all items in your shopping cart')) ?>" class="button btn-inline-ver-carrinho" onclick="setLocation('<?php echo $this->getUrl('checkout/cart') ?>')"><span><span>Ver Carrinho</span></span></button>
<?php if($_cartQty && $this->isPossibleOnepageCheckout()): ?>
<button type="button" class="button btn-checkout-finalizar-compra btn-inline" onclick="setLocation('<?php echo $this->getCheckoutUrl(); ?>')"><span><span>Finalizar<br>Compra</span></span></button>
<?php echo $this->getChildHtml('extra_actions') ?>
<?php endif; ?>
</div>
</div> <!-- end: inner block -->
</div> <!-- end: dropdown-content -->
<?php else: ?>
``` | 2017/09/22 | [
"https://magento.stackexchange.com/questions/194382",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/56552/"
] | There are several ways how to do this, so below is just one example. For purpose of simplicity lets say that you have one select(A), and based on its value (or change of its value) you want to load new options for the other select (B) (with ajax in this example). The example below was used where select A represented attributes in magento and it was populating select B with their options.
You want to create new component for the select A that looks something like this:
```
define([
'jquery',
'Magento_Ui/js/form/element/select',
'uiRegistry'
], function ($, Select, uiRegistry) {
var self;
return Select.extend({
initialize: function () {
self = this;
this._super();
self.value.subscribe(function () {
self.updateValueOptions();
});
return this;
},
/**
* Update options in value select.
*/
updateValueOptions: function () {
if (self.value()) {
$.ajax({
url: 'http://myajaxcallback.com/',
type: 'post',
dataType: 'json',
cache: false,
showLoader: true,
data: {attributeId: self.value()}
}).
done(function (response) {
if (!response.error) {
uiRegistry.get('my_form.my_form.fieldsetname.bselectname').
options(response.options);
}
});
}
else {
uiRegistry.get('my_form.my_form.fieldsetname.bselectname').options([]);
}
}
});
});
```
Each time the value of select A changes(attribute in this case), this component will take the value and if it's not empty it will start ajax request to your controller looking for json data.
The controller should look something like this:
```
<?php
namespace Company\Values\Controller\Adminhtml\Values;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultFactory;
class Load extends \Magento\Backend\App\Action
{
/** @var \Magento\Eav\Api\AttributeRepositoryInterface */
private $eavAttributeRepository;
/** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute */
private $eavAttributeResource;
/**
* Load constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttributeResource
* @param \Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepository
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttributeResource,
\Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepository
) {
parent::__construct($context);
$this->eavAttributeRepository = $eavAttributeRepository;
$this->eavAttributeResource = $eavAttributeResource;
}
const ADMIN_RESOURCE = 'Company_Module::aclrule';
/**
* Dispatch request
*
* @return \Magento\Framework\Controller\ResultInterface|ResponseInterface
* @throws \Magento\Framework\Exception\NotFoundException
*/
public function execute()
{
$result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$responseData = [
'error' => true
];
try {
$attribute = $this->eavAttributeRepository->get('catalog_product', $this->_request->getParam('attributeId', null));
$responseData['error'] = false;
$responseData['options'] = $attribute->getSource()->getAllOptions();
} catch (\Exception $e) {
}
return $result->setData($responseData);
}
}
```
This is by no means perfect and needs a bit work (hardcoded values, perhaps moving the ajax to separate file etc.), but it should give you pretty good overview of such a feature. If you already have the options for select B loaded somewhere, just remove the ajax call and write your logic there.
[Documentation](http://devdocs.magento.com/guides/v2.0/ui-components/ui_components_js.html#comp_link) is a good read about how two components can communicate with each other. | **app/code/VendoreName/ModuleName/view/adminhtml/ui\_component**
**ui\_formname.xml**
```
<form>
...............................................................................................................
...............................................................................................................
<fieldset name="dynamic_data">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="collapsible" xsi:type="boolean">false</item>
<item name="label" xsi:type="string" translate="true">Dynamic Options</item>
<item name="sortOrder" xsi:type="number">10</item>
</item>
</argument>
<field name="max_email_send">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">VendoreName\ModuleName\Model\Config\Source\MaximumEmailSend</item>
<item name="config" xsi:type="array">
<item name="sortOrder" xsi:type="number">10</item>
<item name="dataType" xsi:type="string">string</item>
<item name="component" xsi:type="string">VendoreName_ModuleName/js/form/element/max-email-send</item>
<item name="label" xsi:type="string" translate="true">How Many Time Send Email</item>
<item name="formElement" xsi:type="string">select</item>
<item name="source" xsi:type="string">max_email_send</item>
<item name="dataScope" xsi:type="string">max_email_send</item>
</item>
</argument>
</field>
<field name="coupon_code_send">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Which Email Send Coupon Code</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">select</item>
<item name="sortOrder" xsi:type="number">20</item>
</item>
</argument>
</field>
<container name="custom_tab_container">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="sortOrder" xsi:type="string">1</item>
</item>
</argument>
<htmlContent name="html_content">
<argument name="block" xsi:type="object">VendoreName\ModuleName\Block\Adminhtml\SetParamsToJs</argument>
</htmlContent>
</container>
</fieldset>
</form>
```
**app/code/VendoreName/ModuleName/Model/Config/Source**
**MaximumEmailSend.php**
```
<?php
namespace VendoreName\ModuleName\Model\Config\Source;
class MaximumEmailSend implements \Magento\Framework\Option\ArrayInterface
{
public function getOptionArray()
{
$options = [];
for ($i = 1; $i <= 10; $i++) {
$options[$i] = (__($i));
}
return $options;
}
public function getAllOptions()
{
$res = $this->getOptions();
array_unshift($res, ['value' => '', 'label' => '']);
return $res;
}
public function getOptions()
{
$res = [];
foreach ($this->getOptionArray() as $index => $value) {
$res[] = ['value' => $index, 'label' => $value];
}
return $res;
}
public function toOptionArray()
{
return $this->getOptions();
}
}
```
**app/code/VendoreName/ModuleName/view/adminhtml/web/js/form/element**
**max-email-send.js**
```
define([
'jquery',
'Magento_Ui/js/form/element/select',
'uiRegistry'
], function ($, Select, uiRegistry) {
var self;
return Select.extend({
initialize: function () {
self = this;
this._super();
var statusVal = this.value();
setTimeout(function(){
if (statusVal) {
$.ajax({
url: window.optionAjaxUrl,
type: 'post',
dataType: 'json',
cache: false,
showLoader: true,
data: {attributeId: statusVal}
}).
done(function (response) {
if (!response.error) {
uiRegistry.get('ui_formname.ui_formname.dynamic_data.coupon_code_send').
options(response.options);
}
});
}
}, 800);
self.value.subscribe(function () {
self.updateValueOptions();
});
return this;
},
/**
* Update options in value select.
*/
updateValueOptions: function () {
if (self.value()) {
$.ajax({
url: window.optionAjaxUrl,
type: 'post',
dataType: 'json',
cache: false,
showLoader: true,
data: {attributeId: self.value()}
}).
done(function (response) {
if (!response.error) {
uiRegistry.get('ui_formname.ui_formname.dynamic_data.coupon_code_send').
options(response.options);
}
});
}
else {
uiRegistry.get('ui_formname.ui_formname.dynamic_data.coupon_code_send').options([]);
}
}
});
});
```
**app/code/VendoreName/ModuleName/Block/Adminhtml**
**SetParamsToJs.php**
```
<?php
namespace VendoreName\ModuleName\Block\Adminhtml;
class SetParamsToJs extends \Magento\Backend\Block\Template
{
/**
* Block template.
*
* @var string
*/
protected $_template = 'set_params.phtml';
}
```
**app/code/VendoreName/ModuleName/view/adminhtml/templates**
**set\_params.phtml**
```
<script type="text/javascript">
window.optionAjaxUrl = "<?php echo $block->getUrl('adminroutename/index/loadoptions'); ?>";
</script>
```
**app/code/VendoreName/ModuleName/Controller/Adminhtml/Index**
**LoadOptions.php**
```
<?php
namespace VendoreName\ModuleName\Controller\Adminhtml\Index;
use Magento\Framework\Controller\ResultFactory;
class LoadOptions extends \Magento\Backend\App\Action
{
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$data = $this->getRequest()->getPostValue();
$result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$responseData = [
'error' => true,
];
if ($data['attributeId']) {
try {
$responseData['error'] = false;
$options = [];
for ($i = 1; $i <= $data['attributeId']; $i++) {
//$options[] = ['label' => (__($i)), 'value' => (__($i))];
$options[] = ['label' => (__($i)), 'value' => $i];
}
$responseData['options'] = $options;
} catch (\Exception $e) {
$responseData['options'] = [];
}
}
return $result->setData($responseData);
}
}
``` |
27,530,868 | I have a simple program, WITHOUT "public int a;", the program runs no problem,
but after add "public int a;", the programm has errors, what is the problem?
there is no special meaning for this int field "a", i just want to try something and find this problem
 | 2014/12/17 | [
"https://Stackoverflow.com/questions/27530868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3334920/"
] | You need to declare fields and properties at the class level, not the method:
```
class Program
{
public int a;
...
}
```
Because the access modifier has meaning in this context. In your method you can only have local variables and they can only be accessed from the method that they declared. Curly-braces determine the scope of local variables.So specifying an access modifier for them is not allowed. | just use:
```
int a
```
as the word "public" is reserved for Class Variables / methods |
532,658 | As a student I always learned a "rule" to work through my statistics problems: If the sample is true in my null hypothesis, then I'm doing things wrong and it should be the other way around. It worked most of the time in my exams.
Is there any reason or theory to backup this idea?
### Example:
X is the mean of the sample.
Sample returns X=24
The following would be "wrong" according to my rule, because the null hypothesis is already true in the sample:
Ho: X ≥ 22
Ha: X < 22
Then I would quickly turn things around to:
Ho: X ≤ 22
Ha: X > 22
Any idea why this works and what's the theory behind it?
I used it in my exams and always worked. | 2021/06/29 | [
"https://stats.stackexchange.com/questions/532658",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/326854/"
] | **There's no supporting theory, because this doesn't work except by chance alone.**
Your choice of null and alternative hypotheses depend only on what you're trying to prove and not the sample value. Suppose you have some new drug that's supposed to lower cholesterol, and you want to test if it works. The null hypotheses is that the drug increases cholesterol or has no effect, while the alternative is that the drug actually does lower cholesterol. To claim that the drug does lower cholesterol, you need a significant amount of data to support that, typically enough to have an alpha of 0.05 - only 1 time in 20 will you say the drug has the intended effect when it actually does not.
If you flip your hypotheses arbitrarily, you're implicitly assuming that the drug works as intended, and requiring significant evidence to show that it does not. But that's not how proof works - a new claim requires positive evidence, you don't just assume it's true and then look for evidence it's false (which you could always fail to find just by collecting little evidence). Failing to show that the drug doesn't work as intended might just be a failure of your sample size, but is not alone evidence that it *does* work as expected. If you collect only 3 patients' worth of data, you won't have enough evidence to reject the possibility that the drug works as intended, but that's not meaningful at all. You should view that data as showing that you don't have evidence to conclude that the drug works, not that you've failed to rule out the drug's efficacy.
As you can see, none of this line of reasoning requires you to know anything at all about the cholesterol values actually observed in the population. *How you test* whether the drug works should not depend on whether the drug *actually does work* or not. The only reason this worked in your exams is because you got lucky defining the null and alternative hypotheses as your instructor intended (you had a 50/50 chance each time). The sample value has absolutely no role in defining the directionality of the hypothesis test. | You decide on your null and alternative hypothesis before you analyze the data (preferably before you even collect the data), so you have made a mistake in peeking.
By flipping the inequality to point away from the observed value, you assure yourself of not being able to reject (perhaps with some exotic exceptions, but this definitely applies to a t-test). That is, if you observe that $\bar{x} = 1$ and you try to show $H\_a: \mu<0$, you will fail to reject $H\_0: \mu\ge 0$ e(unless you have some silly $\alpha$ like $0.9$ instead of that usual suspects like $0.05$, $0.01$, and $0.1$).
But you should not be doing that, because you have not seen the calculation results when you decide on your null and alternative hypotheses. |
21,109,598 | I want to register a notification observer outside of the class that is observing the notification reception.
i tried to do it like this :
```
[[NSNotificationCenter defaultCenter]
addObserver:[ViewController class]
selector:@selector(NotificationReceived:)
name:@"notification" object:nil];
```
however, this forces me to make the method NotificationReceived in ViewController class to be `+(void)` instead of `-(void)` like i want it to be
is there a way to register the ViewController as a notification observer outside the ViewController class ? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21109598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2136812/"
] | You have two possibilities:
* Simply set the attribute `AutoPostBack="false"` on your button or whatever control.
* As an alternative you could also add the following javascript to the click event of the button :
```
onclick="return false"
```
This prevents the button from submitting. | First you have to know about Sever Control and normal HTML control.
If you used Server Button Control then your Page reload on each click.
If you wan to stop it then you have to use AutoPostBack="false", using this your server side method calling is stop.
Otherwise use Normal HTML Button Control and use JavaScript to reset your form. |
21,109,598 | I want to register a notification observer outside of the class that is observing the notification reception.
i tried to do it like this :
```
[[NSNotificationCenter defaultCenter]
addObserver:[ViewController class]
selector:@selector(NotificationReceived:)
name:@"notification" object:nil];
```
however, this forces me to make the method NotificationReceived in ViewController class to be `+(void)` instead of `-(void)` like i want it to be
is there a way to register the ViewController as a notification observer outside the ViewController class ? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21109598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2136812/"
] | Try following:
```
<asp:button runat="server".... OnClientClick="return false;" />
``` | First you have to know about Sever Control and normal HTML control.
If you used Server Button Control then your Page reload on each click.
If you wan to stop it then you have to use AutoPostBack="false", using this your server side method calling is stop.
Otherwise use Normal HTML Button Control and use JavaScript to reset your form. |
57,272,749 | I inherited some code to maintain, with this line in it:
```
this.setState({}); // Force update
```
Is this guaranteed to cause a re-render? | 2019/07/30 | [
"https://Stackoverflow.com/questions/57272749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275803/"
] | `setState` merges the object passed as argument into the actual state in an immutable way. `this.setState({})` will merge nothing to state but will actually return a new object, the shallow comparison performed by `React` will always assert to `false` and a re render will be triggered, unless explicitly cancelled with `shouldComponentUpdate`. So yes, in this case it is equivalent to `forceUpdate` and it comes with the same [caveats](https://reactjs.org/docs/react-component.html#forceupdate). | According to the documentation it is and several other methods in order
1. static getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
please see this [link](https://reactjs.org/docs/react-component.html#updating) for detailed |
57,272,749 | I inherited some code to maintain, with this line in it:
```
this.setState({}); // Force update
```
Is this guaranteed to cause a re-render? | 2019/07/30 | [
"https://Stackoverflow.com/questions/57272749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275803/"
] | `setState` merges the object passed as argument into the actual state in an immutable way. `this.setState({})` will merge nothing to state but will actually return a new object, the shallow comparison performed by `React` will always assert to `false` and a re render will be triggered, unless explicitly cancelled with `shouldComponentUpdate`. So yes, in this case it is equivalent to `forceUpdate` and it comes with the same [caveats](https://reactjs.org/docs/react-component.html#forceupdate). | You can actually [test it](https://snack.expo.io/@remeus/force-re-render) easily:
```js
import React, { Component } from 'react';
import { Button } from 'react-native';
class Test extends Component {
render() {
console.log('render');
return <Button onPress={() => this.setState({})} title='Test' />;
}
}
export default Test;
```
Every time the button is clicked, the console.log triggers.
An interesting point is that if you replace `this.setState({})` by `this.setState()`, there is no re-render after a click. |
57,272,749 | I inherited some code to maintain, with this line in it:
```
this.setState({}); // Force update
```
Is this guaranteed to cause a re-render? | 2019/07/30 | [
"https://Stackoverflow.com/questions/57272749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275803/"
] | `setState` merges the object passed as argument into the actual state in an immutable way. `this.setState({})` will merge nothing to state but will actually return a new object, the shallow comparison performed by `React` will always assert to `false` and a re render will be triggered, unless explicitly cancelled with `shouldComponentUpdate`. So yes, in this case it is equivalent to `forceUpdate` and it comes with the same [caveats](https://reactjs.org/docs/react-component.html#forceupdate). | It depends. If you want to render a component, react internally checks is DOM equals with previous(this occurs if props of component is not changed at all). If dom equals with previous version, react checks `shouldComponentUpdate`. `forceUpdate` is different than `this.setState({})`, which always render components. |
57,272,749 | I inherited some code to maintain, with this line in it:
```
this.setState({}); // Force update
```
Is this guaranteed to cause a re-render? | 2019/07/30 | [
"https://Stackoverflow.com/questions/57272749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275803/"
] | You can actually [test it](https://snack.expo.io/@remeus/force-re-render) easily:
```js
import React, { Component } from 'react';
import { Button } from 'react-native';
class Test extends Component {
render() {
console.log('render');
return <Button onPress={() => this.setState({})} title='Test' />;
}
}
export default Test;
```
Every time the button is clicked, the console.log triggers.
An interesting point is that if you replace `this.setState({})` by `this.setState()`, there is no re-render after a click. | According to the documentation it is and several other methods in order
1. static getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
please see this [link](https://reactjs.org/docs/react-component.html#updating) for detailed |
57,272,749 | I inherited some code to maintain, with this line in it:
```
this.setState({}); // Force update
```
Is this guaranteed to cause a re-render? | 2019/07/30 | [
"https://Stackoverflow.com/questions/57272749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275803/"
] | According to the documentation it is and several other methods in order
1. static getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
please see this [link](https://reactjs.org/docs/react-component.html#updating) for detailed | It depends. If you want to render a component, react internally checks is DOM equals with previous(this occurs if props of component is not changed at all). If dom equals with previous version, react checks `shouldComponentUpdate`. `forceUpdate` is different than `this.setState({})`, which always render components. |
57,272,749 | I inherited some code to maintain, with this line in it:
```
this.setState({}); // Force update
```
Is this guaranteed to cause a re-render? | 2019/07/30 | [
"https://Stackoverflow.com/questions/57272749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275803/"
] | You can actually [test it](https://snack.expo.io/@remeus/force-re-render) easily:
```js
import React, { Component } from 'react';
import { Button } from 'react-native';
class Test extends Component {
render() {
console.log('render');
return <Button onPress={() => this.setState({})} title='Test' />;
}
}
export default Test;
```
Every time the button is clicked, the console.log triggers.
An interesting point is that if you replace `this.setState({})` by `this.setState()`, there is no re-render after a click. | It depends. If you want to render a component, react internally checks is DOM equals with previous(this occurs if props of component is not changed at all). If dom equals with previous version, react checks `shouldComponentUpdate`. `forceUpdate` is different than `this.setState({})`, which always render components. |
56,381,375 | I have a column [LongText] in a table and its row value is merging of all Attributes and their values. Below is the example.
Can we split colon before and after words into two columns as shown in expected result? need it in sql 2014
```
Longtext
TYPE: SOLID WEDGE 1,SOLID WEDGE 2, VALVE SIZE: 1 IN, PRESSURE RATING: 800 LB, CONNECTION TYPE: SOCKET WELD, BONNET STYLE: BOLTED
```
Expected Output into 2 columns Attribute and Value:
```
Attribute | Value
----------------------------------------------
TYPE | SOLID WEDGE 1,SOLID WEDGE 2
VALVE SIZE | 1 IN
PRESSURE RATING | 800 LB
CONNECTION TYPE | SOCKET WELD
BONNET STYLE | BOLTED
``` | 2019/05/30 | [
"https://Stackoverflow.com/questions/56381375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11578665/"
] | Swift 5
=======
Indeed there is - I found the answer at the UIKonf 2019 where I heard from Erica Sadun that there is a way by using `Swift 5 String Interpolation` to achieve this in one single line. All you need is this reusable extension:
```swift
extension String.StringInterpolation {
mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
guard condition() else { return }
appendLiteral(literal)
}
}
```
It enables you to transform your 4 lines into just one:
```swift
"Contact: \(me.name)\(if: me.isFavorite, " is a favorite contact")"
```
You can read about the different possibilities of Swift's string interpolation in in Erica's article: <https://ericasadun.com/2018/12/12/the-beauty-of-swift-5-string-interpolation/>
Playground
----------
Start getting your hands dirty with this:
```swift
import Foundation
// *****************************************************************************
// Many thanks to Erica Sadun for describing the new possibilities of string
// interpolation in Swift 5
// *****************************************************************************
// *****************************************************************************
// Conditional Interpolation
struct Contact {
let name: String
let isFavorite: Bool
}
let me = Contact(name: "Stefan", isFavorite: true)
// ***************************************************************** Swift 4
var message = "Contact \(me.name)"
if me.isFavorite {
message.append(" is favorite")
}
message // we need 4 lines to construct this message!!!
"Contact: \(me.name)\(me.isFavorite ? " is favorite" : "")" // or a complex ternary operator
// ***************************************************************** Swift 5
extension String.StringInterpolation {
mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
guard condition() else { return }
appendLiteral(literal)
}
}
"Contact: \(me.name)\(if: me.isFavorite, " is favorite")" // simple and clean - no extras
// *****************************************************************************
// Optional Interpolation
let optionalMe: Contact? = Contact(name: "Stefan", isFavorite: true)
// ***************************************************************** Swift 4
"Contact: \(optionalMe?.name)" // shows warning
// ***************************************************************** Swift 5
// Interpolate nil value
extension String.StringInterpolation {
/// Provides `Optional` string interpolation without forcing the
/// use of `String(describing:)`.
public mutating func appendInterpolation<T>(_ value: T?, default defaultValue: String) {
if let value = value {
appendInterpolation(value)
} else {
appendLiteral(defaultValue)
}
}
}
let nilContact: Contact? = nil
"Contact: \(nilContact?.name, default: "nil")"
// Strip `Optional`
extension String.StringInterpolation {
/// Interpolates an optional using "stripped" interpolation, omitting
/// the word "Optional" from both `.some` and `.none` cases
public mutating func appendInterpolation<T>(describing value: T?) {
if let value = value {
appendInterpolation(value)
} else {
appendLiteral("nil")
}
}
}
"Contact: \(describing: optionalMe?.name)"
``` | You can use [Ternary operator](https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html#ID71)
```
let msg = "Contact \(me.name)" + (me.isFavorite ? " is a favorite contact" : "")
``` |
56,381,375 | I have a column [LongText] in a table and its row value is merging of all Attributes and their values. Below is the example.
Can we split colon before and after words into two columns as shown in expected result? need it in sql 2014
```
Longtext
TYPE: SOLID WEDGE 1,SOLID WEDGE 2, VALVE SIZE: 1 IN, PRESSURE RATING: 800 LB, CONNECTION TYPE: SOCKET WELD, BONNET STYLE: BOLTED
```
Expected Output into 2 columns Attribute and Value:
```
Attribute | Value
----------------------------------------------
TYPE | SOLID WEDGE 1,SOLID WEDGE 2
VALVE SIZE | 1 IN
PRESSURE RATING | 800 LB
CONNECTION TYPE | SOCKET WELD
BONNET STYLE | BOLTED
``` | 2019/05/30 | [
"https://Stackoverflow.com/questions/56381375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11578665/"
] | Swift 5
=======
Indeed there is - I found the answer at the UIKonf 2019 where I heard from Erica Sadun that there is a way by using `Swift 5 String Interpolation` to achieve this in one single line. All you need is this reusable extension:
```swift
extension String.StringInterpolation {
mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
guard condition() else { return }
appendLiteral(literal)
}
}
```
It enables you to transform your 4 lines into just one:
```swift
"Contact: \(me.name)\(if: me.isFavorite, " is a favorite contact")"
```
You can read about the different possibilities of Swift's string interpolation in in Erica's article: <https://ericasadun.com/2018/12/12/the-beauty-of-swift-5-string-interpolation/>
Playground
----------
Start getting your hands dirty with this:
```swift
import Foundation
// *****************************************************************************
// Many thanks to Erica Sadun for describing the new possibilities of string
// interpolation in Swift 5
// *****************************************************************************
// *****************************************************************************
// Conditional Interpolation
struct Contact {
let name: String
let isFavorite: Bool
}
let me = Contact(name: "Stefan", isFavorite: true)
// ***************************************************************** Swift 4
var message = "Contact \(me.name)"
if me.isFavorite {
message.append(" is favorite")
}
message // we need 4 lines to construct this message!!!
"Contact: \(me.name)\(me.isFavorite ? " is favorite" : "")" // or a complex ternary operator
// ***************************************************************** Swift 5
extension String.StringInterpolation {
mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
guard condition() else { return }
appendLiteral(literal)
}
}
"Contact: \(me.name)\(if: me.isFavorite, " is favorite")" // simple and clean - no extras
// *****************************************************************************
// Optional Interpolation
let optionalMe: Contact? = Contact(name: "Stefan", isFavorite: true)
// ***************************************************************** Swift 4
"Contact: \(optionalMe?.name)" // shows warning
// ***************************************************************** Swift 5
// Interpolate nil value
extension String.StringInterpolation {
/// Provides `Optional` string interpolation without forcing the
/// use of `String(describing:)`.
public mutating func appendInterpolation<T>(_ value: T?, default defaultValue: String) {
if let value = value {
appendInterpolation(value)
} else {
appendLiteral(defaultValue)
}
}
}
let nilContact: Contact? = nil
"Contact: \(nilContact?.name, default: "nil")"
// Strip `Optional`
extension String.StringInterpolation {
/// Interpolates an optional using "stripped" interpolation, omitting
/// the word "Optional" from both `.some` and `.none` cases
public mutating func appendInterpolation<T>(describing value: T?) {
if let value = value {
appendInterpolation(value)
} else {
appendLiteral("nil")
}
}
}
"Contact: \(describing: optionalMe?.name)"
``` | I tend to create a second `String` variable which may or may not be empty, and unconditionally append it...
```swift
let me = Contact(name: "Stefan", isFavorite: true)
let favorite = me.isFavorite ? " is a favorite contact" : ""
var message = "Contact \(me.name)\(favorite)"
``` |
56,381,375 | I have a column [LongText] in a table and its row value is merging of all Attributes and their values. Below is the example.
Can we split colon before and after words into two columns as shown in expected result? need it in sql 2014
```
Longtext
TYPE: SOLID WEDGE 1,SOLID WEDGE 2, VALVE SIZE: 1 IN, PRESSURE RATING: 800 LB, CONNECTION TYPE: SOCKET WELD, BONNET STYLE: BOLTED
```
Expected Output into 2 columns Attribute and Value:
```
Attribute | Value
----------------------------------------------
TYPE | SOLID WEDGE 1,SOLID WEDGE 2
VALVE SIZE | 1 IN
PRESSURE RATING | 800 LB
CONNECTION TYPE | SOCKET WELD
BONNET STYLE | BOLTED
``` | 2019/05/30 | [
"https://Stackoverflow.com/questions/56381375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11578665/"
] | You can use [Ternary operator](https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html#ID71)
```
let msg = "Contact \(me.name)" + (me.isFavorite ? " is a favorite contact" : "")
``` | I tend to create a second `String` variable which may or may not be empty, and unconditionally append it...
```swift
let me = Contact(name: "Stefan", isFavorite: true)
let favorite = me.isFavorite ? " is a favorite contact" : ""
var message = "Contact \(me.name)\(favorite)"
``` |
1,219,635 | I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
```
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
```
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
```
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
```
This would keep from polluting the jQuery function namespace.
You could then call the plugins like
```
$('#example').foo()
$('#other_example').foo.bar()
```
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
Any ideas or opinions would be appreciated.
-Matt | 2009/08/02 | [
"https://Stackoverflow.com/questions/1219635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42523/"
] | As soon as you use `$.fn.foo.bar()` -- `this` points to `$.fn.foo`, which is what you would expect in JavaScript (`this` being the object that the function is called on.)
I have noticed in plugins from jQuery UI (like sortable) where you call functions like:
```
$(...).sortable("serialize");
$(...).sortable({options});
```
If you were doing something like this - you could extend jQuery itself:
```
$.foo_plugin = {
bar: function() {},
baz: function() {}
}
$.fn.foo = function(opts) {
if (opts == 'bar') return $.foo_plugin.bar.call(this);
if (opts == 'baz') return $.foo_plugin.baz.call(this);
}
``` | Well, I'm sure there are many ways to skin this cat. The jQuery UI library uses a pattern like this:
```
// initialize a dialog window from an element:
$('#selector').dialog({});
// call the show method of a dialog:
$('#selector').dialog('show');
``` |
1,219,635 | I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
```
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
```
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
```
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
```
This would keep from polluting the jQuery function namespace.
You could then call the plugins like
```
$('#example').foo()
$('#other_example').foo.bar()
```
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
Any ideas or opinions would be appreciated.
-Matt | 2009/08/02 | [
"https://Stackoverflow.com/questions/1219635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42523/"
] | I know this has already been answered but I have created a plugin that does exactly what you want:
<http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js>
I've included a small example below, but check out this jQuery Dev Group post for a more in-depth example: <http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/72cf730045d4333a?hl=en&q=structure+plugin+authoring#72cf730045d4333a>
It allows you to create an object with as many methods as you want:
```
var _myPlugin = function() {
// return the plugin namespace
return this;
}
_myPlugin.prototype.alertHtml = function() {
// use this the same way you would with jQuery
alert($(this).html());
}
$.fn.plugin.add('myPlugin', _myPlugin);
```
now you can go:
```
$(someElement).myPlugin().alertHtml();
```
There are, of course, many, many other possibilities with this as explained in the dev group post. | Well, I'm sure there are many ways to skin this cat. The jQuery UI library uses a pattern like this:
```
// initialize a dialog window from an element:
$('#selector').dialog({});
// call the show method of a dialog:
$('#selector').dialog('show');
``` |
1,219,635 | I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
```
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
```
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
```
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
```
This would keep from polluting the jQuery function namespace.
You could then call the plugins like
```
$('#example').foo()
$('#other_example').foo.bar()
```
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
Any ideas or opinions would be appreciated.
-Matt | 2009/08/02 | [
"https://Stackoverflow.com/questions/1219635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42523/"
] | Well, I'm sure there are many ways to skin this cat. The jQuery UI library uses a pattern like this:
```
// initialize a dialog window from an element:
$('#selector').dialog({});
// call the show method of a dialog:
$('#selector').dialog('show');
``` | I'm a fan of the pattern I've seen on Eric Martin's [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/). This works well for when I'm NOT acting on DOM elements -- in this case a wrapper to utilize localStorage.
This way I can easily refer to the constructor:
```
$.totalStorage('robo', 'cop');
```
...or a public method:
```
$.totalStorage.getItem('robo'); //returns 'cop'
```
Here's the internals:
```
;(function($){
/* Variables I'll need throghout */
var ls;
var supported = true;
if (typeof localStorage == 'undefined' || typeof JSON == 'undefined') {
supported = false;
} else {
ls = localStorage;
}
/* Make the methods public */
$.totalStorage = function(key, value, options){
return $.totalStorage.impl.init(key, value);
}
$.totalStorage.setItem = function(key, value){
return $.totalStorage.impl.setItem(key, value);
}
$.totalStorage.getItem = function(key){
return $.totalStorage.impl.getItem(key);
}
/* Object to hold all methods: public and private */
$.totalStorage.impl = {
init: function(key, value){
if (typeof value != 'undefined') {
return this.setItem(name, value);
} else {
return this.getItem(name);
}
},
setItem: function(key, value){
if (!supported){
$.cookie(key, value);
return true;
}
ls.setItem(key, JSON.stringify(value));
return true;
},
getItem: function(key){
if (!supported){
return this.parseResult($.cookie(key));
}
return this.parseResult(ls.getItem(key));
},
parseResult: function(res){
var ret;
try {
ret = JSON.parse(res);
if (ret == 'true'){
ret = true;
}
if (ret == 'false'){
ret = false;
}
if (parseFloat(ret) == ret){
ret = parseFloat(ret);
}
} catch(e){}
return ret;
}
}})(jQuery);
``` |
1,219,635 | I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
```
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
```
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
```
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
```
This would keep from polluting the jQuery function namespace.
You could then call the plugins like
```
$('#example').foo()
$('#other_example').foo.bar()
```
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
Any ideas or opinions would be appreciated.
-Matt | 2009/08/02 | [
"https://Stackoverflow.com/questions/1219635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42523/"
] | As soon as you use `$.fn.foo.bar()` -- `this` points to `$.fn.foo`, which is what you would expect in JavaScript (`this` being the object that the function is called on.)
I have noticed in plugins from jQuery UI (like sortable) where you call functions like:
```
$(...).sortable("serialize");
$(...).sortable({options});
```
If you were doing something like this - you could extend jQuery itself:
```
$.foo_plugin = {
bar: function() {},
baz: function() {}
}
$.fn.foo = function(opts) {
if (opts == 'bar') return $.foo_plugin.bar.call(this);
if (opts == 'baz') return $.foo_plugin.baz.call(this);
}
``` | I know this has already been answered but I have created a plugin that does exactly what you want:
<http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js>
I've included a small example below, but check out this jQuery Dev Group post for a more in-depth example: <http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/72cf730045d4333a?hl=en&q=structure+plugin+authoring#72cf730045d4333a>
It allows you to create an object with as many methods as you want:
```
var _myPlugin = function() {
// return the plugin namespace
return this;
}
_myPlugin.prototype.alertHtml = function() {
// use this the same way you would with jQuery
alert($(this).html());
}
$.fn.plugin.add('myPlugin', _myPlugin);
```
now you can go:
```
$(someElement).myPlugin().alertHtml();
```
There are, of course, many, many other possibilities with this as explained in the dev group post. |
1,219,635 | I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
```
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
```
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
```
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
```
This would keep from polluting the jQuery function namespace.
You could then call the plugins like
```
$('#example').foo()
$('#other_example').foo.bar()
```
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
Any ideas or opinions would be appreciated.
-Matt | 2009/08/02 | [
"https://Stackoverflow.com/questions/1219635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42523/"
] | As soon as you use `$.fn.foo.bar()` -- `this` points to `$.fn.foo`, which is what you would expect in JavaScript (`this` being the object that the function is called on.)
I have noticed in plugins from jQuery UI (like sortable) where you call functions like:
```
$(...).sortable("serialize");
$(...).sortable({options});
```
If you were doing something like this - you could extend jQuery itself:
```
$.foo_plugin = {
bar: function() {},
baz: function() {}
}
$.fn.foo = function(opts) {
if (opts == 'bar') return $.foo_plugin.bar.call(this);
if (opts == 'baz') return $.foo_plugin.baz.call(this);
}
``` | I'm a fan of the pattern I've seen on Eric Martin's [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/). This works well for when I'm NOT acting on DOM elements -- in this case a wrapper to utilize localStorage.
This way I can easily refer to the constructor:
```
$.totalStorage('robo', 'cop');
```
...or a public method:
```
$.totalStorage.getItem('robo'); //returns 'cop'
```
Here's the internals:
```
;(function($){
/* Variables I'll need throghout */
var ls;
var supported = true;
if (typeof localStorage == 'undefined' || typeof JSON == 'undefined') {
supported = false;
} else {
ls = localStorage;
}
/* Make the methods public */
$.totalStorage = function(key, value, options){
return $.totalStorage.impl.init(key, value);
}
$.totalStorage.setItem = function(key, value){
return $.totalStorage.impl.setItem(key, value);
}
$.totalStorage.getItem = function(key){
return $.totalStorage.impl.getItem(key);
}
/* Object to hold all methods: public and private */
$.totalStorage.impl = {
init: function(key, value){
if (typeof value != 'undefined') {
return this.setItem(name, value);
} else {
return this.getItem(name);
}
},
setItem: function(key, value){
if (!supported){
$.cookie(key, value);
return true;
}
ls.setItem(key, JSON.stringify(value));
return true;
},
getItem: function(key){
if (!supported){
return this.parseResult($.cookie(key));
}
return this.parseResult(ls.getItem(key));
},
parseResult: function(res){
var ret;
try {
ret = JSON.parse(res);
if (ret == 'true'){
ret = true;
}
if (ret == 'false'){
ret = false;
}
if (parseFloat(ret) == ret){
ret = parseFloat(ret);
}
} catch(e){}
return ret;
}
}})(jQuery);
``` |
1,219,635 | I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.
```
(function($){
$.fn.foo = function(){
//plugin part A
}
$.fn.bar = function(){
//plugin part B
}
$.fn.baz = function(){
//plugin part C
}
}(jQuery))
```
Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin
```
$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}
```
This would keep from polluting the jQuery function namespace.
You could then call the plugins like
```
$('#example').foo()
$('#other_example').foo.bar()
```
The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.
Any ideas or opinions would be appreciated.
-Matt | 2009/08/02 | [
"https://Stackoverflow.com/questions/1219635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42523/"
] | I know this has already been answered but I have created a plugin that does exactly what you want:
<http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js>
I've included a small example below, but check out this jQuery Dev Group post for a more in-depth example: <http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/72cf730045d4333a?hl=en&q=structure+plugin+authoring#72cf730045d4333a>
It allows you to create an object with as many methods as you want:
```
var _myPlugin = function() {
// return the plugin namespace
return this;
}
_myPlugin.prototype.alertHtml = function() {
// use this the same way you would with jQuery
alert($(this).html());
}
$.fn.plugin.add('myPlugin', _myPlugin);
```
now you can go:
```
$(someElement).myPlugin().alertHtml();
```
There are, of course, many, many other possibilities with this as explained in the dev group post. | I'm a fan of the pattern I've seen on Eric Martin's [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/). This works well for when I'm NOT acting on DOM elements -- in this case a wrapper to utilize localStorage.
This way I can easily refer to the constructor:
```
$.totalStorage('robo', 'cop');
```
...or a public method:
```
$.totalStorage.getItem('robo'); //returns 'cop'
```
Here's the internals:
```
;(function($){
/* Variables I'll need throghout */
var ls;
var supported = true;
if (typeof localStorage == 'undefined' || typeof JSON == 'undefined') {
supported = false;
} else {
ls = localStorage;
}
/* Make the methods public */
$.totalStorage = function(key, value, options){
return $.totalStorage.impl.init(key, value);
}
$.totalStorage.setItem = function(key, value){
return $.totalStorage.impl.setItem(key, value);
}
$.totalStorage.getItem = function(key){
return $.totalStorage.impl.getItem(key);
}
/* Object to hold all methods: public and private */
$.totalStorage.impl = {
init: function(key, value){
if (typeof value != 'undefined') {
return this.setItem(name, value);
} else {
return this.getItem(name);
}
},
setItem: function(key, value){
if (!supported){
$.cookie(key, value);
return true;
}
ls.setItem(key, JSON.stringify(value));
return true;
},
getItem: function(key){
if (!supported){
return this.parseResult($.cookie(key));
}
return this.parseResult(ls.getItem(key));
},
parseResult: function(res){
var ret;
try {
ret = JSON.parse(res);
if (ret == 'true'){
ret = true;
}
if (ret == 'false'){
ret = false;
}
if (parseFloat(ret) == ret){
ret = parseFloat(ret);
}
} catch(e){}
return ret;
}
}})(jQuery);
``` |
70,024,064 | I'm using react and this is my code.
```
import { useEffect, useState } from "react";
const Test = (props) => {
const [sort, setSort] = useState(1);
const [albums, setAlbums] = useState([
{
"userId": 1,
"id": 1,
"title": "A letter",
"photos": {
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
},
{
"userId": 1,
"id": 2,
"title": "C letter",
"photos": {
"albumId": 2,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
},
{
"userId": 1,
"id": 3,
"title": "B letter",
"photos": {
"albumId": 3,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
},
]);
useEffect(() => {
if (sort == 1) {
setAlbums(albums.sort((a, b) => (a.id > b.id) ? 1 : -1));
} else if (sort == 2) {
setAlbums(albums.sort((a, b) => (a.title > b.title) ? 1 : -1));
} else if (sort == 3) {
setAlbums(albums.sort((a, b) => (a.title < b.title) ? 1 : -1));
}
}, [sort]);
return (
<>
<select value={sort} onChange={e => setSort(e.target.value)} >
<option value='1'>val 1</option>
<option value='2'>val 2</option>
<option value='3'>val 3</option>
</select>
{albums.map((item, key) => {
return (
<p>{item.title}</p>
)
})}
</>
)
}
export default Test;
```
I'm using react and trying **to sort array items with select dropdown**. But when I sort it's always one level behind. That means if I select 2 nothing would happen and then select 3 it will get sorted according to value 2. It would be great if someone can give a solution and explain why this happens... | 2021/11/18 | [
"https://Stackoverflow.com/questions/70024064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2395282/"
] | Don't do this with String split, replace etc. At some point, it will fail.
You should parse the sql statement. Example with [JsqlParser](https://github.com/JSQLParser/JSqlParser) like
```
public class Main {
public static void main(String[] args) throws JSQLParserException {
Select stmt = (Select) CCJSqlParserUtil.parse(
"SELECT COUNT(project_id) AS 'count', project.name AS 'projects' FROM test\n"
+ "JOIN project ON project_id = project.id ");
for (SelectItem selectItem : ((PlainSelect) stmt.getSelectBody()).getSelectItems()) {
selectItem.accept(new SelectItemVisitorAdapter() {
@Override
public void visit(SelectExpressionItem item) {
System.err.println(item.getAlias().getName());
}
});
}
}
}
```
Output:
```
'count'
'projects'
``` | You can do it as follow:
```
String query = "SELECT COUNT(project_id) AS 'count', project.name AS 'projects' FROM test JOIN project ON project_id = project.id";
LinkedList<String> queryColumns = new LinkedList<>();
String[] test = query.replace("SELECT", "").split("FROM")[0].split(","); //You have a string from which you need to extract single names, taking care of aliases.
for(String s : test) {
int aliasIndex = s.indexOf("AS");
String column;
if(aliasIndex != -1) {
//if there is an alias
column = s.substring(aliasIndex + 2).replace("'","").strip();
} else {
//if there isn't an alias
column = s.replace("'","").strip();
}
queryColumns.add(column);
}
```
I assume that the alias is indicated as 'AS' in uppercase, if it can be lowercase too, it's easy to change and adapt the code. |
10,668,405 | There are various points in a Grid.
Say (x,y) can be reached from (x-1,y+1) in a single unit of time. then what would be the general formula for finding distance between a point (x1,y1) to (x2,y2).
say for (0,0) to (-2,-1) i.e. coordinate can be negative too.
I could not think of general formula. | 2012/05/19 | [
"https://Stackoverflow.com/questions/10668405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646961/"
] | If I understand the question correctly, and diagonal movements have the same cost as "manhattan" movements, it's cheaper than the manhattan distance in most cases -- only the maximum of the x and y distances is relevant:
max(abs(x1 - x2), abs(y1 - y2))
Basically you move diagonally at cost 1 per unit until you have reached x2 or y2, then along the grid. | if (x,y) can be reached from (x-1, y+1).
Then all points reachable from (x1,y1) are (x1+k, y1-k) where k is greater than 0. |
1,478,697 | I frequently see python code similar to
```
for line in open(filename):
do_something(line)
```
When does filename get closed with this code?
Would it be better to write
```
with open(filename) as f:
for line in f.readlines():
do_something(line)
``` | 2009/09/25 | [
"https://Stackoverflow.com/questions/1478697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173922/"
] | `filename` would be closed when it falls out of scope. That normally would be the end of the method.
Yes, it's better to use `with`.
>
> Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the `close` method on the object, to close the connection to the file:
>
>
>
> ```
> input.close()
>
> ```
>
> In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that `try`/`finally` is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.
>
>
>
*[Python Cookbook, Page 59.](http://books.google.com.ar/books?id=1Shx_VXS6ioC&pg=PA59&lpg=PA59&dq=garbage+collection+python+file+open&source=bl&ots=BB6-bAT8Q2&sig=w3L8P8EOVDQ-HS6NlBWdXdiN-kk&hl=es&ei=GgO9SvaJIdWPtgfU-8yKAw&sa=X&oi=book_result&ct=result&resnum=2#v=onepage&q=garbage%20collection%20python%20file%20open&f=false)* | The `with` part is better because it close the file afterwards.
You don't even have to use `readlines()`. `for line in file` is enough.
I don't think the first one closes it. |
1,478,697 | I frequently see python code similar to
```
for line in open(filename):
do_something(line)
```
When does filename get closed with this code?
Would it be better to write
```
with open(filename) as f:
for line in f.readlines():
do_something(line)
``` | 2009/09/25 | [
"https://Stackoverflow.com/questions/1478697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173922/"
] | The `with` part is better because it close the file afterwards.
You don't even have to use `readlines()`. `for line in file` is enough.
I don't think the first one closes it. | python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.
File objects close their file handle when the are deleted/finalized.
Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes. |
1,478,697 | I frequently see python code similar to
```
for line in open(filename):
do_something(line)
```
When does filename get closed with this code?
Would it be better to write
```
with open(filename) as f:
for line in f.readlines():
do_something(line)
``` | 2009/09/25 | [
"https://Stackoverflow.com/questions/1478697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173922/"
] | `filename` would be closed when it falls out of scope. That normally would be the end of the method.
Yes, it's better to use `with`.
>
> Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the `close` method on the object, to close the connection to the file:
>
>
>
> ```
> input.close()
>
> ```
>
> In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that `try`/`finally` is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.
>
>
>
*[Python Cookbook, Page 59.](http://books.google.com.ar/books?id=1Shx_VXS6ioC&pg=PA59&lpg=PA59&dq=garbage+collection+python+file+open&source=bl&ots=BB6-bAT8Q2&sig=w3L8P8EOVDQ-HS6NlBWdXdiN-kk&hl=es&ei=GgO9SvaJIdWPtgfU-8yKAw&sa=X&oi=book_result&ct=result&resnum=2#v=onepage&q=garbage%20collection%20python%20file%20open&f=false)* | python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.
File objects close their file handle when the are deleted/finalized.
Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.