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 |
|---|---|---|---|---|---|
13,141,197 | I have `n*n` grid, where for example `n=10`. I have to fill it with black and white elements. Every black element has to have one, two or three black neighbors. It is not allowed to contain black elements with four or zero neighbors.
How should I build this kind of grid ?
Edit:
To be more specific, it is two-dimensional array built for example with two `for` loops:
```
n = 10
array = [][];
for ( x = 0; x < n; x++ ) {
for ( y = 0; y < n; y++ ) {
array[x][y] = rand(black/white)
}
}
```
This pseudo code builds somethind like:

And what I expect is:
 | 2012/10/30 | [
"https://Stackoverflow.com/questions/13141197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223386/"
] | Obviously, you're trying to generate "black path" shapes on a write grid.
So let's just do it.
* Start with a white grid.
* Randomly position some turtles on it.
* Then, while your grid doesn't meet a proper white/black cell ratio, do the following
+ Move each turtle one cell in a random direction and paint it black unless doing so break the "no more than three black neighbors" rule. | With the size that you show here, you could easily go for a bit of a brute force implementation.
Write a function that checks if you meet the requirements, simply by iterating through all cells and counting neighbors.
After that, do something like this:
```
Start out with a white grid.
Then repeatedly:
pick a random cell
If the cell is white:
make it black
call the grid checking routine.
if the grid became invalid:
color it gray to make sure you don't try this one again
do this until you think it took long enough, or there are no more white cells.
then make all gray cells white.
```
If your grid is large (thousands of pixels), you should probably look for a more efficient algorithm, but for a 10x10 grid this will be calculated in a flash. |
13,141,197 | I have `n*n` grid, where for example `n=10`. I have to fill it with black and white elements. Every black element has to have one, two or three black neighbors. It is not allowed to contain black elements with four or zero neighbors.
How should I build this kind of grid ?
Edit:
To be more specific, it is two-dimensional array built for example with two `for` loops:
```
n = 10
array = [][];
for ( x = 0; x < n; x++ ) {
for ( y = 0; y < n; y++ ) {
array[x][y] = rand(black/white)
}
}
```
This pseudo code builds somethind like:

And what I expect is:
 | 2012/10/30 | [
"https://Stackoverflow.com/questions/13141197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223386/"
] | Obviously, you're trying to generate "black path" shapes on a write grid.
So let's just do it.
* Start with a white grid.
* Randomly position some turtles on it.
* Then, while your grid doesn't meet a proper white/black cell ratio, do the following
+ Move each turtle one cell in a random direction and paint it black unless doing so break the "no more than three black neighbors" rule. | Maybe this python code could be of some use. Its basic idea is to do some sort of breadth first traversal of the grid, ensuring that the blackened pixels respect the constraint that they have no more than 3 black neighbours. The graph corresponding to the blackened part of the grid is a tree, as your desired result seemed to be.
```
import Queue
import Image
import numpy as np
import random
#size of the problem
size = 50
#grid initialization
grid = np.zeros((size,size),dtype=np.uint8)
#start at the center
initpos = (size/2,size/2)
#create the propagation queue
qu = Queue.Queue()
#queue the starting point
qu.put((initpos,initpos))
#the starting point is queued
grid[initpos] = 1
#get the neighbouring grid cells from a position
def get_neighbours(pos):
n1 = (pos[0]+1,pos[1] )
n2 = (pos[0] ,pos[1]+1)
n3 = (pos[0]-1,pos[1] )
n4 = (pos[0] ,pos[1]-1)
return [neigh for neigh in [n1,n2,n3,n4]
if neigh[0] > -1 and \
neigh[0]<size and \
neigh[1] > -1 and \
neigh[1]<size \
]
while(not qu.empty()):
#pop a new element from the queue
#pos is its position in the grid
#parent is the position of the cell which propagated this one
(pos,parent) = qu.get()
#get the neighbouring cells
neighbours = get_neighbours(pos)
#legend for grid values
#0 -> nothing
#1 -> stacked
#2 -> black
#3 -> white
#if any neighbouring cell is black, we could join two branches
has_black = False
for neigh in neighbours:
if neigh != parent and grid[neigh] == 2:
has_black = True
break
if has_black:
#blackening this cell means joining branches, abort
grid[pos] = 3
else:
#this cell does not join branches, blacken it
grid[pos] = 2
#select all valid neighbours for propagation
propag_candidates = [n for n in neighbours if n != parent and grid[n] == 0]
#shuffle to avoid deterministic patterns
random.shuffle(propag_candidates)
#propagate the first two neighbours
for neigh in propag_candidates[:2]:
#queue the neighbour
qu.put((neigh,pos))
#mark it as queued
grid[neigh] = 1
#render image
np.putmask(grid,grid!=2,255)
np.putmask(grid,grid<255,0)
im = Image.fromarray(grid)
im.save('data.png')
```
Here is a result setting `size = 50`

and another one setting `size = 1000`

You can also play with the root of the tree. |
13,141,197 | I have `n*n` grid, where for example `n=10`. I have to fill it with black and white elements. Every black element has to have one, two or three black neighbors. It is not allowed to contain black elements with four or zero neighbors.
How should I build this kind of grid ?
Edit:
To be more specific, it is two-dimensional array built for example with two `for` loops:
```
n = 10
array = [][];
for ( x = 0; x < n; x++ ) {
for ( y = 0; y < n; y++ ) {
array[x][y] = rand(black/white)
}
}
```
This pseudo code builds somethind like:

And what I expect is:
 | 2012/10/30 | [
"https://Stackoverflow.com/questions/13141197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223386/"
] | Maybe this python code could be of some use. Its basic idea is to do some sort of breadth first traversal of the grid, ensuring that the blackened pixels respect the constraint that they have no more than 3 black neighbours. The graph corresponding to the blackened part of the grid is a tree, as your desired result seemed to be.
```
import Queue
import Image
import numpy as np
import random
#size of the problem
size = 50
#grid initialization
grid = np.zeros((size,size),dtype=np.uint8)
#start at the center
initpos = (size/2,size/2)
#create the propagation queue
qu = Queue.Queue()
#queue the starting point
qu.put((initpos,initpos))
#the starting point is queued
grid[initpos] = 1
#get the neighbouring grid cells from a position
def get_neighbours(pos):
n1 = (pos[0]+1,pos[1] )
n2 = (pos[0] ,pos[1]+1)
n3 = (pos[0]-1,pos[1] )
n4 = (pos[0] ,pos[1]-1)
return [neigh for neigh in [n1,n2,n3,n4]
if neigh[0] > -1 and \
neigh[0]<size and \
neigh[1] > -1 and \
neigh[1]<size \
]
while(not qu.empty()):
#pop a new element from the queue
#pos is its position in the grid
#parent is the position of the cell which propagated this one
(pos,parent) = qu.get()
#get the neighbouring cells
neighbours = get_neighbours(pos)
#legend for grid values
#0 -> nothing
#1 -> stacked
#2 -> black
#3 -> white
#if any neighbouring cell is black, we could join two branches
has_black = False
for neigh in neighbours:
if neigh != parent and grid[neigh] == 2:
has_black = True
break
if has_black:
#blackening this cell means joining branches, abort
grid[pos] = 3
else:
#this cell does not join branches, blacken it
grid[pos] = 2
#select all valid neighbours for propagation
propag_candidates = [n for n in neighbours if n != parent and grid[n] == 0]
#shuffle to avoid deterministic patterns
random.shuffle(propag_candidates)
#propagate the first two neighbours
for neigh in propag_candidates[:2]:
#queue the neighbour
qu.put((neigh,pos))
#mark it as queued
grid[neigh] = 1
#render image
np.putmask(grid,grid!=2,255)
np.putmask(grid,grid<255,0)
im = Image.fromarray(grid)
im.save('data.png')
```
Here is a result setting `size = 50`

and another one setting `size = 1000`

You can also play with the root of the tree. | With the size that you show here, you could easily go for a bit of a brute force implementation.
Write a function that checks if you meet the requirements, simply by iterating through all cells and counting neighbors.
After that, do something like this:
```
Start out with a white grid.
Then repeatedly:
pick a random cell
If the cell is white:
make it black
call the grid checking routine.
if the grid became invalid:
color it gray to make sure you don't try this one again
do this until you think it took long enough, or there are no more white cells.
then make all gray cells white.
```
If your grid is large (thousands of pixels), you should probably look for a more efficient algorithm, but for a 10x10 grid this will be calculated in a flash. |
9,120,891 | I am creating table in MySql by using the coomand, `create table person ( id int, name int)`. Actually, I want to create table person if there exists no person table in database. Can anybody help me, how to acive this ? | 2012/02/02 | [
"https://Stackoverflow.com/questions/9120891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060880/"
] | How about `CREATE TABLE IF NOT EXISTS person (id INT, name INT)`? | [The manual page](http://dev.mysql.com/doc/refman/5.1/en/create-table.html) says that you should use
```
CREATE TABLE IF NOT EXISTS person (id int, name int);
``` |
9,120,891 | I am creating table in MySql by using the coomand, `create table person ( id int, name int)`. Actually, I want to create table person if there exists no person table in database. Can anybody help me, how to acive this ? | 2012/02/02 | [
"https://Stackoverflow.com/questions/9120891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060880/"
] | How about `CREATE TABLE IF NOT EXISTS person (id INT, name INT)`? | ```
CREATE TABLE IF NOT EXISTS person (id int, ...);
```
See [manual](http://dev.mysql.com/doc/refman/5.5/en/create-table.html). |
9,120,891 | I am creating table in MySql by using the coomand, `create table person ( id int, name int)`. Actually, I want to create table person if there exists no person table in database. Can anybody help me, how to acive this ? | 2012/02/02 | [
"https://Stackoverflow.com/questions/9120891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060880/"
] | How about `CREATE TABLE IF NOT EXISTS person (id INT, name INT)`? | Use `IF NOT EXISTS`:
create table if not exists person ( id int, name int).
[See MySQL documentation](http://dev.mysql.com/doc/refman/5.1/en/create-table.html) |
9,120,891 | I am creating table in MySql by using the coomand, `create table person ( id int, name int)`. Actually, I want to create table person if there exists no person table in database. Can anybody help me, how to acive this ? | 2012/02/02 | [
"https://Stackoverflow.com/questions/9120891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060880/"
] | [The manual page](http://dev.mysql.com/doc/refman/5.1/en/create-table.html) says that you should use
```
CREATE TABLE IF NOT EXISTS person (id int, name int);
``` | Use `IF NOT EXISTS`:
create table if not exists person ( id int, name int).
[See MySQL documentation](http://dev.mysql.com/doc/refman/5.1/en/create-table.html) |
9,120,891 | I am creating table in MySql by using the coomand, `create table person ( id int, name int)`. Actually, I want to create table person if there exists no person table in database. Can anybody help me, how to acive this ? | 2012/02/02 | [
"https://Stackoverflow.com/questions/9120891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060880/"
] | ```
CREATE TABLE IF NOT EXISTS person (id int, ...);
```
See [manual](http://dev.mysql.com/doc/refman/5.5/en/create-table.html). | Use `IF NOT EXISTS`:
create table if not exists person ( id int, name int).
[See MySQL documentation](http://dev.mysql.com/doc/refman/5.1/en/create-table.html) |
52,509,951 | I have created some npm modules and compile them to:
* commonJS (using `exports.default =`) and
* esm (using `export default`)
I set up my package.json like so:
```
main: "index.cjs.js",
module: "index.esm.js"
```
When I npm install the package and I simple import it like:
```
import myPackage from 'my-package'
```
It will automatically choose the `main` file, not the module.
### My question:
Is there a way to import the `module` file instead when doing `import myPackage from 'my-package'` in a JavaScript file?
### Why I choose the commonJS file for "main":
I noticed that using Node, importing an `esm` file is not possible because of `export default`, it has to be commonJS. I have some simple helper JS functions like [this](https://github.com/mesqueeb/find-and-replace-anything) and [this](https://github.com/mesqueeb/merge-anything), and I would want them to be usable to the widest audience. That's why I chose `cjs` for the `"main"` path in package.json.
### Why I define a separate "module" in package.json:
Lots of famous libraries like Vue.js are already doing this. See further information on this Stackoverflow thread:
[What is the "module" package.json field for?](https://stackoverflow.com/questions/42708484/what-is-the-module-package-json-field-for)
### Why do I want to be able to import the "module" file instead of the "main" file:
There is currently a [bug in Rollup](https://github.com/rollup/rollup/issues/2478) where it will not properly show JSDoc comments when coding after having imported a `cjs` file, but it *does* work when importing a `es` file.
### The workaround I want to avoid:
Just set "main" to the `esm` file in package.json, right? But then all users who are using my packages in Node apps will not be able to use it anymore...
→ I'm really confused about all this as well, but I think I did enough research to make sense of all it. That being said, if anyone knows a better approach or any other advice, please do tell me in the comments down below!! | 2018/09/26 | [
"https://Stackoverflow.com/questions/52509951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2697506/"
] | Just don't use extension for main file and have es6 and CommonJS version as two separate files with the same name and in the same directory, but with different extension, so:
```
index.js // transpiled CommonJS code for old nodejs
index.mjs // es6 module syntax
```
and in `package.json`:
```
{
"main": "index"
}
```
If node is launched with `--experimental-modules` flag, it would use `*.mjs` file, otherwise `*.js`. | Nodejs does not support "module" but does support the newer "exports" spec.
<https://nodejs.org/api/packages.html#exports>
<https://github.com/nodejs/node/blob/v16.14.0/lib/internal/modules/esm/resolve.js#L910>
```
"exports": {
"import": "./main-module.js",
"require": "./main-require.cjs"
},
``` |
43,240,325 | Currently I have a hundreds of thousands of files like so:
```
{
"_id": "1234567890",
"type": "file",
"name": "Demo File",
"file_type": "application/pdf",
"size": "1400",
"timestamp": "1491421149",
"folder_id": "root"
}
```
Currently, I index all the names, and a client can search for files based on the name of the file. These files also have `tags` that need to be associated with the file but they also have specific labels.
An example would be:
```
{
"tags": [
{ "client": "john doe" },
{ "office": "virginia" },
{ "ssn": "1234" }
]
}
```
Is adding the `tags` array to my above file object the ideal solution if I want to be able to search thousands of files with a client of **John Doe**?
The only other solution I can think of is having something an object per tag and having an array of file ID's associated with each tag like so:
```
{
"_id": "11111111",
"type": "tag",
"label": "client",
"items": [
"1234567890",
"1222222222",
"1333333333"
]
}
```
With this being a LOT of objects I need to add tags to, I'd rather do it the most efficient way possible FIRST so I don't have to backtrack in the near future when I start running into issues.
Any guidance would be greatly appreciated. | 2017/04/05 | [
"https://Stackoverflow.com/questions/43240325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2761425/"
] | Your original design, with a tags array, works well with Cloudant Search: <https://console.ng.bluemix.net/docs/services/Cloudant/api/search.html#search>.
With this approach you would define a single design document that will index any tag in the tags array. You do not have to create different views for different tags and you can use the Lucene syntax for queries: <http://lucene.apache.org/core/4_3_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Overview>.
So, using your example, if you have a document that looks like this with tags:
```
{
"_id": "1234567890",
"type": "file",
"name": "Demo File",
"file_type": "application/pdf",
"size": "1400",
"timestamp": "1491421149",
"folder_id": "root",
"tags": [
{ "client": "john doe" },
{ "office": "virginia" },
{ "ssn": "1234" }
]
}
```
You can create a design document that indexes each tag like so:
```
{
"_id": "_design/searchFiles",
"views": {},
"language": "javascript",
"indexes": {
"byTag": {
"analyzer": "standard",
"index": "function (doc) {\n if (doc.type === \"file\" && doc.tags) {\n for (var i=0; i<doc.tags.length; i++) {\n for (var name in doc.tags[i]) {\n index(name, doc.tags[i][name]);\n }\n }\n }\n}"
}
}
}
```
The function looks like this:
```
function (doc) {
if (doc.type === "file" && doc.tags) {
for (var i=0; i<doc.tags.length; i++) {
for (var name in doc.tags[i]) {
index(name, doc.tags[i][name]);
}
}
}
}
```
Then you would search like this:
```
https://your_cloudant_account.cloudant.com/your_db/_design/searchFiles/_search/byTag
?q=client:jack+OR+office:virginia
&include_docs=true
``` | The solution, that comes into my mind would be using map reduce functions.
To do that, you would add the tags to your original document:
```
{
"_id": "1234567890",
"type": "file",
"name": "Demo File",
"file_type": "application/pdf",
"size": "1400",
"timestamp": "1491421149",
"folder_id": "root",
"client": "john",
...
}
```
Afterwards, you can create a design document, that looks like this:
```
{
"_id": "_design/query",
"views": {
"byClient": {
"map": "function(doc) { if(doc.client) { emit(doc.client, doc._id) }}"
}
}
}
```
After the view is processed, you can open it with
`GET /YOURDB/_design/query/_view/byClient?key="john"`
By adding the query parameter `include_docs=true`, the whole document will be returned, instead of the id.
You can also write your tags into an tags attribute, but you have to update the map function to match the new design.
More information about views can be found here:
<http://docs.couchdb.org/en/2.0.0/api/ddoc/views.html> |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | ZFS supports deduplication since last month: <http://blogs.oracle.com/bonwick/en_US/entry/zfs_dedup>
Though I wouldn't call this a "common" filesystem (afaik, it is currently only supported by \*BSD), it is definitely one worth looking at. | NTFS has [single instance storage](http://en.wikipedia.org/wiki/Single-instance_storage). |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | ZFS supports deduplication since last month: <http://blogs.oracle.com/bonwick/en_US/entry/zfs_dedup>
Though I wouldn't call this a "common" filesystem (afaik, it is currently only supported by \*BSD), it is definitely one worth looking at. | It would require a fair amount of work to make this work in a file system. First of all, a user might be creating a copy of a file, planning to edit one copy, while the other remains intact -- so when you eliminate the duplication, the hard link you created that way would have to give COW semantics.
Second, the permissions on a file are often based on the directory into which that file's name is placed. You'd have to ensure that when you create your hidden hard link, that the permissions were correctly applied based on the link, not just the location of the actual content.
Third, users are likely to be upset if they make (say) three copies of a file on physically separate media to ensure against data loss from hardware failure, *then* find out that there was really only one copy of the file, so when that hardware failed, all three copies disappeared.
This strikes me as a bit like a second-system effect -- a solution to a problem long after the problem ceased to exist (or at least matter). With hard drives current running less than $100US/terabyte, I find it hard to believe that this would save most people a whole dollar worth of hard drive space. At that point, it's hard to imagine most people caring much. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | `btrfs` supports online de-duplication of data at the block level. I'd recommend [`duperemove`](https://github.com/markfasheh/duperemove) as an external tool is needed. | It would require a fair amount of work to make this work in a file system. First of all, a user might be creating a copy of a file, planning to edit one copy, while the other remains intact -- so when you eliminate the duplication, the hard link you created that way would have to give COW semantics.
Second, the permissions on a file are often based on the directory into which that file's name is placed. You'd have to ensure that when you create your hidden hard link, that the permissions were correctly applied based on the link, not just the location of the actual content.
Third, users are likely to be upset if they make (say) three copies of a file on physically separate media to ensure against data loss from hardware failure, *then* find out that there was really only one copy of the file, so when that hardware failed, all three copies disappeared.
This strikes me as a bit like a second-system effect -- a solution to a problem long after the problem ceased to exist (or at least matter). With hard drives current running less than $100US/terabyte, I find it hard to believe that this would save most people a whole dollar worth of hard drive space. At that point, it's hard to imagine most people caring much. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | NTFS has [single instance storage](http://en.wikipedia.org/wiki/Single-instance_storage). | It would require a fair amount of work to make this work in a file system. First of all, a user might be creating a copy of a file, planning to edit one copy, while the other remains intact -- so when you eliminate the duplication, the hard link you created that way would have to give COW semantics.
Second, the permissions on a file are often based on the directory into which that file's name is placed. You'd have to ensure that when you create your hidden hard link, that the permissions were correctly applied based on the link, not just the location of the actual content.
Third, users are likely to be upset if they make (say) three copies of a file on physically separate media to ensure against data loss from hardware failure, *then* find out that there was really only one copy of the file, so when that hardware failed, all three copies disappeared.
This strikes me as a bit like a second-system effect -- a solution to a problem long after the problem ceased to exist (or at least matter). With hard drives current running less than $100US/terabyte, I find it hard to believe that this would save most people a whole dollar worth of hard drive space. At that point, it's hard to imagine most people caring much. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | [NetApp](http://www.netapp.com/us/) has supported [deduplication](http://www.netapp.com/us/products/platform-os/dedupe.html) (that's what its called in the storage industry) in the [WAFL](http://en.wikipedia.org/wiki/Write_Anywhere_File_Layout) filesystem (yeah, not your common filesystem) for a [few years](http://www.networkworld.com/news/2007/051507-netapp-deduplication.html) now. This is one of the most important features found in the enterprise filesystems today (and NetApp stands out because they support this on their [primary storage](http://www.enterprisestorageforum.com/sans/features/article.php/3707306) also as compared to other similar products which support it only on their backup or secondary storage; they are too slow for primary storage).
The amount of data which is duplicate in a large enterprise with thousands of users is staggering. A lot of those users store the same documents, source code, etc. across their home directories. [Reports of 50-70% data deduplicated](http://vmblog.com/archive/2007/11/28/netapp-deduplication-delivers-significant-storage-space-savings-for-vmware-environments.aspx) have been seen often, saving [lots of space](http://www.dedupecalc.com/) and [tons of money for large enterprises](http://blogs.netapp.com/drdedupe/2009/06/netapp-dedupication-revisited.html).
All of this means that if you create any common filesystem on a LUN exported by a NetApp filer, then you get deduplication for free, no matter what the filesystem created in that LUN. Cheers. Find out how it works [here](http://www.netapp.com/us/communities/tech-ontap/dedupe-0708.html) and [here](http://blogs.netapp.com/dropzone/2009/06/dedup-for-speed-higher-performance-through-deduplication.html). | `btrfs` supports online de-duplication of data at the block level. I'd recommend [`duperemove`](https://github.com/markfasheh/duperemove) as an external tool is needed. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | ZFS supports deduplication since last month: <http://blogs.oracle.com/bonwick/en_US/entry/zfs_dedup>
Though I wouldn't call this a "common" filesystem (afaik, it is currently only supported by \*BSD), it is definitely one worth looking at. | `btrfs` supports online de-duplication of data at the block level. I'd recommend [`duperemove`](https://github.com/markfasheh/duperemove) as an external tool is needed. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | It would save space, but the time cost is prohibitive. The products you mention are already io bound, so the computational cost of hashing is not a bottleneck. If you hashed at the filesystem level, all io operations which are already slow will get worse. | It would require a fair amount of work to make this work in a file system. First of all, a user might be creating a copy of a file, planning to edit one copy, while the other remains intact -- so when you eliminate the duplication, the hard link you created that way would have to give COW semantics.
Second, the permissions on a file are often based on the directory into which that file's name is placed. You'd have to ensure that when you create your hidden hard link, that the permissions were correctly applied based on the link, not just the location of the actual content.
Third, users are likely to be upset if they make (say) three copies of a file on physically separate media to ensure against data loss from hardware failure, *then* find out that there was really only one copy of the file, so when that hardware failed, all three copies disappeared.
This strikes me as a bit like a second-system effect -- a solution to a problem long after the problem ceased to exist (or at least matter). With hard drives current running less than $100US/terabyte, I find it hard to believe that this would save most people a whole dollar worth of hard drive space. At that point, it's hard to imagine most people caring much. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | NTFS has [single instance storage](http://en.wikipedia.org/wiki/Single-instance_storage). | `btrfs` supports online de-duplication of data at the block level. I'd recommend [`duperemove`](https://github.com/markfasheh/duperemove) as an external tool is needed. |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | ZFS supports deduplication since last month: <http://blogs.oracle.com/bonwick/en_US/entry/zfs_dedup>
Though I wouldn't call this a "common" filesystem (afaik, it is currently only supported by \*BSD), it is definitely one worth looking at. | [NetApp](http://www.netapp.com/us/) has supported [deduplication](http://www.netapp.com/us/products/platform-os/dedupe.html) (that's what its called in the storage industry) in the [WAFL](http://en.wikipedia.org/wiki/Write_Anywhere_File_Layout) filesystem (yeah, not your common filesystem) for a [few years](http://www.networkworld.com/news/2007/051507-netapp-deduplication.html) now. This is one of the most important features found in the enterprise filesystems today (and NetApp stands out because they support this on their [primary storage](http://www.enterprisestorageforum.com/sans/features/article.php/3707306) also as compared to other similar products which support it only on their backup or secondary storage; they are too slow for primary storage).
The amount of data which is duplicate in a large enterprise with thousands of users is staggering. A lot of those users store the same documents, source code, etc. across their home directories. [Reports of 50-70% data deduplicated](http://vmblog.com/archive/2007/11/28/netapp-deduplication-delivers-significant-storage-space-savings-for-vmware-environments.aspx) have been seen often, saving [lots of space](http://www.dedupecalc.com/) and [tons of money for large enterprises](http://blogs.netapp.com/drdedupe/2009/06/netapp-dedupication-revisited.html).
All of this means that if you create any common filesystem on a LUN exported by a NetApp filer, then you get deduplication for free, no matter what the filesystem created in that LUN. Cheers. Find out how it works [here](http://www.netapp.com/us/communities/tech-ontap/dedupe-0708.html) and [here](http://blogs.netapp.com/dropzone/2009/06/dedup-for-speed-higher-performance-through-deduplication.html). |
1,903,416 | Many file storage systems use hashes to avoid duplication of the same file content data (among other reasons), e.g., Git and Dropbox both use SHA256. The file names and dates can be different, but as long as the content gets the same hash generated, it never gets stored more than once.
It seems this would be a sensible thing to do in a OS file system in order to save space. Are there any file systems for Windows or \*nix that do this, or is there a good reason why none of them do?
This would, for the most part, eliminate the need for duplicate file finder utilities, because at that point the only space you would be saving would be for the file entry in the file system, which for most users is not enough to matter.
Edit: Arguably this could go on serverfault, but I feel developers are more likely to understand the issues and trade-offs involved. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] | It would save space, but the time cost is prohibitive. The products you mention are already io bound, so the computational cost of hashing is not a bottleneck. If you hashed at the filesystem level, all io operations which are already slow will get worse. | `btrfs` supports online de-duplication of data at the block level. I'd recommend [`duperemove`](https://github.com/markfasheh/duperemove) as an external tool is needed. |
25,049,770 | So in Java if I have two objects of the same type and I set one of them to the other one(both have the same reference) will the garbage collector be called?
```
ClassName obj1 = new ClassName();
ClassName obj2 = new ClassName();
obj1 = obj2;
```
Will this call garbage collector? The reason I am asking is because I am making a game for android and I can't have the garbage collector being called while the game is running, as I want the best performance. I know that the "new" keyword will call garbage collection but I don't know if this will. Thanks! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25049770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843164/"
] | The constructor ("new" keyword) doesn't call the garbage collector.
Once you assign `obj2` to `obj1`, if there are no more references to the original object referred by `obj1`, the garbage collector can collect it, but you don't know when that would happen. | The object that obj1 *was* pointing to will become **eligible** for garbage collection. You cannot control when the garbage collector is called. |
25,049,770 | So in Java if I have two objects of the same type and I set one of them to the other one(both have the same reference) will the garbage collector be called?
```
ClassName obj1 = new ClassName();
ClassName obj2 = new ClassName();
obj1 = obj2;
```
Will this call garbage collector? The reason I am asking is because I am making a game for android and I can't have the garbage collector being called while the game is running, as I want the best performance. I know that the "new" keyword will call garbage collection but I don't know if this will. Thanks! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25049770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843164/"
] | Simply unreferencing objects does not force the garbage collector to run. It simply means the object is eligible for collection at some point in the future.
There are multiple garbage collection strategies and implementations. Oracle continues to provide new GC strategies through all recent java versions. I am not as familiar with android, but I assume it likely uses even different GC strategies than Oracle. | The object that obj1 *was* pointing to will become **eligible** for garbage collection. You cannot control when the garbage collector is called. |
10,258,144 | How would you design a database to meet the following **two** requirements
Device Addressbook requirements
```
User 1.* Device
Device 1.* Contact
Contact 1.* Email
Contact 1.* Phone
```
Facebook/Twitter Requirements
```
User 1.* SocialNetworkAccount (i.e 1 user can have many facebook accounts)
SocialNetworkAccount 1.* FSocialNetworkAccountFriends (i.e 1 facebook account can have many facebook friends)
```
---
USER is the application user.
Device can be iPhone, ipad, Android, Windows Phone etc | 2012/04/21 | [
"https://Stackoverflow.com/questions/10258144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103264/"
] | Try: `ys2w"` (`ys` takes a motion or text object, and then the character with which you want to surround). | Press `b` first and then `ys2w"` |
10,258,144 | How would you design a database to meet the following **two** requirements
Device Addressbook requirements
```
User 1.* Device
Device 1.* Contact
Contact 1.* Email
Contact 1.* Phone
```
Facebook/Twitter Requirements
```
User 1.* SocialNetworkAccount (i.e 1 user can have many facebook accounts)
SocialNetworkAccount 1.* FSocialNetworkAccountFriends (i.e 1 facebook account can have many facebook friends)
```
---
USER is the application user.
Device can be iPhone, ipad, Android, Windows Phone etc | 2012/04/21 | [
"https://Stackoverflow.com/questions/10258144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103264/"
] | Try: `ys2w"` (`ys` takes a motion or text object, and then the character with which you want to surround). | When using surround commands, I find the most logical solution is to sequence the "marking" and the "surrounding" operations.
Thus, with text objects, I use v2aw to visually mark the two words, then s" for the total of
```
v2aws"
``` |
10,258,144 | How would you design a database to meet the following **two** requirements
Device Addressbook requirements
```
User 1.* Device
Device 1.* Contact
Contact 1.* Email
Contact 1.* Phone
```
Facebook/Twitter Requirements
```
User 1.* SocialNetworkAccount (i.e 1 user can have many facebook accounts)
SocialNetworkAccount 1.* FSocialNetworkAccountFriends (i.e 1 facebook account can have many facebook friends)
```
---
USER is the application user.
Device can be iPhone, ipad, Android, Windows Phone etc | 2012/04/21 | [
"https://Stackoverflow.com/questions/10258144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103264/"
] | Press `b` first and then `ys2w"` | When using surround commands, I find the most logical solution is to sequence the "marking" and the "surrounding" operations.
Thus, with text objects, I use v2aw to visually mark the two words, then s" for the total of
```
v2aws"
``` |
14,884 | can someone with salesforce API integration help me understand the requirements to access a client's Sandbox? I need to access the sandbox and pull data into our MySQL server.
I hired a programmer but he seems to be having a hard time accessing the sandbox and I want to try to help by guiding him in the right direction? Client provided us with the following credentials for the sandbox.
Target URL: <http://xxx.my.salesforce.com>
Username: user@clientdomain.com.beta
password: xxxxxxx
token: gave us a token to access through API.
Your help will be greatly appreciated... | 2013/08/02 | [
"https://salesforce.stackexchange.com/questions/14884",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3451/"
] | In addition to sfdcfox pointing out that you generally login to a sandbox at <https://test.salesforce.com>, there is another option. Since you are using my domain you can login through its URL:
Production URL: `https://mydomain.my.salesforce.com`
Sandbox URL: `https://mydomain--sandboxName.[Instance].my.salesforce.com`. Note that the instance can change when the sandbox is refreshed.
Does the client have it configured so you must login through their custom domain? If not, use <https://test.salesforce.com>. | >
> For access via the API or a client, the user must add their security
> token to the end of their password in order to log in. A security
> token is an automatically-generated key from Salesforce. For example,
> if a user’s password is mypassword, and their security token is
> XXXXXXXXXX, then the user must enter mypasswordXXXXXXXXXX to log in.
>
>
>
Source:
<http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_concepts_security.htm> |
14,884 | can someone with salesforce API integration help me understand the requirements to access a client's Sandbox? I need to access the sandbox and pull data into our MySQL server.
I hired a programmer but he seems to be having a hard time accessing the sandbox and I want to try to help by guiding him in the right direction? Client provided us with the following credentials for the sandbox.
Target URL: <http://xxx.my.salesforce.com>
Username: user@clientdomain.com.beta
password: xxxxxxx
token: gave us a token to access through API.
Your help will be greatly appreciated... | 2013/08/02 | [
"https://salesforce.stackexchange.com/questions/14884",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3451/"
] | >
> For access via the API or a client, the user must add their security
> token to the end of their password in order to log in. A security
> token is an automatically-generated key from Salesforce. For example,
> if a user’s password is mypassword, and their security token is
> XXXXXXXXXX, then the user must enter mypasswordXXXXXXXXXX to log in.
>
>
>
Source:
<http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_concepts_security.htm> | For anyone who is hitting this issue, also be sure to check that you have taken the url from Classic and not Lightning. Below is the difference
<https://test--dev.cs52.my.salesforce.com/services/>
<https://test--dev.lightning.force.com/services/> |
14,884 | can someone with salesforce API integration help me understand the requirements to access a client's Sandbox? I need to access the sandbox and pull data into our MySQL server.
I hired a programmer but he seems to be having a hard time accessing the sandbox and I want to try to help by guiding him in the right direction? Client provided us with the following credentials for the sandbox.
Target URL: <http://xxx.my.salesforce.com>
Username: user@clientdomain.com.beta
password: xxxxxxx
token: gave us a token to access through API.
Your help will be greatly appreciated... | 2013/08/02 | [
"https://salesforce.stackexchange.com/questions/14884",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3451/"
] | In addition to sfdcfox pointing out that you generally login to a sandbox at <https://test.salesforce.com>, there is another option. Since you are using my domain you can login through its URL:
Production URL: `https://mydomain.my.salesforce.com`
Sandbox URL: `https://mydomain--sandboxName.[Instance].my.salesforce.com`. Note that the instance can change when the sandbox is refreshed.
Does the client have it configured so you must login through their custom domain? If not, use <https://test.salesforce.com>. | Here is how I was able to log in to sandbox (C# app)
config
```
<endpoint address="https://test.salesforce.com/services/Soap/c/32.0/<org id goes here>"
binding="basicHttpBinding" bindingConfiguration="SoapBinding1"
contract="sforce.Soap" name="SoapTest" />
```
Make sure that username is appended with ".[sanboxname]".
<https://help.salesforce.com/HTViewHelpDoc?id=data_sandbox_create.htm&language=en_US>
Users can log in to the sandbox at <https://test.salesforce.com> by appending .sandbox\_name to their Salesforce usernames. For example, if a username for a production organization is user1@acme.com, and the sandbox is named “test”, the modified username to log in to the sandbox is user1@acme.com.test.
The password needs to have security token appended. If password = test and token = 123, then you need test123 |
14,884 | can someone with salesforce API integration help me understand the requirements to access a client's Sandbox? I need to access the sandbox and pull data into our MySQL server.
I hired a programmer but he seems to be having a hard time accessing the sandbox and I want to try to help by guiding him in the right direction? Client provided us with the following credentials for the sandbox.
Target URL: <http://xxx.my.salesforce.com>
Username: user@clientdomain.com.beta
password: xxxxxxx
token: gave us a token to access through API.
Your help will be greatly appreciated... | 2013/08/02 | [
"https://salesforce.stackexchange.com/questions/14884",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3451/"
] | In addition to sfdcfox pointing out that you generally login to a sandbox at <https://test.salesforce.com>, there is another option. Since you are using my domain you can login through its URL:
Production URL: `https://mydomain.my.salesforce.com`
Sandbox URL: `https://mydomain--sandboxName.[Instance].my.salesforce.com`. Note that the instance can change when the sandbox is refreshed.
Does the client have it configured so you must login through their custom domain? If not, use <https://test.salesforce.com>. | For anyone who is hitting this issue, also be sure to check that you have taken the url from Classic and not Lightning. Below is the difference
<https://test--dev.cs52.my.salesforce.com/services/>
<https://test--dev.lightning.force.com/services/> |
14,884 | can someone with salesforce API integration help me understand the requirements to access a client's Sandbox? I need to access the sandbox and pull data into our MySQL server.
I hired a programmer but he seems to be having a hard time accessing the sandbox and I want to try to help by guiding him in the right direction? Client provided us with the following credentials for the sandbox.
Target URL: <http://xxx.my.salesforce.com>
Username: user@clientdomain.com.beta
password: xxxxxxx
token: gave us a token to access through API.
Your help will be greatly appreciated... | 2013/08/02 | [
"https://salesforce.stackexchange.com/questions/14884",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/3451/"
] | Here is how I was able to log in to sandbox (C# app)
config
```
<endpoint address="https://test.salesforce.com/services/Soap/c/32.0/<org id goes here>"
binding="basicHttpBinding" bindingConfiguration="SoapBinding1"
contract="sforce.Soap" name="SoapTest" />
```
Make sure that username is appended with ".[sanboxname]".
<https://help.salesforce.com/HTViewHelpDoc?id=data_sandbox_create.htm&language=en_US>
Users can log in to the sandbox at <https://test.salesforce.com> by appending .sandbox\_name to their Salesforce usernames. For example, if a username for a production organization is user1@acme.com, and the sandbox is named “test”, the modified username to log in to the sandbox is user1@acme.com.test.
The password needs to have security token appended. If password = test and token = 123, then you need test123 | For anyone who is hitting this issue, also be sure to check that you have taken the url from Classic and not Lightning. Below is the difference
<https://test--dev.cs52.my.salesforce.com/services/>
<https://test--dev.lightning.force.com/services/> |
408,767 | I am studying tensor calculus and one says that a tensor equality is valid in all systems of coordinates (I think we should rather say "in all system of curvlinear coordinates").
I ask myself if, starting from Cartesian coordinates, we can build an infinity of curvilinear coordinates? For the moment, I know polar, cylindrical, spherical, ellipsoid coordinates but can we construct an infinity of systems?
Are there as many curvilinear coordinates systems as surfaces (or sub-surfaces (called "hypersurfaces?", i.e taking one of coordinates constant) to represent them?
Does the Jacobian between Cartesian and curvilinear coordinates have to respect some specific rules or properties?
**EDIT 1:**
The definition of basis vectors in curviliniear coordinates is :
$\vec{e'\_{k}}=\dfrac{\partial \vec{OM}}{\partial u^{k}}$ with $(u^{k})$ the set of curvilinear coordintates and $\vec{OM}$ the position vector.
We can write the position vector $\vec{OM}=x^{i}\vec{e\_{i}}$, so
$\vec{e'\_{k}}=\dfrac{\partial x^{i}}{\partial u^{k}}\vec{e\_{i}}=J\_{ik}\vec{e\_{i}}$
with $J\_{ik}$ the Jacobian matrix.
The possibily for a Jacobian to be invertible (I mean $det(J)\neq 0$) is a sufficient condition to construct curvilinear coordinates $(u^{k})$ ?
Regards | 2018/05/28 | [
"https://physics.stackexchange.com/questions/408767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/87745/"
] | When someone says (hkl)-oriented anything, they almost always mean the surface normal of the sample is parallel to (hkl). So Si-(111) would mean silicon oriented so the surface normal is along the (111) direction.
If you have a layered material, then having a (001) orientation means the c-axis is perpendicular to the surface of the sample. This is an extremely common orientation for layered crystals for example. | It depends on context. In a surface science experiment, it would be the surface. In experiments on bulk properties, the surface could be irrelevant and rough, but one would measure some property along a cubic axis (or maybe paricularly along the c-axis), like velocity of sound or conductivity, etc. |
30,653,002 | I have a table called `raw_data` that contains a column with a large string of data fields formatted in fixed length sub-strings. I also have a table `table_1` that specifies the column name and the data range in the string for each value. I need to create a SQL `INSERT` statement to move data from `raw_data` into a table called `table_2` with all the columns. `table_1` has about 600 rows, so I am wondering if I can loop through each record to create the SQL statement that inserts the data into `table_2`.
```
Table_1
Name Start Length
AAA 1 2
BBB 3 3
CCC 6 1
```
I haven't learned how to use cursors; the below query could be incorrect. There will be 3 tables involved in this task. `table_1` to look up the name, start, length values. `table_2` will be the table I need to insert the data into. The third table `raw_data` has the column with the sub-strings of each needed value.
```
DECLARE @SQL VARCHAR(200)
DECLARE @NAME VARCHAR(200)
DECLARE @START VARCHAR(200)
DECLARE @LENGTH VARCHAR(200)
SET @NAME = ''
DECLARE Col_Cursor CURSOR FOR
SELECT Name, Start, Length FROM ODS_SIEMENS_LAYOUT WHERE RecordType = '1'
OPEN Col_Cursor
FETCH NEXT FROM Col_Cursor INTO @NAME, @START, @LENGTH
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = @NAME + '=' + 'SUBSTRING(RAW_DATA,' + @START + ',' + @LENGTH + ')'
FETCH NEXT FROM Col_Cursor INTO @NAME, @START, @LENGTH
END
CLOSE Col_Cursor
DEALLOCATE Col_Cursor
```
I need to generate something like the below query:
```
INSERT INTO TABLE_2
'AAA' = SUBSTRING(RAW_DATA,1,2)
'BBB' = SUBSTRING(RAW_DATA,3,3)
'CCC' = SUBSTRING(RAW_DATA,5,2)
........
```
**Can I loop through each column to form the SQL Statement instead of manually coding 600 columns?** | 2015/06/04 | [
"https://Stackoverflow.com/questions/30653002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804925/"
] | Actually, we have a library which does exactly that. We have several sklearn transformators and predictors up and running. It's name is sparkit-learn.
From our examples:
```js
from splearn.rdd import DictRDD
from splearn.feature_extraction.text import SparkHashingVectorizer
from splearn.feature_extraction.text import SparkTfidfTransformer
from splearn.svm import SparkLinearSVC
from splearn.pipeline import SparkPipeline
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
X = [...] # list of texts
y = [...] # list of labels
X_rdd = sc.parallelize(X, 4)
y_rdd = sc.parralelize(y, 4)
Z = DictRDD((X_rdd, y_rdd),
columns=('X', 'y'),
dtype=[np.ndarray, np.ndarray])
local_pipeline = Pipeline((
('vect', HashingVectorizer()),
('tfidf', TfidfTransformer()),
('clf', LinearSVC())
))
dist_pipeline = SparkPipeline((
('vect', SparkHashingVectorizer()),
('tfidf', SparkTfidfTransformer()),
('clf', SparkLinearSVC())
))
local_pipeline.fit(X, y)
dist_pipeline.fit(Z, clf__classes=np.unique(y))
y_pred_local = local_pipeline.predict(X)
y_pred_dist = dist_pipeline.predict(Z[:, 'X'])
```
You can find it [here](https://github.com/lensacom/sparkit-learn). | Im not 100% sure that I am following, but there are a number of partition methods, such as `mapPartitions`. These operators hand you the `Iterator` on each node, and you can do whatever you want to the data and pass it back through a new `Iterator`
```
rdd.mapPartitions(iter=>{
//Spin up something expensive that you only want to do once per node
for(item<-iter) yield {
//do stuff to the items using your expensive item
}
})
``` |
30,653,002 | I have a table called `raw_data` that contains a column with a large string of data fields formatted in fixed length sub-strings. I also have a table `table_1` that specifies the column name and the data range in the string for each value. I need to create a SQL `INSERT` statement to move data from `raw_data` into a table called `table_2` with all the columns. `table_1` has about 600 rows, so I am wondering if I can loop through each record to create the SQL statement that inserts the data into `table_2`.
```
Table_1
Name Start Length
AAA 1 2
BBB 3 3
CCC 6 1
```
I haven't learned how to use cursors; the below query could be incorrect. There will be 3 tables involved in this task. `table_1` to look up the name, start, length values. `table_2` will be the table I need to insert the data into. The third table `raw_data` has the column with the sub-strings of each needed value.
```
DECLARE @SQL VARCHAR(200)
DECLARE @NAME VARCHAR(200)
DECLARE @START VARCHAR(200)
DECLARE @LENGTH VARCHAR(200)
SET @NAME = ''
DECLARE Col_Cursor CURSOR FOR
SELECT Name, Start, Length FROM ODS_SIEMENS_LAYOUT WHERE RecordType = '1'
OPEN Col_Cursor
FETCH NEXT FROM Col_Cursor INTO @NAME, @START, @LENGTH
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = @NAME + '=' + 'SUBSTRING(RAW_DATA,' + @START + ',' + @LENGTH + ')'
FETCH NEXT FROM Col_Cursor INTO @NAME, @START, @LENGTH
END
CLOSE Col_Cursor
DEALLOCATE Col_Cursor
```
I need to generate something like the below query:
```
INSERT INTO TABLE_2
'AAA' = SUBSTRING(RAW_DATA,1,2)
'BBB' = SUBSTRING(RAW_DATA,3,3)
'CCC' = SUBSTRING(RAW_DATA,5,2)
........
```
**Can I loop through each column to form the SQL Statement instead of manually coding 600 columns?** | 2015/06/04 | [
"https://Stackoverflow.com/questions/30653002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804925/"
] | Actually, we have a library which does exactly that. We have several sklearn transformators and predictors up and running. It's name is sparkit-learn.
From our examples:
```js
from splearn.rdd import DictRDD
from splearn.feature_extraction.text import SparkHashingVectorizer
from splearn.feature_extraction.text import SparkTfidfTransformer
from splearn.svm import SparkLinearSVC
from splearn.pipeline import SparkPipeline
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
X = [...] # list of texts
y = [...] # list of labels
X_rdd = sc.parallelize(X, 4)
y_rdd = sc.parralelize(y, 4)
Z = DictRDD((X_rdd, y_rdd),
columns=('X', 'y'),
dtype=[np.ndarray, np.ndarray])
local_pipeline = Pipeline((
('vect', HashingVectorizer()),
('tfidf', TfidfTransformer()),
('clf', LinearSVC())
))
dist_pipeline = SparkPipeline((
('vect', SparkHashingVectorizer()),
('tfidf', SparkTfidfTransformer()),
('clf', SparkLinearSVC())
))
local_pipeline.fit(X, y)
dist_pipeline.fit(Z, clf__classes=np.unique(y))
y_pred_local = local_pipeline.predict(X)
y_pred_dist = dist_pipeline.predict(Z[:, 'X'])
```
You can find it [here](https://github.com/lensacom/sparkit-learn). | If your data set is small (it is possible to load it and train on one worker) you can do something like this:
```scala
def trainModel[T](modelId: Int, trainingSet: List[T]) = {
//trains model with modelId and returns it
}
//fake data
val data = List()
val numberOfModels = 100
val broadcastedData = sc.broadcast(data)
val trainedModels = sc.parallelize(Range(0, numberOfModels))
.map(modelId => (modelId, trainModel(modelId, broadcastedData.value)))
```
I assume you have some list of models (or some how parametrized models) and you can give them ids. Then in function trainModel you pick one depending on id. And as result you will get rdd of pairs of trained models and their ids. |
85,939 | I recently inflated a tire to 50 PSI. The tire/innertube is recommended to inflated to 30 to 80 PSI (standard tires on RadWagon 3). At 50 PSI however, the innertube started bulging to the point that the tire bulged. After deflating it to 30 PSI, the bulge disappeared and the tire now looks normal again. In the past I noticed the same innertube / tire gradually losing air over time.
I'm now somewhat worried that the innertube is damaged and there is a chance of catastrophic failure. Should I go ahead and replace the innertube or is it safe to ride as long as there is no bulge visible at current inflation levels? | 2022/09/19 | [
"https://bicycles.stackexchange.com/questions/85939",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/66844/"
] | If your inner tube didn't pop/rupture then it is fine to reuse.
Instead, your tyre's bead/hook failed to maintain its grab on the rim. Either it wasn't located right before you started inflating, or the hook is weak/damaged.
I would suggest you inspect the tyre and rim where they interface, and try reinstalling the tyre at a different rotation. If it still doesn't hold the rim, you might need a new tyre.
Remember the tube's only job is to hold air. The tyre's job is to restrain the tube. | You probably pinched the tube between tyre and rim. If it still holds air there should be no permanent damage.
I’d deflate everything, then make sure the tyre is seated properly.
What I do after installing tyres (before inflation): Go around the rim, push the tyre bead+sidewall away from the rim along the whole circumference and check that you can’t see the tube. Repeat on the other side. Inflate to a low pressure and repeat the procedure. Then inflate to maximum pressure (or even slightly more) to check that nothing explodes. You might hear a few small “pop” sounds as the tyre bead settles. Release air and inflate to your desired pressure. |
85,939 | I recently inflated a tire to 50 PSI. The tire/innertube is recommended to inflated to 30 to 80 PSI (standard tires on RadWagon 3). At 50 PSI however, the innertube started bulging to the point that the tire bulged. After deflating it to 30 PSI, the bulge disappeared and the tire now looks normal again. In the past I noticed the same innertube / tire gradually losing air over time.
I'm now somewhat worried that the innertube is damaged and there is a chance of catastrophic failure. Should I go ahead and replace the innertube or is it safe to ride as long as there is no bulge visible at current inflation levels? | 2022/09/19 | [
"https://bicycles.stackexchange.com/questions/85939",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/66844/"
] | If your inner tube didn't pop/rupture then it is fine to reuse.
Instead, your tyre's bead/hook failed to maintain its grab on the rim. Either it wasn't located right before you started inflating, or the hook is weak/damaged.
I would suggest you inspect the tyre and rim where they interface, and try reinstalling the tyre at a different rotation. If it still doesn't hold the rim, you might need a new tyre.
Remember the tube's only job is to hold air. The tyre's job is to restrain the tube. | I agree with the other answers that if the inner tube is still intact, it's fine to reuse. The inner tube holds the air in. The tire holds the inner tube.
A tire that bulges is damaged. Discard the tire now.
The strength members within the tire should hold its shape at any pressure. If it bulges, it means that some strength members, e.g., the tire cords, are broken - perhaps corroded, perhaps severed by something puncturing the tire. Increased strain will be put on the adjacent members which will be much more prone to failure. In the bulging section, all the strength is now being provided by the rubber, which will creep over time.
It's good that you witnessed the bulging when not riding. It's saved you from an unexpected blowout. |
85,939 | I recently inflated a tire to 50 PSI. The tire/innertube is recommended to inflated to 30 to 80 PSI (standard tires on RadWagon 3). At 50 PSI however, the innertube started bulging to the point that the tire bulged. After deflating it to 30 PSI, the bulge disappeared and the tire now looks normal again. In the past I noticed the same innertube / tire gradually losing air over time.
I'm now somewhat worried that the innertube is damaged and there is a chance of catastrophic failure. Should I go ahead and replace the innertube or is it safe to ride as long as there is no bulge visible at current inflation levels? | 2022/09/19 | [
"https://bicycles.stackexchange.com/questions/85939",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/66844/"
] | The tube holds the air, the tire holds the pressure. A bulge is entirely a failure of the tire. If the tube remained intact then the tube is fine.
I would not ride a tire that had bulged as you described without identifying why. If, as suggested by @Criggie already, the tire was not seated properly, then reseating will fix it. If on the other hand it's a failure in the tire, there's nothing to stop that failure occurring at lower pressures and while you are riding.
Deflate the tire, work the beads and reinflate to the maximum pressure on the tire side wall. Carefully inspect the tire for bulging, and discard it if you find any.
Personally, I would still be very wary of that tire and probably discard it. If I had no choice, I would run it on the back wheel where a sudden blowout is less likely to cause an accident (Risk of a blow out on the front wheel is almost certain, back wheel is highly probably). | You probably pinched the tube between tyre and rim. If it still holds air there should be no permanent damage.
I’d deflate everything, then make sure the tyre is seated properly.
What I do after installing tyres (before inflation): Go around the rim, push the tyre bead+sidewall away from the rim along the whole circumference and check that you can’t see the tube. Repeat on the other side. Inflate to a low pressure and repeat the procedure. Then inflate to maximum pressure (or even slightly more) to check that nothing explodes. You might hear a few small “pop” sounds as the tyre bead settles. Release air and inflate to your desired pressure. |
85,939 | I recently inflated a tire to 50 PSI. The tire/innertube is recommended to inflated to 30 to 80 PSI (standard tires on RadWagon 3). At 50 PSI however, the innertube started bulging to the point that the tire bulged. After deflating it to 30 PSI, the bulge disappeared and the tire now looks normal again. In the past I noticed the same innertube / tire gradually losing air over time.
I'm now somewhat worried that the innertube is damaged and there is a chance of catastrophic failure. Should I go ahead and replace the innertube or is it safe to ride as long as there is no bulge visible at current inflation levels? | 2022/09/19 | [
"https://bicycles.stackexchange.com/questions/85939",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/66844/"
] | The tube holds the air, the tire holds the pressure. A bulge is entirely a failure of the tire. If the tube remained intact then the tube is fine.
I would not ride a tire that had bulged as you described without identifying why. If, as suggested by @Criggie already, the tire was not seated properly, then reseating will fix it. If on the other hand it's a failure in the tire, there's nothing to stop that failure occurring at lower pressures and while you are riding.
Deflate the tire, work the beads and reinflate to the maximum pressure on the tire side wall. Carefully inspect the tire for bulging, and discard it if you find any.
Personally, I would still be very wary of that tire and probably discard it. If I had no choice, I would run it on the back wheel where a sudden blowout is less likely to cause an accident (Risk of a blow out on the front wheel is almost certain, back wheel is highly probably). | I agree with the other answers that if the inner tube is still intact, it's fine to reuse. The inner tube holds the air in. The tire holds the inner tube.
A tire that bulges is damaged. Discard the tire now.
The strength members within the tire should hold its shape at any pressure. If it bulges, it means that some strength members, e.g., the tire cords, are broken - perhaps corroded, perhaps severed by something puncturing the tire. Increased strain will be put on the adjacent members which will be much more prone to failure. In the bulging section, all the strength is now being provided by the rubber, which will creep over time.
It's good that you witnessed the bulging when not riding. It's saved you from an unexpected blowout. |
85,939 | I recently inflated a tire to 50 PSI. The tire/innertube is recommended to inflated to 30 to 80 PSI (standard tires on RadWagon 3). At 50 PSI however, the innertube started bulging to the point that the tire bulged. After deflating it to 30 PSI, the bulge disappeared and the tire now looks normal again. In the past I noticed the same innertube / tire gradually losing air over time.
I'm now somewhat worried that the innertube is damaged and there is a chance of catastrophic failure. Should I go ahead and replace the innertube or is it safe to ride as long as there is no bulge visible at current inflation levels? | 2022/09/19 | [
"https://bicycles.stackexchange.com/questions/85939",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/66844/"
] | You probably pinched the tube between tyre and rim. If it still holds air there should be no permanent damage.
I’d deflate everything, then make sure the tyre is seated properly.
What I do after installing tyres (before inflation): Go around the rim, push the tyre bead+sidewall away from the rim along the whole circumference and check that you can’t see the tube. Repeat on the other side. Inflate to a low pressure and repeat the procedure. Then inflate to maximum pressure (or even slightly more) to check that nothing explodes. You might hear a few small “pop” sounds as the tyre bead settles. Release air and inflate to your desired pressure. | I agree with the other answers that if the inner tube is still intact, it's fine to reuse. The inner tube holds the air in. The tire holds the inner tube.
A tire that bulges is damaged. Discard the tire now.
The strength members within the tire should hold its shape at any pressure. If it bulges, it means that some strength members, e.g., the tire cords, are broken - perhaps corroded, perhaps severed by something puncturing the tire. Increased strain will be put on the adjacent members which will be much more prone to failure. In the bulging section, all the strength is now being provided by the rubber, which will creep over time.
It's good that you witnessed the bulging when not riding. It's saved you from an unexpected blowout. |
30,209,114 | I am new in cocos2dx android game development, I want to know how can i get the center point of sprite in cocos2dx. I am using the version 3.3.
Let me explain the problem I have one scheduler which call one of my function each 5 seconds. It will change the position of sprint. now over this sprite i want to put another sprite over this sprite exactly center over it. I want to know how to find the center point of running sprint in cocos2dx.
Any help appreciate :)
Thank you | 2015/05/13 | [
"https://Stackoverflow.com/questions/30209114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/593248/"
] | You have two problems:
1. Double underscore attribute names invoke *"name mangling"*, so e.g. `__hp` becomes `_Avatar__hp` (see e.g. [the style guide on inheritance](https://www.python.org/dev/peps/pep-0008/#designing-for-inheritance)).
2. In `check_hasattr` you check for the attribute on `Avatar`, *the class*, rather than `self`, *the instance*.
This would work:
```
class Avatar:
def __init__(self, HP=100, damage=10, defends=10, magic=5):
self.__hp = HP
self.__dam = damage
self.__def = defends
self.__mag = magic
def check_hasattr(self):
print hasattr(self, '_Avatar__hp')
```
However, there is no need to protect access to these attributes (and if there was, you should use a `@property` rather than name mangling); see e.g. [Python name mangling](https://stackoverflow.com/q/7456807/3001761)
Note also that `Class.method(instance)` can be rewritten as `instance.method()`. In this case, though, the simplest approach would be to remove the method altogether and just call `hasattr(warrior, '_Avatar__hp')`. | Your code does not work because you are checking that the class `Avatar` has the attribute `__hp`, which it does not have it, only instances have it, since that attribute is defined in `__init__`. In other words, the `hasattr` should be called on the `self` or `avatar` object, not on the `Avatar` class.
Moreover, double underscores have a special meaning in python, it mangles the name so that is "private" in the sense that cannot be accessed directly. This means that checking that the instance has the attribute `__hp` will not work (you should check `_Avatar__hp` instead)
I changed your code to simplify and remove things that do not make too much sense:
```
class Avatar:
def __init__(self,HP=100):
self._hp = HP
>>> avatar = Avatar()
>>> hasattr(avatar, '_hp')
True
```
Note: if you create an instance of Avatar `avatar = Avatar()`, you should be calling the methods directly on the object `avatar.mymethod()`, and not `Avatar.mymethod(avatar)` |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | Reading this [azure forum](http://feedback.azure.com/forums/223579-azure-preview-portal/suggestions/6178622-ability-to-move-resources-from-one-resource-group) it looks like they have implemented the cmdlet but not all resources support being moved yet.
>
> We have released a new powershell cmdlet to move resources across resource groups. Not all resources have support yet, but the "main" ones do like hosted services, virtual machines & storage accounts.
>
>
>
Looking back at the example I was following, this does only use VM's. So based on this I think websites aren't supported yet. That fact that no error or warning is returned for unsupported resources is a bit poor. | FYI. To move a VM using Move-AzureResourceGroup you need to move the containing cloud service and all its VMs at the same time. For example:
```
Get-AzureResource -ResourceGroupName OriginalResourceGroup | where { $_.ResourceType -match 'Microsoft.ClassicCompute' } | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
By default, the resources in a cloud service are put in a resource group with the same name as the DNS name of the cloud service. |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | Reading this [azure forum](http://feedback.azure.com/forums/223579-azure-preview-portal/suggestions/6178622-ability-to-move-resources-from-one-resource-group) it looks like they have implemented the cmdlet but not all resources support being moved yet.
>
> We have released a new powershell cmdlet to move resources across resource groups. Not all resources have support yet, but the "main" ones do like hosted services, virtual machines & storage accounts.
>
>
>
Looking back at the example I was following, this does only use VM's. So based on this I think websites aren't supported yet. That fact that no error or warning is returned for unsupported resources is a bit poor. | For some reason, Azure PowerShell Version 1.0 has trouble moving over web apps from one Resource Group to another. If you follow the instrctions below, you will be able to move the web app over via powershell.
Download Azure PowerShell Version 1. The below instructions only work for this version. Type the commands below in order.
```
1) **Login-AzureRmAccount** (a login window will pop up asking for your azure credentials, type them in)
2) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName"** (if you are moving over a website, you will see 2 files, you need the one that is a resource type of Microsoft.Web/sites)
3) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
4) Assign value 3 to a variable of your name choice. I Chose $a, so **$a = Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
5) **Move-AzureRmResource -DestinationResourceGroup "DestinationResourceGroup" -ResourceId $a.ResourceId**
6) It will ask you if you are sure type "Y" and hit enter.
``` |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | Though not all resources are currently supported, I understand the current version - 0.9.1 - does have a bug which means that even a supported resource may not be moved with the symptoms as seen by the author of the question. I understand this is being worked on for the next release, but in the interim (as a temp. work around) the previous powershell cmdlets release of 2 versions ago should work fine. <https://github.com/Azure/azure-powershell/releases> | FYI. To move a VM using Move-AzureResourceGroup you need to move the containing cloud service and all its VMs at the same time. For example:
```
Get-AzureResource -ResourceGroupName OriginalResourceGroup | where { $_.ResourceType -match 'Microsoft.ClassicCompute' } | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
By default, the resources in a cloud service are put in a resource group with the same name as the DNS name of the cloud service. |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | Though not all resources are currently supported, I understand the current version - 0.9.1 - does have a bug which means that even a supported resource may not be moved with the symptoms as seen by the author of the question. I understand this is being worked on for the next release, but in the interim (as a temp. work around) the previous powershell cmdlets release of 2 versions ago should work fine. <https://github.com/Azure/azure-powershell/releases> | For some reason, Azure PowerShell Version 1.0 has trouble moving over web apps from one Resource Group to another. If you follow the instrctions below, you will be able to move the web app over via powershell.
Download Azure PowerShell Version 1. The below instructions only work for this version. Type the commands below in order.
```
1) **Login-AzureRmAccount** (a login window will pop up asking for your azure credentials, type them in)
2) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName"** (if you are moving over a website, you will see 2 files, you need the one that is a resource type of Microsoft.Web/sites)
3) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
4) Assign value 3 to a variable of your name choice. I Chose $a, so **$a = Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
5) **Move-AzureRmResource -DestinationResourceGroup "DestinationResourceGroup" -ResourceId $a.ResourceId**
6) It will ask you if you are sure type "Y" and hit enter.
``` |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | The original issue is fixed in the [0.9.4 release](https://github.com/Azure/azure-powershell/releases/tag/0.9.4-June2015). I just tried and it works. | FYI. To move a VM using Move-AzureResourceGroup you need to move the containing cloud service and all its VMs at the same time. For example:
```
Get-AzureResource -ResourceGroupName OriginalResourceGroup | where { $_.ResourceType -match 'Microsoft.ClassicCompute' } | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
By default, the resources in a cloud service are put in a resource group with the same name as the DNS name of the cloud service. |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | FYI. To move a VM using Move-AzureResourceGroup you need to move the containing cloud service and all its VMs at the same time. For example:
```
Get-AzureResource -ResourceGroupName OriginalResourceGroup | where { $_.ResourceType -match 'Microsoft.ClassicCompute' } | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
By default, the resources in a cloud service are put in a resource group with the same name as the DNS name of the cloud service. | For some reason, Azure PowerShell Version 1.0 has trouble moving over web apps from one Resource Group to another. If you follow the instrctions below, you will be able to move the web app over via powershell.
Download Azure PowerShell Version 1. The below instructions only work for this version. Type the commands below in order.
```
1) **Login-AzureRmAccount** (a login window will pop up asking for your azure credentials, type them in)
2) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName"** (if you are moving over a website, you will see 2 files, you need the one that is a resource type of Microsoft.Web/sites)
3) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
4) Assign value 3 to a variable of your name choice. I Chose $a, so **$a = Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
5) **Move-AzureRmResource -DestinationResourceGroup "DestinationResourceGroup" -ResourceId $a.ResourceId**
6) It will ask you if you are sure type "Y" and hit enter.
``` |
30,123,326 | I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
```
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
```
Or:
```
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
```
Or:
just `Move-AzureResource`, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to `$DebugPreference = "Continue"` I got only the following:
```
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my@account.tld'...
```
Please note that I'm able to create a new resource group (`New-AzureResourceGroup`), list resource groups (`Get-AzureResourceGroup`), list resources (`Get-AzureResource`), etc.
Note: you have to call `Switch-AzureMode AzureResourceManager` before you can use the cmdlets. The authentication is done by `Add-AzureAccount`.
Articles I've been referring to:
* [Moving resources between Azure Resource Groups](http://blog.kloud.com.au/2015/03/24/moving-resources-between-azure-resource-groups/)
* [Move-AzureResource](https://msdn.microsoft.com/en-us/library/dn986795.aspx?f=255&MSPPError=-2147217396)
* [Using Azure PowerShell with Azure Resource Manager](http://azure.microsoft.com/en-in/documentation/articles/powershell-azure-resource-manager/)
* [GitHub - Using Azure PowerShell with Azure Resource Manager](https://github.com/Azure/azure-content/blob/master/articles/powershell-azure-resource-manager.md) | 2015/05/08 | [
"https://Stackoverflow.com/questions/30123326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332034/"
] | The original issue is fixed in the [0.9.4 release](https://github.com/Azure/azure-powershell/releases/tag/0.9.4-June2015). I just tried and it works. | For some reason, Azure PowerShell Version 1.0 has trouble moving over web apps from one Resource Group to another. If you follow the instrctions below, you will be able to move the web app over via powershell.
Download Azure PowerShell Version 1. The below instructions only work for this version. Type the commands below in order.
```
1) **Login-AzureRmAccount** (a login window will pop up asking for your azure credentials, type them in)
2) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName"** (if you are moving over a website, you will see 2 files, you need the one that is a resource type of Microsoft.Web/sites)
3) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
4) Assign value 3 to a variable of your name choice. I Chose $a, so **$a = Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
5) **Move-AzureRmResource -DestinationResourceGroup "DestinationResourceGroup" -ResourceId $a.ResourceId**
6) It will ask you if you are sure type "Y" and hit enter.
``` |
62,272,090 | I am very confused why this is displaying the default image instead of a round blue circle over New York. Any insight about this as well as when the default image is used will be greatly appreciated.
```
import UIKit
import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupMapview()
}
func setupMapview(){
let mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 40.74699, longitude: -73.98742), zoomLevel: 9, animated: false)
view.addSubview(mapView)
let annotation = MGLPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: 40.77014, longitude: -73.97480)
mapView.addAnnotation(annotation)
mapView.delegate = self
}
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
print("CORDINATE")
print(annotation.coordinate)
if annotation is MGLPointAnnotation {
print("SET\n\n\n")
let av = RoundedAnnotationView(annotation: annotation, reuseIdentifier: "ResuseIdentifier")
av.configure()
return av
}
return nil
}
}
class RoundedAnnotationView: MGLAnnotationView{
func configure(){
backgroundColor = .blue
layer.cornerRadius = 24
clipsToBounds = true
}
}
```
Output:
[iPhone\_Screen](https://i.stack.imgur.com/Dv7mN.png)
[print\_statements](https://i.stack.imgur.com/Q7ZVB.png) | 2020/06/08 | [
"https://Stackoverflow.com/questions/62272090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11767661/"
] | Both embedding techniques, traditional **word embedding** (e.g. word2vec, Glove) and **contextual embedding** (e.g. ELMo, BERT), aim to learn a **continuous (vector) representation** for each word in the documents. Continuous representations can be used in downstream machine learning tasks.
Traditional **word embedding techniques** learn a global word embedding. They first build a global vocabulary using unique words in the documents by ignoring the meaning of words in different context. Then, similar representations are learnt for the words appeared more frequently close each other in the documents. The problem is that in such word representations the words' contextual meaning (the meaning derived from the words' surroundings), is ignored. For example, **only one** representation is learnt for "left" in sentence "I **left** my phone on the **left** side of the table." However, "left" has two different meanings in the sentence, and needs to have two different representations in the embedding space.
On the other hand, **contextual embedding methods** are used to learn **sequence-level semantics** by considering the sequence of all words in the documents. Thus, such techniques learn **different representations** for **polysemous words**, e.g. "left" in example above, based on their context. | Word embeddings and contextual embeddings are slightly different.
While both word embeddings and contextual embeddings are obtained from the models using unsupervised learning, there are some differences.
Word embeddings provided by `word2vec` or `fastText` has a vocabulary (dictionary) of words. The elements of this vocabulary (or dictionary) are words and its corresponding word embeddings. Hence, given a word, its embeddings is always the same in whichever sentence it occurs. Here, the pre-trained word embeddings are `static`.
However, contextual embeddings (are generally obtained from the transformer based models). The emeddings are obtained from a model by passing the entire sentence to the pre-trained model. Note that, here there is a vocabulary of words, but the vocabulary will not contain the contextual embeddings. The embeddings generated for each word depends on the other words in a given sentence. (The other words in a given sentence is referred as `context`. The transformer based models work on attention mechanism, and attention is a way to look at the relation between a word with its neighbors). Thus, given a word, it will not have a static embeddings, but the embeddings are dynamically generated from pre-trained (or fine-tuned) model.
For example, consider the two sentences:
1. I will show you a valid point of reference and talk to the point.
2. Where have you placed the point.
Now, the word embeddings from a pre-trained embeddings such as word2vec, the embeddings for the word `'point'` is same for both of its occurrences in example 1 and also the same for the word `'point'` in example 2. (all three occurrences has same embeddings).
While, the embeddings from BERT or ELMO or any such transformer based models, the the two occurrences of the word `'point'` in example 1 will have different embeddings. Also, the word `'point'` occurring in example 2 will have different embeddings than the ones in example 1. |
29,355,454 | Does anyone know if Telerik's NativeScript functions with the iOS Keychain and wherever Android would store an applications encryption certificates? Doing some research on cross-platform solutions and securely storing encryption certificates. | 2015/03/30 | [
"https://Stackoverflow.com/questions/29355454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287720/"
] | The interesting thing is that as long as the API has it;
(i.e. Android: <https://developer.android.com/training/articles/keystore.html> and iOS: <https://developer.apple.com/library/ios/documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html>) then you can access it via NativeScript.
At this moment (2015/04/25) only the basics are built cross-platform as this is a very new platform.
They do not have any keychain code built for either platform. However, with that said I just build a fully functional sqlite library (android side) in a couple days; once I understood how NativeScript interfaces with Android. I am guessing it will take me a couple more days to do the iOS side. Then my sqlite will be cross platform and I can code my apps to use much simpler code. So if you have done any work on either platform; then creating the abstraction libraries that you need should not be very difficult. | Yes, you can sign your apps, see
tns build android -h
tns build ios -h |
66,148,757 | In below code , I am trying to filter masterObject list having sublist values of 2 or 3 or 4 . I am not able to filter the list even with single element. Can you guys help me in pointing out what lamba function needs to be used to get expectedList as output
```
fun main() {
data class ChildObject(var id: Int, var subList: List<Int>)
data class MasterObject(var identifier: Int, var listObject: List<ChildObject>)
val initialList = arrayListOf<MasterObject>(
MasterObject(100, arrayListOf(ChildObject(101, arrayListOf(10, 2, 13)), ChildObject(102, arrayListOf(14, 15, 6)), ChildObject(103, arrayListOf(17, 20, 9)))),
MasterObject(200, arrayListOf(ChildObject(201, arrayListOf(11, 40, 6)), ChildObject(202, arrayListOf(4, 5, 20)), ChildObject(203, arrayListOf(7, 13, 9)))),
MasterObject(300, arrayListOf(ChildObject(301, arrayListOf(1, 2, 30)), ChildObject(302, arrayListOf(4, 15, 60)), ChildObject(303, arrayListOf(7, 20, 90)))))
/*actual goal is to print final list of master objects containing any of (2,3,4) elements in listobject. for now I am stuck with filtering single element */
val expectedList = arrayListOf<MasterObject>(
MasterObject(100, arrayListOf(ChildObject(101, arrayListOf(10, 2, 13)))),
MasterObject(200, arrayListOf(ChildObject(202, arrayListOf(4, 5, 20)))),
MasterObject(300, arrayListOf(ChildObject(301, arrayListOf(1, 2, 30)),ChildObject(302, arrayListOf(4, 15, 60)))))
/*not able apply 2 filters and resulting in error*/
val finalListWithFilter = initialList.filter { masterObject ->
masterObject.listObject.filter { childObject -> childObject.subList.contains(2) }
}
/* prints entire childObject list for any or doesnt print any list for all*/
val finalListWithAny = initialList.filter { masterObject ->
masterObject.listObject.any { childObject ->
childObject.subList.contains(2)
}
}
/*prints list childObject but I need list of masterObject*/
val finalListWithMap = initialList.flatMap { masterObject ->
masterObject.listObject.filter { childObject ->
childObject.subList.contains(2)
}
}
println(finalListWithAny)
print(finalListWithMap)
}
```
Thanks | 2021/02/11 | [
"https://Stackoverflow.com/questions/66148757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1403174/"
] | Your assumption of how the filtering works is wrong in this case. Filtering just helps you to narrow down the list of objects. However the contents (the objects themselves) will always look the same regardless of what you filter. This is also the reason why filtering for child elements with id 2, 3 and 4 will basically result in the input list, because each master object has such an element.
As your data class does not contain mutable lists, I assume that a copy of master objects is ok and therefore the following could be a working solution for you:
```
val childrenMatchingIds = listOf(2, 3, 4) // the child id's you are interested in
val result = initialList.mapNotNull { master -> // [1]
master.listObject.filter { child -> childrenMatchingIds.any(child.subList::contains) } // [2]
.takeUnless { it.isEmpty() } // [3]
?.let { // [4]
master.copy(listObject = it) // [5]
}
}
```
1. [`mapNotNull`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-not-null.html) ensures that we skip those master objects later where no children match
2. [`filter`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter.html) will return us those children where any child is matching the id (therefore [`any`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/any.html) within the filter). Note: this list is detached from the original master object. However its contents are valid references to the same objects of the master object's `listObject`-list.
3. here we ensure that if this list is empty, we will continue with a `null` instead (see [scope functions `takeIf` / `takeUnless`](https://kotlinlang.org/docs/scope-functions.html#takeif-and-takeunless))
4. which we then choose to ignore if it is `null` (see [safe calls `?.`](https://kotlinlang.org/docs/null-safety.html#safe-calls))
5. finally we copy (see [Data classes - Copying](https://kotlinlang.org/docs/data-classes.html#copying)) the old infos to a completely new (detached - i.e. not the same anymore, but may contain same references) master object, which contains all the details the old one contained, whose references in the `listObject` are the same as those from the old master object, but is filtered.
Back to point 1 & 4: as we filtered out empty children (therefore getting `null` from the `takeIf`), the `mapNotNull` will filter out those master objects that do not contain our children.
Feel free to ask clarifying questions if anything is still unclear.
And yes: there are probably also a dozen of other variants how you could accomplish this. As long as you require a filtered representation of the master object, you will however always require a new master object for that. If your lists were mutable and you rather wanted to remove elements, the solution would be completely different (with all its pros and cons). | This works:
```
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
println("Hello, world!!!")
val list = listOf(
mapOf( "id" to 100, "name" to "xyz", "sublist" to listOf(2, 3, 4 )),
mapOf( "id" to 101, "name" to "abc", "sublist" to listOf(1, 5, 10 )),
mapOf( "id" to 102, "name" to "qwerty", "sublist" to listOf(2, 6, 12 ))
)
val result = list.filter {
(it["sublist"] as List<Int>).any { it == 2 }
}
println(result)
data class ChildObject(var id: Int, var subList: List<Int>)
data class MasterObject(var identifier: Int, var listObject: List<ChildObject>)
val initialList = arrayListOf<MasterObject>(
MasterObject(100, arrayListOf(ChildObject(101, arrayListOf(1, 2, 3)), ChildObject(102, arrayListOf(4, 5, 6)), ChildObject(103, arrayListOf(7, 2, 9)))),
MasterObject(200, arrayListOf(ChildObject(201, arrayListOf(1, 4, 6)), ChildObject(202, arrayListOf(4, 5, 2)), ChildObject(203, arrayListOf(7, 3, 9)))),
MasterObject(300, arrayListOf(ChildObject(301, arrayListOf(1, 2, 3)), ChildObject(302, arrayListOf(4, 5, 6)), ChildObject(303, arrayListOf(7, 2, 9)))))
/*actual goal is to print final list of master objects containing any of (2,3,4) elements in listobject. for now I am stuck with filtering single element */
val expectedList = arrayListOf<MasterObject>(
MasterObject(100, arrayListOf(ChildObject(101, arrayListOf(1, 2, 3)), ChildObject(103, arrayListOf(7, 2, 9)))),
MasterObject(200, arrayListOf(ChildObject(202, arrayListOf(4, 5, 2)))),
MasterObject(300, arrayListOf(ChildObject(301, arrayListOf(1, 4, 3)))))
var resultList = initialList.filter { master ->
master.listObject.filter { child ->
child.subList.any { it == 2 } || child.subList.any { it == 3 } || child.subList.any { it == 4 }
}.size > 0
}
print(resultList)
}
```
Output:
```
Hello, world!!!
[{id=100, name=xyz, sublist=[2, 3, 4]}, {id=102, name=qwerty, sublist=[2, 6, 12]}]
[MasterObject(identifier=100, listObject=[ChildObject(id=101, subList=[1, 2, 3]), ChildObject(id=102, subList=[4, 5, 6]), ChildObject(id=103, subList=[7, 2, 9])]), MasterObject(identifier=200, listObject=[ChildObject(id=201, subList=[1, 4, 6]), ChildObject(id=202, subList=[4, 5, 2]), ChildObject(id=203, subList=[7, 3, 9])]), MasterObject(identifier=300, listObject=[ChildObject(id=301, subList=[1, 2, 3]), ChildObject(id=302, subList=[4, 5, 6]), ChildObject(id=303, subList=[7, 2, 9])])]
``` |
2,467,518 | Is the [Erdős–Faber–Lovász Conjecture](https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Faber%E2%80%93Lov%C3%A1sz_conjecture) open still? According to [Wikipedia](https://en.wikipedia.org) it is unsolved still, but I think this is not hard to solve this conjecture.
>
> **Conjecture:** If $n$ complete graphs, each having exactly $n$ vertices, have the property that every pair of complete graphs has at most one shared vertex, then the union of the graphs can be colored with $n$ colors.
>
>
> **My attempt:** Consider the, $n-1$ complete graphs $K\_n$ which all has a common vertex, say $u$. then this graph can be colored with $n$ colors. by choosing $n-1$ vertices (one from each graph $K\_n\backslash \{u\}$) by different color and construct a graph with this vertices and a new vertex, say $v$. we can assign to $v$ color of $u$. Why this is not correct or maybe I don't understand the problem ?
>
>
> | 2017/10/11 | [
"https://math.stackexchange.com/questions/2467518",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272127/"
] | I don't think you understand the problem. It's not just $n-1$ complete graphs with one vertex common to all of them. Each pair of complete graphs can have at most one shared vertex, but different pairs can have different shared vertices. So for $n=4$ you could have the graph pictured: the $K\_4$s are circled and the five central vertices are each shared by two of the complete graphs. As $n$ increases, the number of possible configurations increases rapidly.
[](https://i.stack.imgur.com/0TPdA.png) | Looks likes you missed the point regarding common vertices. At most ONE common vertex is permissible for each pair of k-graph. So each graph among the k, can have up to k-1 common vertices in common with one or another of the remaining k-1 egraphs.
Since no pair of graphs have more than one vertex in common, total number of edges remains the same as taken separately for each graph viz K*k*(k-1)/2 edges in the Union of graphs.
Trust this will help you in making fresh efforts. |
2,467,518 | Is the [Erdős–Faber–Lovász Conjecture](https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Faber%E2%80%93Lov%C3%A1sz_conjecture) open still? According to [Wikipedia](https://en.wikipedia.org) it is unsolved still, but I think this is not hard to solve this conjecture.
>
> **Conjecture:** If $n$ complete graphs, each having exactly $n$ vertices, have the property that every pair of complete graphs has at most one shared vertex, then the union of the graphs can be colored with $n$ colors.
>
>
> **My attempt:** Consider the, $n-1$ complete graphs $K\_n$ which all has a common vertex, say $u$. then this graph can be colored with $n$ colors. by choosing $n-1$ vertices (one from each graph $K\_n\backslash \{u\}$) by different color and construct a graph with this vertices and a new vertex, say $v$. we can assign to $v$ color of $u$. Why this is not correct or maybe I don't understand the problem ?
>
>
> | 2017/10/11 | [
"https://math.stackexchange.com/questions/2467518",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272127/"
] | I don't think you understand the problem. It's not just $n-1$ complete graphs with one vertex common to all of them. Each pair of complete graphs can have at most one shared vertex, but different pairs can have different shared vertices. So for $n=4$ you could have the graph pictured: the $K\_4$s are circled and the five central vertices are each shared by two of the complete graphs. As $n$ increases, the number of possible configurations increases rapidly.
[](https://i.stack.imgur.com/0TPdA.png) | On January 2021 The problem was settled for sufficiently large values of $n$ <https://arxiv.org/abs/2101.04698> |
2,467,518 | Is the [Erdős–Faber–Lovász Conjecture](https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Faber%E2%80%93Lov%C3%A1sz_conjecture) open still? According to [Wikipedia](https://en.wikipedia.org) it is unsolved still, but I think this is not hard to solve this conjecture.
>
> **Conjecture:** If $n$ complete graphs, each having exactly $n$ vertices, have the property that every pair of complete graphs has at most one shared vertex, then the union of the graphs can be colored with $n$ colors.
>
>
> **My attempt:** Consider the, $n-1$ complete graphs $K\_n$ which all has a common vertex, say $u$. then this graph can be colored with $n$ colors. by choosing $n-1$ vertices (one from each graph $K\_n\backslash \{u\}$) by different color and construct a graph with this vertices and a new vertex, say $v$. we can assign to $v$ color of $u$. Why this is not correct or maybe I don't understand the problem ?
>
>
> | 2017/10/11 | [
"https://math.stackexchange.com/questions/2467518",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272127/"
] | On January 2021 The problem was settled for sufficiently large values of $n$ <https://arxiv.org/abs/2101.04698> | Looks likes you missed the point regarding common vertices. At most ONE common vertex is permissible for each pair of k-graph. So each graph among the k, can have up to k-1 common vertices in common with one or another of the remaining k-1 egraphs.
Since no pair of graphs have more than one vertex in common, total number of edges remains the same as taken separately for each graph viz K*k*(k-1)/2 edges in the Union of graphs.
Trust this will help you in making fresh efforts. |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | You've already got other valid answers, but my preferred form would be:
```
Select T.course_id
From course as T
Where (Select Count(*)
From section as R
Where T.course_id = R.course_id and R.year = 2009) = 1;
``` | Just rewrite your `unique` query as a subquery to join to `course`:
```
select t.course_id
from course as t
join(
select course_id
from section
where year=2009
group by course_id
having count(1)=1
)r
on (t.course_id=r.course_id);
``` |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | Just rewrite your `unique` query as a subquery to join to `course`:
```
select t.course_id
from course as t
join(
select course_id
from section
where year=2009
group by course_id
having count(1)=1
)r
on (t.course_id=r.course_id);
``` | The UNIQUE construct returns *true* if the subquery is empty. Therefore, the correct equivalent to this query is (notice the <=):
```
SELECT
T.course_id
FROM
course as T
WHERE
1 <= (
SELECT
COUNT(*)
FROM
section AS R
WHERE
T.course_id = R.course_id
AND
R.year = 2009
);
```
P.S. This is an example in the textbook *Database System Concepts* (6th ed.). The example is given on p. 94 and the equivalent statement I mentioned is given on p. 95. |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | Just rewrite your `unique` query as a subquery to join to `course`:
```
select t.course_id
from course as t
join(
select course_id
from section
where year=2009
group by course_id
having count(1)=1
)r
on (t.course_id=r.course_id);
``` | There is a mistake on a book example.
See: <https://www.db-book.com/db6/errata-dir/errata-part1.pdf> (No.11)
A collect workaround for unique query:
```
SELECT T.course_id
FROM course as T
WHERE (
SELECT count(R.course_id)
FROM section as R
WHERE T.course_id = R.course_id AND R.year = 2019
) <= 1;
``` |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | You've already got other valid answers, but my preferred form would be:
```
Select T.course_id
From course as T
Where (Select Count(*)
From section as R
Where T.course_id = R.course_id and R.year = 2009) = 1;
``` | Off the top of my head:
```
Select T.course_id
From course as T
Where exists(select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009
group by course_id having count(*)=1);
``` |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | Off the top of my head:
```
Select T.course_id
From course as T
Where exists(select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009
group by course_id having count(*)=1);
``` | The UNIQUE construct returns *true* if the subquery is empty. Therefore, the correct equivalent to this query is (notice the <=):
```
SELECT
T.course_id
FROM
course as T
WHERE
1 <= (
SELECT
COUNT(*)
FROM
section AS R
WHERE
T.course_id = R.course_id
AND
R.year = 2009
);
```
P.S. This is an example in the textbook *Database System Concepts* (6th ed.). The example is given on p. 94 and the equivalent statement I mentioned is given on p. 95. |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | Off the top of my head:
```
Select T.course_id
From course as T
Where exists(select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009
group by course_id having count(*)=1);
``` | There is a mistake on a book example.
See: <https://www.db-book.com/db6/errata-dir/errata-part1.pdf> (No.11)
A collect workaround for unique query:
```
SELECT T.course_id
FROM course as T
WHERE (
SELECT count(R.course_id)
FROM section as R
WHERE T.course_id = R.course_id AND R.year = 2019
) <= 1;
``` |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | You've already got other valid answers, but my preferred form would be:
```
Select T.course_id
From course as T
Where (Select Count(*)
From section as R
Where T.course_id = R.course_id and R.year = 2009) = 1;
``` | The UNIQUE construct returns *true* if the subquery is empty. Therefore, the correct equivalent to this query is (notice the <=):
```
SELECT
T.course_id
FROM
course as T
WHERE
1 <= (
SELECT
COUNT(*)
FROM
section AS R
WHERE
T.course_id = R.course_id
AND
R.year = 2009
);
```
P.S. This is an example in the textbook *Database System Concepts* (6th ed.). The example is given on p. 94 and the equivalent statement I mentioned is given on p. 95. |
9,572,930 | Using the schemas member(memb\_no, name, age), book(isbn, title, authors, publisher), and borrowed(memb\_no, isbn, date), I have the following query. Only problem is I'm not supposed to use the unique construct. How can I re-write this without using the unique construct?
```
Select T.course_id
From course as T
Where unique (select R.course_id
From section as R
Where T.course_id = R.course_id and R.year = 2009);
``` | 2012/03/05 | [
"https://Stackoverflow.com/questions/9572930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044858/"
] | You've already got other valid answers, but my preferred form would be:
```
Select T.course_id
From course as T
Where (Select Count(*)
From section as R
Where T.course_id = R.course_id and R.year = 2009) = 1;
``` | There is a mistake on a book example.
See: <https://www.db-book.com/db6/errata-dir/errata-part1.pdf> (No.11)
A collect workaround for unique query:
```
SELECT T.course_id
FROM course as T
WHERE (
SELECT count(R.course_id)
FROM section as R
WHERE T.course_id = R.course_id AND R.year = 2019
) <= 1;
``` |
16,185,869 | I m working on canvas. Here I just want to draw some geometric figures on canvas which may be resized according to the touch\_move positions. By figures , I just meant triangle,rectangle,circle and some polygons. Is there a way to achieve this? . I haven't seen such apps which can draw these figures over canvas. So this seems to be complicated.. Thanks in advance | 2013/04/24 | [
"https://Stackoverflow.com/questions/16185869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1986827/"
] | See [this](http://www.betaful.com/2012/01/programmatic-shapes-in-android/) link.
If your application does not require a significant amount of processing or frame-rate speed (perhaps for a chess game, a snake game, or another slowly-animated application), then you should consider creating a custom View component and drawing with a Canvas in `View.onDraw()`. The most convenient aspect of doing so is that the Android framework will provide you with a pre-defined Canvas to which you will place your drawing calls. | I'm sure you can find some open-sourced out-of-the-box solutions for this if you tried a little.
If you actually want to learn something you should read the tutorials of per example;
-[Custom Views](http://developer.android.com/training/custom-views/index.html)
-[OpenGL](http://developer.android.com/training/graphics/opengl/index.html)
After doing the tutorials, you'll have 2 ways to draw basic shapes, a triangle and a circle I believe, already done. |
47,604,622 | I am trying to update date fields that are NULL to have "0000-00-00" in them. I am trying:
```
UPDATE `results` SET `date_of_birth` = '0000-00-00' WHERE `date_of_birth` IS NULL
```
But when I simulate it, it says 0 matched records. However, if I run this, it brings back 31 records:
```
SELECT * FROM `results` WHERE `date_of_birth` IS NULL
```
Seems to be contradiction, or I am just missing something.
Any ideas? | 2017/12/02 | [
"https://Stackoverflow.com/questions/47604622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3304303/"
] | You can not use any of the statement to update this which not contain a proper date value if this column has type date.
```
UPDATE `results` SET `date_of_birth` = '' WHERE `date_of_birth` = '' or cast(`date_of_birth` as date) is null or `date_of_birth` is null;
#With no strict mode.
UPDATE `results` SET `date_of_birth` = '0000-00-00' WHERE `date_of_birth` = '' or cast(`date_of_birth` as date) is null or `date_of_birth` is null;
``` | Check your sql.mode
**To Check MYSQL mode**
```
SELECT @@GLOBAL.sql_mode global, @@SESSION.sql_mode session
```
>
> Strict mode affects whether the server permits '0000-00-00' as a valid date: If strict mode is not enabled, '0000-00-00' is permitted and inserts produce no warning. If strict mode is enabled, '0000-00-00' is not permitted and inserts produce an error, unless IGNORE is given as well. For INSERT IGNORE and UPDATE IGNORE, '0000-00-00' is permitted and inserts produce a warning.
>
>
>
[Refer](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict) |
64,124,984 | It needs to look like this:
[](https://i.stack.imgur.com/WjEgc.png)
I have a for loop code that works but I can't turn it into a correct while loop one.
Here is the for loop code:
```java
public class NumPyramid {
public static void main(String[] args) {
int rows = 9;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= (rows - i) * 2; j++) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--) {
System.out.print(" " + k); //create left half
}
for (int l = 2; l <= i; l++) {
System.out.print(" " + l); //create right half
}
System.out.println();
}
}
}
``` | 2020/09/29 | [
"https://Stackoverflow.com/questions/64124984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14362952/"
] | In general, this is how you convert a `for` loop to a while loop:
```
for (initial; condition; iterate) {
statement;
}
```
becomes
```
initial;
while (condition) {
statement;
iterate;
}
``` | You may use a `StringBuilder` to hold the entire string you need to print and fill it with spaces.
For the initial step you set `'1'` into the middle and print the contents of the string.
After that you "move" to the left and right, set the next `i` and repeat printing until all rows are done.
**Update**
Added `space` parameter to control the distance between digits in the pyramid.
```java
int n = 9;
int i = 1;
int space = 2; // distance between two adjacent digits
int width = 2 * space * (n - 2) + 1; // 0 not included
StringBuilder sb = new StringBuilder();
while (i++ <= width) {
sb.append(' '); // prepare StringBuilder with whitespaces
}
i = 0;
int left = width / 2;
int right = width / 2;
while (i++ < n - 1) { // print 1..8
sb.setCharAt(left, (char)(i + '0'));
sb.setCharAt(right, (char)(i + '0'));
System.out.println(sb);
left -= space;
right += space;
}
``` |
64,124,984 | It needs to look like this:
[](https://i.stack.imgur.com/WjEgc.png)
I have a for loop code that works but I can't turn it into a correct while loop one.
Here is the for loop code:
```java
public class NumPyramid {
public static void main(String[] args) {
int rows = 9;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= (rows - i) * 2; j++) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--) {
System.out.print(" " + k); //create left half
}
for (int l = 2; l <= i; l++) {
System.out.print(" " + l); //create right half
}
System.out.println();
}
}
}
``` | 2020/09/29 | [
"https://Stackoverflow.com/questions/64124984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14362952/"
] | This is what I did and it works!
```
int rows = 9, i = 1;
while (i <= rows)
{
int j = 1;
while (j<=(rows-i)*2)
{
System.out.print(" ");
j++;
}
int k = i;
while (k >= 1)
{
System.out.print(" "+k);
k--;
}
int l = 2;
while (l<=i)
{
System.out.print(" "+l);
l++;
}
System.out.println();
i++;
}
``` | You may use a `StringBuilder` to hold the entire string you need to print and fill it with spaces.
For the initial step you set `'1'` into the middle and print the contents of the string.
After that you "move" to the left and right, set the next `i` and repeat printing until all rows are done.
**Update**
Added `space` parameter to control the distance between digits in the pyramid.
```java
int n = 9;
int i = 1;
int space = 2; // distance between two adjacent digits
int width = 2 * space * (n - 2) + 1; // 0 not included
StringBuilder sb = new StringBuilder();
while (i++ <= width) {
sb.append(' '); // prepare StringBuilder with whitespaces
}
i = 0;
int left = width / 2;
int right = width / 2;
while (i++ < n - 1) { // print 1..8
sb.setCharAt(left, (char)(i + '0'));
sb.setCharAt(right, (char)(i + '0'));
System.out.println(sb);
left -= space;
right += space;
}
``` |
52,909,482 | im kinda new to programming ,and i have that exercise.I made a program that runs just right for small ranges of numbers,but for this exercise we are given a high range of nums,and it just takes much time to finish examining.
Any suggestions how can i make it faster?
```
#include <stdio.h>
#define START 190000000
#define END 200000000
int main()
{
int primenum = 0, i = 0, j = 0, c = 0;
for (i = START; i <= END; i++)
{
printf("EXMINING %d\r\n", i);
c = 2;
for (j = 2; j <= i-1; j++)
{
if (i%j == 0)
{ c=1;
break;
}
}
if (c == 2) primenum = primenum + 1;
printf("Prime Numbers Found so far: %d\r\n", primenum);
}
printf("THE PRIME NUMBERS ARE %d", primenum);
return 0;
}
``` | 2018/10/20 | [
"https://Stackoverflow.com/questions/52909482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10532692/"
] | Best is to use [`NumberFormatter::parseCurrency`](http://php.net/manual/en/numberformatter.parsecurrency.php):
```
<?php
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$amount = '$100';
echo $formatter->parseCurrency($amount, $curr);
```
[Demo here](https://3v4l.org/lkPF4)
This will also allow characters that can usually belong in a money amount (floating points and commas), and convert it to a proper float value. | You don't need preg\_match\_all, a normal preg\_match is all that is needed.
And your pattern suggests there is multiple digits?
This works, but not sure what your string looks like. You didn't include that in your question.
It matches only digits.
```
$price = "$100";
preg_match('/([\d\.]+)/',$price,$match);
var_dump($match); //100
```
<https://3v4l.org/BE0Nj> |
52,909,482 | im kinda new to programming ,and i have that exercise.I made a program that runs just right for small ranges of numbers,but for this exercise we are given a high range of nums,and it just takes much time to finish examining.
Any suggestions how can i make it faster?
```
#include <stdio.h>
#define START 190000000
#define END 200000000
int main()
{
int primenum = 0, i = 0, j = 0, c = 0;
for (i = START; i <= END; i++)
{
printf("EXMINING %d\r\n", i);
c = 2;
for (j = 2; j <= i-1; j++)
{
if (i%j == 0)
{ c=1;
break;
}
}
if (c == 2) primenum = primenum + 1;
printf("Prime Numbers Found so far: %d\r\n", primenum);
}
printf("THE PRIME NUMBERS ARE %d", primenum);
return 0;
}
``` | 2018/10/20 | [
"https://Stackoverflow.com/questions/52909482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10532692/"
] | You don't need preg\_match\_all, a normal preg\_match is all that is needed.
And your pattern suggests there is multiple digits?
This works, but not sure what your string looks like. You didn't include that in your question.
It matches only digits.
```
$price = "$100";
preg_match('/([\d\.]+)/',$price,$match);
var_dump($match); //100
```
<https://3v4l.org/BE0Nj> | ```
$str = "$100";
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
```
[Reference](https://gist.github.com/lerua83/7448987)
```
Array (
[0] => Array (
[0] => 100
)
)
echo $matches[0][0];
```
Output: `100` |
52,909,482 | im kinda new to programming ,and i have that exercise.I made a program that runs just right for small ranges of numbers,but for this exercise we are given a high range of nums,and it just takes much time to finish examining.
Any suggestions how can i make it faster?
```
#include <stdio.h>
#define START 190000000
#define END 200000000
int main()
{
int primenum = 0, i = 0, j = 0, c = 0;
for (i = START; i <= END; i++)
{
printf("EXMINING %d\r\n", i);
c = 2;
for (j = 2; j <= i-1; j++)
{
if (i%j == 0)
{ c=1;
break;
}
}
if (c == 2) primenum = primenum + 1;
printf("Prime Numbers Found so far: %d\r\n", primenum);
}
printf("THE PRIME NUMBERS ARE %d", primenum);
return 0;
}
``` | 2018/10/20 | [
"https://Stackoverflow.com/questions/52909482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10532692/"
] | Best is to use [`NumberFormatter::parseCurrency`](http://php.net/manual/en/numberformatter.parsecurrency.php):
```
<?php
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$amount = '$100';
echo $formatter->parseCurrency($amount, $curr);
```
[Demo here](https://3v4l.org/lkPF4)
This will also allow characters that can usually belong in a money amount (floating points and commas), and convert it to a proper float value. | ```
$str = "$100";
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
```
[Reference](https://gist.github.com/lerua83/7448987)
```
Array (
[0] => Array (
[0] => 100
)
)
echo $matches[0][0];
```
Output: `100` |
601,142 | So I've been trying to wrap my head around GR for a bit now, but one thing that keeps me down is the idea that while earth bends spacetime around us, the earth is also accelerating towards us at $9.8\text{ m/s}^2$, which is why objects accelerate towards it at that rate. However, I haven't been able to source this claim, it comes up independently in the information I am consuming. One claim by "ScienceClic English" claims that the geological forces of the earth itself is expanding the earth at a rate of $9.8\text{ m/s}^2$ while the curvature of spacetime keeps earth the same size. You can imagine my difficulties sourcing this as all results on "expanding earth" in any variation returns debunking of the expanding earth theory itself. The other claims do not go into any detail, they merely claim that the earth is accelerating "up" at $9.8\text{ m/s}^2$.
What is the deal with this? I feel a force acting upon me, so already there's the natural intuition towards gravity existing. Yet we know gravity isn't a real force, I am just experiencing the curvature of spacetime, but what else? What governs the law that things fall towards the earth at $9.8\text{ m/s}^2$ on earth? | 2020/12/17 | [
"https://physics.stackexchange.com/questions/601142",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/282874/"
] | A crucial issue here is what we mean by acceleration. In Newtonian physics, objects which are not under the influence of external forces move in straight lines at constant speed; deviation from this behavior is called *coordinate* acceleration because it refers to the rate at which the object's coordinates change.
On the other hand, in GR there is a subtly different concept called *proper* acceleration, which measures the deviation of an object from a free-fall trajectory. A pencil sitting on a table is not moving, so it does not possess any coordinate acceleration. However, since a free-fall trajectory (on the surface of the earth) would be accelerating downward at 9.8 m/s$^2$, the proper acceleration $\mathbf a\_\text{proper} = \mathbf a\_\text{coordinate} - \mathbf a\_\text{free fall}$ is directed *upward* at 9.8 m/s$^2$.
In GR, one typically refers to force as the things which induce proper acceleration - essentially, $\mathbf F = m\mathbf a\_\text{proper}$. It is in this sense that gravitation is sometimes said not to be a force - under the influence of gravity, objects are in free-fall and therefore their proper acceleration is zero.
On the other hand, if you multiply $\mathbf a\_\text{free fall}$ by an object's mass and move it to the other side of the equation, you get
$$\mathbf F + \underbrace{m\mathbf a\_\text{free fall}}\_{\text{Gravitational force?}} = m\mathbf a\_\text{coordinate}$$
Ultimately, the debate over whether to call the gravity a force comes down to whether you want $m\mathbf a\_{\text{free fall}}$ to be on the left or right hand side of the equation of motion, and is therefore in some sense a semantic point. There are subtleties, of course - the facts that non-tidal gravitational forces are not measurable and that gravitational and inertial masses are observed to be universally proportional, along with the beautiful geometry of general relativity, seem to suggest very strongly that we should adopt the proper acceleration POV. But if you're only interested in doing calculations, it doesn't really matter. | "The earth is also accelerating towards us at 9.8m/s2, " What? That sentence is totally wrong. Let's look at the Newton's third law.
$F\_{you \; put \; on \; earth} = - F\_{earth\; puts\; on\; you}$
This equation is about force and not acceleration.
$m\_{earth}a\_{of \; the \;earth \;moving \;toward \; you} = - m\_{you} a\_{of \;you \;moving \;toward \; the \; earth}$
$a\_{of \;you \;moving \;toward \; the \; earth}$ is $9.8\;m/s^2$ , mass of the earth is $5.79\times 10^24 \; kg$. Use your mass and calculate the acceleration at which the earth move toward you.
Before understanding GR you need to understand Newtonian gravity very well. |
601,142 | So I've been trying to wrap my head around GR for a bit now, but one thing that keeps me down is the idea that while earth bends spacetime around us, the earth is also accelerating towards us at $9.8\text{ m/s}^2$, which is why objects accelerate towards it at that rate. However, I haven't been able to source this claim, it comes up independently in the information I am consuming. One claim by "ScienceClic English" claims that the geological forces of the earth itself is expanding the earth at a rate of $9.8\text{ m/s}^2$ while the curvature of spacetime keeps earth the same size. You can imagine my difficulties sourcing this as all results on "expanding earth" in any variation returns debunking of the expanding earth theory itself. The other claims do not go into any detail, they merely claim that the earth is accelerating "up" at $9.8\text{ m/s}^2$.
What is the deal with this? I feel a force acting upon me, so already there's the natural intuition towards gravity existing. Yet we know gravity isn't a real force, I am just experiencing the curvature of spacetime, but what else? What governs the law that things fall towards the earth at $9.8\text{ m/s}^2$ on earth? | 2020/12/17 | [
"https://physics.stackexchange.com/questions/601142",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/282874/"
] | A crucial issue here is what we mean by acceleration. In Newtonian physics, objects which are not under the influence of external forces move in straight lines at constant speed; deviation from this behavior is called *coordinate* acceleration because it refers to the rate at which the object's coordinates change.
On the other hand, in GR there is a subtly different concept called *proper* acceleration, which measures the deviation of an object from a free-fall trajectory. A pencil sitting on a table is not moving, so it does not possess any coordinate acceleration. However, since a free-fall trajectory (on the surface of the earth) would be accelerating downward at 9.8 m/s$^2$, the proper acceleration $\mathbf a\_\text{proper} = \mathbf a\_\text{coordinate} - \mathbf a\_\text{free fall}$ is directed *upward* at 9.8 m/s$^2$.
In GR, one typically refers to force as the things which induce proper acceleration - essentially, $\mathbf F = m\mathbf a\_\text{proper}$. It is in this sense that gravitation is sometimes said not to be a force - under the influence of gravity, objects are in free-fall and therefore their proper acceleration is zero.
On the other hand, if you multiply $\mathbf a\_\text{free fall}$ by an object's mass and move it to the other side of the equation, you get
$$\mathbf F + \underbrace{m\mathbf a\_\text{free fall}}\_{\text{Gravitational force?}} = m\mathbf a\_\text{coordinate}$$
Ultimately, the debate over whether to call the gravity a force comes down to whether you want $m\mathbf a\_{\text{free fall}}$ to be on the left or right hand side of the equation of motion, and is therefore in some sense a semantic point. There are subtleties, of course - the facts that non-tidal gravitational forces are not measurable and that gravitational and inertial masses are observed to be universally proportional, along with the beautiful geometry of general relativity, seem to suggest very strongly that we should adopt the proper acceleration POV. But if you're only interested in doing calculations, it doesn't really matter. | Without external forces, we move along geodesics defined by the geodesic equation:
$$ \ddot x^m = - \Gamma^m\_{ij}\dot x^j\dot x^i$$
where $\Gamma^i\_{jk}$ are the Christoffel symbols.
In the approximation that the Earth is not rotating near the speed of light, we can use the Christoffel symbols from the Schwarzschild metric, but before we do that, remember the we are not moving near the speed of light either, so that our 4-velocity is:
$$ \dot x^{\mu} = \gamma(c, v\_x, v\_y, v\_z) \approx (c, 0,0,0) = (x^0,0,0,0) $$
so that the geodesic equation is:
$$ \ddot x^m = -\Gamma^m\_{00}x^0x^0 = -\Gamma^m\_{00}c^2$$
and we only need (with $c=1$) a few Christoffel symbols:
$$ \Gamma^t\_{00} = 0$$
$$ \Gamma^r\_{00} = \frac{GM}{r^2}(1-\frac{2GM}r)^{-1}$$
$$ \Gamma^{\theta}\_{00} = 0$$
$$ \Gamma^{\phi}\_{00} = 0$$
That means only the velocity in the $r$ coordinate changes, and the non-zero part of the geodesic equation is:
$$ \ddot r = -\frac{GM}{r^2}(1-\frac{2GM}r)^{-1}$$
Since the Earth is not near being a black hole, $$ r \gg 2GM $$
so:
$$ \ddot r = -\frac{GM}{r^2}$$
which is exactly Newton's Law of gravity: you accelerate radially inward at:
$$ \frac{GM}{R\_{\rm Earth}^2} \approx 9.8\,{\rm m/s^2} $$
It's remarkable that an equation with so much going on reduces to the simple form we're used to (and we used the solution that predicted black holes, even). |
601,142 | So I've been trying to wrap my head around GR for a bit now, but one thing that keeps me down is the idea that while earth bends spacetime around us, the earth is also accelerating towards us at $9.8\text{ m/s}^2$, which is why objects accelerate towards it at that rate. However, I haven't been able to source this claim, it comes up independently in the information I am consuming. One claim by "ScienceClic English" claims that the geological forces of the earth itself is expanding the earth at a rate of $9.8\text{ m/s}^2$ while the curvature of spacetime keeps earth the same size. You can imagine my difficulties sourcing this as all results on "expanding earth" in any variation returns debunking of the expanding earth theory itself. The other claims do not go into any detail, they merely claim that the earth is accelerating "up" at $9.8\text{ m/s}^2$.
What is the deal with this? I feel a force acting upon me, so already there's the natural intuition towards gravity existing. Yet we know gravity isn't a real force, I am just experiencing the curvature of spacetime, but what else? What governs the law that things fall towards the earth at $9.8\text{ m/s}^2$ on earth? | 2020/12/17 | [
"https://physics.stackexchange.com/questions/601142",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/282874/"
] | A crucial issue here is what we mean by acceleration. In Newtonian physics, objects which are not under the influence of external forces move in straight lines at constant speed; deviation from this behavior is called *coordinate* acceleration because it refers to the rate at which the object's coordinates change.
On the other hand, in GR there is a subtly different concept called *proper* acceleration, which measures the deviation of an object from a free-fall trajectory. A pencil sitting on a table is not moving, so it does not possess any coordinate acceleration. However, since a free-fall trajectory (on the surface of the earth) would be accelerating downward at 9.8 m/s$^2$, the proper acceleration $\mathbf a\_\text{proper} = \mathbf a\_\text{coordinate} - \mathbf a\_\text{free fall}$ is directed *upward* at 9.8 m/s$^2$.
In GR, one typically refers to force as the things which induce proper acceleration - essentially, $\mathbf F = m\mathbf a\_\text{proper}$. It is in this sense that gravitation is sometimes said not to be a force - under the influence of gravity, objects are in free-fall and therefore their proper acceleration is zero.
On the other hand, if you multiply $\mathbf a\_\text{free fall}$ by an object's mass and move it to the other side of the equation, you get
$$\mathbf F + \underbrace{m\mathbf a\_\text{free fall}}\_{\text{Gravitational force?}} = m\mathbf a\_\text{coordinate}$$
Ultimately, the debate over whether to call the gravity a force comes down to whether you want $m\mathbf a\_{\text{free fall}}$ to be on the left or right hand side of the equation of motion, and is therefore in some sense a semantic point. There are subtleties, of course - the facts that non-tidal gravitational forces are not measurable and that gravitational and inertial masses are observed to be universally proportional, along with the beautiful geometry of general relativity, seem to suggest very strongly that we should adopt the proper acceleration POV. But if you're only interested in doing calculations, it doesn't really matter. | The short answer is that Earth doesn't expand upward. Instead, a massive object like Earth curves space-time. Objects with no forces on them follow straight paths at constant speed in flat space-time. In curved space-time, those paths are not straight. Two objects that start out near each other can follow different paths that accelerate away from each other. This is the cause of gravity.
To get a start on seeing how this all works, see [Why can't I do this to get infinite energy?](https://physics.stackexchange.com/q/178417/37364). This talks about a simple thought experiment that led Einstein to General Relativity. The upshot is that some straightforward properties of the universe, like conservation of energy, lead to the conclusion that time must run slower near the earth.
A consequence of slower time near Earth is space-time is curved. To get an understanding of what this curvature means, see my answer to [Intrinsic Curvature of a Cylinder](https://physics.stackexchange.com/q/600101/37364).
A consequence of curved space-time is that light is deflected toward the earth as it passes by. To see this, consider light from a distant star. The light is a plane wave. Part of the wave passes near the Earth, where time runs slower. That part of the wave travels slower and gets a little behind. The wavefronts are no longer planar. They have been tilted a little toward the Earth. Light propagates perpendicular to its wavefronts. Light is deflected a little toward the Earth.
The same thing happens as starlight passes near the Sun. This is the famous solar eclipse experiment that provided the first evidence for General Relativity.
However, the outcome was twice as much deflection as Einstein predicted. Einstein went back to the drawing board. After some thought, he concluded that in addition to a distortion of time, there is also a distortion of space. The distance to the center of the Earth is slightly longer than you would expect from measuring the circumference of a distant orbit. From this, it is possible to show that the trajectory of matter is also deflected.
Without curvature, an object sitting at rest on the surface of the Earth would float there. Because space-time is curved, it is deflected toward the Earth. The ground is rigid, and resists being pushed into. It pushed back hard enough to hold the object still. This is the upward force you are thinking of. |
601,142 | So I've been trying to wrap my head around GR for a bit now, but one thing that keeps me down is the idea that while earth bends spacetime around us, the earth is also accelerating towards us at $9.8\text{ m/s}^2$, which is why objects accelerate towards it at that rate. However, I haven't been able to source this claim, it comes up independently in the information I am consuming. One claim by "ScienceClic English" claims that the geological forces of the earth itself is expanding the earth at a rate of $9.8\text{ m/s}^2$ while the curvature of spacetime keeps earth the same size. You can imagine my difficulties sourcing this as all results on "expanding earth" in any variation returns debunking of the expanding earth theory itself. The other claims do not go into any detail, they merely claim that the earth is accelerating "up" at $9.8\text{ m/s}^2$.
What is the deal with this? I feel a force acting upon me, so already there's the natural intuition towards gravity existing. Yet we know gravity isn't a real force, I am just experiencing the curvature of spacetime, but what else? What governs the law that things fall towards the earth at $9.8\text{ m/s}^2$ on earth? | 2020/12/17 | [
"https://physics.stackexchange.com/questions/601142",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/282874/"
] | A crucial issue here is what we mean by acceleration. In Newtonian physics, objects which are not under the influence of external forces move in straight lines at constant speed; deviation from this behavior is called *coordinate* acceleration because it refers to the rate at which the object's coordinates change.
On the other hand, in GR there is a subtly different concept called *proper* acceleration, which measures the deviation of an object from a free-fall trajectory. A pencil sitting on a table is not moving, so it does not possess any coordinate acceleration. However, since a free-fall trajectory (on the surface of the earth) would be accelerating downward at 9.8 m/s$^2$, the proper acceleration $\mathbf a\_\text{proper} = \mathbf a\_\text{coordinate} - \mathbf a\_\text{free fall}$ is directed *upward* at 9.8 m/s$^2$.
In GR, one typically refers to force as the things which induce proper acceleration - essentially, $\mathbf F = m\mathbf a\_\text{proper}$. It is in this sense that gravitation is sometimes said not to be a force - under the influence of gravity, objects are in free-fall and therefore their proper acceleration is zero.
On the other hand, if you multiply $\mathbf a\_\text{free fall}$ by an object's mass and move it to the other side of the equation, you get
$$\mathbf F + \underbrace{m\mathbf a\_\text{free fall}}\_{\text{Gravitational force?}} = m\mathbf a\_\text{coordinate}$$
Ultimately, the debate over whether to call the gravity a force comes down to whether you want $m\mathbf a\_{\text{free fall}}$ to be on the left or right hand side of the equation of motion, and is therefore in some sense a semantic point. There are subtleties, of course - the facts that non-tidal gravitational forces are not measurable and that gravitational and inertial masses are observed to be universally proportional, along with the beautiful geometry of general relativity, seem to suggest very strongly that we should adopt the proper acceleration POV. But if you're only interested in doing calculations, it doesn't really matter. | >
> the earth is also accelerating towards us at 9.8m/s2, which is why objects accelerate towards it at that rate. However, I haven't been able to source this claim
>
>
>
You don’t need to source the claim, you can measure it experimentally with an accelerometer. For example, you can use the one in your cell phone. Simply use an app that lets you read the accelerometer, place the phone on the ground, and you will see that the ground is accelerating upward at $9.8 \text{ m/s}^2$.
This type of acceleration is called proper acceleration. It is physical and independent of the coordinates. The other type of acceleration is coordinate acceleration, which depends on the reference frame. In non inertial frames the coordinate acceleration differs from the proper acceleration, and the difference is described by introducing “fictitious forces” or “inertial forces”.
So, if the surface of the earth is accelerating then how does it stay the same size? This is due to curvature. Consider the surface of a sphere. If you walk straight forward on the surface of a sphere you will travel in a great circle. The equator is a great circle, but other latitude lines are not. To stay on any other latitude line you cannot walk straight forward but must continuously turn towards the nearest pole. In other words, a person walking due east on the 1 deg N line is continually turning away from a person walking due east on the 1 deg S line, although the distance between them is constant. Geometrically this is nearly identical to how the curvature of spacetime works. |
62,191,736 | I am writing an interactive REPL program in `c`.
Some examples of commands (lines starting with `>`) I would like to handle are:
```
$ ./my_program // run the program
> add user
id: 123 // this is the output of above command
> update user 123 name "somename"
> remove user 123
> quit
```
So basically the command is a line with multiple strings.
This is how I am trying to handle the commands.
* scan the whole line
* parse the command and get a corresponding `int` value unique to command
* do whatever needs to be done for the command
```c
#include <stdio.h>
int parse_cmd(const char *buffer)
{
// parse command
}
int main(int argc, const char **argv)
{
// init code
char buffer[100];
int cmd;
while (1) {
printf("> ");
scanf("%[^\n]%*c", buffer);
cmd = parse_cmd(buffer);
if (cmd < 0) {
printf("error: invalid command\n");
continue;
}
switch (cmd) {
// handle commands
}
}
// deinit code
}
```
There are a lot of cli programs I have seen that take command inputs in similar way.
I wonder if there is a general way of writing cli programs?
I can write code to parse the commands, just wanted to know the standard approach for such situations? | 2020/06/04 | [
"https://Stackoverflow.com/questions/62191736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8455110/"
] | While there's no real standard way, quite a lot of opensource console tools with an interactive mode use the GNU readline library (<https://tiswww.case.edu/php/chet/readline/rltop.html>).
It's actually quite easy to use, even simpler than implementing everything 100% correctly by yourself.
Your example rebased on readline:
```
int main(int argc, const char **argv)
{
// init code
int cmd;
char* line;
while (1) {
line = readline("> ");
if (line) {
cmd = parse_cmd(line);
switch (cmd) {
// handle commands
default:
printf("error: invalid command\n");
}
free(line);
} else {
break;
}
}
// deinit code
}
```
This isn't any more complex than your example, but you immediately gain:
* command line editing at the interactive prompt, with correct handling of each and every possible terminal
* correct handling of EOF (important if stdin is redirected)
* unlimited input line size
And it's not very hard to add a command history, with arrow-up and down to repeat previous lines, incremental search, optionally persisted to a file, et et. | There's not really a standard way to do it. This is not a 100% fair comparison, but your question is kind of like if there is a standard way to construct a compiler, because you are in fact constructing a language, although a very simple one.
But one reasonably common way that works fairly well for simple programs is this approach. Let's assume that we have two commands `add` and `del`. Create a function for both these commands. First we search for one of the strings `"add "` or `"del "`. Notice the spaces. Put a pointer on the next character and call the corresponding function with the rest of the line as argument and allow them to determine things.
Here is some pseudo:
```
parse(bufferptr)
word = getFirstWord(bufferptr)
ptr = bufferptr + strlen(word)
if word == "add"
return add(ptr)
else if word == "del"
return del(ptr)
return -1
add(bufferptr)
word = getFirstWord(bufferptr)
if userExist(word)
return -1
else
return addUser(word)
del(bufferptr)
word = getFirstWord(bufferptr)
if not userExist(word)
return -1
else
return delUser(word)
buffer = input()
int res = parse(buffer)
``` |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | Use **sessions** when you want to temporarly store some data (for one session - until user closes his browser).
Use **cookies** when you want to store data for longer (like login cereditials).
You should also have on your mind that user can change value of stored cookies, but can't for sessions, since sessions are stored on a server, but cookies are stored on client's computer. | PHP cookies if you want to store long term, but don't care whether the user changes the values or not.
PHP sessions if you don't want the user to have the ability to change values but don't need long term storage (this sounds like what you want)
Both session and cookies if you want to store long term and don't want users to have access to changing the values. You would want to use a database with this so that you could check the cookie information with the database to see if it was correct, and then store the data in sessions for easy access.
This is how many sites 'remember users'.. They store a cookie with the username and password, and then when the user visits the site (if a session is not set) they check the username and password with the database and then if it is correct, they create a session specific to that user. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | I believe cookies is the answer you need, as php session is only stored between page loads, so you are effectively sending the data back to the server already (not what you want) and as far as I know, javascript cookies are just cookies set with javascript.
So to clarify, I think you should set a cookie (by using javascript) every time some data is created - which will store locally on the browser (still fairly volatile) until the user presses the save button, where it will be sent back to the server. | PHP cookies if you want to store long term, but don't care whether the user changes the values or not.
PHP sessions if you don't want the user to have the ability to change values but don't need long term storage (this sounds like what you want)
Both session and cookies if you want to store long term and don't want users to have access to changing the values. You would want to use a database with this so that you could check the cookie information with the database to see if it was correct, and then store the data in sessions for easy access.
This is how many sites 'remember users'.. They store a cookie with the username and password, and then when the user visits the site (if a session is not set) they check the username and password with the database and then if it is correct, they create a session specific to that user. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | **PHP and Javascript** cookies are the **same thing**, they are just **data stored client side**, php and javascript are the technology used to store them, nothing more.
Since PHP cookies can only be set **before an output is sent to the page**, it seems Javascript cookies would be best.
You would use cookies instead of a session because you mention you would leave the page, in which case the session would **terminate** and you would lose your data. | PHP cookies if you want to store long term, but don't care whether the user changes the values or not.
PHP sessions if you don't want the user to have the ability to change values but don't need long term storage (this sounds like what you want)
Both session and cookies if you want to store long term and don't want users to have access to changing the values. You would want to use a database with this so that you could check the cookie information with the database to see if it was correct, and then store the data in sessions for easy access.
This is how many sites 'remember users'.. They store a cookie with the username and password, and then when the user visits the site (if a session is not set) they check the username and password with the database and then if it is correct, they create a session specific to that user. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | >
> php sessions, cookies, or javascript cookies?
>
>
>
There is either a session or cookie so there are **two** things not three.
Now a **session is also a cookie** but is saved on **server** unlike simple JS cookie which is saved in **user's machine**.
>
> I would like to save that data so it repopulates if I leave the page
>
>
>
If it is **sensitive** information, always use **database** to store it and if it is **not** sensitive data:
* Use cookies or `localStorage` but it can be **deleted** by user
* Use session which can't be deleted by a user but will **expire** based on php.ini settings
On the other hand, to save it **permanently**, use the database instead. | PHP cookies if you want to store long term, but don't care whether the user changes the values or not.
PHP sessions if you don't want the user to have the ability to change values but don't need long term storage (this sounds like what you want)
Both session and cookies if you want to store long term and don't want users to have access to changing the values. You would want to use a database with this so that you could check the cookie information with the database to see if it was correct, and then store the data in sessions for easy access.
This is how many sites 'remember users'.. They store a cookie with the username and password, and then when the user visits the site (if a session is not set) they check the username and password with the database and then if it is correct, they create a session specific to that user. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | **PHP and Javascript** cookies are the **same thing**, they are just **data stored client side**, php and javascript are the technology used to store them, nothing more.
Since PHP cookies can only be set **before an output is sent to the page**, it seems Javascript cookies would be best.
You would use cookies instead of a session because you mention you would leave the page, in which case the session would **terminate** and you would lose your data. | Use **sessions** when you want to temporarly store some data (for one session - until user closes his browser).
Use **cookies** when you want to store data for longer (like login cereditials).
You should also have on your mind that user can change value of stored cookies, but can't for sessions, since sessions are stored on a server, but cookies are stored on client's computer. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | >
> php sessions, cookies, or javascript cookies?
>
>
>
There is either a session or cookie so there are **two** things not three.
Now a **session is also a cookie** but is saved on **server** unlike simple JS cookie which is saved in **user's machine**.
>
> I would like to save that data so it repopulates if I leave the page
>
>
>
If it is **sensitive** information, always use **database** to store it and if it is **not** sensitive data:
* Use cookies or `localStorage` but it can be **deleted** by user
* Use session which can't be deleted by a user but will **expire** based on php.ini settings
On the other hand, to save it **permanently**, use the database instead. | Use **sessions** when you want to temporarly store some data (for one session - until user closes his browser).
Use **cookies** when you want to store data for longer (like login cereditials).
You should also have on your mind that user can change value of stored cookies, but can't for sessions, since sessions are stored on a server, but cookies are stored on client's computer. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | **PHP and Javascript** cookies are the **same thing**, they are just **data stored client side**, php and javascript are the technology used to store them, nothing more.
Since PHP cookies can only be set **before an output is sent to the page**, it seems Javascript cookies would be best.
You would use cookies instead of a session because you mention you would leave the page, in which case the session would **terminate** and you would lose your data. | I believe cookies is the answer you need, as php session is only stored between page loads, so you are effectively sending the data back to the server already (not what you want) and as far as I know, javascript cookies are just cookies set with javascript.
So to clarify, I think you should set a cookie (by using javascript) every time some data is created - which will store locally on the browser (still fairly volatile) until the user presses the save button, where it will be sent back to the server. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | >
> php sessions, cookies, or javascript cookies?
>
>
>
There is either a session or cookie so there are **two** things not three.
Now a **session is also a cookie** but is saved on **server** unlike simple JS cookie which is saved in **user's machine**.
>
> I would like to save that data so it repopulates if I leave the page
>
>
>
If it is **sensitive** information, always use **database** to store it and if it is **not** sensitive data:
* Use cookies or `localStorage` but it can be **deleted** by user
* Use session which can't be deleted by a user but will **expire** based on php.ini settings
On the other hand, to save it **permanently**, use the database instead. | I believe cookies is the answer you need, as php session is only stored between page loads, so you are effectively sending the data back to the server already (not what you want) and as far as I know, javascript cookies are just cookies set with javascript.
So to clarify, I think you should set a cookie (by using javascript) every time some data is created - which will store locally on the browser (still fairly volatile) until the user presses the save button, where it will be sent back to the server. |
11,369,167 | I have some observed data by hour. I am trying to subset this data by the day or even week intervals. I am not sure how to proceed with this task in `R`.
The sample of the data is below.
```
date obs
2011-10-24 01:00:00 12
2011-10-24 02:00:00 4
2011-10-24 19:00:00 18
2011-10-24 20:00:00 7
2011-10-24 21:00:00 4
2011-10-24 22:00:00 2
2011-10-25 00:00:00 4
2011-10-25 01:00:00 2
2011-10-25 02:00:00 2
2011-10-25 15:00:00 12
2011-10-25 18:00:00 2
2011-10-25 19:00:00 3
2011-10-25 21:00:00 2
2011-10-25 23:00:00 9
2011-10-26 00:00:00 13
2011-10-26 01:00:00 11
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610545/"
] | >
> php sessions, cookies, or javascript cookies?
>
>
>
There is either a session or cookie so there are **two** things not three.
Now a **session is also a cookie** but is saved on **server** unlike simple JS cookie which is saved in **user's machine**.
>
> I would like to save that data so it repopulates if I leave the page
>
>
>
If it is **sensitive** information, always use **database** to store it and if it is **not** sensitive data:
* Use cookies or `localStorage` but it can be **deleted** by user
* Use session which can't be deleted by a user but will **expire** based on php.ini settings
On the other hand, to save it **permanently**, use the database instead. | **PHP and Javascript** cookies are the **same thing**, they are just **data stored client side**, php and javascript are the technology used to store them, nothing more.
Since PHP cookies can only be set **before an output is sent to the page**, it seems Javascript cookies would be best.
You would use cookies instead of a session because you mention you would leave the page, in which case the session would **terminate** and you would lose your data. |
2,778,849 | If $a,b,c,d,e,f$ are six real numbers such that:
$$ a + b + c = d + e + f $$
$$ a^2 + b^2 + c^2 = d^2 + e^2 + f^2 $$
$$ a^3 + b^3 + c^3 = d^3 + e^3 + f^3 $$
Prove by mathematical induction that:
$$ a^n + b^n + c^n = d^n + e^n + f^n $$
---
I tried solving this question by correlating to
$$ a^k + b^k = (a + b)(a^{k-1} + b^{k-1}) - ab(a^{k-2} + b^{k-2}) $$
The problem is that terms with $abc$ do not come in common while expanding. Could you please help me solve this question?
*This question originates from the level III excercise of SK Goyal's book of Algebra for JEE Mains and Advanced.* | 2018/05/13 | [
"https://math.stackexchange.com/questions/2778849",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/519180/"
] | Consider the polynomial $p(x)=x^3-sx^2+ux-v$ where $s=a+b+c=d+e+f$, $u=ab+bc+ca=\frac 12\left((a+b+c)^2-a^2+b^2+c^2\right)=de+ef+fd$ and $v=abc=\frac 13\left((a^3+b^3+c^3)-s(a^2+b^2+c^2)+u(a+b+c)\right)=def$
Then $p(a)=p(b)=p(c)=p(d)=p(e)=p(f)=0$ and you can use $$a^rp(a)+b^rp(b)+c^rp(c)=0$$ to obtain an expression for the sum $a^{r+3}+b^{r+3}+c^{r+3}$ in terms of sums of lower powers and the common constants $s,u,v$. This can be used for the inductive step. | Let $ P(n): a^n + b^n + c^n = d^n + e^n + f^n $,
**Step I:**
For $ n=1,2,3 $ it is already **given** that $P(n)$ is true. There is no need to do extra **cross-checking** here.
**Step II:**
Assume that for $ n=k,k-1,k-2 $ the result is true, i.e.
$$ P(k): a^{k} + b^{k} + c^{k} = d^{k} + e^{k} + f^{k} $$
$$ P(k-1): a^{k-1} + b^{k-1} + c^{k-1} = d^{k-1} + e^{k-1} + f^{k-1} $$
$$ P(k-2): a^{k-2} + b^{k-2} + c^{k-2} = d^{k-2} + e^{k-2} + f^{k-2} $$
**Step III:**
For $n=k+1$,
$$ P(k+1): a^{k+1} + b^{k+1} + c^{k+1} = d^{k+1} + e^{k+1} + f^{k+1} $$
We know that,
$$ a^{k+1} + b^{k+1} + c^{k+1} = (a + b + c)(a^k + b^k + c^k) - a(b^k + c^k) - b(c^k + a^k) - c(a^k + b^k) \tag{1} $$
$$ a^{k+1} + b^{k+1} + c^{k+1} = (a^2 + b^2 + c^2)(a^{k-1} + b^{k-1} + c^{k-1}) - a^2(b^{k-1} + c^{k-1}) - b^2(c^{k-1} + a^{k-1}) - c^2(a^{k-1} + b^{k-1}) \tag{2} $$
Adding $(1)$ and $(2)$,
$$ 2(a^{k+1} + b^{k+1} + c^{k+1}) = (a+b+c)(a^k+b^k+c^k) + (a^2+b^2+c^2)(a^{k-1}+b^{k-1}+c^{k-1}) - a(b^k+c^k) - a^2(b^{k-1}+c^{k-1}) - b(c^k+a^k) - b^2(c^{k-1} + a^{k-1}) - c(a^k+b^k) - c^2(a^{k-1} + b^{k-1}) $$
Let's try to simply our equation here,
$$ 2(a^{k+1} + b^{k+1} + c^{k+1}) = (a+b+c)(a^k+b^k+c^k) + (a^2+b^2+c^2)(a^{k-1}+b^{k-1}+c^{k-1}) - 2ab(a^{k-1}+b^{k-1}) - 2bc(b^{k-1}+c^{k-1}) - 2ca(c^{k-1}+a^{k-1}) $$
We've reached here, now as you said terms with $abc$ are hard to find, yes they are but we'll change the terms a bit here:
$$ 2(a^{k+1} + b^{k+1} + c^{k+1}) = (a+b+c)(a^k+b^k+c^k) + (a^2+b^2+c^2)(a^{k-1}+b^{k-1}+c^{k-1}) - 2ab(a^{k-1}+b^{k-1}+c^{k-1}) - 2bc(a^{k-1}+b^{k-1}+c^{k-1}) - 2ca(a^{k-1}+b^{k-1}+c^{k-1}) + 2(abc^{k-1} + a^{k-1}bc + ab^{k-1}c) $$
$$ 2(a^{k+1} + b^{k+1} + c^{k+1}) = (a+b+c)(a^k+b^k+c^k) + (a^2+b^2+c^2)(a^{k-1}+b^{k-1}+c^{k-1}) - 2(ab+bc+ca)(a^{k-1}+b^{k-1}+c^{k-1}) + 2abc(c^{k-2} + a^{k-2} + b^{k-2}) $$
Oh! Dang it, we've got $ab+bc+ca$ and $abc$ to make our work harder. But there is a simple solution to this:
*Given that $a+b+c=d+e+f$, $a^2+b^2+c^2=d^2+e^2+f^2$, $a^3+b^3+c^3=d^3+e^3+f^3$*,
Result I:
$$ (a+b+c)^2 - (a^2+b^2+c^2) = (d+e+f)^2 - 2(de+ef+fd) $$
$$ 2(ab+bc+ca) = 2(de+ef+fd) \tag{3} $$
Result II:
$$(a+b+c)^3 - 3(a+b+c)(a^2+b^2+c^2) + 2(a^3+b^3+c^3) = (d+e+f)^3 - 3(d+e+f)(d^2+e^2+f^2) + 2(d^3+e^3+f^3)$$
$$ 6abc=6def $$
$$ abc = def \tag{4} $$
Putting in $(3)$,$(4)$,$P(k)$,$P(k-1)$,$P(k-2)$ in our equation,
$$ 2(a^{k+1} + b^{k+1} + c^{k+1}) = (d+e+f)(d^k+e^k+f^k) + (d^2+e^2+f^2)(d^{k-1}+e^{k-1}+f^{k-1}) - 2(de+ef+fd)(d^{k-1}+e^{k-1}+f^{k-1}) + 2def(d^{k-2} + e ^{k-2} + f^{k-2}) $$
The way we have factored out $P(k+1)$ in terms of $a,b,c$ we could do that with $d,e,f$ so we don't have to again simplify the right-hand side,
$$ 2(a^{k+1} + b^{k+1} + c^{k+1}) = 2(d^{k+1} + e^{k+1} + f^{k+1}) $$
$$ \therefore a^{k+1} + b^{k+1} + c^{k+1} = d^{k+1} + e^{k+1} + f^{k+1}$$ |
89,852 | I am considering two job offers for entry level positions straight out of college. They are essentially the same salary, but one of them has a more convenient location (company A), while the other (company B) would require a car and longer commute. I am therefore leaning toward company A.
However, company B offered 15 days PTO (Paid time off), while company A offered only 10. Company A is a medium sized company (~2000 employees), and company B is large. Vacation time is very important to me since where I am living and will be working is across the country from any of my family.
Is it safe to negotiate with company A so that I could have 15 days PTO even though I am entry level? | 2017/04/26 | [
"https://workplace.stackexchange.com/questions/89852",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/69189/"
] | It's perhaps worth asking the questions, they can only say no.
But personally I would opt for A as the time you spend commuting will more than add up to 5 work days over the course of a year. If there is nothing distinguishing the jobs other than the PTO, then take the one nearer and use the time you would spend travelling, and the extra money that you are saving, to put back into your life, and career. | If one job requires things that the other job doesn't (longer commute, a car), then they may offer "essentially the same salary" but they really shouldn't be considered "essentially the same". Even if you're only talking $40 a week extra for gas, you're still talking $2000 a year. And that doesn't even take into account the extra commute time - what is your time worth?
That being said, there is no harm in asking for what you want or need. Negotiating is a part of the hiring process. You may find that a company has strict rules that say that all new hires get 10 days and that is it, but you may find they have some flexibility - but you'll never know if you don't ask. I have found that PTO is one of those things that is more than likely set in stone. It is often used to reward employees who stay with a company for a long time (i.e. 5 years = 15 days, 10 years = 20 days, etc.).
From a company's standpoint, it wouldn't seem fair to older employees who have been there for a while to have possibly less PTO than the new guy who just started. And unlike salary, which no one will know unless you tell them, PTO is something that everyone sees you take. If you're on vaca for 3 weeks then everyone is going to know that you have 15 days PTO. It could turn into a morale issue at the company if they just hand out PTO in different amounts to different people they hire. And if they were to give someone 15 days now, then they would probably have to give all those people who haven't reached that level (say 5 years for 15 days) that same amount as well.
So you're chances don't really look good to me. You'd probably have a better chance asking for more money; but then you're entry level, so I'm not sure that would be successful either. You just have to decide if the extra PTO is worth the extra commute and live with that decision. |
89,852 | I am considering two job offers for entry level positions straight out of college. They are essentially the same salary, but one of them has a more convenient location (company A), while the other (company B) would require a car and longer commute. I am therefore leaning toward company A.
However, company B offered 15 days PTO (Paid time off), while company A offered only 10. Company A is a medium sized company (~2000 employees), and company B is large. Vacation time is very important to me since where I am living and will be working is across the country from any of my family.
Is it safe to negotiate with company A so that I could have 15 days PTO even though I am entry level? | 2017/04/26 | [
"https://workplace.stackexchange.com/questions/89852",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/69189/"
] | >
> Vacation time is very important to me since where I am living and will
> be working is across the country from any of my family. Is it safe to
> negotiate with company A so that I could have 15 days PTO even though
> I am entry level?
>
>
>
You could ask for more time off, but be aware of how that may look to your potential employer.
You are an entry level worker. While time off may be important to you, your employer likely wants to hear how important *work* is to you, how you want to launch your career, how you want to learn and grow rapidly and the value you can add to their company.
Indicating that time away from work is of primary importance to you might be a red flag for some employers (it would be for me). It might make for a poor first impression.
You might have enough leverage to pull it off. The employer might want you to work for them so much that they are willing to change their PTO for an entry level employee. But I'm guessing that won't happen.
You might also consider asking for *unpaid* time off, if the time is really what is most important to you. When my company hired folks from a country half-way around the world, they typically took no time off the first year, carried it over to the second year, and then occasionally augmented that with unpaid time off. This made their trip home worthwhile and we considered that concession part of the price of hiring folks from that country.
But they never came in asking for that right away as a entry-level employee, in my experience. | If one job requires things that the other job doesn't (longer commute, a car), then they may offer "essentially the same salary" but they really shouldn't be considered "essentially the same". Even if you're only talking $40 a week extra for gas, you're still talking $2000 a year. And that doesn't even take into account the extra commute time - what is your time worth?
That being said, there is no harm in asking for what you want or need. Negotiating is a part of the hiring process. You may find that a company has strict rules that say that all new hires get 10 days and that is it, but you may find they have some flexibility - but you'll never know if you don't ask. I have found that PTO is one of those things that is more than likely set in stone. It is often used to reward employees who stay with a company for a long time (i.e. 5 years = 15 days, 10 years = 20 days, etc.).
From a company's standpoint, it wouldn't seem fair to older employees who have been there for a while to have possibly less PTO than the new guy who just started. And unlike salary, which no one will know unless you tell them, PTO is something that everyone sees you take. If you're on vaca for 3 weeks then everyone is going to know that you have 15 days PTO. It could turn into a morale issue at the company if they just hand out PTO in different amounts to different people they hire. And if they were to give someone 15 days now, then they would probably have to give all those people who haven't reached that level (say 5 years for 15 days) that same amount as well.
So you're chances don't really look good to me. You'd probably have a better chance asking for more money; but then you're entry level, so I'm not sure that would be successful either. You just have to decide if the extra PTO is worth the extra commute and live with that decision. |
89,852 | I am considering two job offers for entry level positions straight out of college. They are essentially the same salary, but one of them has a more convenient location (company A), while the other (company B) would require a car and longer commute. I am therefore leaning toward company A.
However, company B offered 15 days PTO (Paid time off), while company A offered only 10. Company A is a medium sized company (~2000 employees), and company B is large. Vacation time is very important to me since where I am living and will be working is across the country from any of my family.
Is it safe to negotiate with company A so that I could have 15 days PTO even though I am entry level? | 2017/04/26 | [
"https://workplace.stackexchange.com/questions/89852",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/69189/"
] | Companies commonly trade off salary and PTO in negotiating with senior level candidates. Most employers have automatic increases in annual leave with time on the job, and senior employees will have much more than the minimum, and want to keep it. The hiring companies are used to it. Your case is different. You could explain that you have obligations or commitments that make you need more time and say that you would, of course, expect them to reduce their salary offer. | If one job requires things that the other job doesn't (longer commute, a car), then they may offer "essentially the same salary" but they really shouldn't be considered "essentially the same". Even if you're only talking $40 a week extra for gas, you're still talking $2000 a year. And that doesn't even take into account the extra commute time - what is your time worth?
That being said, there is no harm in asking for what you want or need. Negotiating is a part of the hiring process. You may find that a company has strict rules that say that all new hires get 10 days and that is it, but you may find they have some flexibility - but you'll never know if you don't ask. I have found that PTO is one of those things that is more than likely set in stone. It is often used to reward employees who stay with a company for a long time (i.e. 5 years = 15 days, 10 years = 20 days, etc.).
From a company's standpoint, it wouldn't seem fair to older employees who have been there for a while to have possibly less PTO than the new guy who just started. And unlike salary, which no one will know unless you tell them, PTO is something that everyone sees you take. If you're on vaca for 3 weeks then everyone is going to know that you have 15 days PTO. It could turn into a morale issue at the company if they just hand out PTO in different amounts to different people they hire. And if they were to give someone 15 days now, then they would probably have to give all those people who haven't reached that level (say 5 years for 15 days) that same amount as well.
So you're chances don't really look good to me. You'd probably have a better chance asking for more money; but then you're entry level, so I'm not sure that would be successful either. You just have to decide if the extra PTO is worth the extra commute and live with that decision. |
89,852 | I am considering two job offers for entry level positions straight out of college. They are essentially the same salary, but one of them has a more convenient location (company A), while the other (company B) would require a car and longer commute. I am therefore leaning toward company A.
However, company B offered 15 days PTO (Paid time off), while company A offered only 10. Company A is a medium sized company (~2000 employees), and company B is large. Vacation time is very important to me since where I am living and will be working is across the country from any of my family.
Is it safe to negotiate with company A so that I could have 15 days PTO even though I am entry level? | 2017/04/26 | [
"https://workplace.stackexchange.com/questions/89852",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/69189/"
] | In your situation it might be wise to mention to Company A that you would rather work for them, but since your family lives cross country, and Company B is offering more PTO you are unsure of what to do. You can ask if there is any way that they could match that time. | If one job requires things that the other job doesn't (longer commute, a car), then they may offer "essentially the same salary" but they really shouldn't be considered "essentially the same". Even if you're only talking $40 a week extra for gas, you're still talking $2000 a year. And that doesn't even take into account the extra commute time - what is your time worth?
That being said, there is no harm in asking for what you want or need. Negotiating is a part of the hiring process. You may find that a company has strict rules that say that all new hires get 10 days and that is it, but you may find they have some flexibility - but you'll never know if you don't ask. I have found that PTO is one of those things that is more than likely set in stone. It is often used to reward employees who stay with a company for a long time (i.e. 5 years = 15 days, 10 years = 20 days, etc.).
From a company's standpoint, it wouldn't seem fair to older employees who have been there for a while to have possibly less PTO than the new guy who just started. And unlike salary, which no one will know unless you tell them, PTO is something that everyone sees you take. If you're on vaca for 3 weeks then everyone is going to know that you have 15 days PTO. It could turn into a morale issue at the company if they just hand out PTO in different amounts to different people they hire. And if they were to give someone 15 days now, then they would probably have to give all those people who haven't reached that level (say 5 years for 15 days) that same amount as well.
So you're chances don't really look good to me. You'd probably have a better chance asking for more money; but then you're entry level, so I'm not sure that would be successful either. You just have to decide if the extra PTO is worth the extra commute and live with that decision. |
4,300,857 | I'm trying to integrate AuthLogic into my rails application, and I followed the example which defines persistence\_token as a string :
<https://github.com/binarylogic/authlogic_example>
However when I run it with PostgreSQL 8.4 on my ubuntu desktop I get the following error :
```
ActiveRecord::StatementInvalid in UsersController#index
PGError: ERROR: operator does not exist: character varying = integer
LINE 1: ...* FROM "users" WHERE ("users"."persistence_token" = 21007622...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT * FROM "users" WHERE ("users"."persistence_token" = 2100762299) LIMIT 1
```
I tried to change persistence\_token to an integer, but then it seemed other parts of AuthLogic did not update it.
I'm sure this must be a common problem but googling around was not very helpful, any ideas how to resolve this?
Ruby version: 1.8.7
Rails version: 2.3.5
AuthLogic version: 2.1.6 | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523443/"
] | This is a problem because the rows in your table have a 'persistence\_token' value of nil. Setting the column to a value will cause this error to go away. I suspect it has something to do with the way rails inspects the table columns and its interaction with authlogic. | Can you show the code that declares persistence\_token?
I'd try type casts and conversions first. On the SQL side, all these will work.
```
WHERE ("users"."persistence_token" = cast(2100762299 as varchar))
WHERE ("users"."persistence_token" = 2100762299::text)
WHERE ("users"."persistence_token" = text(2100762299))
WHERE ("users"."persistence_token" = 2100762299 || '')
```
That last one is an implicit type coercion. It forces PostgreSQL to treat the number as a string by concatenating it to an empty string.
But you might have to change the data type at run time in Ruby.
```
yournumber.to_s
``` |
24,525,847 | I am confused about this Javascript code which I used to get total rows in a table. It will always output an excess of 1. Example: it will print 5 instead of 4!
```
<script>
(function() {
var div = document.getElementById('divID11');
div.innerHTML = document.getElementById('tableId11').rows.length;
})();
</script>
<div id =divID11></div>
```
and table structure is shown below
```
<table id="tableId11>
<thead>
<tr>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $data ?></td>
</tr>
</tbody>
```
What I am lacking here?

Outputs 3 for the name column when in fact there only 2. | 2014/07/02 | [
"https://Stackoverflow.com/questions/24525847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you want count only `TBODY` rows, use this JavaScript code:
```
(function() {
var div = document.getElementById('divID11');
div.innerHTML = document.getElementById('tableId11').getElementsByTagName("tbody")[0].rows.length;
})();
```
Your JavaScript code counting all rows in table (thead and tbody). If you want count only tbody rows, you must specify the element (so you must modify your code to specify, with which part of your table you wanna work).
**[JSFiddle here](http://jsfiddle.net/pJ86u/3/)** | Try this :
```
var div = document.getElementById('divID11');
div.innerHTML = document.getElementById('tableId1').getElementsByTagName('tbody')[0].rows.length;
``` |
8,327,510 | Suppose I have a MySQL query with two conditions:
```
SELECT * FROM `table` WHERE `field_1` = 1 AND `field_2` LIKE '%term%';
```
The first condition is obviously going to be a lot cheaper than the second, so I'd like to be sure that it runs first, limiting the pool of rows which will be compared with the LIKE clause. Do MySQL query conditions run in the order they're listed or, if not, is there a way to specify order? | 2011/11/30 | [
"https://Stackoverflow.com/questions/8327510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253705/"
] | MySQL has an internal query optimizer that takes care of such things in most cases. So, typically, you don't need to worry about it.
But, of course, the query optimizer is not foolproof. So...
Sorry to do this to you, but you'll want to get familiar with `EXPLAIN` if you suspect that a query may be running less efficiently than it should.
<http://dev.mysql.com/doc/refman/5.0/en/explain.html> | If you have doubts about MySQL usage of index, you can suggest what index should be used.
<http://dev.mysql.com/doc/refman/5.1/en/index-hints.html> |
8,327,510 | Suppose I have a MySQL query with two conditions:
```
SELECT * FROM `table` WHERE `field_1` = 1 AND `field_2` LIKE '%term%';
```
The first condition is obviously going to be a lot cheaper than the second, so I'd like to be sure that it runs first, limiting the pool of rows which will be compared with the LIKE clause. Do MySQL query conditions run in the order they're listed or, if not, is there a way to specify order? | 2011/11/30 | [
"https://Stackoverflow.com/questions/8327510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253705/"
] | MySQL has an internal query optimizer that takes care of such things in most cases. So, typically, you don't need to worry about it.
But, of course, the query optimizer is not foolproof. So...
Sorry to do this to you, but you'll want to get familiar with `EXPLAIN` if you suspect that a query may be running less efficiently than it should.
<http://dev.mysql.com/doc/refman/5.0/en/explain.html> | The optimiser will evaluate the WHERE conditions in the order it sees fit.
SQL is [declarative](http://en.wikipedia.org/wiki/Declarative_programming): you tell the optimiser *what* you want, not *how* to do it.
In a [procedural/imperative](http://en.wikipedia.org/wiki/Imperative_programming) language (.net, Java, php etc) then you say *how* and would choose which condition is evaluated first.
Note: "left to right" does apply in certain expressions like `(a+b)*c` as you'd expect |
8,327,510 | Suppose I have a MySQL query with two conditions:
```
SELECT * FROM `table` WHERE `field_1` = 1 AND `field_2` LIKE '%term%';
```
The first condition is obviously going to be a lot cheaper than the second, so I'd like to be sure that it runs first, limiting the pool of rows which will be compared with the LIKE clause. Do MySQL query conditions run in the order they're listed or, if not, is there a way to specify order? | 2011/11/30 | [
"https://Stackoverflow.com/questions/8327510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253705/"
] | The optimiser will evaluate the WHERE conditions in the order it sees fit.
SQL is [declarative](http://en.wikipedia.org/wiki/Declarative_programming): you tell the optimiser *what* you want, not *how* to do it.
In a [procedural/imperative](http://en.wikipedia.org/wiki/Imperative_programming) language (.net, Java, php etc) then you say *how* and would choose which condition is evaluated first.
Note: "left to right" does apply in certain expressions like `(a+b)*c` as you'd expect | If you have doubts about MySQL usage of index, you can suggest what index should be used.
<http://dev.mysql.com/doc/refman/5.1/en/index-hints.html> |
61,481,173 | I have the following `ListView`-
```
<ListView x:Name="listViewm" ItemsSource="{ Binding Rows }">
<ListView.Header >
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Text="Name" Grid.Column="3" FontSize="Medium" />
<Label Text="Age" Grid.Column="2" FontSize="Medium" />
<Label Text="DOB" Grid.Column="1" FontSize="Medium" />
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<!--I need my Row values here-->
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
I need to create a row for each entry I have in a list and add it to the grid dynamically -
```
protected override void OnAppearing()
{
CreateGrid();
}
public ObservableCollection<Row> Rows { get; set; }
public class Row
{
public string Name { get; set; }
public string Age { get; set; }
public string DOB { get; set; }
}
public void CreateGrid()
{
Rows = new ObservableCollection<Row>();
Rows.Clear();
foreach(var entry in entryList) { // entryList just contains values I use to populate row info
var row = new Row();
row.Name = entry.name;
row.Age = entry.age;
row.DOB = entry.dob;
Rows.Add(row);
}
}
```
The itemSource is not binding so no new rows are being create, I tried removing `ItemsSource="{ Binding Rows }"` in the XAML and using `listViewm.ItemsSource = Rows` in the code behind instead however this also did not work.
So if `entryList` had 3 test entries for John, Bob and Bill the table should look like -
```
+----------------+
| Name Age DOB |
+----------------+
| John 31 06/09 |
| Bill 32 07/10 |
| Bob 34 08/11 |
+----------------+
``` | 2020/04/28 | [
"https://Stackoverflow.com/questions/61481173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/466844/"
] | Your are not adding your values to the listview.
```
<ListView x:Name="listViewm" ItemsSource="{ Binding Rows }">
<ListView.Header >
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Text="Name" Grid.Column="3" FontSize="Medium" />
<Label Text="Age" Grid.Column="2" FontSize="Medium" />
<Label Text="DOB" Grid.Column="1" FontSize="Medium" />
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<!--I need my Row values here-->
<Label Text="{Binding Name}" />
<Label Grid.Column="1" Text="{Binding Age}" />
<Label Grid.Column="2" Text="{Binding DOB}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
``` | I could be wrong but when you initialize the Rows object , you should update the itemsSource of the listview.
```cs
public void CreateGrid()
{
Rows = new ObservableCollection<Row>();
Rows.Clear();
// Rows is initialized as a new collection so update the itemssource
listViewm.ItemsSource = Rows;
foreach(var entry in entryList)
{
// entryList just contains values I use to populate row info
var row = new Row();
row.Name = entry.name;
row.Age = entry.age;
row.DOB = entry.dob;
Rows.Add(row);
}
}
``` |
6,847,561 | I used [this](http://mckennedy.org/blog/2009/02/25/javascript-onmouseover-link-change-divs-background-image/) code to make a nav in which onMouseOver, the neighboring div's background changes to a corresponding image.
However, I amended the code to reflect the multiple navigation buttons I needed. This is probably where I went wrong. Also, I am working in a ColdFusion environment on Sitemaker CMS. This could also be a problem.
Here's the code.
```
<script>
function changeStyle1() {
document.getElementById('banners').style.backgroundImage = url('images/banners/contractingbanner.jpg');
}
function changeStyle2() {
document.getElementById('banners').style.backgroundImage = url('images/banners/procurementbanner.jpg');
}
function changeStyle3() {
document.getElementById('banners').style.backgroundImage = url('images/banners/distributionbanner.jpg');
}
function changeStyle4() {
document.getElementById('banners').style.backgroundImage = url('images/banners/printingbanner.jpg');
}
function changeStyle5() {
document.getElementById('banners').style.backgroundImage = url('images/banners/custompacksbanner.jpg');
}
function changeStyle6() {
document.getElementById('banners').style.backgroundImage = url('images/banners/businessdevelopmentbanner.jpg');
}
function changeStyle7() {
document.getElementById('banners').style.backgroundImage = url('images/banners/sustainabilitybanner.jpg');
}
function changeStyleBack() {
document.getElementById('banners').style.backgroundImage = url('images/banners/laundrybanner.jpg');
}</script>
```
---
```
<div id="banners">
</div>
<ul id="nav">
<li><a id="contractingservices" href="body.cfm?id=1" onmouseover="changeStyle1()"; onmouseout="changeStyleBack()">Contracting Services</a></li>
<li><a id="procurement" href="body.cfm?id=1" onmouseover="changeStyle2()"; onmouseout="changeStyleBack()" >Procurement & Data Management</a></li>
<li><a id="distribution" href="body.cfm?id=1" onmouseover="changeStyle3()"; onmouseout="changeStyleBack()">Distribution</a></li>
<li><a id="printing" href="body.cfm?id=1" onmouseover="changeStyle4()"; onmouseout="changeStyleBack()" >Printing</a></li>
<li><a id="laundry" href="body.cfm?id=1">Laundry</a></li>
<li><a id="custompacks" href="body.cfm?id=1" onmouseover="changeStyle5()"; onmouseout="changeStyleBack()" >Custom Packs</a></li>
<li><a id="businessdevelopment" href="body.cfm?id=1" onmouseover="changeStyle6()"; onmouseout="changeStyleBack()" >Business Development</a></li>
<li><a id="sustainability" href="body.cfm?id=1" onmouseover="changeStyle7()"; onmouseout="changeStyleBack()" >Sustainability</a></li>
```
How do I fix this code to make it operational or find another JavaScript or jQuery solution? I've searched and search only to come up with dozens of same-div JS background changers, which can easily be replicated with CSS. | 2011/07/27 | [
"https://Stackoverflow.com/questions/6847561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/865837/"
] | This is not a trivial problem with a "the library you want is here" answer.
You are going to have to start getting familiar with what a Fast Fourier Transform is, and there are various libraries that implement those. FFTs can translate time-dimension data like a music file, to frequency-dimension data. You could use an FFT algorithm to convert the music file, look for frequency peaks, try to map them to notes and chords.
Here is a [wikipedia entry](http://en.wikipedia.org/wiki/Fourier_analysis#Applications_in_signal_processing) showing what Fourier analysis is and examples of what it can be applied to.
Here is a SO answer for someone looking for a [C# FFT library](https://stackoverflow.com/questions/170394/fast-fourier-transform-in-c)
Not easy at all - good luck. | EDIT: As recursive pointed out, you're not simply looking for a way to read/write midi files. I misunderstood. If you're trying to extract notes from a mp3/wav file, you won't have much luck finding any library that does that. It's not as simple, since you're working with essentially analog data instead of digital. I've seen some application that will at least show you a spectrograph of your audio, and if the audio is clean enough and only a single instrument, you can see what appears to be the notes. But you'd have to figure it all out manually. [Izotope RX](http://www.izotope.com/products/audio/rx/) was the VST I was thinking of.
I had this problem maybe 5 or 6 years ago and eventually started writing my own (not as easy as it sounds). I got something working to read, but not write, but eventually ran out of time to work on the project.
I would try [NAudio](http://naudio.codeplex.com/). I can't specifically vouch for it, as I haven't personally used it. However, the feature list says it has extensive support for reading and writing MIDI files. |
57,665,414 | I am trying to use GroovyClassLoader in java to execute a method in Groovy Class.
I have created a Java Class, pubic method which creates a instance of GroovyClassLoader , parseClass and then creates a new Instance of the class, Calls a method in the class.
```
public class Gtest{
public static void main(String args[])throws IOException , InstantiationException ,IllegalAccessException {
GroovyClassLoader gcl = new GroovyClassLoader();
Class cls = gcl.parseClass("class Foo { void doIt() { println \"ok\" } }");
Object obj = cls.newInstance();
if(obj == null){
System.out.println("null");
}
obj.doIt();
}
}
```
Error : Gtest.java:22: error: cannot find symbol
obj.doIt();
^
symbol: method doIt()
location: variable obj of type Object
1 error | 2019/08/26 | [
"https://Stackoverflow.com/questions/57665414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11870347/"
] | How a rewrite rule works; it has 2 parts:
```
`RewriteRule 1_FIND_THIS 2_OVERWRITE_WHITH_THIS`
```
Keep in mind that you re using plain Regular Expressions in both (a special syntax though) with all of its power.
so in your case probably
`RewriteRule search\/([\w]+)\/$ page.php?search=$1 [NC,L]` | Here's a copy of my answer to a [similar question](https://stackoverflow.com/a/57666990/6456163). Hopefully it'll help you:
[This](https://grokbase.com/t/php/php-general/0159ts8x8h/passing-parameters-in-the-url-using-forward-slashes#20010509ss83mvqx7894e90njxvrsjgkcg) page appears to have a solution to what you are trying to do:
```
<?
$Params = explode( '/', $PATH_INFO );
while( list( $Index, $Value ) = each( $Params )) {
echo "Params[ $Index ] = $Value<BR>\n" );
}
?>
```
>
> Hit this URL:
>
>
> <http://whatever.site.com/ThisIsAProgram/these/directories/are/not/real>
>
>
> You should get:
>
>
> Params[ 0 ] =
>
>
> Params[ 1 ] = these
>
>
> Params[ 2 ] = directories
>
>
> Params[ 3 ] = are
>
>
> Params[ 4 ] = not
>
>
> Params[ 5 ] = real
>
>
>
And to display the PHP file as just the file name, try this:
```
Options +MultiViews
RewriteEngine On
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]
```
---
If you are wanting a more **complete** example, [this answer](https://serverfault.com/a/210766) covers it a lot more in depth than I could. This will definitely help you cover all your bases and understand the issue if my other linked article doesn't make it clear enough. |
86,179 | Notation:
* $E$ is a non-CM Elliptic curve over $\mathbb{Q}$.
* $p$ is an ordinary prime.
* $f$ - cuspidal eigenform of weight $k$ = 2 attached with $E$.
* $\rho\_f$ - the global 2-dimensional $p$-adic Galois representation attached with $f$.
$\rho\_f$ : $G\_S$ $\rightarrow$ $\mathrm{GL}\_2({\mathbb{Z}}\_p)$.
* $G\_S:= \mathrm{Gal}(\mathbb{Q}\_S/{\mathbb{Q}})$, where $\mathbb{Q}\_S$ - maximal unramified extension outside the set
$S=\{\text{ bad primes of } E \} \cup\{ p, \infty \}$.
Assume that the residual representation $\overline{\rho}\_f$ is $p$-split.
The prime $p$ is an ordinary prime. So the the image of $\rho\_f$ restricted to the decomposition group $G\_p:=\mathrm{Gal}(\overline{\mathbb{Q}\_p}/\mathbb{Q}\_p)$ will be of the form $\rho\_f$ $\mid$ $G\_p$ $\sim$
$\begin{pmatrix} a & \* \\ 0
& d \end{pmatrix}$. The residual representation $\overline{\rho}\_f$ is $p$-split. So, $\overline{\rho}\_f$ $\sim$
$\begin{pmatrix} \omega \lambda\_p^{-1}(\overline{a}\_p) & 0 \\ 0
& \lambda\_p(\overline{a}\_p)
\end{pmatrix}$, where $\lambda\_p$ is an unramified character which sends $\mathrm{Frob}\_p$ to $\overline{a}\_p$, $\overline{a}\_p \in \mathbb{F}\_p$ is the mod $p$ reduction of the
$p$-th coefficent $a\_p$ of $f$, and $\omega$
is the $p$-adic cyclotomic character.
>
> **Question**: What is the image of the representation $\rho\_f: G\_p \rightarrow \mathrm{GL}\_2(\mathbb{Z}/p^n \mathbb{Z})$,
> where $(\mathbb{Z}/p^n\mathbb{Z})^2 \simeq (E[p^n])$, the $p^n$-torsion points of $E$,
> for some fixed $n \geq 2$? Is it possible to compute it (or atleast it's order) by using MAGMA/SAGE/PARI?
>
>
> | 2012/01/20 | [
"https://mathoverflow.net/questions/86179",
"https://mathoverflow.net",
"https://mathoverflow.net/users/20754/"
] | See [Serre's paper](http://www.digizeitschriften.de/en/dms/toc/?PPN=GDZPPN002089629) where he shows how the the image in $GL\_2(Z\_p)$ (and hence mod $p^n$ for any $n>0$) is determined by the image of Galois in $GL\_2(Z/{pZ})$; there are more recent works by Zywina among others.treating the case of abelian varieties. Serre's paper does the case of non-CM elliptic curve (the CM case can be found in Serre-Tate's Good reduction paper). | One can say something about the image of $\rho\_f|G\_p$ by checking if $f$ has a companion form mod $p^n$. This can be explicitly done because one knows what the weight of this companion (if it exists) should be ($p^{n-1}(p-1)$, since $k=2$) and the conguences mod $p^n$ that the form's Fourier coefficients must satisfy *vis a vis* the $a\_p$'s. One need only check that these congruences are satisfied up to the Sturm bound to conclude that the companion exists. If a companion mod $p^n$ exists then $\rho\_f|G\_p$ mod $p^n$ splits and $p^n$ won't divide the order of its image, else it will. |
26,014,518 | I'm making a flipping counter which is supposed to change color when reaching the target number (1000 in the example). But the thing is the different parts of the counter doesn't change color at the same time, we can clearly see a delay between the tiles that make up the counter...
I'm using a simple jQuery addClass to trigger the color change:
```
$("#rhcounter .count").addClass("red");
```
Any ideas what could be causing that ?
Here is the fiddle: <http://jsfiddle.net/ka6ke28m/6/>
Thanks for your help ! | 2014/09/24 | [
"https://Stackoverflow.com/questions/26014518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253358/"
] | You should first move to first record of `Cursor` by using `moveToFirst()`, like
```
if (resultSet != null && resultSet.moveToFirst());
{
do {
if (resultSet != null) {
values[i] = resultSet.getString(resultSet.getColumnIndex("noteTitle"));
i++;
}
}while (resultSet.moveToNext());
resultSet.close();
}
``` | There is no issue in code that I have mentioned above in question (of course after Manish correction).
I figured out that in my application, I am using 'App drawer'. 'App drawer' code is checking all contents to display in list and all those supposed to come from data base (i.e. using this code. Reading from database). This is giving me error "Index 0 requested, with a size of 0". This is referring for App drwaer values. I have removed app drawer part and this code works fine (i.e. my application didn't crash and no exception). I need to find solution for dynamic 'App drawer' (this will be different story).
I just mentioned this becasue if you are wondering whats wrong with your code. Then probably you need to look into other sections/module of your application. |
26,014,518 | I'm making a flipping counter which is supposed to change color when reaching the target number (1000 in the example). But the thing is the different parts of the counter doesn't change color at the same time, we can clearly see a delay between the tiles that make up the counter...
I'm using a simple jQuery addClass to trigger the color change:
```
$("#rhcounter .count").addClass("red");
```
Any ideas what could be causing that ?
Here is the fiddle: <http://jsfiddle.net/ka6ke28m/6/>
Thanks for your help ! | 2014/09/24 | [
"https://Stackoverflow.com/questions/26014518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253358/"
] | You should first move to first record of `Cursor` by using `moveToFirst()`, like
```
if (resultSet != null && resultSet.moveToFirst());
{
do {
if (resultSet != null) {
values[i] = resultSet.getString(resultSet.getColumnIndex("noteTitle"));
i++;
}
}while (resultSet.moveToNext());
resultSet.close();
}
``` | You should call moveToNext method on the resultSet first
```
while(resultSet.moveToNext){
if(resultSet != null) {
values[i] = resultSet.getString(resultSet.getColumnIndex("noteTitle"));
}
}
resultSet.close()
```
for details on reading from sqlite database <https://developer.android.com/training/data-storage/sqlite> |
68,366,445 | I am using a cloud based EDR platform to monitor processes occurring on a client's compromised network. Something I have seen a lot of recently is msiexec.exe called with the option "-Embedding"
```
C:\Windows\System32\MsiExec.exe -Embedding 35507F61C46FB5B70D1543A9D335C298B
```
The msiexec documentation (found [here](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/msiexec)) has no mention of this option. Can anyone explain its usage? | 2021/07/13 | [
"https://Stackoverflow.com/questions/68366445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955556/"
] | You can find some information from
**[Aaron Stebner](https://twitter.com/astebner)** here: <https://learn.microsoft.com/en-us/archive/blogs/astebner/more-info-about-how-msi-custom-actions-work-behind-the-scenes>
Here is an extract:
>
> **msiexec.exe -Embedding (GUID)** - this is the custom action server (indicated by the -Embedding switch)
>
>
>
***Custom Action***: A custom action is a custom piece of code that runs during installation. They can be in script or binary form - **`dll`**, **`exe`**, **`vbscripts`**, **`etc...`** Danger close. With elevated rights they can basically do "anything", but usually they are OK.
***msiexec.exe***: There will be numerous **`msiexec.exe`** processes during the installation of any MSI file, and some MSI files can trigger quite a few of them. This has to do with how many custom actions exist in the MSI and probably a number of other things. There will also always be a **`client msiexec.exe process`** running in **`user context`** and a **`server msiexec.exe process`** running as **`LocalSystem`** (unless the server is run silently - then there is no user part to the install). These processes run the actual installation itself.
***Technical Tidbit***: I believe the **`msiexec.exe`** processes remain in the process list for about 10 minutes after the install. This at least used to be normal behavior (things change). [Old blog from Heath Stewart on this](https://devblogs.microsoft.com/setup/the-windows-installer-service/).
***Malware***: With regards to this in a malware-sense. The custom action process can certainly be infected, but most often it is not and the anti-virus software could decide to mess with it because of a false positive. System mode custom actions run elevated with temporary administrator rights and can certainly infect the computer with just about anything. Non-elevated MSI files can install trojans and other kinds of malware by launching them on startup and such things. However, elevated custom actions can install drivers and services and all kinds of madness.
***Anti-Virus Blues***: A common problem for MSI files is that an anti-virus could decide to quarantine an MSI in the super-hidden MSI cache folder: C:\Windows\Installer. This folder is highly protected and should not be accessed by anything, and messing around here typically causes MSI packages that can not be uninstalled (packages are cached to facilitate uninstall, modify and repair). [There are some hacks and fixes for such un-uninstallable packages](https://stackoverflow.com/a/53876981/129130). Additionally, [there are other reasons why the MSI source can be missing](https://stackoverflow.com/a/50478416/129130) (with System Restore weirdness being one of my suspected key culprits).
***Keys to the City***: Having gone well beyond what you actually asked: if you are sure an MSI is infected, I would be hesitant to invoke its uninstaller... I guess that goes without saying. If it runs elevated it has "the keys to the city". Use that Microsoft FixIt tool (found in the linked answer above) or some other approach to wipe the install. Or better yet: rebuild your box I suppose - as if you are not busy enough?
---
***Links:***
* [Comprehensive list of ways to uninstall MSI packages](https://stackoverflow.com/a/1055933/129130)
* [Why are there multiple msiexec.exe instances?](https://serverfault.com/a/67161/20599)
* [Locations where packages are cached](https://stackoverflow.com/a/48823086/129130) | That's not an option for us.
On NT based OS, MsiExec runs multiple times. Once in the user context and the other as a windows service. There are also other processes depending on custom action impersonation. Embedding is part of the process of how the client (user) side passes off the session to the server (service) side. |
12,952,553 | I am reading some tutorials on embedded programming and one of them says `int` and `signed int` are different but does not explain how or why.
I understand why `unsigned int` and `int` are different but `int` and `signed int` being different is a new one for me. | 2012/10/18 | [
"https://Stackoverflow.com/questions/12952553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/734154/"
] | It is for historical reasons only. Today whenever you declare `int` you get a `signed int`. The only point where you might see a difference even with today's compilers is with `char` versus `signed char` which are different by specification (and notable when assigning a literal string) but not with `int`. | As far as I know the difference exists only for char data type. Where `char a;` can be `signed char a;` or `unsigned char a;` depending on compiler options. As [this article](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka11308.html) says. (--signed\_chars)
For int data types, there is no difference between `int` and `signed int`. |
4,649 | Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы.
Спасибо. | 2012/05/15 | [
"https://rus.stackexchange.com/questions/4649",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/3/"
] | Если **этруски** и русские - родственные народы, то это должно наблюдаться в языке. А этого как раз нет (кроме созвучия названий). Родственные связи этрусского языка являются дискуссионными. Составление словаря этрусского языка и расшифровка текстов продвигаются медленно и по сей день далеки от завершения. Этрусский язык считается языком-изолятом и не имеет признанных наукой родственников. Одной из гипотез о возможном родстве этрусского является версия Старостина и Дьяконова о родстве этрусского языка с вымершими хурритским и урартским. Другие исследователи продолжают настаивать о родстве этрусского с анатолийской (хетто-лувийской) ветвью индоевропейских языков. Учитывая **немногочисленность известных этрусских слов** и лишь *ограниченное знание этрусской грамматики*, все эти предположения в очень большой степени **спекулятивны**.
Главное, чтó при наивном, любительском отношении к делу остается незамеченным и чем грешат многочисленные псевдонаучные сочинения, — это непонимание того, что никакие языки не остаются в ходе времени неизменными. Никто не будет отрицать, что этруски жили примерно 25 веков назад. Так что даже если предположить, что это русские, то они говорили на русском языке двадцатипятивековой давности, а не на современном языке. А разница между нынешним языком и языком, который был двадцать пять веков назад, колоссальная!
Что касается **пруссов**, то о происхождении их этнического самоназвания prūss, prūsai («прусс», «пруссы») и регионима Prūsa («Пруссия») среди исследователей нет единого мнения. По замечанию некоторых исследователей романтиков, самоназвание страны пруссов (Prūsa — произн. как «Пруса») созвучно древнему имени страны фризов (Frusa — «Фруза»); вероятно, как раз не пожелавшие отступиться от язычества фризы, будучи главными союзниками «мятежных» саксов, и принесли на территорию Погезании, Помезании и Вармии прототип самоназвания древних пруссов.
По другой версии, название «Пруссия» возникло из гидронима Русс или Русне, то есть названия правого рукава дельты Немана, или же из «Руссна» — прежнего названия Куршского залива, которое можно прочесть на карте Пруссии, составленной в 1576 г. немецким историком и картографом Каспаром Генненбергером (англ.)русск. (1529—1600).
Третья версия самоназвание древних пруссов выводит из коневодства, которым славились древние пруссы. *Прус* означает 'конь' в готском языке, а также 'кобыла' в старославянском.
Как видите, схожесть названий может натолкнуть на ложный след и совершенно не означает, что народы, носящие эти названия, родственны. К тому же специалисты сами подчеркивают, что не обладают достаточным объемом информации, чтобы делать такие "сенсационные" выводы. Нужны доказательства, а их-то у историков-любителей и нет. | Этру**сс**ки - это очередной шедевр от Задорнова.
Этим всё сказано. Честно говоря, не заслуживает оно развернутых комментариев.
А вот насчет пруссов...
Начнем от печки. Поскольку этнохороним "русские" не имеет ясной этимологии (посмотрите в Интренете, столько всего понаписано) и версии строятся в ориентации на разные языки-источники (от скифских до норманских), то и разговоры о родстве его с ещё менее понятным самоназванием далёкого от всех народа ещё менее состоятельны. Вообще пруссы - исчезнувший народ балтийской группы, родственен литовскому. Таким образом сторонникам родства пруссов и русских надо копать в сторону балто-славянских корней топонима Русь или этнохоронима руссы. Но такие версии сейчас непопулярны. Хотя можно порыскать, глядишь что-то и найдётся.
Касательно же самого происхождения названия пруссы я повторяться не буду. **Olsa** даёт всё более чем исчерпывающе. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.