qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
556,662 | We know that black holes are actually "black" because no light can escape them due to their gravity and that's why they appear black. That means the mass of the black hole most be extremely large even in a cosmological scale.
If light cannot escape black holes due to the their gravity, and the more massive an object the stronger its gravity is, why there are black holes that have a mass only 6 times the mass of the Sun? Light should escape them in that case and make them visible. No? | 2020/06/02 | [
"https://physics.stackexchange.com/questions/556662",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/266351/"
] | The intuition that a black hole must have a very large mass is not true. The relevant parameter is how much mass is there within a (volume of some characteristic) radius. In the case of simple spherical objects, if a mass $M$ is concentrated within a radius $2GM/c^2$ then light (or anything else for that matter) cannot escape from the region $r< 2GM/c^2$, and the region $r< 2GM/c^2$ is called a black hole. Thus, for any small amount of mass, if it is concentrated within a (volume characterized by a) small enough radius, then it is a black hole. In principle, you can have a black hole of the mass of a human being, but of course, its radius would be ridiculously small. This doesn't mean that all astrophysical stars, no matter their mass, would turn into black holes because the non-gravitational forces within the stars can resist the mass of the star from concentrating up to the required small radius $2GM/c^2$ if the mass of the star is not large enough. However, if the mass of the star is large enough (as described by the ~~Chandrashekhar~~ Tolman-Oppenheimer-Volkoff limit$^\*$), the mass of the star would reach a stage where it's confined within the radius $2GM/c^2$, and it would become a black hole.
**Edit**
Notice that the relevant parameter is $M/r$, not $M/r^3$. The radius of a (non-rotating uncharged) black hole with mass $M$ scales as $r\_s\sim M$. In other words, the density of a black hole with mass $M$ scales as $ M/r^3\_s\sim 1/M^2$. Thus, if you have a black hole with small enough mass (which would correspond to a black hole with a small enough radius), you can get as high a density as you want. There is no fundamental restriction on the maximum density as such besides whatever restrictions might exist on how small you can make a black hole in a quantum theory of gravity.
---
$^\*$ Thanks to `@CharlesFrancis` for this correction. The Chandrashekhar limit is the limit on the maximum mass of a stable white dwarf which can either devolve into a neutron star or a black hole if the mass is higher than this limit. However, the Tolman-Oppenheimer-Volkoff limit is the limit on the maximum mass of a neutron star beyond which it would devolve into a black hole. | what makes a black hole is how much mass is squeezed down into *how much space*, which establishes how strong the force of gravity is *at its surface*. That in turn determines its *escape velocity*; once the escape velocity equals the speed of light, a black hole forms.
If you squeezed the earth down to the size of a pea, the surface gravity of that pea would be great enough to form a black hole.
If you squeezed the mass of the entire sun down into a sphere with a diameter of 6 kilometers or less, a black hole would form.
In the universe today, gravity is the only force capable of compressing matter enough to form a black hole all on its own. The minimum size of a black hole thus formed is somewhere between 1.5 and 3 solar masses.
That size of black hole is produced when a star runs out of fuel and thence cools off enough for gravity to overcome the pressure caused by heat inside the star.
(Since the earth contains so little mass compared to 1.5 solar masses, gravity will never be capable of squeezing the earth down to the size of a pea.) |
21,036,530 | How to prevent duplication in dropdownlist using JSTL .
```
<select class="abc" name="folder" >
<c:forEach items="${model.abc}" var="folder" varStatus="status">
<option value="${folder}">${folder}</option>
</c:forEach>
</select>
```
Suppose my model object abc is having some data like :
Folder :"abc" , "bcd", "abc"
How to prevent abc to be populated in dropdown multiple times? | 2014/01/10 | [
"https://Stackoverflow.com/questions/21036530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2439770/"
] | Yes,if you need to use BackgroungAudioPlayer, it is necessary to create another project for AudioPlayer and add reference of it to your project.
Through MediaPlayer you can play files from medialibrary or IsolatedStorage.
So,for you it is necessary to follow those steps.Hope this helps. | Use the media element tag from the Windows Phone 8 Toolbox:
You should be able to achieve this without any difficulty, But it will not run in the background. |
43,204,496 | We are trying to SET pickled object of size 2.3GB into redis through redis-py package. Encountered the following error.
>
> BrokenPipeError: [Errno 32] Broken pipe
>
>
> redis.exceptions.ConnectionError: Error 104 while writing to socket. Connection reset by peer.
>
>
>
I would like to understand the root cause. Is it due to input/output buffer limitation at server side or client side ? Is it due to any limitations on RESP protocol? Is single value (bytes) of 2.3 Gb allowed to store into Redis ?
>
> import redis
>
>
> r = redis.StrictRedis(host='10.X.X.X', port=7000, db=0)
>
>
> pickled\_object = pickle.dumps(obj\_to\_be\_pickled)
>
>
> r.set('some\_key', pickled\_object)
>
>
>
**Client Side Error**
>
> BrokenPipeError: [Errno 32] Broken pipe
>
>
> /usr/local/lib/python3.4/site-packages/redis/connection.py(544)send\_packed\_command()
>
>
> self.\_sock.sendall(item)
>
>
>
**Server Side Error**
>
> 31164:M 04 Apr 06:02:42.334 - Protocol error from client: id=95 addr=10.2.130.144:36120 fd=11 name= age=0 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=16384 qbuf-free=16384 obl=42 oll=0 omem=0 events=r cmd=NULL
>
>
> 31164:M 04 Apr 06:07:09.591 - Protocol error from client: id=96 addr=10.2.130.144:36139 fd=11 name= age=9 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=40 qbuf-free=32728 obl=42 oll=0 omem=0 events=r cmd=NULL
>
>
>
Redis Version : 3.2.8 / 64 bit | 2017/04/04 | [
"https://Stackoverflow.com/questions/43204496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621477/"
] | Redis' String data type can be at most 512MB. | The issue is with the data size being passed to Redis. The command is sent to Redis as two items follows the RESP Standards
item #1
```
b'*3\r\n$3\r\nSET\r\n$8\r\nsome_key\r\n$2460086692\r\n'
Where
*3 - indicates RESP array of three elements
\r\n - indicates the RESP Carriage return Line Feeder(separator)
$3 - indicates Bulk string of length 3 bytes(here it is 'SET')
$8 - indicates Bulk String of length 8 bytes(he it is 'some_key')
$2460086692 - indicates Bulk String of length 2460086692 bytes (the length of value 2460 MB to be passed to Redis as next item )
```
item #2
```
b'\x80\x03csklearn.ensemble.forest\nRandomForestC...
Here item #2 indicates the actual data
```
* The moment item #1 instruction is passed to Redis Server, the server closed the connection as the value $2460086692 violated the protocol rule of 512 MB
* When the item #2 is sent to the Redis Server, we got Broken Pipe exception as the connection is already closed by the server. |
57,352,744 | Suppose i have a code that validates the username
```
oValidationManager.sUsername = document.getElementById('username');
validateUsername: function () {
oValidationManager.sUsername.addEventListener('focus', function(event){
oValidationManager.sUsername.style.borderColor = '#FF0000';
oValidationManager.sUsername.style.boxShadow = 'inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6)';
});
oValidationManager.sUsername.addEventListener('blur', function(){
oValidationManager.sUsername.style.borderColor = '';
oValidationManager.sUsername.style.boxShadow = '';
});
if (oValidationManager.sUsername.value === '') {
oValidationManager.sShowUsernameError.innerHTML = oValidationManager.aErrorMsg.username.required;
} else {
oValidationManager.sUsername.addEventListener('focus', function(event){
oValidationManager.sUsername.style.borderColor = '#00FF00';
oValidationManager.sUsername.style.boxShadow = 'inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 255, 0, 0.6)';
});
oValidationManager.sShowUsernameError.innerHTML = '';
return true;
}
return false;
},
```
What I want to happen is to change the focus color if the field is valid even when the user is typing. Using the code above i can get the result however I need to click somewhere to see the updated focus color it is not being updated while typing. | 2019/08/05 | [
"https://Stackoverflow.com/questions/57352744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9934276/"
] | Try doing this without event listeners. Rather than changing the css properties directly try adding and removing classes. Do your error check and if there is one add a class like `.invalid` to the input. Then just have a different style for that class.
CSS:
```css
.input-field{
border: 2px solid transparent;
}
.input-field:focus{
border-color: blue;
}
.input-field.invalid:focus{
border-color: red;
}
```
HTML:
```html
<input type="text" class="input-field"/>
```
JS:
```js
let myInput = document.querySelector(".input-field");
if(/*Something is wrong*/){
myInput.classlist.add("invalid");
}else{
myInput.classlist.remove("invalid");
}
``` | ```css
input:invalid {
background-color: red;
}
```
```html
<input type="email">
``` |
206,471 | We have mocap animations and when adding those animations to characters in unity their lower bodies get twisted like that.
But when I import those animatinos to Blender to inspect they don't have such problem.
Also I remember, we asked another person to look at these animatinos in another 3D software and he said, he saw errors in animatinos right away. I can't even see Them in Blender, and don't know where to look to solve this problem.
Would be so thankful if anyone could give me directions. Thanks a lot.
[](https://i.stack.imgur.com/6hBYX.png) | 2020/12/29 | [
"https://blender.stackexchange.com/questions/206471",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/113674/"
] | You need to override the context. Context properties are described [here](https://docs.blender.org/api/current/bpy.context.html). And more specifically, for particle settings, [here](https://docs.blender.org/api/current/bpy.context.html#bpy.context.particle_settings).
To make it work, just add the following to your code:
```
# Copy the current context
context_override = bpy.context.copy()
# Override the wanted property
context_override["particle_settings"] = settings
# Call the operator
bpy.ops.boid.rule_add(context_override, type='FLOCK')
```
To assign an object as goal, you can:
```
import bpy
# Get the particle object
obj = bpy.context.object
# Get the goal
empty = bpy.data.objects["Empty"]
settings = bpy.data.particles["ParticleSettings"]
# You can also:
# settings = obj.particles_systems["ParticleSettings"].settings
# Get the boid part
boids_part = settings.boids
# Get the state (it seems there is one boid state)
state = boids_part.states[0]
# Or:
#state = boids_part.states['State']
# Get the 'Goal' rule from its index
# You should know its index as you've set it up earlier
rule = state.rules[2] # '2' is an example, so
# Or:
#rule = state.rules['Goal'] # But may be the same name several times
# Assign the empty as goal
rule.object = empty
``` | **Some further notes on this.**
AFAIC @lemon has provided the answer re which member is required to override. This is a little TL;DR ...looked at this prior to answer having tried "particle\_system"., didn't work, put in the look at later.
The properties panel has what is known as 'BUTTONS' context which contains `particle_system`, `particle_system_editable` and `particle_settings` See <https://docs.blender.org/api/current/bpy.context.html#bpy.context.particle_system>
This is where the particle settings are displayed. If we view source in the particle tab, opening UI file `bl_ui/poperties_particle.py` can see that a little helper function is included to get the particle settings from context. Notice it uses either the context member available or those pinned to the panel.
```
def particle_get_settings(context):
if context.particle_system:
return context.particle_system.settings
elif isinstance(context.space_data.pin_id, bpy.types.ParticleSettings):
return context.space_data.pin_id
return None
```
One wonders why it doesn't use `context.particle_settings`. Since you are adding a new system, and quite likely not from the properties space will not use this.. moving on.
Other things to look for are the setting of a context pointer in a draw method, eg in this case something like
```
def draw(self, context):
self.layout.context_pointer_set(
"particle_settings",
particle_get_settings(context)
)
self.layout.operator("boid.foo")
```
*Not used here but another way to set a context member. THe operator "boid.foo" would use the `context.particle_settings` a returned from the method* Not used in this case moving on...
**Using the reference**
In as much as you have checked for no particle systems before adding one, and referencing it as the zeroth time of the objects particle systems... Can instead get the particle system from the new modifiers reference.
```
>>> mod = C.object.modifiers.new("Foo", type='PARTICLE_SYSTEM')
>>> ps = mod.particle_system
>>> settings = ps.settings
>>> mod
bpy.data.objects['Cube'].modifiers["Foo"]
>>> ps
bpy.data.objects['Cube'].particle_systems["Foo"]
>>> settings
bpy.data.particles['Foo']
```
Setting to boids, adds two default rules separate and flock, in that order.
```
>>> settings.physics_type = 'BOIDS'
>>> settings.boids.states['State'].rules[:]
[bpy.data.particles['Foo'].rules["Separate"], bpy.data.particles['Foo'].rules["Flock"]]
```
Note that using `settings.boids.active_boid_state.rule` avoids the need for state name.
**Finding the override.**
A usual rule of thumb to find an override, armed with the big possibility that outside of properties area need to set one of the aforementioned *particlish* context members, can check using the operators `poll` method.
```
>>> override = {
... "particle_system" : ps,
... "particle_editable_system" : ps,
... "particle_settings" : settings,
... }
>>> bpy.ops.boid.rule_add.poll()
True
>>> bpy.ops.boid.rule_add()
{'CANCELLED'}
```
Which is a bummer, if there was a poll error could try polling against different context members... but alas in this instance the boid operators poll regardless.
```
>>> bpy.ops.boid.rule_add.poll(override)
True
>>> bpy.ops.boid.rule_add.poll({"snoo" : 'LUMP'})
True
```
Sheesh, not much luck, moving on
```
>>> bpy.ops.boid.rule_move_up(override)
{'FINISHED'}
```
At last, the Eureka moment of seeing 'FINISHED' indicating the operator has done its thing.
**Cleaning the slate.**
Ok, using the single context override as suggested by @lemon
May be simpler to remove the two default rules and rebuild rather than a list shuffle.
```
>>> while settings.boids.active_boid_state.rules:
... bpy.ops.boid.rule_del({"particle_settings" : settings})
...
{'FINISHED'}
{'FINISHED'}
```
*Note, am of the opinion since 2.8 can pass only the overridden props to the operator.*
**Add the new rules in order.**
Example. Add the new rules based on some data. If the rule is a goal, set the goal object to some previously set target object.
```
>>> state = settings.boids.active_boid_state
>>> rules = ('FLOCK', 'GOAL', 'FIGHT', 'FLOCK')
>>> for rule in rules:
... bpy.ops.boid.rule_add({"particle_settings" : settings}, type=rule)
... if rule == 'GOAL':
... state.active_boid_rule.object = target_object
...
{'FINISHED'}
{'FINISHED'}
{'FINISHED'}
{'FINISHED'}
``` |
37,160,808 | I have Websphere Portal 8.5.5.2 Cluster of 2 Windows Server Nodes.
I have a separate Jenkins Build Server (also windows), I configured the plugin correctly and click test connection returns connection successful.
when running build now to deploy the ear file it returns an error:
```
13:51:31 Started by user Jenkins
13:51:31 Building in workspace C:\Jenkins\workspace\Deploy
13:51:31 Connecting to IBM WebSphere Application Server...
13:51:31 The following artifacts will be deployed in this order...
13:51:31 -------------------------------------------
13:51:31 AdvisorsThemeEAR_20160505.ear
13:51:31 -------------------------------------------
13:51:31 Error deploying to IBM WebSphere Application Server: org.jenkinsci.plugins.websphere.services.deployment.DeploymentServiceException: ADMA0092E: An unexpected exception occurred while preparing task MapJaspiProvider. Check the server machine First Failure Data Capture tool (FFDC) for more information.
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:193)
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:169)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.getAppName(WebSphereDeployerPlugin.java:318)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.createArtifact(WebSphereDeployerPlugin.java:275)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.perform(WebSphereDeployerPlugin.java:197)
13:51:31 at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:723)
13:51:31 at hudson.model.Build$BuildExecution.post2(Build.java:185)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:668)
13:51:31 at hudson.model.Run.execute(Run.java:1763)
13:51:31 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
13:51:31 at hudson.model.ResourceController.execute(ResourceController.java:98)
13:51:31 at hudson.model.Executor.run(Executor.java:410)
13:51:31 Caused by: com.ibm.websphere.management.application.client.AppDeploymentException: ADMA0092E: An unexpected exception occurred while preparing task MapJaspiProvider. Check the server machine First Failure Data Capture tool (FFDC) for more information. [Root exception is java.lang.NoSuchMethodError: com.ibm.ejs.models.base.bindings.applicationbnd.ApplicationBinding.getJaspiRefBinding()Lcom/ibm/ejs/models/base/bindings/commonbnd/JaspiRefBinding;]
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNthTask(AppDeploymentController.java:575)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNextTask(AppDeploymentController.java:611)
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:185)
13:51:31 ... 13 more
13:51:31 Caused by: java.lang.NoSuchMethodError: com.ibm.ejs.models.base.bindings.applicationbnd.ApplicationBinding.getJaspiRefBinding()Lcom/ibm/ejs/models/base/bindings/commonbnd/JaspiRefBinding;
13:51:31 at com.ibm.ws.security.jaspi.MapJaspiHelper.prepareTask(MapJaspiHelper.java:148)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.prepareTask(AppDeploymentController.java:586)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNthTask(AppDeploymentController.java:567)
13:51:31 ... 15 more
13:51:31
13:51:31 Build step 'Deploy To IBM WebSphere Application Server' changed build result to FAILURE
13:51:31 Finished: FAILURE
```
I checked that I can deploy the ear file using wsadmin with the same parameters configured in the plugin (SOAP Port, cell, node, server...) and it was successful.
What am I missing? I tried searching for similar error messages but didn't find anything.
I also tried to search the ffdc logs but the logs don't update even after running the plugin so I am clueless. | 2016/05/11 | [
"https://Stackoverflow.com/questions/37160808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6319840/"
] | Try This:
```
.card.noradius {
border-radius: 6px;
border: 1px solid rgba(0, 0, 0, 0.1);
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
``` | i think you need like this
```css
body {
background : #0c1013;
font-family : arial;
}
.card {
margin: 0 auto 2em;
padding: 2em;
width: 80%;
border-radius:10px;
background-color: #f2f2f2;
word-wrap: break-word;
box-shadow: 0 0.0625em 0.1875em 0 rgba(0, 0, 0, 0.1), 0 0.5em 0 -0.25em #6C7071, 0 0.5em 0.1875em -0.25em rgba(0, 0, 0, 0.1), 0 1em 0 -0.5em #3B3F40, 0 1em 0.1875em -0.5em rgba(0, 0, 0, 0.1) !important;
}
.card.noradius {
border-radius:0;
}
```
```html
<div class="card">
<p>Here's a stack of cards <code>with border radius</code>. </p>
</div>
<div class="card noradius">
<p>Here's a stack of cards <code>without border radius</code>. </p>
</div>
``` |
37,160,808 | I have Websphere Portal 8.5.5.2 Cluster of 2 Windows Server Nodes.
I have a separate Jenkins Build Server (also windows), I configured the plugin correctly and click test connection returns connection successful.
when running build now to deploy the ear file it returns an error:
```
13:51:31 Started by user Jenkins
13:51:31 Building in workspace C:\Jenkins\workspace\Deploy
13:51:31 Connecting to IBM WebSphere Application Server...
13:51:31 The following artifacts will be deployed in this order...
13:51:31 -------------------------------------------
13:51:31 AdvisorsThemeEAR_20160505.ear
13:51:31 -------------------------------------------
13:51:31 Error deploying to IBM WebSphere Application Server: org.jenkinsci.plugins.websphere.services.deployment.DeploymentServiceException: ADMA0092E: An unexpected exception occurred while preparing task MapJaspiProvider. Check the server machine First Failure Data Capture tool (FFDC) for more information.
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:193)
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:169)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.getAppName(WebSphereDeployerPlugin.java:318)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.createArtifact(WebSphereDeployerPlugin.java:275)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.perform(WebSphereDeployerPlugin.java:197)
13:51:31 at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:723)
13:51:31 at hudson.model.Build$BuildExecution.post2(Build.java:185)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:668)
13:51:31 at hudson.model.Run.execute(Run.java:1763)
13:51:31 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
13:51:31 at hudson.model.ResourceController.execute(ResourceController.java:98)
13:51:31 at hudson.model.Executor.run(Executor.java:410)
13:51:31 Caused by: com.ibm.websphere.management.application.client.AppDeploymentException: ADMA0092E: An unexpected exception occurred while preparing task MapJaspiProvider. Check the server machine First Failure Data Capture tool (FFDC) for more information. [Root exception is java.lang.NoSuchMethodError: com.ibm.ejs.models.base.bindings.applicationbnd.ApplicationBinding.getJaspiRefBinding()Lcom/ibm/ejs/models/base/bindings/commonbnd/JaspiRefBinding;]
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNthTask(AppDeploymentController.java:575)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNextTask(AppDeploymentController.java:611)
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:185)
13:51:31 ... 13 more
13:51:31 Caused by: java.lang.NoSuchMethodError: com.ibm.ejs.models.base.bindings.applicationbnd.ApplicationBinding.getJaspiRefBinding()Lcom/ibm/ejs/models/base/bindings/commonbnd/JaspiRefBinding;
13:51:31 at com.ibm.ws.security.jaspi.MapJaspiHelper.prepareTask(MapJaspiHelper.java:148)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.prepareTask(AppDeploymentController.java:586)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNthTask(AppDeploymentController.java:567)
13:51:31 ... 15 more
13:51:31
13:51:31 Build step 'Deploy To IBM WebSphere Application Server' changed build result to FAILURE
13:51:31 Finished: FAILURE
```
I checked that I can deploy the ear file using wsadmin with the same parameters configured in the plugin (SOAP Port, cell, node, server...) and it was successful.
What am I missing? I tried searching for similar error messages but didn't find anything.
I also tried to search the ffdc logs but the logs don't update even after running the plugin so I am clueless. | 2016/05/11 | [
"https://Stackoverflow.com/questions/37160808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6319840/"
] | If you don't need to use box shadow for the card effect, you can use the after and before pseudo elements to gain more control of the lower cards border radii:
```css
body {
background: #0c1013;
font-family: arial;
}
.card {
position: relative;
margin: 0 auto 2em;
width: 80%;
}
.card .inner {
padding: 2em;
border-radius: 4px;
background-color: #f2f2f2;
word-wrap: break-word;
position: relative;
z-index: 3;
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.75);
}
.card:before,
.card:after {
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.75);
content: '';
display: block;
position: absolute;
height: 9px;
border-radius: 4px;
}
.card:before {
bottom: -4px;
left: 4px;
right: 4px;
background-color: #6B6F70;
z-index: 2;
}
.card:after {
bottom: -8px;
left: 8px;
right: 8px;
background-color: #3B3F40;
z-index: 1;
}
.card.noradius .inner,
.card.noradius:before,
.card.noradius:after {
border-radius: 0;
}
```
```html
<div class="card">
<div class="inner">
<p>Here's a stack of cards <code>with border radius</code>.</p>
</div>
</div>
<div class="card noradius">
<div class="inner">
<p>Here's a stack of cards <code>without border radius</code>.</p>
</div>
</div>
``` | Try This:
```
.card.noradius {
border-radius: 6px;
border: 1px solid rgba(0, 0, 0, 0.1);
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
``` |
37,160,808 | I have Websphere Portal 8.5.5.2 Cluster of 2 Windows Server Nodes.
I have a separate Jenkins Build Server (also windows), I configured the plugin correctly and click test connection returns connection successful.
when running build now to deploy the ear file it returns an error:
```
13:51:31 Started by user Jenkins
13:51:31 Building in workspace C:\Jenkins\workspace\Deploy
13:51:31 Connecting to IBM WebSphere Application Server...
13:51:31 The following artifacts will be deployed in this order...
13:51:31 -------------------------------------------
13:51:31 AdvisorsThemeEAR_20160505.ear
13:51:31 -------------------------------------------
13:51:31 Error deploying to IBM WebSphere Application Server: org.jenkinsci.plugins.websphere.services.deployment.DeploymentServiceException: ADMA0092E: An unexpected exception occurred while preparing task MapJaspiProvider. Check the server machine First Failure Data Capture tool (FFDC) for more information.
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:193)
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:169)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.getAppName(WebSphereDeployerPlugin.java:318)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.createArtifact(WebSphereDeployerPlugin.java:275)
13:51:31 at org.jenkinsci.plugins.websphere_deployer.WebSphereDeployerPlugin.perform(WebSphereDeployerPlugin.java:197)
13:51:31 at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:723)
13:51:31 at hudson.model.Build$BuildExecution.post2(Build.java:185)
13:51:31 at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:668)
13:51:31 at hudson.model.Run.execute(Run.java:1763)
13:51:31 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
13:51:31 at hudson.model.ResourceController.execute(ResourceController.java:98)
13:51:31 at hudson.model.Executor.run(Executor.java:410)
13:51:31 Caused by: com.ibm.websphere.management.application.client.AppDeploymentException: ADMA0092E: An unexpected exception occurred while preparing task MapJaspiProvider. Check the server machine First Failure Data Capture tool (FFDC) for more information. [Root exception is java.lang.NoSuchMethodError: com.ibm.ejs.models.base.bindings.applicationbnd.ApplicationBinding.getJaspiRefBinding()Lcom/ibm/ejs/models/base/bindings/commonbnd/JaspiRefBinding;]
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNthTask(AppDeploymentController.java:575)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNextTask(AppDeploymentController.java:611)
13:51:31 at org.jenkinsci.plugins.websphere.services.deployment.WebSphereDeploymentService.getAppName(WebSphereDeploymentService.java:185)
13:51:31 ... 13 more
13:51:31 Caused by: java.lang.NoSuchMethodError: com.ibm.ejs.models.base.bindings.applicationbnd.ApplicationBinding.getJaspiRefBinding()Lcom/ibm/ejs/models/base/bindings/commonbnd/JaspiRefBinding;
13:51:31 at com.ibm.ws.security.jaspi.MapJaspiHelper.prepareTask(MapJaspiHelper.java:148)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.prepareTask(AppDeploymentController.java:586)
13:51:31 at com.ibm.websphere.management.application.client.AppDeploymentController.getNthTask(AppDeploymentController.java:567)
13:51:31 ... 15 more
13:51:31
13:51:31 Build step 'Deploy To IBM WebSphere Application Server' changed build result to FAILURE
13:51:31 Finished: FAILURE
```
I checked that I can deploy the ear file using wsadmin with the same parameters configured in the plugin (SOAP Port, cell, node, server...) and it was successful.
What am I missing? I tried searching for similar error messages but didn't find anything.
I also tried to search the ffdc logs but the logs don't update even after running the plugin so I am clueless. | 2016/05/11 | [
"https://Stackoverflow.com/questions/37160808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6319840/"
] | If you don't need to use box shadow for the card effect, you can use the after and before pseudo elements to gain more control of the lower cards border radii:
```css
body {
background: #0c1013;
font-family: arial;
}
.card {
position: relative;
margin: 0 auto 2em;
width: 80%;
}
.card .inner {
padding: 2em;
border-radius: 4px;
background-color: #f2f2f2;
word-wrap: break-word;
position: relative;
z-index: 3;
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.75);
}
.card:before,
.card:after {
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.75);
content: '';
display: block;
position: absolute;
height: 9px;
border-radius: 4px;
}
.card:before {
bottom: -4px;
left: 4px;
right: 4px;
background-color: #6B6F70;
z-index: 2;
}
.card:after {
bottom: -8px;
left: 8px;
right: 8px;
background-color: #3B3F40;
z-index: 1;
}
.card.noradius .inner,
.card.noradius:before,
.card.noradius:after {
border-radius: 0;
}
```
```html
<div class="card">
<div class="inner">
<p>Here's a stack of cards <code>with border radius</code>.</p>
</div>
</div>
<div class="card noradius">
<div class="inner">
<p>Here's a stack of cards <code>without border radius</code>.</p>
</div>
</div>
``` | i think you need like this
```css
body {
background : #0c1013;
font-family : arial;
}
.card {
margin: 0 auto 2em;
padding: 2em;
width: 80%;
border-radius:10px;
background-color: #f2f2f2;
word-wrap: break-word;
box-shadow: 0 0.0625em 0.1875em 0 rgba(0, 0, 0, 0.1), 0 0.5em 0 -0.25em #6C7071, 0 0.5em 0.1875em -0.25em rgba(0, 0, 0, 0.1), 0 1em 0 -0.5em #3B3F40, 0 1em 0.1875em -0.5em rgba(0, 0, 0, 0.1) !important;
}
.card.noradius {
border-radius:0;
}
```
```html
<div class="card">
<p>Here's a stack of cards <code>with border radius</code>. </p>
</div>
<div class="card noradius">
<p>Here's a stack of cards <code>without border radius</code>. </p>
</div>
``` |
917,355 | I'm hosting a webpage with Apache on a Raspberry Pi (Debian), and can't seem to get the server to issue the current certificate. I generated a self-signed SSL certificate in `/home/pi/ssl/` with:
```
openssl req -new -sha256 -x509 -nodes -days 365 -out example.com.pem -keyout example.com.key
```
Apache looks up the `.pem` and `.key` file pair from file `/etc/apache2/sites-enabled/owncloud.conf`, which contains:
```
SSLCertificateFile /home/pi/ssl/example.com.pem
SSLCertificateKeyFile /home/pi/ssl/example.com.key
```
When I delete these files and restart Apache I get error `[FAIL] Reloading web server config: apache2 failed!`. This error doesn't happen when restarting after a new certificate file pair has been generated, so Apache does seem to be calling the certificate.
However the certificate that comes through in browsers (Chrome Incognito or FF/Safari private windows, and even a browser on a computer that surely never requested the domain before) is an old certificate I generated a month ago - see below:

Any ideas why this is happening? | 2015/05/20 | [
"https://superuser.com/questions/917355",
"https://superuser.com",
"https://superuser.com/users/210314/"
] | It turns out the certificate being issued was for some reason the default Apache "snakeoil" certificate. I established this by:
```
grep -i -r "SSLCertificateChainFile" /etc/apache2/
```
.. which returned 2 lines from file `/etc/apache2/sites-available/default-ssl` that referenced the snakeoil certificate. I commented these lines out and the browser now returns the customised certificate. | A common source of such problems is multiple running instances of Apache. The config changes are picked up by a process that you (re)start but the request is served by an old process which is running with old configuration.
Stop the service:
```
service apache2 stop
```
Check if the site is still accessible. If yes, then you have identified the cause.
Now run
```
ps aux | grep apache
```
It will give you list of running apache2 process and their PIDs. Kill them all (Note, this command may also return unrelated processes with Apache in their name/user etc. like Apache Tomcat, you might not want kill them.)
```
kill <pid>
```
Run ps aux again and ensure that processes are no longer running.
Check again if site is accessible. It shouldn't be.
Now start apache service
```
service apache2 start
```
Verify that the new certificate is being served.
If you don't want to kill processes, you may reboot the system. It will have the same effect. |
7,870 | I am currently enrolled in a circuit training gym and just 'leveled up' to level 3 last month (after about half a year of being in level 1-2 sporadically). I have been more consistent now (2-3 times a week) but now I also attend some yoga and body balance classes to accompany my wife.
The current workout consists of 2 days of circuit training. 1 complete circuit is 10 minutes of 20 stations of quick workouts for 30 seconds each. every even numbered station is made of "active rest": jumping jacks, side steps, jumping rope, box hops, skaters, etc. Odd numbered stations focus on different parts of the body: rows, shrugs, kettlebell swings, clean and jerks, and squats.
My basic goal is to lose my tummy and gradually tone my muscles and abs. So far, my muscles are turning out fine, but the tummy isn't going away. I know this is the last part to actually go away but I just want to make sure I'm doing everything right.
So my new plan now is to yoga/body balance class on T/TH/S and then circuit train on W/F or M/W. Question is, **how do I maximize the benefits of these workouts through my food intake?**
The food context for this workout is: weekday breakfast consists of what I can get a hold on(noodles - not healthy but still looking for other alternatives. oats? sandwiches?) lunch is usually rice with some tuna or chicken. dinner is a chicken sandwich before working out(but then based on the comments it looks like i should postpone it to after working out...its kinda hard to workout hungry though)
Is this diet okay so far?( besides the bad breakfasts). I also usually go hungry throughout the day and would like some suggestions as to how to alleviate this without compromising the workouts. I hope this provides enough information :) | 2012/08/29 | [
"https://fitness.stackexchange.com/questions/7870",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/4147/"
] | Over emphasis on any one macro nutrient is going to work against you, and it appears you have a big emphasis on carbohydrates. So my answer is not against carbs, but more in keeping everything balanced.
**Bottom Line**
You have to eat fewer Calories than you burn to lose weight. No amount of carb cycling, ketosis, paleo, or whatever diet is going to work if you are eating more Calories than you burn.
**Training**
Your circuit training is primarily conditioning related work. This is similar to what Crossfit does for you: you work hard, have a limited measured rest, and go again until the circuit is completed. This is interval training. You have the following benefits:
* Builds your cardio vascular system
* Limited strength improvements
* Burns a lot of calories.
The yoga/body balance is much slower. While it doesn't have the same Calorie burning potential as the circuit training, it does improve your core strength, mobility, and stability.
**Food Planning**
You should have 3 Calorie targets: your off day, your yoga/body balance day, and your circuit training day. Your off day will have the deepest Caloric deficit, perhaps 20-30% lower than your normal Caloric requirements. Your yoga/body balance will have a slightly lower deficit, perhaps 5-10% lower than normal. The circuit training will have a 5% Caloric surplus, i.e. more than required for maintenance.
Because Caloric deficits can leave your body wanting lots of food, you should focus on foods that leave you full longer. These will be foods that are high in protein and fat. Do make sure you have your vegetables every day--preferably a healthy portion of green vegetables. On the days where you can have more food, increase the carbohydrates--particularly on circuit training days.
The purpose of the Calorie cycling is to match your energy intake with the time you need it. It's also important to not overeat, so play with the exact balance of everything to make it work for you.
Macro Requirements based on your training:
* Protein: at least 0.5g per pound of body weight. I.e. if you weigh 250lbs, that's 125g of protein.
* Fat: as much as needed to fill in the balance of Calories for the day
* Carbs: on circuit training days, as much as 1g per pound but no more. Other days, about 0.5g per pound body weight (or less if you want).
The idea is to ramp up the carbs for when you need them most, and when they cost you the least.
The Calorie goals will do the bulk of the work. The recommended macro suggestions will support your training, and hopefully help you stick with the plan. Sometimes to meet your protein target while minimizing Calories, you will need to supplement with a protein shake. That's OK, but do get the bulk of your Calories through real food. | Here's something I wrote up for myself a while back...maybe it can help you:
CUTTING:
- increase water intake
- macronutrients become key
- increase protein intake
- figure out strategy, low carb or carb cycling
- more bites per calorie
- check progress every 2 weeks
- eat the same thing every day if the body can take it
- replace carbs with high-quality fats from nuts, avocadoes, oils
- add fiber to diet
- have a protein shake (in water) before dinner |
131,002 | This may sound a little bit very basic but I would like to know what Sharepoint Provider app is? Is it a component that resides in any server and gets its data from SharePoint? or is it a component that do not use SharePoint at all or if it uses what and how?
EDIT:- Wanted to check if a SharePoint app can work without SharePoint?
Any help in understanding it would be much appreciated.
Thanks in advance. | 2015/02/06 | [
"https://sharepoint.stackexchange.com/questions/131002",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/9972/"
] | Here's some links that might help you understand better and get started: <https://msdn.microsoft.com/en-us/library/office/fp142381.aspx> and <https://msdn.microsoft.com/EN-US/library/office/fp179923.aspx>
And to better answer the question, provider hosted apps are applications that run in a server that is external to SharePoint's. It has its own infrastructure and the Provider is responsible for keeping it running. They allow you to use Server Side code and uses the .NET CSOM (not the Microsoft.SharePoint.dll [technically you can host a Provider hosted app in the same server as sharepoint with an app pool that has the security requirements to access SharePoint's server side components {but you should probably avoid doing this}]
Compared to SharePoint Hosted Apps, they are much more powerful as they can leverage resources the a Client-Side only app simply cannot use.
In an on premises environment, you also have the alternative of developing High Trust Provider Hosted Apps, this model allows the App to tell SharePoint WHO the app is acting as and can effectively Impersonate users and do things that the app or the user running the app does not have permission to do (thus the name High Trust).
A Provider Hosted app can still have it's SharePoint Hosted counterpart, earning itself an AppWeb and running client side code that has support from SharePoint like the ListView Controls and owning content that are "isolated" from the rest of the site collection.
Hope I've described this clearly, feel free to point out htings that might've come out confusing. | Provider-hosted apps
Provider-hosted apps for SharePoint include components that are deployed and hosted outside the SharePoint farm. They are installed to the host web, but their remote components are hosted on another server.

[Choose patterns for developing and hosting your app for SharePoint](https://msdn.microsoft.com/en-us/library/office/fp179887(v=office.15).aspx) |
46,022,293 | I'm receiving and http post request, with raw body, and I'm trying to read the http body Stream into a String.
I'm using the basic Hello World web project generated by the *dotnet web* command. According to the [documentation](http://In%20the%20.NET%20Framework%204%20and%20earlier%20versions,%20you%20have%20to%20use%20methods%20such%20as%20BeginRead%20and%20EndRead%20to%20implement%20asynchronous%20I/O%20operations.%20These%20methods%20are%20still%20available%20in%20the%20.NET%20Framework%204.5%20to%20support%20legacy%20code;%20however,%20the%20new%20async%20methods,%20such%20as%20ReadAsync,%20WriteAsync,%20CopyToAsync,%20and%20FlushAsync,%20help%20you%20implement%20asynchronous%20I/O%20operations%20more%20easily.):
>
> In the .NET Framework 4 and earlier versions, you have to use methods
> such as BeginRead and EndRead to implement asynchronous I/O
> operations. These methods are still available in the .NET Framework
> 4.5 to support legacy code; however, the new async methods, such as ReadAsync, WriteAsync, CopyToAsync, and FlushAsync, help you implement
> asynchronous I/O operations more easily.
>
>
>
So I tried with the [ReadAsync](https://msdn.microsoft.com/en-us/library/hh137813(v=vs.110).aspx) method with something like this:
```
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// _controller = controller;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
using (Stream Body = context.Request.Body) {
byte[] result;
result = new byte[context.Request.Body.Length];
await context.Request.Body.ReadAsync(result, 0, (int)context.Request.Body.Length);
String body = System.Text.Encoding.UTF8.GetString(result).TrimEnd('\0');
_log.LogInformation($"Body: {body}");
}
await context.Response.WriteAsync("Hello World!");
});
}
```
But I'm getting the following error:
>
> info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1](http://In%20the%20.NET%20Framework%204%20and%20earlier%20versions,%20you%20have%20to%20use%20methods%20such%20as%20BeginRead%20and%20EndRead%20to%20implement%20asynchronous%20I/O%20operations.%20These%20methods%20are%20still%20available%20in%20the%20.NET%20Framework%204.5%20to%20support%20legacy%20code;%20however,%20the%20new%20async%20methods,%20such%20as%20ReadAsync,%20WriteAsync,%20CopyToAsync,%20and%20FlushAsync,%20help%20you%20implement%20asynchronous%20I/O%20operations%20more%20easily.)
> Request starting HTTP/1.1 POST <http://localhost:5000/json/testing?id=2342&name=sas> application/json
> 82 fail: Microsoft.AspNetCore.Server.Kestrel[13]
> Connection id "0HL7ISBH941G6", Request id "0HL7ISBH941G6:00000001": An unhandled exception was thrown by the
> application. System.NotSupportedException: Specified method is not
> supported. at
> Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestStream.get\_Length()
> at mtss.ws.Startup.<b\_\_4\_0>d.MoveNext() in
> /home/inspiron/devel/apps/dotnet/mtss-ws/Startup.cs:line 47
>
>
>
-- update
I could get something working setting the size of the buffer to Int16.MaxValue, but that way I can't read bodies larger that 32k. | 2017/09/03 | [
"https://Stackoverflow.com/questions/46022293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47633/"
] | I found [this question](https://stackoverflow.com/questions/43403941/how-to-read-asp-net-core-response-body) at SO that helped my find the following solution:
```
app.Run(async (context) =>
{
string body = new StreamReader(context.Request.Body).ReadToEnd();
_log.LogInformation($"Body: {body}");
_log.LogInformation($"Body.Length: {body.Length}");
await context.Response.WriteAsync("Hello World!");
});
```
and the async version is pretty much alike:
```
string body = await new StreamReader(context.Request.Body).ReadToEndAsync();
```
Not sure if this is the best way to do it... | I, too, had issues with ReadAsync stopping short of the full content. My solution is similar to the one offered by [opensas](https://stackoverflow.com/users/47633/opensas), however, I did it with a "using" so the StreamReader's dispose method would be called automatically. I also added the UTF8 encoding option to the StreamReader.
```
using StreamReader reader = new StreamReader (Request.Body, Encoding.UTF8);
string body = await reader.ReadToEndAsync ();
``` |
44,967,011 | I normally work as a Java programmer and I love the fact that with Java alot of the code design is standardized. For example you read Java example about Spring or Hibernate the code structurally looks the same for the whole world.
I am now working on ReactJS with redux and I just can't seem to understand it. Every example I have seen does everything completely different and it seams as if the entire JavaScript community just can't make up there minds on how to do something the same so I am hoping someone here can explain how ReactJS / redux works.
I have a login page and when I click on a button a http post must be done to a oauth2 auth server and on success a redirect must be done.
My Component works. It is LoginPage and I can confirm that when I click on the login button an action is called.
```
class LoginPage extends React.Component {
render() {
return (
<div id="login-container">
<LoginForm {...this.props} />
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
};
}
const mapDispatchToProps = (dispatch) => {
return {
handleSubmit: (evt) => {
evt.preventDefault();
performLogin(dispatch, evt.target.username.value, evt.target.password.value );
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);
```
The performLogin method is an action and my actions.js looks like this:
```
export function performLogin( dispatch, username, password ) {
login(username, password).then(function (response) {
dispatch({
type: LOGIN_SUCCESS
});
})
.catch(function (error) {
dispatch({
type: LOGIN_FAILURE
});
});
}
```
The reducer looks like this:
```
const loginReducer = (state = initialState, action) => {
switch (action.type) {
case LOGIN_SUCCESS:
return [
...state, {
auth: {
'login': true
}
}
]
case LOGIN_FAILURE:
return [
...state, {
auth: {
'login': false
}
}
]
default:
return state;
}
};
```
I have tried doing a axios post in the action but I got the error something like the action needs to be a plain object or something like that.
My question is where do you perform ajax calls and redirects in ReactJS/redux? In the action or the reducer?
This is a part of my packages.json:
```
"react": "^15.1.0",
"react-addons-test-utils": "^15.1.0",
"react-dom": "^15.1.0",
"react-redux": "^5.0.4",
"react-router": "^3.0.2",
"react-router-dom": "^4.1.1",
"react-router-redux": "^4.0.8",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.5.2",
"redux-form": "^6.8.0",
"redux-logger": "^2.6.1",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",
``` | 2017/07/07 | [
"https://Stackoverflow.com/questions/44967011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4614579/"
] | Just use `browserHistory.push("page-url");` method to change your route, after success promise | For the error "action needs to be a plain object or something like that" I believe your Redux-thunk is set up incorrectly. `dispatch(performLogin(username, password))`
`export function performLogin( username, password ) {
return function (dispatch) {
return login(username, password)
.then(function (response) {
dispatch({
type: LOGIN_SUCCESS
});
})
}
}`
See example `makeASandwichWithSecretSauce` <https://github.com/gaearon/redux-thunk> |
28,933,409 | I am new to C#...
I am attempting to pass objects between forms using the 'Constructor Method'
Here is the constructor for the called/invoked class:
```
public frmPeripheralOptions(List<PeriphItem> PeriphSelect)
{
// code...
}
```
Here is the invoking code:
```
frmPeripheralOptions PeriphForm = new frmPeripheralOptions(PeriphSelect);
```
These are the compile-time errors that I receive at the above line:
C# won't let me insert the `PeriphSelect` as a parameter to the constructor.
>
> Error 1 The best overloaded method match for
> 'BingP3.frmPeripheralOptions.frmPeripheralOptions(System.Collections.Generic.List)'
> has some invalid arguments C:\Users\scott\Documents\Visual Studio
> 2013\Projects\BingP3\BingP3\frmComputerOrder.cs 200 47 BingP3
>
>
> Error 2 Argument 1: cannot convert from
> 'System.Collections.Generic.List'
> to
> 'System.Collections.Generic.List' C:\Users\scott\Documents\Visual
> Studio 2013\Projects\BingP3\BingP3\frmComputerOrder.cs 200 72 BingP3
>
>
>
Here is the definition of the list. It is identically defined in both classes:
```
public struct PeriphItem
{
public int pos;
public int qty;
public string entry;
}
public System.Collections.Generic.List<PeriphItem> PeriphSelect { get; set; }
```
The list is initialized in the calling class default constructor as follows:
```
PeriphSelect = new List<PeriphItem>();
```
The goal here is to be able to access the same iteration of the `PeriphSelect` List from both classes.
I have successfully passed lists to constructors in this current project, but they were lists of standard objects such `List<Int> and`List`, but not lists of user-defined objects. | 2015/03/09 | [
"https://Stackoverflow.com/questions/28933409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4647907/"
] | Just `#include` everywhere you want. If the library is not horribly broken, it will work fine. The library itself is responsible for having mechanisms that make it usable, in case of a header only library that means making it usable by including the header(s).
Nothing would make this bad practice, simply using by including is the purpose of a header only library. | Header files will use **include guards** ([Include Guard wiki](http://en.wikipedia.org/wiki/Include_guard)) that keep library functions from being defined twice. Basically, a header file will use a conditional statement that is evaluated during compilation that checks for an existing library definition. If it is defined already it ignores anymore additional definitions. These guards look like this:
```
/* library_name.h */
#ifndef SOME_IDENTIFIER
#define SOME_IDENTIFIER
[function prototypes]
#endif
```
A Daniel's Computer Blog article ([Here](http://daniel-albuschat.blogspot.com/2010/08/what-include-guards-in-c-are-and-what.html)) provides a very digestable explanation of what's going on behind the scenes and flushes out more nuances that I didn't address.
Baum mit Augen is right. If the lib uses include guards there will be no problem using `#include<library_name>` anywhere you want as many times as you want.
Ideally you will use `#include<library_name>` once at the top of any file that uses a function/class/constant from the library. |
32,136,491 | I know how to use custom button as Facebook login.
Now I'd like to **bind `onlogin` event to customized button**, but I don't know how to do.
*Original code*
```
<fb:login-button scope="public_profile,email" onlogin="afterLogin();">
</fb:login-button>
<script>
/* Assume that Facebook SDK loaded asyncronously and initilized */
function afterLogin() {
// Do stuff
}
</script>
```
*My code*
```
<button id="cusomized-button" onclick="fbLogin();" onlogin="afterLogin();">
Customized button
</button>
<script>
/* Assume that Facebook SDK loaded asynchronously and initialized */
// Show facebook login modal
function fbLogin() {
FB.login(function() {}, {
scope: 'email,public_profile'
});
};
function afterLogin() {
// Do stuff
}
</script>
``` | 2015/08/21 | [
"https://Stackoverflow.com/questions/32136491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3126753/"
] | Assuming you use version 2.4 of the Graph API, you are able to subscribe to an event called [`auth.login`](https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.4) which is fired whenever the login status changes.
So, if you want to react to when the user logs in, you can do this and your function named `afterLogin` would be called once the user logs in to your app:
```js
FB.Event.subscribe('auth.login', afterLogin);
```
Do note that Facebook recommends everyone to listen to `auth.statusChange` instead, otherwise your application will not know if the user has logged out or deauthorized the application, which would invalidate the token.
Here's an example using `auth.statusChange`, the `response` argument passed to the function contains a response object [which is detailed here](https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus#response_and_session_objects):
```js
FB.Event.subscribe('auth.statusChange', function(response) {
if(response.status === 'connected') {
// `connected` means that the user is logged in and that your app is authorized to do requests on the behalf of the user
afterLogin();
} else if(response.status === 'not_authorized') {
// The user is logged in on Facebook, but has not authorized your app
} else {
// The user is not logged in on Facebook
}
});
```
As an alternative, the first argument to `FB.login` is a function which is called after the user returns from Facebook, so you could do something like this:
```js
FB.login(function(response) {
if (response.authResponse) {
afterLogin();
} else {
// The user cancelled the login or did not authorize your app
}
}, {
scope: 'email,public_profile'
});
``` | Here's an alternative using `onlogin()` in the way you originally wanted.
There's a subtle reason why you may need this:
* You are using Facebook login just as a way to login to your own website
* User is already connected (has previously connected to your FB)
* User is NOT logged into your website.
* You don't want to magically log someone in just because they're 'connected' It's not a good user experience.
* So you show them the 'Login' button and once clicked you log the user in locally (provided you've established a linkage before).
In that case you do the following in the button code.
```
onlogin="window.fbOnLogin()"
```
Then depending upon your environment, somewhere in your code you would need to create a function on `window`. I'm using an Angular service and doing the following. This is typescript, so omit the `<any>` part if you're using pure JS.
```
constructor()
{
// Pure JS
// window.fbOnLogin = this.onLogin;
// Typescript (use lambda to keep 'this')
(<any>window).fbOnLogin = () => this.onLogin();
}
onLogin() {
call_my_server_to_login(token);
alert('Thanks for logging in with Facebook');
}
```
Now you can display the button to the user (and you secretly already know they're a user because the `auto.authResponseChange` event (or `FB.getLoginStatus()`) has told you they are `"connected"`.
Note: None of the events, including `auth.login` will actually get triggered if you just click the button.
Once they click it FB returns immediately (becuase you're already logged in and connected) and calls your function. You then login the user your own website (you have to do a server side lookup to make sure they already logged in before). If you don't know who the user is then you have to do one of those 'associate your username' pages. |
2,273,079 | If a sequence $\{a\_n\}$ converges to $1$, can you prove that $\{a\_n\}^2$ converges as well? If possible, how? I know the definition of convergence but I am stuck. Thank you. | 2017/05/09 | [
"https://math.stackexchange.com/questions/2273079",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/437446/"
] | We have that
$$
|a\_n^2-1|=|a\_n-1||a\_n+1|\to0
$$
since $|a\_n-1|\to0$ and $|a\_n+1|\to2$ as $n\to\infty$. Hence, $a\_n^2\to1$ as $n\to\infty$.
Actually, much more is true. If $f$ is a continuous function and $a\_n\to a$ as $n\to\infty$, then $f(a\_n)\to f(a)$ as $n\to\infty$. | The product of two convergent sequences is convergent. So it is true. |
6,155,681 | In Flex, lets say I have a super-class... something like:
```
class SuperComponent extends DragStack {
private var _childReference:UIComponent;
public function SuperComponent() {
// ???
addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
}
private function onCreationComplete(e:FlexEvent):void {
//The 'this[]' technique doesn't seem to work and causes run-time errors:
//trace("Component found: " + this["myButton"]);
}
}
```
And then I make use of the following derived-class in my application (just a mockup MXML as an example):
```
<!-- Component ChildComponent.mxml -->
<mx:SuperComponent>
<mx:Button id="myButton" label="Press Me!" />
</mx:SuperComponent>
```
How do I go about verifying the presence of "myButton" from the SuperComponent class, and referencing it? Do I need to use getChildByName( ... ) ? | 2011/05/27 | [
"https://Stackoverflow.com/questions/6155681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468206/"
] | I'm not sure what type of component DragStack is. Does it extend Container (Flex 3) or Group (Flex4)? If so, then the component will go through it's [lifecycle process](http://livedocs.adobe.com/flex/3/html/help.html?content=ascomponents_advanced_2.html), and myButton should be accessible after createChildren method is executed.
I believe that MXML does some magic under the hood to create the button as a child of your component.
If DragStack is not a container, then you have to tell us what the default property of DragStack is. The DefaultProperty would be specified in [class metadata](http://livedocs.adobe.com/flex/3/html/metadata_3.html#166318).
I believe what the MXML does is, basically, assign the XML Children to the default property of the SuperComponent class if no other property is specified. If you want to assign it to a different property, you'll have to specify it, like this:
```
<mx:SuperComponent>
<mx:myProperty>
<mx:Button id="myButton" label="Press Me!" />
</mx:myProperty>
</mx:SuperComponent>
```
This syntax is usually only used in situations where the property doesn't have a simple value, such as the array of columns for a DataGrid. | You can't use `this["myButton"]` from within containers even if `myButton` is a child of that container added in MXML. `myButton` is still not a class property but element of container's children.
You'd better [use `getChildByName()`](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/Container.html#getChildByName%28%29) passing `"myButton"` as a name. |
8,798 | I have a power adapter that works for Great Britain. Can I use the same adapter in Canada and/or the USA too? | 2012/08/07 | [
"https://travel.stackexchange.com/questions/8798",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/693/"
] | No, you can't. They're different types of adapters.
What I do when I need confirmation is to check this website:
<http://www.worldstandards.eu/electricity.htm>
It has an EXHAUSTIVE list of each and every type, the voltage and the countries that use them. It's been handy for some of the stranger countries I've been to and hasn't failed yet.
Myself, I have a multi-adapter. The only country it doesn't seem to handle is South Africa, which has 3 giant prongs - bigger than the UK ones! | No, they are different types of plugs. People in the UK need to buy an adapter to get US or other plugs to work in the UK. |
8,798 | I have a power adapter that works for Great Britain. Can I use the same adapter in Canada and/or the USA too? | 2012/08/07 | [
"https://travel.stackexchange.com/questions/8798",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/693/"
] | No, you can't. They're different types of adapters.
What I do when I need confirmation is to check this website:
<http://www.worldstandards.eu/electricity.htm>
It has an EXHAUSTIVE list of each and every type, the voltage and the countries that use them. It's been handy for some of the stranger countries I've been to and hasn't failed yet.
Myself, I have a multi-adapter. The only country it doesn't seem to handle is South Africa, which has 3 giant prongs - bigger than the UK ones! | It is not the current that is different between the UK and North America, it is the voltage rating and frequency as expressed in Hertz or Hz. Many devices can handle a range of voltages from 110 volt through to 250 volt and also varying frequencies. However, you need to look at the supply label on each device you are wanting to use in North America to determine if it is suitable. You cannot change a 110 volt, (standard voltage in North America), to 220 volt which most all devices in the UK are supplied. You can however adapt to 220 volt and use a grounded circuit to convert to 110 volt in the UK if coming from North America and wanting to supply North American devices. You simply need an adaptor. |
8,798 | I have a power adapter that works for Great Britain. Can I use the same adapter in Canada and/or the USA too? | 2012/08/07 | [
"https://travel.stackexchange.com/questions/8798",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/693/"
] | No, they are different types of plugs. People in the UK need to buy an adapter to get US or other plugs to work in the UK. | It is not the current that is different between the UK and North America, it is the voltage rating and frequency as expressed in Hertz or Hz. Many devices can handle a range of voltages from 110 volt through to 250 volt and also varying frequencies. However, you need to look at the supply label on each device you are wanting to use in North America to determine if it is suitable. You cannot change a 110 volt, (standard voltage in North America), to 220 volt which most all devices in the UK are supplied. You can however adapt to 220 volt and use a grounded circuit to convert to 110 volt in the UK if coming from North America and wanting to supply North American devices. You simply need an adaptor. |
8,709,019 | I have to develop a Java EE project. I am confused after reading different tutorials on JDBC and Hibernate.
After reading those tutorials, I found out both have some pros and cons. Now the problem is how I can decide which one is best? Additionally I'd like to know for which type of project in general I would use JDBC and for which type of project I would use Hibernate.
Using a test application where I have 100.000 records in a single table, I noticed that when using JDBC I can fetch all records in 3 to 4 seconds. When I used Hibernate it took 12 to 14 seconds.
Why is Hibernate's performance so much worse, and how can I increase the performance of Hibernate to be near that of JDBC? | 2012/01/03 | [
"https://Stackoverflow.com/questions/8709019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am not an expert in hibernate though i am just pointing out few points why i prefer hibernate over simple jdbc on my experience.
I have used hibernate with JPA annotations in a maven project
1. You can create all your model and define relationships using annotations.Then running one maven command created the entire relational database,tables and relation based on my models.Well that saves a lot of time
2. Hibernate will convert the result set into your models in the background based on your getters and setters.Unlike jdbc you will not have to extract the result set by yourself into models.Again you saved a lot of time
3. Hibernate usually fetches all your relational objects eagerly.So you don't have to bother writing join queries.(You can always specify whether you want to eager fetch/lazy fetch)
4.There are methods for save,update,delete where you can pass the model instance as argument
So if you are set out to write a Java EE project which is going to grow over the time and you want to save some time from writing extra classes you can go for Hibernate.All of this are from my small experience.But there is a lot more you can do in hibernate.Please refer the hibernate docs | Well Irrespective what type of project you are into, Hibernate will always make your life easier. This brings database operations closer to your domain model. You query database using the convention of java classes, just how you would access fields in java same why you can specify fields in your query (rather than typing in the SQL and everytime you type a query you need to cross check which field is mapped by which column name). Also, hibernate will return you the domain objects after hitting database query and that is always helpful if you look at JDBC where you have to construct all this stuff by yourself.
Over all if you working in a relativly small project you can get away using JDBC as well but when in mid-to-large size projects it is always helpful to use some ORM solution not necessarly Hibernate. |
8,709,019 | I have to develop a Java EE project. I am confused after reading different tutorials on JDBC and Hibernate.
After reading those tutorials, I found out both have some pros and cons. Now the problem is how I can decide which one is best? Additionally I'd like to know for which type of project in general I would use JDBC and for which type of project I would use Hibernate.
Using a test application where I have 100.000 records in a single table, I noticed that when using JDBC I can fetch all records in 3 to 4 seconds. When I used Hibernate it took 12 to 14 seconds.
Why is Hibernate's performance so much worse, and how can I increase the performance of Hibernate to be near that of JDBC? | 2012/01/03 | [
"https://Stackoverflow.com/questions/8709019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am not an expert in hibernate though i am just pointing out few points why i prefer hibernate over simple jdbc on my experience.
I have used hibernate with JPA annotations in a maven project
1. You can create all your model and define relationships using annotations.Then running one maven command created the entire relational database,tables and relation based on my models.Well that saves a lot of time
2. Hibernate will convert the result set into your models in the background based on your getters and setters.Unlike jdbc you will not have to extract the result set by yourself into models.Again you saved a lot of time
3. Hibernate usually fetches all your relational objects eagerly.So you don't have to bother writing join queries.(You can always specify whether you want to eager fetch/lazy fetch)
4.There are methods for save,update,delete where you can pass the model instance as argument
So if you are set out to write a Java EE project which is going to grow over the time and you want to save some time from writing extra classes you can go for Hibernate.All of this are from my small experience.But there is a lot more you can do in hibernate.Please refer the hibernate docs | It is not an "either or" situation. There are lots of interesting [ORM solutions](http://sourceforge.net/search/?q=&fq%5B%5D=trove:45&fq%5B%5D=trove:809&fq%5B%5D=trove:198) in addition to Hibernate. I would be less concerned about performance unless you have a particularly db-intensive algorithm. You should consider learning curve and source code maintainability. My ORM library strives for simple learning curve and minimal programming: [sormula](http://www.sormula.org) |
37,120,615 | I'm creating a reaction time game and I've been seeing quite the diversity in results, based on which device I'm using and how many FPS it's running (e.g. PC 60 FPS 0.25 average reaction, Smartphone 30 FPS 0.5 average reaction).
I'm working in a 2D environment as shown:
[](https://i.stack.imgur.com/bmkGg.png)
The player has a static Y-axis, while the red triangle, the obstacle, is moving along the Y-axis negatively.
I got two classes, one for my player:
```
public ObstacleSpawn oScript;
public GameObject player;
public Text warningText;
public float playerDimensionY;
float warningFade;
float warningAlpha;
public bool isRight = true;
public bool inAir = false;
public bool mouseClicked = false;
public bool mouseClickedTimeCheck;
public bool thereHaveBeenClicked = false;
bool warningTextAlive;
public int flyingSpeed;
float timeStamp1;
float timeStamp2;
// Use this for initialization
void Start () {
Vector2 sprite_size = GetComponent<SpriteRenderer> ().sprite.rect.size;
Vector2 spriteScale = transform.localScale;
float sizeAndScaleY = sprite_size.y * spriteScale.y;
float player_local_sprite_sizeY = (sizeAndScaleY / GetComponent<SpriteRenderer> ().sprite.pixelsPerUnit) * 0.5F;
playerDimensionY = player_local_sprite_sizeY;
}
// Update is called once per frame
void Update () {
warningText.GetComponent<CanvasRenderer> ().SetAlpha (warningAlpha);
mouseClickedTimeCheck = false;
if (oScript.maxClicks != 10) {
if (isRight == true && mouseClicked == true) {
transform.position += Vector3.right * flyingSpeed * Time.deltaTime;
} else if (isRight == false && mouseClicked) {
transform.position += Vector3.left * flyingSpeed * Time.deltaTime;
}
if (warningTextAlive == true) {
if (warningFade < 400F) {
warningAlpha = 1F;
warningFade++;
} else if (warningFade < 500F) {
warningAlpha -= 0.01F;
warningFade++;
} else if (warningFade == 500F) {
warningText.text = "";
warningAlpha = 1F;
warningTextAlive = false;
warningFade = 0F;
}
}
if (Input.GetMouseButtonDown (0) && oScript.instantiatedObstacle == null) {
warningText.text = "Slow down - do not click without an obstacle visible" + "\nObstacle spawn-time reset";
warningTextAlive = true;
oScript.CancelInvoke ();
oScript.InvokeRepeating ("Spawn", Random.Range (oScript.randomSpawnMin, oScript.randomSpawnMax), Random.Range (oScript.randomSpawnMin, oScript.randomSpawnMax));
} else if (Input.GetMouseButtonDown (0) && inAir == false && oScript.instantiatedObstacle != null && thereHaveBeenClicked == false) {
mouseClicked = true;
inAir = true;
mouseClickedTimeCheck = true;
oScript.canSpawn = true;
thereHaveBeenClicked = true;
if (isRight == true) {
isRight = false;
} else if (isRight == false) {
isRight = true;
}
} else if (Input.GetMouseButtonDown (0) && inAir == true && oScript.instantiatedObstacle != null) {
warningText.text = "Slow down - do not click without an obstacle visible" + "\nObstacle spawn-time reset";
warningTextAlive = true;
oScript.CancelInvoke ();
oScript.InvokeRepeating ("Spawn", Random.Range (oScript.randomSpawnMin, oScript.randomSpawnMax), Random.Range (oScript.randomSpawnMin, oScript.randomSpawnMax));
}
}
}
void OnCollisionEnter2D(Collision2D coll) {
inAir = false;
mouseClicked = false;
}
}
```
and one for my obstacle:
```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ObstacleSpawn : MonoBehaviour {
//Reaction times: 1.0(4F), 0.9(3.6F), 0.8(3.2F), 0.7(2.8F), 0.6(2.4F), 0.5(2F), 0.4(1.6F), 0.35(1.4F), 0.3(1.2F), 0.25(1F);
public PlayerScript pScript;
public GameObject player;
public GameObject obstacle;
public GameObject endGamePanel;
public GameObject infoText;
public Text Average;
public Text BestReaction;
public GameObject instantiatedObstacle;
public float randomSpawnMin;
public float randomSpawnMax;
public float endingSpeed;
public float speed;
public float canvasMoveTowardsSpeed;
public float spawnTime;
public float maxReactionTime;
public float reactionTime;
float obstacleDimensionY;
float spawnTimeDistance;
float reactionClick;
float amountOfTries;
float panelAlpha = 0F;
float gamePanelAlpha = 1F;
private float[] reactionTimeArray = new float[10];
public int maxClicks;
public bool canSpawn = true;
bool reactionCap;
bool pointOneChange;
int fade = 0;
// Use this for initialization
void Start () {
spawnTimeDistance = 4F;
maxReactionTime = 1F;
InvokeRepeating ("Spawn", Random.Range (randomSpawnMin, randomSpawnMax), Random.Range (randomSpawnMin, randomSpawnMax));
Vector2 sprite_size = obstacle.GetComponent<SpriteRenderer> ().sprite.rect.size;
Vector2 spriteScale = obstacle.transform.localScale;
float sizeAndScaleY = sprite_size.y * spriteScale.y;
float obstacle_local_sprite_sizeY = (sizeAndScaleY / obstacle.GetComponent<SpriteRenderer> ().sprite.pixelsPerUnit) * 0.5F;
obstacleDimensionY = obstacle_local_sprite_sizeY;
}
// Update is called once per frame
void Update () {
endGamePanel.GetComponent<CanvasRenderer> ().SetAlpha (panelAlpha);
Average.GetComponent<CanvasRenderer> ().SetAlpha (panelAlpha);
BestReaction.GetComponent<CanvasRenderer> ().SetAlpha (panelAlpha);
infoText.GetComponent<CanvasRenderer> ().SetAlpha (gamePanelAlpha);
if (instantiatedObstacle != null) {
if (instantiatedObstacle.transform.position.x > 1.78F) {
instantiatedObstacle.transform.position += new Vector3 (-1, -1, 0) * speed * Time.deltaTime;
} else if (instantiatedObstacle.transform.position.x < -1.78) {
instantiatedObstacle.transform.position += new Vector3 (1, -1, 0) * speed * Time.deltaTime;
} else {
instantiatedObstacle.transform.position += new Vector3 (0, -1, 0) * speed * Time.deltaTime;
}
if (instantiatedObstacle.GetComponent<Renderer> ().isVisible != true ) {
Destroy (instantiatedObstacle);
pScript.thereHaveBeenClicked = false;
}
}
if (amountOfTries == 10) {
float moveTowardsSpeed = endingSpeed * Time.deltaTime;
player.transform.position = Vector2.MoveTowards (player.transform.position, new Vector2 (0, -2), moveTowardsSpeed);
if (fade < 100) {
panelAlpha += 0.01F;
gamePanelAlpha -= 0.1F;
fade++;
}
}
if (maxReactionTime >= 0.4F) {
pointOneChange = true;
} else if (maxReactionTime < 0.4F) {
pointOneChange = false;
}
if (maxReactionTime == 1F) {
reactionCap = true;
} else {
reactionCap = false;
}
if (pScript.mouseClickedTimeCheck == true && amountOfTries <= 10 && maxClicks != 10) {
reactionClick = Time.unscaledTime;
amountOfTries += 1;
maxClicks += 1;
reactionTime = reactionClick - spawnTime;
if (reactionTimeArray [0] == 0) {
reactionTimeArray [0] = reactionTime;
} else if (reactionTimeArray [1] == 0) {
reactionTimeArray [1] = reactionTime;
} else if (reactionTimeArray [2] == 0) {
reactionTimeArray [2] = reactionTime;
} else if (reactionTimeArray [3] == 0) {
reactionTimeArray [3] = reactionTime;
} else if (reactionTimeArray [4] == 0) {
reactionTimeArray [4] = reactionTime;
} else if (reactionTimeArray [5] == 0) {
reactionTimeArray [5] = reactionTime;
} else if (reactionTimeArray [6] == 0) {
reactionTimeArray [6] = reactionTime;
} else if (reactionTimeArray [7] == 0) {
reactionTimeArray [7] = reactionTime;
} else if (reactionTimeArray [8] == 0) {
reactionTimeArray [8] = reactionTime;
} else if (reactionTimeArray [9] == 0) {
reactionTimeArray [9] = reactionTime;
}
float averageReaction = (reactionTimeArray[0] + reactionTimeArray [1] + reactionTimeArray [2] + reactionTimeArray [3] + reactionTimeArray [4] + reactionTimeArray [5] + reactionTimeArray [6] + reactionTimeArray [7] + reactionTimeArray [8] + reactionTimeArray [9]) / 10;
BestReaction.text = "Best reaction: " + Mathf.Min(reactionTimeArray[0], reactionTimeArray[1], reactionTimeArray[2], reactionTimeArray[3], reactionTimeArray[4], reactionTimeArray[5], reactionTimeArray[6], reactionTimeArray[7], reactionTimeArray[8], reactionTimeArray[9]);
Average.text = "Average reaction: " + averageReaction;
if (reactionTime <= maxReactionTime && pointOneChange == true) {
maxReactionTime -= 0.1F;
spawnTimeDistance -= 0.4F;
} else if (reactionTime <= maxReactionTime && pointOneChange == false) {
maxReactionTime -= 0.05F;
spawnTimeDistance -= 0.2F;
} else if (reactionTime > maxReactionTime && pointOneChange == true && reactionCap == false) {
maxReactionTime += 0.1F;
spawnTimeDistance += 0.4F;
} else if (reactionTime > maxReactionTime && pointOneChange == false && reactionCap == false) {
maxReactionTime += 0.05F;
spawnTimeDistance += 0.2F;
}
Debug.Log (string.Format ("ReactionClick: " + reactionClick));
Debug.Log (string.Format ("ReactionTime: " + reactionTime));
Debug.Log (string.Format ("Max Reaction Time: " + maxReactionTime));
}
}
public void Spawn() {
if (pScript.isRight == true && pScript.inAir == false) {
obstacle.transform.localScale = new Vector3 (-1, 1, 1);
spawnTime = Time.unscaledTime;
instantiatedObstacle = (GameObject)Instantiate (obstacle, player.transform.position + new Vector3(0.50F , (spawnTimeDistance + obstacleDimensionY + pScript.playerDimensionY), -1), Quaternion.identity);
Debug.Log (string.Format ("Spawn time: " + spawnTime));
} else if (pScript.isRight == false && pScript.inAir == false) {
obstacle.transform.localScale = new Vector3 (1, 1, 1);
spawnTime = Time.unscaledTime;
instantiatedObstacle = (GameObject)Instantiate (obstacle, player.transform.position + new Vector3(-0.50F , (spawnTimeDistance + obstacleDimensionY + pScript.playerDimensionY), -1), Quaternion.identity);
Debug.Log (string.Format ("Spawn time: " + spawnTime));
}
}
}
```
As you can see in my obstacle class, I'm getting the users reaction time with following line:
```
reactionTime = reactionClick - spawnTime;
```
spawnTime being Time.time from when the obstacle appears
and
reactionClick being the Time.time when the player clicks.
However, as this line is getting called in my Update() function, it is very dependent on FPS, which causes my issue stating previously.
How do I make the results independent from device FPS, so they're stable across different devices?
I've considered and tried unscaledTime and multithreading, but without luck. | 2016/05/09 | [
"https://Stackoverflow.com/questions/37120615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6188567/"
] | First of all, try installing the package without using the `-g` flag:
```
npm install jasmine-expect
```
Also, move the `require('jasmine-expect');` from under the `describe` into the `onPrepare()` in your Protractor configuration file:
```
onPrepare: function () {
require("jasmine-expect");
},
``` | Ensure the dependency is being added to your package.json file.
```
npm install jasmine-expect --save-dev
``` |
320,882 | Yesterday I posted a question and, between the comments, I noted this:
>
> I wrote: ok, but for example can a blue laser and a violet laser interfere? I think that there isn't much different between their wavelenghts
>
>
> The answer: Yes, in theory, there can be an interference pattern between them, but this is highly theoretical. Keep in mind that the coherence length of a common laser pointer isn't usually much more than 10cm and the wavelengths in that vary by only about 10 to 20nm. If you mix blue and violet, you probably wont see any interference patterns more than a millimeter or so from where the waves mixed. As I said, it's possible but extremely difficult
>
>
> I wrote: *Blue laser and violet laser **encounter only in one point for cycle**, so we don't notice the interference. But if I take two blue laser, I'll see the interference because the waves concide. Is it right?*
>
>
> The answer: *If I interpreted you correctly, then yes, that is correct*
>
>
>
So I image that the bold text is something like this:
[](https://i.stack.imgur.com/uakev.jpg)
The waves, which have different wavelenghts because they are different, encounter only in two points in the image, so there is interference but it isn't very visible.
But now I'm thinking that also the destructive waves, which have the same wavelenght because they are the same waves,encounter in only two points:
[](https://i.stack.imgur.com/3LIx7.jpg)
And this waves interfere a lot between them, in fact they annul. Why don't the first two waves make a visible interference? Why don't they annul or interfere?
Does this mean that the bold text isn't right? Is it due to the different wavelenghts? | 2017/03/23 | [
"https://physics.stackexchange.com/questions/320882",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/149531/"
] | A key feature of waves is that they move in both space and time. The reason destructive interference is so interesting is that, at certain points in space, the equation for amplitude is 0, independent of time. For those points of destructive interference, it doesn't matter what phase one beam is in, the other beam is always exactly 180 degrees out of phase with it, perfectly canceling it out.
If you like math, remember that the 1-d wave equation is $A(x,t)=A\_{max}\sin(\frac{\lambda}{2\pi} x + \omega t)$ Destructive interference occurs when you have two waves with amplitudes $A\_1$ and $A\_2$ and different path lengths $x\_1$ and $x\_2$ such that the sum of their amplitudes is $$A\_{total}(x\_1,x\_2,t)=A\_1\sin(\frac{\lambda}{2\pi} x\_1 + \omega t) + A\_2\sin(\frac{\lambda}{2\pi} x\_2 + \omega t)$$
Permit me some rearranging which makes the math more straightforward, I'll express the second wave as the sum of $A\_1$ and $A\_2-A\_1$. This is just a mathematical rearranging which makes the destructive interference more visible in the equations
$$A\_{total}(x\_1,x\_2,t)=A\_1[\sin(\frac{\lambda}{2\pi} x\_1 + \omega t) + \sin(\frac{\lambda}{2\pi} x\_2 + \omega t)] + (A\_2-A\_1)\sin(\frac{\lambda}{2\pi} x\_2 + \omega t)$$
By notating it this way, we can see some common factors. when $x1-x2$ is a multiple of $\frac{\lambda}{2}$ (i.e. there's a half-wavelength difference in their path lengths), then we see the two sine terms are always exactly $\frac{\pi}{2}$ out of phase or exactly in phase. This is true regardless of what $t$ is. This means that at these points, you have either maximally destructive or maximally constructive interference.
However, consider if the frequencies are different. If the frequencies are different, then you no longer have that super-easy cancelation. The sine terms will not always be perfectly out of phase with each other at all times.
There is a highly related concept called "beats," which occur when two signals which are close in frequency interfere in time. They interfere in a way that's similar to the spatial interference you are looking at, but they do it in time. It's most noticeable in sound waves. If you have two frequencies which are close together, say 5000Hz and 5005Hz, you will hear them pulsing at the difference between those frequencies (in this case, 5 Hertz).
In your example, blue and violet do interfere this way, creating beats. However, those beats are in the 10-20THz region. This is way too fast to see pulsing directly, but far too slow for our human eyes to detect it as a photon... That happens to be in the microwave region! | I think the point you're missing here at the moment is that these waves are both sinusoidal waves, and their interference pattern will simply be the algebraic sum of both waves. On the second sketch you posted, it's not that the two waves only meet up at two points during any given period and cancel the whole wave out. Instead, notice that at any point along the pink wave, there is a negative "copy" of it which resides on the yellow wave. As such, when we add both contributions up, the net result is zero. This happens for every point along the wave on your second drawing, and would be called destructive interference.
Your first sketch is obviously different. Here, it's not as obvious what the resulting curve will look like, but you can figure out what the sum of the two waves will be at any given point by adding each of their $y$ values. I took a moment and graphed two waves that are similar to yours on Desmos, and then in orange you can see what happens when you add both waves together. The resulting orange wave is the interference pattern. You can check it out [here](https://www.desmos.com/calculator/3cispduk7w). |
48,186,050 | I'm trying to run a function within my Sub but am getting a compile error on the line `x = NINOFunction()` and am not sure how to get it working.
```
Sub CheckNINO()
Dim NINumber As Range, NINumbers As Range
Dim Usdrws As Long, x As Boolean
Usdrws = Worksheets("EeeDetails").Range("C" & Rows.Count).End(xlUp).Row
Set NINumbers = Worksheets("EeeDetails").Range("Q2:Q" & Usdrws)
For Each NINumber In NINumbers
x = NINOFunction(NINumber.Value)
If x = False Then
Range(NINumber).Copy Destination:=Worksheets("Validation").Cells(2, x)
End If
Next
End Sub
Function NINOFunction(sInp As String) As Boolean
Const s1 As String = "[AaBbCcEeGgHhJjKkLlMmNnOoPpRrSsTtWwXxYyZz]"
Const s2 As String = "[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtWwXxYyZz]"
Const s3 As String = "######"
Const s4 As String = "[AaBbCcDd]"
NINO = sInp Like s1 & s2 & s3 & s4
End Function
```
The function is tested and works with a Boolean result.
If the result is False I want to copy the row across to a separate sheet. | 2018/01/10 | [
"https://Stackoverflow.com/questions/48186050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8591599/"
] | Your compilation error is "Argument is not optional". This is quite good error message. Thus write `x = NINOFunction(arg)` and put an argument `sInp`.
Something like `x = NINOFunction ("something")`
or probably you need:
`x = NINOFunction (NINumber)`
Furthermore, your function always returns `False`, because this is the default value of the Boolean function. You may consider fixing it like this:
```
Function NINOFunction(sInp As String) As Boolean
Const s1 As String = "[AaBbCcEeGgHhJjKkLlMmNnOoPpRrSsTtWwXxYyZz]"
Const s2 As String = "[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtWwXxYyZz]"
Const s3 As String = "######"
Const s4 As String = "[AaBbCcDd]"
NINOFunction = sInp Like s1 & s2 & s3 & s4
End Function
``` | `NINOFunction` takes 1 argument, which is a string, but you didn't pass any. Try `x = NINOFunction("something")` |
1,449,618 | need a simply preg\_match, which will find "c.aspx" (without quotes) in the content if it finds, it will return the whole url. As a example
```
$content = '<div>[4]<a href="/m/c.aspx?mt=01_9310ba801f1255e02e411d8a7ed53ef95235165ee4fb0226f9644d439c11039f%7c8acc31aea5ad3998&n=783622212">New message</a><br/>';
```
now it should preg\_match "c.aspx" from $content and will give a output as
```
"/m/c.aspx?mt=01_9310ba801f1255e02e411d8a7ed53ef95235165ee4fb0226f9644d439c11039f%7c8acc31aea5ad3998&n=783622212"
```
The $content should have more links except "c.aspx". I don't want them. I only want all url that have "c.aspx".
Please let me know how I can do it. | 2009/09/19 | [
"https://Stackoverflow.com/questions/1449618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172285/"
] | You use DOM to parse HTML, not regex. You can use regex to parse the attribute value though.
Edit: updated example so it checks for c.aspx.
```
$content = '<div>[4]<a href="/m/c.aspx?mt=01_9310ba801f1255e02e411d8a7ed53ef95235165ee4fb0226f9644d439c11039f%7c8acc31aea5ad3998&n=783622212">New message</a>
<a href="#bar">foo</a>
<br/>';
$dom = new DOMDocument();
$dom->loadHTML($content);
$anchors = $dom->getElementsByTagName('a');
if ( count($anchors->length) > 0 ) {
foreach ( $anchors as $anchor ) {
if ( $anchor->hasAttribute('href') ) {
$link = $anchor->getAttribute('href');
if ( strpos( $link, 'c.aspx') ) {
echo $link;
}
}
}
}
``` | If you want to find any quoted string with c.aspx in it:
```
/"[^"]*c\.aspx[^"]*"|'[^']*c\.aspx[^']*'/
```
But really, for parsing most HTML you'd be better off with some sort of DOM parser so that you can be sure what you're matching is really an href. |
23,393,620 | Making updates on my website, there are a lot of pages that I don't use left. So I delete them.
Unfortunately some slight idexing has been made by search engine so when u type the name of website of mine it appears non more existent pages too in browser results.
I need to create a custum 404 page not found that appears everytime people go on pages that doesn't exist, respecting google SEO policy and w3c standards.
Unfortunately I can't.
Someone could teach me please? | 2014/04/30 | [
"https://Stackoverflow.com/questions/23393620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323340/"
] | Make a .html document in your webserver or website's directory in the htdocs then make a new folder that is called "err", then upload all your Error pages like 404, The page cannot be found or 403, Forbidden. Then place those files in the err folder and re-name them to the error codes. If you are using cPanel then search (Using the search bar) or find (By browsing the tools listed) Error Pages. Go from there with the instructions given on cPanel.
Hope this helps you,
Jay Salway (13 year old developer) | Create a static page containing your custom message and anything else you want (eg. site layout etc.) and save it somewhere appropriate within your site (eg. from the root: /errors/404.asp). Within that page make sure you write a 404 response header (eg. Response.Status = "404 Page Not found")
In IIS (the option will also be available somewhere similar under Apache if you are running that) open up the settings for your website and choose 'Error Pages' then look for the status code 404 (by default there should be one but you may need to create it) open that up and choose the option 'Execute a URL on this site' and enter the url chosen above /error/404.asp) |
5,731 | I'm trying to cut down on the number of profiles in one of my Orgs. One way we're using profiles is to enforce business rules, like "Only a ZZZ user may close opportunities as won," which we do by checking the Profile ID:
```
<validationRules>
<fullName>Changing_an_Opp_to_Closed_Won</fullName>
<active>true</active>
<description>Only the system admin and ZZZ users
can update the stage to closed won</description>
<errorConditionFormula>AND(
AND(ISCHANGED(StageName), IsClosed=True, IsWon=True),
NOT(OR($User.ProfileId == '00eA0000000RhUw',
$User.ProfileId == '00eA00000013Vro'))
)
</errorConditionFormula>
<errorMessage>You do not have the necessary access to mark an opportunity
"Closed Won" Please ask a ZZZ to do it for you.
</errorMessage>
</validationRules>
```
For almost all other purposes, ZZZ users are identical to other users in their department, and I'd like to combine the profiles while making a permission set for ZZZ users. But I can't figure out what I'd do with validation rules like these. **Is there a way to reference permissions/permission sets from formulas?** If not, are there other approaches you've seen for this? | 2012/12/26 | [
"https://salesforce.stackexchange.com/questions/5731",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/63/"
] | I believe such a problem can be solved at the profile level using the new custom Permissions feature and $Permission global variable that is available in Validation Rules/ VF Pages.
```
AND(
AND(ISCHANGED(StageName), IsClosed=True, IsWon=True),
NOT($Permission.nameofyourperm)
)
```
For more information on Custom Permissions.
<https://www.salesforce.com/us/developer/docs/pages/Content/pages_variables_global_permission.htm> | There is an open Idea to allow the usage of [Users Permission Sets in Formulas, Validation Rules and Lookup Filters](http://success.salesforce.com/ideaView?id=08730000000DcgfAAC).
Alternatively, you could create a Field on the User object to store the permission set name. It could be comma separated for multiple permission sets on a single user. This field would then be used in the validation rule. [Source idea from j020](http://boards.developerforce.com/t5/General-Development/Permisssion-Sets-in-Validation-Rule/m-p/497389#M75321). |
5,731 | I'm trying to cut down on the number of profiles in one of my Orgs. One way we're using profiles is to enforce business rules, like "Only a ZZZ user may close opportunities as won," which we do by checking the Profile ID:
```
<validationRules>
<fullName>Changing_an_Opp_to_Closed_Won</fullName>
<active>true</active>
<description>Only the system admin and ZZZ users
can update the stage to closed won</description>
<errorConditionFormula>AND(
AND(ISCHANGED(StageName), IsClosed=True, IsWon=True),
NOT(OR($User.ProfileId == '00eA0000000RhUw',
$User.ProfileId == '00eA00000013Vro'))
)
</errorConditionFormula>
<errorMessage>You do not have the necessary access to mark an opportunity
"Closed Won" Please ask a ZZZ to do it for you.
</errorMessage>
</validationRules>
```
For almost all other purposes, ZZZ users are identical to other users in their department, and I'd like to combine the profiles while making a permission set for ZZZ users. But I can't figure out what I'd do with validation rules like these. **Is there a way to reference permissions/permission sets from formulas?** If not, are there other approaches you've seen for this? | 2012/12/26 | [
"https://salesforce.stackexchange.com/questions/5731",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/63/"
] | There is an open Idea to allow the usage of [Users Permission Sets in Formulas, Validation Rules and Lookup Filters](http://success.salesforce.com/ideaView?id=08730000000DcgfAAC).
Alternatively, you could create a Field on the User object to store the permission set name. It could be comma separated for multiple permission sets on a single user. This field would then be used in the validation rule. [Source idea from j020](http://boards.developerforce.com/t5/General-Development/Permisssion-Sets-in-Validation-Rule/m-p/497389#M75321). | Found this article - hope it helps.
<https://help.salesforce.com/apex/HTViewSolution?id=000221057&language=en_US> |
5,731 | I'm trying to cut down on the number of profiles in one of my Orgs. One way we're using profiles is to enforce business rules, like "Only a ZZZ user may close opportunities as won," which we do by checking the Profile ID:
```
<validationRules>
<fullName>Changing_an_Opp_to_Closed_Won</fullName>
<active>true</active>
<description>Only the system admin and ZZZ users
can update the stage to closed won</description>
<errorConditionFormula>AND(
AND(ISCHANGED(StageName), IsClosed=True, IsWon=True),
NOT(OR($User.ProfileId == '00eA0000000RhUw',
$User.ProfileId == '00eA00000013Vro'))
)
</errorConditionFormula>
<errorMessage>You do not have the necessary access to mark an opportunity
"Closed Won" Please ask a ZZZ to do it for you.
</errorMessage>
</validationRules>
```
For almost all other purposes, ZZZ users are identical to other users in their department, and I'd like to combine the profiles while making a permission set for ZZZ users. But I can't figure out what I'd do with validation rules like these. **Is there a way to reference permissions/permission sets from formulas?** If not, are there other approaches you've seen for this? | 2012/12/26 | [
"https://salesforce.stackexchange.com/questions/5731",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/63/"
] | I believe such a problem can be solved at the profile level using the new custom Permissions feature and $Permission global variable that is available in Validation Rules/ VF Pages.
```
AND(
AND(ISCHANGED(StageName), IsClosed=True, IsWon=True),
NOT($Permission.nameofyourperm)
)
```
For more information on Custom Permissions.
<https://www.salesforce.com/us/developer/docs/pages/Content/pages_variables_global_permission.htm> | Found this article - hope it helps.
<https://help.salesforce.com/apex/HTViewSolution?id=000221057&language=en_US> |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | Add a check to the top of your Entrypoint script
================================================
Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.
If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to `entrypoint.sh`:
```
# Run once, hold otherwise
if [ -f "already_ran" ]; then
echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
cat
fi
touch already_ran
# Do your main things down here
```
To ensure that `cat` holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:
```
docker run -t --entrypoint entrypoint.sh image_name
```
This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:
```
docker start container_name
```
When you restart the container, the `already_ran` file will be found, causing the Entrypoint script to stall with `cat` (which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging `bash` session:
```
docker exec -i container_name bash
```
While the container is running, you can also remove `already_ran` and manually execute the `entrypoint.sh` script to rerun it, if you need to debug that way. | This is not exactly what you're asking for, but you can use `docker export` on a stopped container if all you want is to inspect the files.
```
mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR
``` |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | Add a check to the top of your Entrypoint script
================================================
Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.
If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to `entrypoint.sh`:
```
# Run once, hold otherwise
if [ -f "already_ran" ]; then
echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
cat
fi
touch already_ran
# Do your main things down here
```
To ensure that `cat` holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:
```
docker run -t --entrypoint entrypoint.sh image_name
```
This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:
```
docker start container_name
```
When you restart the container, the `already_ran` file will be found, causing the Entrypoint script to stall with `cat` (which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging `bash` session:
```
docker exec -i container_name bash
```
While the container is running, you can also remove `already_ran` and manually execute the `entrypoint.sh` script to rerun it, if you need to debug that way. | To me Docker always leaves the impression that it was created for a hobby system, it works well for that.
If something fails or doesn't work, don't expect to have a professional solution.
That said: Docker does not only NOT support such basic administrative tasks, it tries to prevent them.
Solution:
1. ```
cd /var/lib/docker/overlay2/
```
2. ```
find | grep somechangedfile
# You now can see the changed file from your container in a hexcoded folder/diff
```
3. ```
cd hexcoded-folder/diff
```
4. Create an `entrypoint.sh` (make sure to backup an existing one if it's there)
```
cat > entrypoint.sh
#!/bin/bash
while ((1)); do sleep 1; done;
```
`Ctrl`+`C`
```
chmod +x entrypoint.sh
```
5. ```
docker stop
docker start
```
You now have your docker container running an endless loop instead of the originally entry, you can exec bash into it, or do whatever you need.
When finished stop the container, remove/rename your custom entrypoint. |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | **My Problem:**
* I started a container with `docker run <IMAGE_NAME>`
* And then added some files to this container
* Then I closed the container and tried to start it again withe same command as above.
* But when I checked the new files, they were missing
* when I run `docker ps -a` I could see two containers.
* That means every time I was running `docker run <IMAGE_NAME>` command, new image was getting created
**Solution:**
To work on the same container you created in the first place run follow these steps
* `docker ps` to get container of your container
* `docker container start <CONTAINER_ID>` to start existing container
* Then you can continue from where you left. e.g. `docker exec -it <CONTAINER_ID> /bin/bash`
* You can then decide to create a new image out of it | To me Docker always leaves the impression that it was created for a hobby system, it works well for that.
If something fails or doesn't work, don't expect to have a professional solution.
That said: Docker does not only NOT support such basic administrative tasks, it tries to prevent them.
Solution:
1. ```
cd /var/lib/docker/overlay2/
```
2. ```
find | grep somechangedfile
# You now can see the changed file from your container in a hexcoded folder/diff
```
3. ```
cd hexcoded-folder/diff
```
4. Create an `entrypoint.sh` (make sure to backup an existing one if it's there)
```
cat > entrypoint.sh
#!/bin/bash
while ((1)); do sleep 1; done;
```
`Ctrl`+`C`
```
chmod +x entrypoint.sh
```
5. ```
docker stop
docker start
```
You now have your docker container running an endless loop instead of the originally entry, you can exec bash into it, or do whatever you need.
When finished stop the container, remove/rename your custom entrypoint. |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | Find your stopped container id
==============================
```
docker ps -a
```
Commit the stopped container:
=============================
This command saves modified container state into a new image `user/test_image`
```
docker commit $CONTAINER_ID user/test_image
```
Start/run with a different entry point:
=======================================
```
docker run -ti --entrypoint=sh user/test_image
```
Entrypoint argument description: <https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime>
Note:
=====
Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.
Steps to start a stopped container have been borrowed from here: (last comment) <https://github.com/docker/docker/issues/18078> | I have found a simple command
```
docker start -a [container_name]
```
This will do the trick
Or
```
docker start [container_name]
```
then
```
docker exec -it [container_name] bash
``` |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | It seems docker can't change entry point after a container started. But you can set a custom entry point and change the code of the entry point next time you restart it.
For example you run a container like this:
```
docker run --name c --entrypoint "/boot" -v "./boot":/boot $image
```
Here is the boot entry point:
```
#!/bin/bash
command_a
```
When you need restart c with a different command, you just change the boot script:
```
#!/bin/bash
command_b
```
And restart:
```
docker restart c
``` | It seems like most of the time people are running into this while modifying a config file, which is what I did. I was trying to bypass CORS for a PHP/Apache server with a Vue SPA as my entry point. Anyway, if you know the file you horked, a simple solution that worked for me was
1. Copy the file you horked out of the image:
docker cp bt-php:/etc/apache2/apache2.conf .
2. Fix it locally
3. Copy it back in
docker cp apache2.conf bt-php:/etc/apache2/apache2.conf
4. Start your container back up
5. \*Bonus points - Since this file is being modified, add it to your Compose or Build scripts so that when you do get it right it will be baked into the image! |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | I took @Dmitriusan's answer and made it into an alias:
>
> alias docker-run-prev-container='prev\_container\_id="$(docker ps -aq | head -n1)" && docker commit "$prev\_container\_id" "prev\_container/$prev\_container\_id" && docker run -it --entrypoint=bash "prev\_container/$prev\_container\_id"'
>
>
>
Add this into your `~/.bashrc` aliases file, and you'll have a nifty new `docker-run-prev-container` alias which'll drop you into a shell in the previous container.
Helpful for debugging failed `docker build`s. | It seems like most of the time people are running into this while modifying a config file, which is what I did. I was trying to bypass CORS for a PHP/Apache server with a Vue SPA as my entry point. Anyway, if you know the file you horked, a simple solution that worked for me was
1. Copy the file you horked out of the image:
docker cp bt-php:/etc/apache2/apache2.conf .
2. Fix it locally
3. Copy it back in
docker cp apache2.conf bt-php:/etc/apache2/apache2.conf
4. Start your container back up
5. \*Bonus points - Since this file is being modified, add it to your Compose or Build scripts so that when you do get it right it will be baked into the image! |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | Find your stopped container id
==============================
```
docker ps -a
```
Commit the stopped container:
=============================
This command saves modified container state into a new image `user/test_image`
```
docker commit $CONTAINER_ID user/test_image
```
Start/run with a different entry point:
=======================================
```
docker run -ti --entrypoint=sh user/test_image
```
Entrypoint argument description: <https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime>
Note:
=====
Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.
Steps to start a stopped container have been borrowed from here: (last comment) <https://github.com/docker/docker/issues/18078> | It seems docker can't change entry point after a container started. But you can set a custom entry point and change the code of the entry point next time you restart it.
For example you run a container like this:
```
docker run --name c --entrypoint "/boot" -v "./boot":/boot $image
```
Here is the boot entry point:
```
#!/bin/bash
command_a
```
When you need restart c with a different command, you just change the boot script:
```
#!/bin/bash
command_b
```
And restart:
```
docker restart c
``` |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | This is not exactly what you're asking for, but you can use `docker export` on a stopped container if all you want is to inspect the files.
```
mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR
``` | To me Docker always leaves the impression that it was created for a hobby system, it works well for that.
If something fails or doesn't work, don't expect to have a professional solution.
That said: Docker does not only NOT support such basic administrative tasks, it tries to prevent them.
Solution:
1. ```
cd /var/lib/docker/overlay2/
```
2. ```
find | grep somechangedfile
# You now can see the changed file from your container in a hexcoded folder/diff
```
3. ```
cd hexcoded-folder/diff
```
4. Create an `entrypoint.sh` (make sure to backup an existing one if it's there)
```
cat > entrypoint.sh
#!/bin/bash
while ((1)); do sleep 1; done;
```
`Ctrl`+`C`
```
chmod +x entrypoint.sh
```
5. ```
docker stop
docker start
```
You now have your docker container running an endless loop instead of the originally entry, you can exec bash into it, or do whatever you need.
When finished stop the container, remove/rename your custom entrypoint. |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | I took @Dmitriusan's answer and made it into an alias:
>
> alias docker-run-prev-container='prev\_container\_id="$(docker ps -aq | head -n1)" && docker commit "$prev\_container\_id" "prev\_container/$prev\_container\_id" && docker run -it --entrypoint=bash "prev\_container/$prev\_container\_id"'
>
>
>
Add this into your `~/.bashrc` aliases file, and you'll have a nifty new `docker-run-prev-container` alias which'll drop you into a shell in the previous container.
Helpful for debugging failed `docker build`s. | I have found a simple command
```
docker start -a [container_name]
```
This will do the trick
Or
```
docker start [container_name]
```
then
```
docker exec -it [container_name] bash
``` |
32,353,055 | I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use 'docker exec'.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option! | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150050/"
] | This is not exactly what you're asking for, but you can use `docker export` on a stopped container if all you want is to inspect the files.
```
mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR
``` | **My Problem:**
* I started a container with `docker run <IMAGE_NAME>`
* And then added some files to this container
* Then I closed the container and tried to start it again withe same command as above.
* But when I checked the new files, they were missing
* when I run `docker ps -a` I could see two containers.
* That means every time I was running `docker run <IMAGE_NAME>` command, new image was getting created
**Solution:**
To work on the same container you created in the first place run follow these steps
* `docker ps` to get container of your container
* `docker container start <CONTAINER_ID>` to start existing container
* Then you can continue from where you left. e.g. `docker exec -it <CONTAINER_ID> /bin/bash`
* You can then decide to create a new image out of it |
37,707,897 | Can help me please to optimize this query in database (access 2010), this query to work very slowly (if use it in a big table):
```
SELECT П1.Code, П1.Field, П1.Number, П1.Data, [П1].[Number]-(select П3.Number from [Table] as П3
where П3.Field = П1.Field
and П3.Data = (select Max(Data)
from [Table] as П2
where П2.Field = П1.Field and П1.Data > П2.Data)) AS Difference
FROM [Table] AS П1
ORDER BY П1.Field, П1.Data;
```
I'm attach a picture: <http://s33.postimg.org/otm859xtb/Table_query.png>
Link in the database: <http://s000.tinyupload.com/?file_id=06711692152703646964> | 2016/06/08 | [
"https://Stackoverflow.com/questions/37707897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6290311/"
] | You must use one of this methods to have a secure API
* JWT TOKEN <https://github.com/tymondesigns/jwt-auth>
* OAUTH2 <https://github.com/lucadegasperi/oauth2-server-laravel>
With this methods you only send once username and password and you obtain a token that is valid for a time you can decide. But as bigger is the time, more insecure.
To solve this, there are a renew token methods. With a valid token, you can obtain another valid and refresh the old. In this way, the username and password are more protected because they are not sent in every request.
Is not a good idea have the same token for each user all the time, as you saw in the example you provide. It´s very insecure. If someone get this token, he always will can send request in your name. The tokens must have a lifetime.
to answer your question how to send API token to mobile app i will recommend you that your mobile apps get a valid token and after refresh it.
Something as this works great to get a token in your app:
```
if ( thereAreTokenStored() )
{
if (! theTokenStoredIsValid() )
{
$authentication = refreshToken();
}
}
else
{
$authentication = authenticate();
}
```
To know all this issues I recommend you this book: <https://apisyouwonthate.com/> . I learnt a lot of the 'API WORLD' with this book. It will help you to know all you need to create an API in a professional way and will provide the necessary tools and packages to achieve it and save a lot of work. And you will love your API!! | Yes this approach is safe. Additionally you also need to secure your connection to server by using HTTPS with a SSL certificate. |
66,011,386 | Spending a huge time on this. I have a `tuple` of non-callable `classes`, all named `SymbolInfo`, with same `attribute` labels. Lets say:
```
In: print(my_tuple)
Out: (SymbolInfo(att_1=False, att_2=0, att_3=1.0),SymbolInfo(att_1=True, att_2=0, att_3=1.5))
```
My objective is to create a dataframe from this `tuple`. When I convert it to `list`, it works fine:
```
df = pd.DataFrame(list(my_tuple))
```
I get the dataframe, but I don't get the column labels, which should be the name of the `classes` `attributes`: (i.e. `att_1`, `att_2`, `att_3`).
The attributes names and their quantity (not values) are standardized for all `classes`. So I could consider any `class` to get it.
I've tried methods like `inspect.getmembers(my_tuple[0])` and `inspect.getfullargspec(my_tuple[0]).args` without success. It's important to get those arguments in the same sequence that they appear. | 2021/02/02 | [
"https://Stackoverflow.com/questions/66011386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7669782/"
] | Got this solution:
```
my_dict = my_tuple[0]._asdict()
my_col_list = list(my_dict.keys())
``` | You can access the attributes (in the order they were added) with the `__dict__` method, like so:
```
class thing():
def __init__(self, att_1, att_2, att_3):
self.z_att_1 = att_1
self.att_2 = att_2
self.att_3 = att_3
a = thing('bob', 'eve', 'alice')
b = thing('john', 'jack', 'dan')
c = (a,b)
# see the attributes
print(c[0].__dict__)
```
Results in.
```
# note that z_att_1 is first
{'z_att_1': 'bob', 'att_2': 'eve', 'att_3': 'alice'}
```
Now you can loop through the dictionary and pull out the keys for the attribute names. |
66,011,386 | Spending a huge time on this. I have a `tuple` of non-callable `classes`, all named `SymbolInfo`, with same `attribute` labels. Lets say:
```
In: print(my_tuple)
Out: (SymbolInfo(att_1=False, att_2=0, att_3=1.0),SymbolInfo(att_1=True, att_2=0, att_3=1.5))
```
My objective is to create a dataframe from this `tuple`. When I convert it to `list`, it works fine:
```
df = pd.DataFrame(list(my_tuple))
```
I get the dataframe, but I don't get the column labels, which should be the name of the `classes` `attributes`: (i.e. `att_1`, `att_2`, `att_3`).
The attributes names and their quantity (not values) are standardized for all `classes`. So I could consider any `class` to get it.
I've tried methods like `inspect.getmembers(my_tuple[0])` and `inspect.getfullargspec(my_tuple[0]).args` without success. It's important to get those arguments in the same sequence that they appear. | 2021/02/02 | [
"https://Stackoverflow.com/questions/66011386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7669782/"
] | Got this solution:
```
my_dict = my_tuple[0]._asdict()
my_col_list = list(my_dict.keys())
``` | Just create a dict from class and then create dataframe:
```
pd.DataFrame(list(map(lambda x: x.__dict__, my_tuple)))
```
And I recommend using `attrs` library for OOP in python. |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | I just got six of these in a row. All within a space of ten minutes, and each one was canceled within one minute of the order being received. And all, apparently, from the same user.
Google's new interface removes some information that used to be provided to developers in its older interface. We no longer receive a zip code for the order - just the nation from which it originated. And if an order failed because of a rejected credit card or due to cancellation by the user, it apparently does not distinguish between such events, instead telling us simply that "The order was cancelled."
It does appear that the User Latest Orders section shows you all other orders for a developer's own products that came from the user associated with the order being viewed. That is useful information as it can tell you how that user progressed from buying one product to buying another one, showing the synergy between product lines, and giving an indication of the success of cross-promoting products.
These six cancellations in a row cannot all be due to the user reverting the purchase, because Google only allows that to be done one time for a given product. After that, the second purchase would be final. But there are six total purchases for this same user, all canceled.
In the past, when using the old system that gave more information about cancellations, repeated cancellations like this were usually due to a user trying a rejected credit card more than one time, or trying more than one credit card and having all of them rejected. I suspect that this is what is happening here, only it appears more mysterious because Google is no longer letting us know about what, specifically, caused each order to be canceled.
BTW, my six canceled orders were not in-app purchases; they were all for the same paid app. So any problems that Google might be having with in-app payments were not the cause of my particular experience of multiple cancellations. | I think the buyer can cancel/revert the payment fox x minutes after buying something in the Google play store.
I have also some cancellations in my payments. But not many. |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | This means that "Payment was cancelled during processing by the user or due to a payment issue". You can check more information in [official documents](https://support.google.com/googleplay/android-developer/answer/2741495?hl=en). | I think the buyer can cancel/revert the payment fox x minutes after buying something in the Google play store.
I have also some cancellations in my payments. But not many. |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | I just got six of these in a row. All within a space of ten minutes, and each one was canceled within one minute of the order being received. And all, apparently, from the same user.
Google's new interface removes some information that used to be provided to developers in its older interface. We no longer receive a zip code for the order - just the nation from which it originated. And if an order failed because of a rejected credit card or due to cancellation by the user, it apparently does not distinguish between such events, instead telling us simply that "The order was cancelled."
It does appear that the User Latest Orders section shows you all other orders for a developer's own products that came from the user associated with the order being viewed. That is useful information as it can tell you how that user progressed from buying one product to buying another one, showing the synergy between product lines, and giving an indication of the success of cross-promoting products.
These six cancellations in a row cannot all be due to the user reverting the purchase, because Google only allows that to be done one time for a given product. After that, the second purchase would be final. But there are six total purchases for this same user, all canceled.
In the past, when using the old system that gave more information about cancellations, repeated cancellations like this were usually due to a user trying a rejected credit card more than one time, or trying more than one credit card and having all of them rejected. I suspect that this is what is happening here, only it appears more mysterious because Google is no longer letting us know about what, specifically, caused each order to be canceled.
BTW, my six canceled orders were not in-app purchases; they were all for the same paid app. So any problems that Google might be having with in-app payments were not the cause of my particular experience of multiple cancellations. | Google is currently having issues with In-app purchases: <https://productforums.google.com/forum/#!topic/play/JhGtK_pqKdA>
They're charging the user but not giving the money to the developer. |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | This means that "Payment was cancelled during processing by the user or due to a payment issue". You can check more information in [official documents](https://support.google.com/googleplay/android-developer/answer/2741495?hl=en). | Google is currently having issues with In-app purchases: <https://productforums.google.com/forum/#!topic/play/JhGtK_pqKdA>
They're charging the user but not giving the money to the developer. |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | I just got six of these in a row. All within a space of ten minutes, and each one was canceled within one minute of the order being received. And all, apparently, from the same user.
Google's new interface removes some information that used to be provided to developers in its older interface. We no longer receive a zip code for the order - just the nation from which it originated. And if an order failed because of a rejected credit card or due to cancellation by the user, it apparently does not distinguish between such events, instead telling us simply that "The order was cancelled."
It does appear that the User Latest Orders section shows you all other orders for a developer's own products that came from the user associated with the order being viewed. That is useful information as it can tell you how that user progressed from buying one product to buying another one, showing the synergy between product lines, and giving an indication of the success of cross-promoting products.
These six cancellations in a row cannot all be due to the user reverting the purchase, because Google only allows that to be done one time for a given product. After that, the second purchase would be final. But there are six total purchases for this same user, all canceled.
In the past, when using the old system that gave more information about cancellations, repeated cancellations like this were usually due to a user trying a rejected credit card more than one time, or trying more than one credit card and having all of them rejected. I suspect that this is what is happening here, only it appears more mysterious because Google is no longer letting us know about what, specifically, caused each order to be canceled.
BTW, my six canceled orders were not in-app purchases; they were all for the same paid app. So any problems that Google might be having with in-app payments were not the cause of my particular experience of multiple cancellations. | Maybe [this article](https://support.google.com/store/answer/2423477?hl=en) will help you.
It says:
>
> It usually takes about an hour for your order to start getting prepared for shipment. During this time the order will be listed as Pending on your order history page. If it is listed as Pending, you can cancel. You can also cancel your order if your item is not in stock.
>
>
> |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | I just got six of these in a row. All within a space of ten minutes, and each one was canceled within one minute of the order being received. And all, apparently, from the same user.
Google's new interface removes some information that used to be provided to developers in its older interface. We no longer receive a zip code for the order - just the nation from which it originated. And if an order failed because of a rejected credit card or due to cancellation by the user, it apparently does not distinguish between such events, instead telling us simply that "The order was cancelled."
It does appear that the User Latest Orders section shows you all other orders for a developer's own products that came from the user associated with the order being viewed. That is useful information as it can tell you how that user progressed from buying one product to buying another one, showing the synergy between product lines, and giving an indication of the success of cross-promoting products.
These six cancellations in a row cannot all be due to the user reverting the purchase, because Google only allows that to be done one time for a given product. After that, the second purchase would be final. But there are six total purchases for this same user, all canceled.
In the past, when using the old system that gave more information about cancellations, repeated cancellations like this were usually due to a user trying a rejected credit card more than one time, or trying more than one credit card and having all of them rejected. I suspect that this is what is happening here, only it appears more mysterious because Google is no longer letting us know about what, specifically, caused each order to be canceled.
BTW, my six canceled orders were not in-app purchases; they were all for the same paid app. So any problems that Google might be having with in-app payments were not the cause of my particular experience of multiple cancellations. | This means that "Payment was cancelled during processing by the user or due to a payment issue". You can check more information in [official documents](https://support.google.com/googleplay/android-developer/answer/2741495?hl=en). |
41,726,072 | I have below 2 classes:
```
public class Counter{
private int a;
public Counter(String id){
a=0;
}
public void increment(){
a++;
}
public int tally(){
return a;
}
public String toString(){
return "Counter is - " + a;
}
}
```
..and
```
/******************************************************************************
* Compilation: javac StdOut.java
* Execution: java StdOut
* Dependencies: none
*
* Writes data of various types to standard output.
*
******************************************************************************/
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* This class provides methods for printing strings and numbers to standard output.
* <p>
* <b>Getting started.</b>
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* <a href = "http://introcs.cs.princeton.edu/java/stdlib/StdOut.java">StdOut.java</a>
* and put a copy in your working directory.
* <p>
* Here is an example program that uses {@code StdOut}:
* <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>
* <p>
* <b>Differences with System.out.</b>
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
* <ul>
* <li> {@code StdOut} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdOut} coerces the locale to {@link Locale#US},
* for consistency with {@link StdIn}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdOut} <em>flushes</em> standard output after each call to
* {@code print()} so that text will appear immediately in the terminal.
* </ul>
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Computer Science: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
```
After this I wrote a client class:
```
public class ObjectTest{
public static void main(String[] args){
Counter C1 = new Counter("Ones");
C1.toString(); //Does not print anything
StdOut.println(C1); //Output is 'Counter is - 0'
}
}
```
Here;
```
C1.toString();
```
does not print anything, but
```
StdOut.println(C1); //Output is 'Counter is - 0'
```
prints 'Counter is - 0'.
Can this be explained please?
Note: This problem refers to Algoithms book by Robert and Kevin Wayne, is that makes any difference. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41726072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493490/"
] | This means that "Payment was cancelled during processing by the user or due to a payment issue". You can check more information in [official documents](https://support.google.com/googleplay/android-developer/answer/2741495?hl=en). | Maybe [this article](https://support.google.com/store/answer/2423477?hl=en) will help you.
It says:
>
> It usually takes about an hour for your order to start getting prepared for shipment. During this time the order will be listed as Pending on your order history page. If it is listed as Pending, you can cancel. You can also cancel your order if your item is not in stock.
>
>
> |
10,857,947 | I am new at making regular expressions, and so this might just be a stupid oversight, but my regex (that aims to match URL's) is not working. My goal was to have it match any urls like:
```
http://www.somewhere.com
somewhere.com
https://ww3.some_where-hi.com
www.goop.go/herp/derp.lol
```
The regex i built is below, however, it does not match a URL like `http://t.co/GZhtBh6c`, it stops matching at the number 6 (As determined by [www.regexpal.com](http://www.regexpal.com)).
```
((http|https)://)?([a-z0-9]+\.)?[a-z0-9\-_]+.[a-z]+(/[a-z0-9\-_]*)*([a-z0-9\-_]*\.[a-z]+){0,1}
```
Can anyone tell me why this is not working? Also, I'm sure this is not the best solution. If you have a more elegant regex for this, I would love to see it.
P.S. This regex will be used with javascript. | 2012/06/01 | [
"https://Stackoverflow.com/questions/10857947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/798173/"
] | Validate if a string holds a URL as specified in RFC 3986. Both absolute and relative URLs are supported.
This matches your provide sample and more. It also lets you extract the different parts of the url
```
^
(# Scheme
[a-z][a-z0-9+\-.]*:
(# Authority & path
//
([a-z0-9\-._~%!$&'()*+,;=]+@)? # User
([a-z0-9\-._~%]+ # Named host
|\[[a-f0-9:.]+\] # IPv6 host
|\[v[a-f0-9][a-z0-9\-._~%!$&'()*+,;=:]+\]) # IPvFuture host
(:[0-9]+)? # Port
(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/? # Path
|# Path without authority
(/?[a-z0-9\-._~%!$&'()*+,;=:@]+(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/?)?
)
|# Relative URL (no scheme or authority)
([a-z0-9\-._~%!$&'()*+,;=@]+(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/? # Relative path
|(/[a-z0-9\-._~%!$&'()*+,;=:@]+)+/?) # Absolute path
)
# Query
(\?[a-z0-9\-._~%!$&'()*+,;=:@/?]*)?
# Fragment
(\#[a-z0-9\-._~%!$&'()*+,;=:@/?]*)?
$
```
In javascript this becomes
```
if (/^([a-z][a-z0-9+\-.]*:(\/\/([a-z0-9\-._~%!$&'()*+,;=]+@)?([a-z0-9\-._~%]+|\[[a-f0-9:.]+\]|\[v[a-f0-9][a-z0-9\-._~%!$&'()*+,;=:]+\])(:[0-9]+)?(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/?[a-z0-9\-._~%!$&'()*+,;=:@]+(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?)?)|([a-z0-9\-._~%!$&'()*+,;=@]+(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)+\/?))(\?[a-z0-9\-._~%!$&'()*+,;=:@\/?]*)?(#[a-z0-9\-._~%!$&'()*+,;=:@\/?]*)?$/im.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
``` | use a `[A-z]` instead of `[a-z]`
your little `a-z` is only matching lowercase letters. |
19,276 | I am playing around with Ettercap and [ARP spoofing](http://en.wikipedia.org/wiki/ARP_spoofing) attacks. I have noticed that the computers that are involved in my attack not are displaying any messages telling that an IP conflict has occured.
Isn't that the case when ARP spoofing? Then two (or more) computers will share the same IP. When does an IP conflict occur?
The computers I spoof are a Windows 7 and Ubuntu machines. | 2012/08/25 | [
"https://security.stackexchange.com/questions/19276",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/7066/"
] | **When ARP Poisoning** You are poisoning the ARP tables. If computer 10.1.1.1 needs to get to computer 10.1.1.2, it keeps the MAC address in its ARP tables. ARP is a *trusting* protocol, which means when a computer responds to a ARP request, there is nothing requiring its response to be correct and no mechanism for verifying it is correct.
So here's the game plan.
1. Victim sends out arp request for 10.1.1.1.
2. Legitimate 10.1.1.1 responds with its MAC Address, but I (the attacker) send out 10 million responses.
3. As long as 1 of my ARP responses gets sent after the legitimate one, the attacker's MAC address will be put into the victim's ARP table.
One interesting thing about ARP is that the victim doesn't need to send out an ARP request to poison them. Like I said, ARP is poisoning them.
**IP Addressing Spoofing** I pick an IP address that already exists on my network. Other Hosts will have issues establishing a TCP connection. For example. The legitimate host that the attacker is spoofing tries to access a webserver. The legitimate host sends a SYN, the legitimate webserver sends an ACK that both the attacker AND the legitimate host responds to. The legitimate host responds with a SYN-ACK like they should. The attacker responds with a RST since they ACK is unexpected to it. It makes it really difficult (impossible) for a IP address being spoofed to use any TCP services.
I'm having trouble interpreting your question (I'm bad at reading) but hopefully this helps. | ARP Spoofing is NOT the same as IP address spoofing.
What ARP spoofing does is associate a MAC Address with an existing IP Address. The exploit involves sending fake ARP reply packets that will associate the attackers MAC address with a legitimate IP address. This involves making use of the fact that the ARP protocol is stateless - it doesn't keep track of any changes. New ARP reply packets will override the old ARP entries in the cache.
To any hosts in the network, they will only see one IP address associated to one MAC address (the attackers MAC). |
19,276 | I am playing around with Ettercap and [ARP spoofing](http://en.wikipedia.org/wiki/ARP_spoofing) attacks. I have noticed that the computers that are involved in my attack not are displaying any messages telling that an IP conflict has occured.
Isn't that the case when ARP spoofing? Then two (or more) computers will share the same IP. When does an IP conflict occur?
The computers I spoof are a Windows 7 and Ubuntu machines. | 2012/08/25 | [
"https://security.stackexchange.com/questions/19276",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/7066/"
] | Get to the roots ! If you know what [ARP](http://en.wikipedia.org/wiki/Address_Resolution_Protocol) does, things will be clearer.
On a subnet (machines plugged into the same set of hubs and switches), the machines talk to each other with MAC addresses: the MAC address uniquely identifies each ethernet/WiFi card. Machines, *a priori*, do not know MAC addresses; they just know IP addresses. So, when machine *A* wants to send a packet to machine *B*, it sends a broadcast frame following the ARP protocol; the packet says: "hey, does anybody knows the MAC address of *B*" ? If someone responds with the information ("*B* has MAC address xx:xx:xx:xx:xx:xx") then *A* will be able to send its data to *B*.
To speed up the process, *A* maintains a cache of known mappings IP-to-MAC, but is ready to remove entries from the cache when the information is not renewed (information renewal is when a packet comes to *A*, tagged with the IP address of *B* as source, and, at the ethernet level, uses the MAC address of *B*). The ARP cache entries must not be too long-lived because *B* is allowed to switch hardware (in case *B*'s ethernet adapter fries and is replaced, the new adapter will have a distinct MAC address, but may assume the same IP address).
Other users of ARP are [switches](http://en.wikipedia.org/wiki/Network_switch). Switch do not emit packets, but they observe a lot. The point of a switch, as opposed to a simpler [hub](http://en.wikipedia.org/wiki/Ethernet_hub), is to optimize things by sending packets only on relevant cables, instead of broadcasting all packets over the complete subnet. A switch "knows" that a given machine (i.e. a MAC address) lies at the other end of a specific link by observing traffic (i.e. the switch has noticed that all packets with that MAC address as source come from a given link). The switch maintains thus a mapping MAC->link in an internal table, which is confusingly (and inappropriately) also called an "ARP cache".
**Spoofing** is the term some people came up with to designate what is otherwise known as a [forgery](http://en.wikipedia.org/wiki/Forgery), when in the context of network security (for some reason, perfectly usable words from previous centuries never seem to be good enough for the technology-addict). [ARP spoofing](http://en.wikipedia.org/wiki/ARP_spoofing) is about sending packets which are forged at the ARP level, i.e. packets which will *deceive* other systems as to the mappings involving ARP (i.e. the ARP caches that machines and switches maintain). The attacker may gain some advantages so doing; for instance, he may convince a switch to send *him* some packets which would otherwise have been sent to another machine on another link. This kind of attack is also know as "ARP cache poisoning" because it ultimately fills some ARP caches with wrong entries.
An **IP conflict** is when two machines, with *distinct* MAC addresses, want to assume the same IP. When an ARP request is sent ("what is the MAC address of *B*"), *both* machines will respond, with conflicting information. The requester (*A*) receives both answers and can warn about the problem: two concurrent mappings with **one** IP and **two** MAC addresses. ARP spoofing tries to do something different: **two** IP addresses (or two links) which map to **one** MAC address. The successful ARP attack is not really distinguishable from a machine which changed its IP address, something which, on a general basis, is normal (when machines get IP addresses dynamically with [DHCP](http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol), their IP address may change from time to time), and thus triggers no special warning. | ARP Spoofing is NOT the same as IP address spoofing.
What ARP spoofing does is associate a MAC Address with an existing IP Address. The exploit involves sending fake ARP reply packets that will associate the attackers MAC address with a legitimate IP address. This involves making use of the fact that the ARP protocol is stateless - it doesn't keep track of any changes. New ARP reply packets will override the old ARP entries in the cache.
To any hosts in the network, they will only see one IP address associated to one MAC address (the attackers MAC). |
19,276 | I am playing around with Ettercap and [ARP spoofing](http://en.wikipedia.org/wiki/ARP_spoofing) attacks. I have noticed that the computers that are involved in my attack not are displaying any messages telling that an IP conflict has occured.
Isn't that the case when ARP spoofing? Then two (or more) computers will share the same IP. When does an IP conflict occur?
The computers I spoof are a Windows 7 and Ubuntu machines. | 2012/08/25 | [
"https://security.stackexchange.com/questions/19276",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/7066/"
] | Get to the roots ! If you know what [ARP](http://en.wikipedia.org/wiki/Address_Resolution_Protocol) does, things will be clearer.
On a subnet (machines plugged into the same set of hubs and switches), the machines talk to each other with MAC addresses: the MAC address uniquely identifies each ethernet/WiFi card. Machines, *a priori*, do not know MAC addresses; they just know IP addresses. So, when machine *A* wants to send a packet to machine *B*, it sends a broadcast frame following the ARP protocol; the packet says: "hey, does anybody knows the MAC address of *B*" ? If someone responds with the information ("*B* has MAC address xx:xx:xx:xx:xx:xx") then *A* will be able to send its data to *B*.
To speed up the process, *A* maintains a cache of known mappings IP-to-MAC, but is ready to remove entries from the cache when the information is not renewed (information renewal is when a packet comes to *A*, tagged with the IP address of *B* as source, and, at the ethernet level, uses the MAC address of *B*). The ARP cache entries must not be too long-lived because *B* is allowed to switch hardware (in case *B*'s ethernet adapter fries and is replaced, the new adapter will have a distinct MAC address, but may assume the same IP address).
Other users of ARP are [switches](http://en.wikipedia.org/wiki/Network_switch). Switch do not emit packets, but they observe a lot. The point of a switch, as opposed to a simpler [hub](http://en.wikipedia.org/wiki/Ethernet_hub), is to optimize things by sending packets only on relevant cables, instead of broadcasting all packets over the complete subnet. A switch "knows" that a given machine (i.e. a MAC address) lies at the other end of a specific link by observing traffic (i.e. the switch has noticed that all packets with that MAC address as source come from a given link). The switch maintains thus a mapping MAC->link in an internal table, which is confusingly (and inappropriately) also called an "ARP cache".
**Spoofing** is the term some people came up with to designate what is otherwise known as a [forgery](http://en.wikipedia.org/wiki/Forgery), when in the context of network security (for some reason, perfectly usable words from previous centuries never seem to be good enough for the technology-addict). [ARP spoofing](http://en.wikipedia.org/wiki/ARP_spoofing) is about sending packets which are forged at the ARP level, i.e. packets which will *deceive* other systems as to the mappings involving ARP (i.e. the ARP caches that machines and switches maintain). The attacker may gain some advantages so doing; for instance, he may convince a switch to send *him* some packets which would otherwise have been sent to another machine on another link. This kind of attack is also know as "ARP cache poisoning" because it ultimately fills some ARP caches with wrong entries.
An **IP conflict** is when two machines, with *distinct* MAC addresses, want to assume the same IP. When an ARP request is sent ("what is the MAC address of *B*"), *both* machines will respond, with conflicting information. The requester (*A*) receives both answers and can warn about the problem: two concurrent mappings with **one** IP and **two** MAC addresses. ARP spoofing tries to do something different: **two** IP addresses (or two links) which map to **one** MAC address. The successful ARP attack is not really distinguishable from a machine which changed its IP address, something which, on a general basis, is normal (when machines get IP addresses dynamically with [DHCP](http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol), their IP address may change from time to time), and thus triggers no special warning. | **When ARP Poisoning** You are poisoning the ARP tables. If computer 10.1.1.1 needs to get to computer 10.1.1.2, it keeps the MAC address in its ARP tables. ARP is a *trusting* protocol, which means when a computer responds to a ARP request, there is nothing requiring its response to be correct and no mechanism for verifying it is correct.
So here's the game plan.
1. Victim sends out arp request for 10.1.1.1.
2. Legitimate 10.1.1.1 responds with its MAC Address, but I (the attacker) send out 10 million responses.
3. As long as 1 of my ARP responses gets sent after the legitimate one, the attacker's MAC address will be put into the victim's ARP table.
One interesting thing about ARP is that the victim doesn't need to send out an ARP request to poison them. Like I said, ARP is poisoning them.
**IP Addressing Spoofing** I pick an IP address that already exists on my network. Other Hosts will have issues establishing a TCP connection. For example. The legitimate host that the attacker is spoofing tries to access a webserver. The legitimate host sends a SYN, the legitimate webserver sends an ACK that both the attacker AND the legitimate host responds to. The legitimate host responds with a SYN-ACK like they should. The attacker responds with a RST since they ACK is unexpected to it. It makes it really difficult (impossible) for a IP address being spoofed to use any TCP services.
I'm having trouble interpreting your question (I'm bad at reading) but hopefully this helps. |
54,418,479 | I have facing this issue when I was changing project name and copying my project from one mac to another. There are some red texts indicate the missing files from the project source codes(But I have all files in Project folder) I have used cocoapods in this project. How to avoid these?
Here I have shown my project screen shot.
[](https://i.stack.imgur.com/VZJsM.jpg) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54418479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4062704/"
] | Computed properties are cached based on their dependencies (data, props and other computed properties). If I've understood correctly, your computed property won't be reactive cause the only dependency is myHandle, and I assume that will never change. Look at it this way, Vue can only check that getName is returning a different value by actually calling the method, so there's nothing to cache.
If the name can only be changed from your Vue component, you can set it as a data field and add a watcher to update the WebAssembly value. Otherwise, if the name can be changed from non-Vue sources and you must call the getName method from the handler every time, you will have to come up with your own mechanism (maybe using a debounce function to limit the number of calls). | I hope this example will help you
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="app">
<my-component :myhandle="myhandle">
</my-component>
<h2>Vue app Object: {{myhandle.name}}</h2>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
Vue.component('my-component', Vue.extend({
props: ["myhandle"],
data () {
return {
name:""
}
},
watch: {
myhandle:{
handler (val, oldVal) {
console.log('Prop changed');
// do your stuff
},
deep: true, // nested data
}
},
methods: {
chName(){
this.myhandle.name = "Henry";
}
},
template:'<div><h1>{{myhandle.name }}</h1><br><button @click="chName()">Cahnge name</button></div>',
}),
);
var app = new Vue({
el:'#app',
data (){
return {
myhandle:{
name:'Jack'
}
}
}
});
</script>
</body>
</html>
``` |
54,418,479 | I have facing this issue when I was changing project name and copying my project from one mac to another. There are some red texts indicate the missing files from the project source codes(But I have all files in Project folder) I have used cocoapods in this project. How to avoid these?
Here I have shown my project screen shot.
[](https://i.stack.imgur.com/VZJsM.jpg) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54418479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4062704/"
] | I don't know how your implementation of setName() is, but if it is
`setName(newName) { this.name = newName; }`
you might have run into the problem described here:
<https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats>
I would like to add that it is probably not a good idea to mutate myHandle as a prop, so I suggest that if you can refactor your code to use myHandle as a data property, to do so. | I hope this example will help you
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="app">
<my-component :myhandle="myhandle">
</my-component>
<h2>Vue app Object: {{myhandle.name}}</h2>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
Vue.component('my-component', Vue.extend({
props: ["myhandle"],
data () {
return {
name:""
}
},
watch: {
myhandle:{
handler (val, oldVal) {
console.log('Prop changed');
// do your stuff
},
deep: true, // nested data
}
},
methods: {
chName(){
this.myhandle.name = "Henry";
}
},
template:'<div><h1>{{myhandle.name }}</h1><br><button @click="chName()">Cahnge name</button></div>',
}),
);
var app = new Vue({
el:'#app',
data (){
return {
myhandle:{
name:'Jack'
}
}
}
});
</script>
</body>
</html>
``` |
54,418,479 | I have facing this issue when I was changing project name and copying my project from one mac to another. There are some red texts indicate the missing files from the project source codes(But I have all files in Project folder) I have used cocoapods in this project. How to avoid these?
Here I have shown my project screen shot.
[](https://i.stack.imgur.com/VZJsM.jpg) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54418479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4062704/"
] | Computed properties are cached based on their dependencies (data, props and other computed properties). If I've understood correctly, your computed property won't be reactive cause the only dependency is myHandle, and I assume that will never change. Look at it this way, Vue can only check that getName is returning a different value by actually calling the method, so there's nothing to cache.
If the name can only be changed from your Vue component, you can set it as a data field and add a watcher to update the WebAssembly value. Otherwise, if the name can be changed from non-Vue sources and you must call the getName method from the handler every time, you will have to come up with your own mechanism (maybe using a debounce function to limit the number of calls). | I don't know how your implementation of setName() is, but if it is
`setName(newName) { this.name = newName; }`
you might have run into the problem described here:
<https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats>
I would like to add that it is probably not a good idea to mutate myHandle as a prop, so I suggest that if you can refactor your code to use myHandle as a data property, to do so. |
54,418,479 | I have facing this issue when I was changing project name and copying my project from one mac to another. There are some red texts indicate the missing files from the project source codes(But I have all files in Project folder) I have used cocoapods in this project. How to avoid these?
Here I have shown my project screen shot.
[](https://i.stack.imgur.com/VZJsM.jpg) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54418479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4062704/"
] | Computed properties are cached based on their dependencies (data, props and other computed properties). If I've understood correctly, your computed property won't be reactive cause the only dependency is myHandle, and I assume that will never change. Look at it this way, Vue can only check that getName is returning a different value by actually calling the method, so there's nothing to cache.
If the name can only be changed from your Vue component, you can set it as a data field and add a watcher to update the WebAssembly value. Otherwise, if the name can be changed from non-Vue sources and you must call the getName method from the handler every time, you will have to come up with your own mechanism (maybe using a debounce function to limit the number of calls). | There is a simple trick - dummy\_toogle - just place it in your component data: {toggle:false}
and in your getter/setter:
get: function(){this.toggle; ... }
set:function(name){...; this.toggle=!this.toggle;}
Now vue will think that computed property is dependent on the toggle and recompute it if toggle is changed + you can make a very stupid callback and pass it to non-vue part of your app as update-trigger |
54,418,479 | I have facing this issue when I was changing project name and copying my project from one mac to another. There are some red texts indicate the missing files from the project source codes(But I have all files in Project folder) I have used cocoapods in this project. How to avoid these?
Here I have shown my project screen shot.
[](https://i.stack.imgur.com/VZJsM.jpg) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54418479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4062704/"
] | I don't know how your implementation of setName() is, but if it is
`setName(newName) { this.name = newName; }`
you might have run into the problem described here:
<https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats>
I would like to add that it is probably not a good idea to mutate myHandle as a prop, so I suggest that if you can refactor your code to use myHandle as a data property, to do so. | There is a simple trick - dummy\_toogle - just place it in your component data: {toggle:false}
and in your getter/setter:
get: function(){this.toggle; ... }
set:function(name){...; this.toggle=!this.toggle;}
Now vue will think that computed property is dependent on the toggle and recompute it if toggle is changed + you can make a very stupid callback and pass it to non-vue part of your app as update-trigger |
54,280,712 | I'm making an LED control program (using FastLED, of course) and using Serial (with the Serial monitor) to control it. I just connected it via USB and for the most part it works just fine. However, I noticed with the long, flashing routines that I couldn't stop them and make the LEDs do something else. The flash routine in my code is very simple:
```cpp
void flash(CRGB color, int count, int del){
for(int i = 0; i < count; i++){
if(pause){
break;
}
fillLeds(color.r, color.g, color.b);
milliDelay(del);
fillLeds(0,0,0);
milliDelay(del);
}
}
```
With `fillLeds(r,g,b)` being a *for* loop, looping through and setting all LEDs to a certain color, and `milliDelay` is just `delay()` using `millis` and not the `delay()` function.
I need to be able to pause not just this, but other functions as well (probably using `break;`) and then execute other code. It seems easy, right? Well, I've noticed that when I send a byte over Serial, it goes into this "queue," if you will, and then is sequentially read.
I can’t have this happen. I need the next byte entering Serial to activate some kind of event that pauses the other `flash()` function running, and then be used. I have implemented this like:
```cpp
void loop()
{
if (Serial.available() > 0)
{
int x = Serial.read();
Serial.print(x);
handleRequest(x);
}
FastLED.show();
FastLED.delay(1000 / UPDATES_PER_SECOND);
}
```
Where `handleRequest(x);` is just a long *switch* statement with calls to the flash method, with different colors being used, etc.
How can I make the Arduino pause other loops whenever a new byte is received, instead of adding it to this "queue" to be acted upon later? If this is not possible thanks for reading anyway. I've tried using `serialEvent()` which doesn't appear to work. | 2019/01/20 | [
"https://Stackoverflow.com/questions/54280712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5255218/"
] | You don't send `$_POST['req_new_pw']` and you are asking if it's set.
You can use `serialize()` to send all form element by post:
```
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
```
Make sure you are setting `$_SESSION['capcode3']` either. | This works like a charm:
```
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});
``` |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | In all seriousness you can't cut up xml execution plans from scratch. Creating them using SSIS is science fiction. Yes it's all XML, but they are from different universes. Looking at Paul's blog on that [topic](http://web.archive.org/web/20180404164406/http://sqlblog.com/blogs/paul_white/archive/2011/12/23/forcing-a-parallel-query-execution-plan.aspx), he's saying "much in the way SSIS allows ..." so possibly you've misunderstood? I don't think he's saying "use SSIS to create plans" but rather "wouldn't it be great to be able to create plans using a drag and drop interface *like* SSIS". Maybe, for a very simple query, you could just about manage this, but it's a stretch, possibly even a waste of time. Busy work you might say.
If I'm creating a plan for a USE PLAN hint or plan guide, I have a couple of approaches. For example, I might remove records from tables (eg on a copy of the db) to influence the stats and encourage the optimizer to make a different decision. I've also used table variables instead of all the table in the query so the optimizer thinks every table contains 1 record. Then in the generated plan, replace all the table variables with the original table names and swap it in as the plan. Another option would be to use the WITH STATS\_STREAM option of UPDATE STATISTICS to spoof statistics which is the method used when cloning statistics-only copies of databases eg
```
UPDATE STATISTICS
[dbo].[yourTable]([PK_yourTable])
WITH
STATS_STREAM = 0x0100etc,
ROWCOUNT = 10000,
PAGECOUNT = 93
```
I have spent some time tinkering with xml execution plans in the past and I have found that in the end, SQL just goes "I'm not using that" and runs the query how it wants anyway.
For your specific example, I'm sure you're aware you could use set rowcount 3 or TOP 3 in the query to get that result, but I guess that is not your point. The *correct* answer would really be: use a temp table. I would upvote that : ) Not a correct answer would be "spend hours even days cutting up your own custom XML execution plan where you attempt to trick the optimzer into doing a lazy spool for the CTE which might not even work anyway, would look *clever* but would also be impossible to maintain".
Not trying to be unconstructive there, just my opinion - hope that helps. | I found traceflag 8649 (force parallel plan) induced this behaviour for the left-hand guid column on my 2008, R2 and 2012 instances. I didn't need to use the flag on SQL 2005 where the CTE behaved correctly. I tried using the plan generated in SQL 2005 in the higher instances but it wouldn't validate.
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
option ( querytraceon 8649 )
```
Either using the hint, using a plan guide including the hint or using the plan generated by the query with the hint on in a USE PLAN etc all worked.
 |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | >
> *Is there ANY way to make the result come up with exactly 3 distinct guids and no more? I'm hoping to be able to better answer questions in
> future by including plan guides with CTE-type queries that are
> referenced multiple times to overcome some SQL Server CTE quirks.*
>
>
>
Not today. Non-recursive common table expressions (CTEs) are treated as in-line view definitions and expanded into the logical query tree at each place they are referenced (just like regular view definitions are) before optimization. The logical tree for your query is:
```
LogOp_OrderByCOL: Union1007 ASC COL: Union1015 ASC
LogOp_Project COL: Union1006 COL: Union1007 COL: Union1014 COL: Union1015
LogOp_Join
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
```
Notice the two View Anchors and the *six* calls to the intrinsic function `newid` before optimization gets started. Nevertheless, many people consider that the optimizer ought to be able to identify that the expanded sub-trees were originally a single referenced object and simplify accordingly. There have also been several [Connect requests](https://web.archive.org/web/20160914051638/https://connect.microsoft.com/SQLServer/feedback/details/218968/provide-a-hint-to-force-intermediate-materialization-of-ctes-or-derived-tables) to allow explicit materialization of a CTE or derived table.
A more general implementation would have the optimizer consider materializing arbitrary common expressions to improve performance (`CASE` with a subquery is another example where [problems](https://web.archive.org/web/20140329083016/https://connect.microsoft.com/SQLServer/feedback/details/546437/coalesce-subquery-1-may-return-null) can occur today). Microsoft Research [published a paper](https://web.archive.org/web/20120515085813/http://research.microsoft.com/en-us/um/people/jrzhou/pub/cse.pdf) (PDF) on that back in 2007, though it remains unimplemented to date. For the time being, we are limited to explicit materialization using things like table variables and temporary tables.
>
> *SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?*
>
>
>
This was just [wishful thinking](https://sql.kiwi/2011/12/forcing-a-parallel-query-execution-plan.html) on my part, and went well beyond the idea of modifying plan guides. It is possible, in principle, to write a tool to manipulate show plan XML directly, but without specific optimizer instrumentation using the tool would likely be a frustrating experience for the user (and the developer come to think of it).
In the particular context of this question, such a tool would still be unable to materialize the CTE contents in a way that could used by multiple consumers (to feed both inputs to the cross join in this case). The optimizer and execution engine do support multi-consumer spools, but only for specific purposes - none of which could be made to apply to this particular example.
>
> *While I'm not certain, I have a fairly strong hunch that the RelOps can be followed (Nested Loop, Lazy Spool) even if the query is not exactly the same as the plan - for instance if you added 4 and 5 to the CTE, it still continues to use the same plan (seemingly - tested on SQL Server 2012 RTM Express).*
>
>
>
There is a reasonable amount of flexibility here. The broad shape of the XML plan is used to *guide* the search for a final plan (though many attributes are ignored completely e.g. partitioning type on exchanges) and the normal search rules are considerably relaxed as well. For example, early pruning of alternatives based on cost considerations is disabled, the explicit introduction of cross joins is allowed, and scalar operations are ignored.
There are too many details to go into in depth, but the placement of Filters and Compute Scalars cannot be forced, and predicates of the form `column = value` are generalized so a plan containing `X = 1` or `X = @X` can be applied to a query containing `X = 502` or `X = @Y`. This particular flexibility can help greatly in finding a natural plan to force.
In the specific example, constant Union All can always be implemented as a Constant Scan; the number of inputs to the Union All does not matter. | In all seriousness you can't cut up xml execution plans from scratch. Creating them using SSIS is science fiction. Yes it's all XML, but they are from different universes. Looking at Paul's blog on that [topic](http://web.archive.org/web/20180404164406/http://sqlblog.com/blogs/paul_white/archive/2011/12/23/forcing-a-parallel-query-execution-plan.aspx), he's saying "much in the way SSIS allows ..." so possibly you've misunderstood? I don't think he's saying "use SSIS to create plans" but rather "wouldn't it be great to be able to create plans using a drag and drop interface *like* SSIS". Maybe, for a very simple query, you could just about manage this, but it's a stretch, possibly even a waste of time. Busy work you might say.
If I'm creating a plan for a USE PLAN hint or plan guide, I have a couple of approaches. For example, I might remove records from tables (eg on a copy of the db) to influence the stats and encourage the optimizer to make a different decision. I've also used table variables instead of all the table in the query so the optimizer thinks every table contains 1 record. Then in the generated plan, replace all the table variables with the original table names and swap it in as the plan. Another option would be to use the WITH STATS\_STREAM option of UPDATE STATISTICS to spoof statistics which is the method used when cloning statistics-only copies of databases eg
```
UPDATE STATISTICS
[dbo].[yourTable]([PK_yourTable])
WITH
STATS_STREAM = 0x0100etc,
ROWCOUNT = 10000,
PAGECOUNT = 93
```
I have spent some time tinkering with xml execution plans in the past and I have found that in the end, SQL just goes "I'm not using that" and runs the query how it wants anyway.
For your specific example, I'm sure you're aware you could use set rowcount 3 or TOP 3 in the query to get that result, but I guess that is not your point. The *correct* answer would really be: use a temp table. I would upvote that : ) Not a correct answer would be "spend hours even days cutting up your own custom XML execution plan where you attempt to trick the optimzer into doing a lazy spool for the CTE which might not even work anyway, would look *clever* but would also be impossible to maintain".
Not trying to be unconstructive there, just my opinion - hope that helps. |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | There is no way (SQL Server versions up to 2012) to re-use a single spool for both occurences of the CTE. Details can be found in SQLKiwi's answer. **Further below** are two ways to materialize the CTE twice, which is unavoidable for the nature of the query. Both options result in a net distinct guid count of 6.
The link from Martin's comment to Quassnoi's site on a [blog about plan guiding a CTE](http://explainextended.com/2009/05/28/generating-xml-in-subqueries/) was partial inspiration for this question. It describes a way to materialize a CTE for the purpose of a correlated subquery, which is referenced only once although the correlation can cause it to be evaluated multiple times. That does not apply to the query in the question.
Option 1 - Plan Guide
---------------------
Taking hints from SQLKiwi's answer, I have pared down the guide to a bare minimum that will still do the job, e.g. the `ConstantScan` nodes only list 2 scalar operators which can sufficiently expand to any number.
```
;with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
OPTION(USE PLAN
N'<?xml version="1.0" encoding="utf-16"?>
<ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.2" Build="11.0.2100.60" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">
<BatchSequence>
<Batch>
<Statements>
<StmtSimple StatementCompId="1" StatementEstRows="1600" StatementId="1" StatementOptmLevel="FULL" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" StatementSubTreeCost="0.0444433" StatementText="with cte(guid,other) as (
 select newid(),1 union all
 select newid(),2 union all
 select newid(),3
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
" StatementType="SELECT" QueryHash="0x43D93EF17C8E55DD" QueryPlanHash="0xF8E3B336792D84" RetrievedFromCache="true">
<StatementSetOptions ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="true" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="true" />
<QueryPlan NonParallelPlanReason="EstimatedDOPIsOne" CachedPlanSize="96" CompileTime="13" CompileCPU="13" CompileMemory="1152">
<MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" />
<OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="157240" EstimatedPagesCached="1420" EstimatedAvailableDegreeOfParallelism="1" />
<RelOp AvgRowSize="47" EstimateCPU="0.006688" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="1600" LogicalOp="Inner Join" NodeId="0" Parallel="false" PhysicalOp="Nested Loops" EstimatedTotalSubtreeCost="0.0444433">
<OutputList>
<ColumnReference Column="Union1163" />
</OutputList>
<Warnings NoJoinPredicate="true" />
<NestedLoops Optimized="false">
<RelOp AvgRowSize="27" EstimateCPU="0.000432115" EstimateIO="0.0112613" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Sort" NodeId="1" Parallel="false" PhysicalOp="Sort" EstimatedTotalSubtreeCost="0.0117335">
<OutputList>
<ColumnReference Column="Union1080" />
<ColumnReference Column="Union1081" />
</OutputList>
<MemoryFractions Input="0" Output="0" />
<Sort Distinct="false">
<OrderBy>
<OrderByColumn Ascending="true">
<ColumnReference Column="Union1081" />
</OrderByColumn>
</OrderBy>
<RelOp AvgRowSize="27" EstimateCPU="4.0157E-05" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Constant Scan" NodeId="2" Parallel="false" PhysicalOp="Constant Scan" EstimatedTotalSubtreeCost="4.0157E-05">
<OutputList>
<ColumnReference Column="Union1080" />
<ColumnReference Column="Union1081" />
</OutputList>
<ConstantScan>
<Values>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(1)">
<Const ConstValue="(1)" />
</ScalarOperator>
</Row>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(2)">
<Const ConstValue="(2)" />
</ScalarOperator>
</Row>
</Values>
</ConstantScan>
</RelOp>
</Sort>
</RelOp>
<RelOp AvgRowSize="27" EstimateCPU="0.0001074" EstimateIO="0.01" EstimateRebinds="0" EstimateRewinds="39" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Lazy Spool" NodeId="83" Parallel="false" PhysicalOp="Table Spool" EstimatedTotalSubtreeCost="0.0260217">
<OutputList>
<ColumnReference Column="Union1162" />
<ColumnReference Column="Union1163" />
</OutputList>
<Spool>
<RelOp AvgRowSize="27" EstimateCPU="0.000432115" EstimateIO="0.0112613" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Sort" NodeId="84" Parallel="false" PhysicalOp="Sort" EstimatedTotalSubtreeCost="0.0117335">
<OutputList>
<ColumnReference Column="Union1162" />
<ColumnReference Column="Union1163" />
</OutputList>
<MemoryFractions Input="0" Output="0" />
<Sort Distinct="false">
<OrderBy>
<OrderByColumn Ascending="true">
<ColumnReference Column="Union1163" />
</OrderByColumn>
</OrderBy>
<RelOp AvgRowSize="27" EstimateCPU="4.0157E-05" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Constant Scan" NodeId="85" Parallel="false" PhysicalOp="Constant Scan" EstimatedTotalSubtreeCost="4.0157E-05">
<OutputList>
<ColumnReference Column="Union1162" />
<ColumnReference Column="Union1163" />
</OutputList>
<ConstantScan>
<Values>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(1)">
<Const ConstValue="(1)" />
</ScalarOperator>
</Row>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(2)">
<Const ConstValue="(2)" />
</ScalarOperator>
</Row>
</Values>
</ConstantScan>
</RelOp>
</Sort>
</RelOp>
</Spool>
</RelOp>
</NestedLoops>
</RelOp>
</QueryPlan>
</StmtSimple>
</Statements>
</Batch>
</BatchSequence>
</ShowPlanXML>'
);
```
Option 2 - Remote Scan
----------------------
By increasing the expense of the query and introducing a Remote Scan, the result is materialized.
```
with cte(guid,other) as (
select *
from OPENQUERY([TESTSQL\V2012], '
select newid(),1 union all
select newid(),2 union all
select newid(),3') x)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
``` | I found traceflag 8649 (force parallel plan) induced this behaviour for the left-hand guid column on my 2008, R2 and 2012 instances. I didn't need to use the flag on SQL 2005 where the CTE behaved correctly. I tried using the plan generated in SQL 2005 in the higher instances but it wouldn't validate.
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
option ( querytraceon 8649 )
```
Either using the hint, using a plan guide including the hint or using the plan generated by the query with the hint on in a USE PLAN etc all worked.
 |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | >
> *Is there ANY way to make the result come up with exactly 3 distinct guids and no more? I'm hoping to be able to better answer questions in
> future by including plan guides with CTE-type queries that are
> referenced multiple times to overcome some SQL Server CTE quirks.*
>
>
>
Not today. Non-recursive common table expressions (CTEs) are treated as in-line view definitions and expanded into the logical query tree at each place they are referenced (just like regular view definitions are) before optimization. The logical tree for your query is:
```
LogOp_OrderByCOL: Union1007 ASC COL: Union1015 ASC
LogOp_Project COL: Union1006 COL: Union1007 COL: Union1014 COL: Union1015
LogOp_Join
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
```
Notice the two View Anchors and the *six* calls to the intrinsic function `newid` before optimization gets started. Nevertheless, many people consider that the optimizer ought to be able to identify that the expanded sub-trees were originally a single referenced object and simplify accordingly. There have also been several [Connect requests](https://web.archive.org/web/20160914051638/https://connect.microsoft.com/SQLServer/feedback/details/218968/provide-a-hint-to-force-intermediate-materialization-of-ctes-or-derived-tables) to allow explicit materialization of a CTE or derived table.
A more general implementation would have the optimizer consider materializing arbitrary common expressions to improve performance (`CASE` with a subquery is another example where [problems](https://web.archive.org/web/20140329083016/https://connect.microsoft.com/SQLServer/feedback/details/546437/coalesce-subquery-1-may-return-null) can occur today). Microsoft Research [published a paper](https://web.archive.org/web/20120515085813/http://research.microsoft.com/en-us/um/people/jrzhou/pub/cse.pdf) (PDF) on that back in 2007, though it remains unimplemented to date. For the time being, we are limited to explicit materialization using things like table variables and temporary tables.
>
> *SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?*
>
>
>
This was just [wishful thinking](https://sql.kiwi/2011/12/forcing-a-parallel-query-execution-plan.html) on my part, and went well beyond the idea of modifying plan guides. It is possible, in principle, to write a tool to manipulate show plan XML directly, but without specific optimizer instrumentation using the tool would likely be a frustrating experience for the user (and the developer come to think of it).
In the particular context of this question, such a tool would still be unable to materialize the CTE contents in a way that could used by multiple consumers (to feed both inputs to the cross join in this case). The optimizer and execution engine do support multi-consumer spools, but only for specific purposes - none of which could be made to apply to this particular example.
>
> *While I'm not certain, I have a fairly strong hunch that the RelOps can be followed (Nested Loop, Lazy Spool) even if the query is not exactly the same as the plan - for instance if you added 4 and 5 to the CTE, it still continues to use the same plan (seemingly - tested on SQL Server 2012 RTM Express).*
>
>
>
There is a reasonable amount of flexibility here. The broad shape of the XML plan is used to *guide* the search for a final plan (though many attributes are ignored completely e.g. partitioning type on exchanges) and the normal search rules are considerably relaxed as well. For example, early pruning of alternatives based on cost considerations is disabled, the explicit introduction of cross joins is allowed, and scalar operations are ignored.
There are too many details to go into in depth, but the placement of Filters and Compute Scalars cannot be forced, and predicates of the form `column = value` are generalized so a plan containing `X = 1` or `X = @X` can be applied to a query containing `X = 502` or `X = @Y`. This particular flexibility can help greatly in finding a natural plan to force.
In the specific example, constant Union All can always be implemented as a Constant Scan; the number of inputs to the Union All does not matter. | There is no way (SQL Server versions up to 2012) to re-use a single spool for both occurences of the CTE. Details can be found in SQLKiwi's answer. **Further below** are two ways to materialize the CTE twice, which is unavoidable for the nature of the query. Both options result in a net distinct guid count of 6.
The link from Martin's comment to Quassnoi's site on a [blog about plan guiding a CTE](http://explainextended.com/2009/05/28/generating-xml-in-subqueries/) was partial inspiration for this question. It describes a way to materialize a CTE for the purpose of a correlated subquery, which is referenced only once although the correlation can cause it to be evaluated multiple times. That does not apply to the query in the question.
Option 1 - Plan Guide
---------------------
Taking hints from SQLKiwi's answer, I have pared down the guide to a bare minimum that will still do the job, e.g. the `ConstantScan` nodes only list 2 scalar operators which can sufficiently expand to any number.
```
;with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
OPTION(USE PLAN
N'<?xml version="1.0" encoding="utf-16"?>
<ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.2" Build="11.0.2100.60" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">
<BatchSequence>
<Batch>
<Statements>
<StmtSimple StatementCompId="1" StatementEstRows="1600" StatementId="1" StatementOptmLevel="FULL" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" StatementSubTreeCost="0.0444433" StatementText="with cte(guid,other) as (
 select newid(),1 union all
 select newid(),2 union all
 select newid(),3
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
" StatementType="SELECT" QueryHash="0x43D93EF17C8E55DD" QueryPlanHash="0xF8E3B336792D84" RetrievedFromCache="true">
<StatementSetOptions ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="true" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="true" />
<QueryPlan NonParallelPlanReason="EstimatedDOPIsOne" CachedPlanSize="96" CompileTime="13" CompileCPU="13" CompileMemory="1152">
<MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" />
<OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="157240" EstimatedPagesCached="1420" EstimatedAvailableDegreeOfParallelism="1" />
<RelOp AvgRowSize="47" EstimateCPU="0.006688" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="1600" LogicalOp="Inner Join" NodeId="0" Parallel="false" PhysicalOp="Nested Loops" EstimatedTotalSubtreeCost="0.0444433">
<OutputList>
<ColumnReference Column="Union1163" />
</OutputList>
<Warnings NoJoinPredicate="true" />
<NestedLoops Optimized="false">
<RelOp AvgRowSize="27" EstimateCPU="0.000432115" EstimateIO="0.0112613" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Sort" NodeId="1" Parallel="false" PhysicalOp="Sort" EstimatedTotalSubtreeCost="0.0117335">
<OutputList>
<ColumnReference Column="Union1080" />
<ColumnReference Column="Union1081" />
</OutputList>
<MemoryFractions Input="0" Output="0" />
<Sort Distinct="false">
<OrderBy>
<OrderByColumn Ascending="true">
<ColumnReference Column="Union1081" />
</OrderByColumn>
</OrderBy>
<RelOp AvgRowSize="27" EstimateCPU="4.0157E-05" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Constant Scan" NodeId="2" Parallel="false" PhysicalOp="Constant Scan" EstimatedTotalSubtreeCost="4.0157E-05">
<OutputList>
<ColumnReference Column="Union1080" />
<ColumnReference Column="Union1081" />
</OutputList>
<ConstantScan>
<Values>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(1)">
<Const ConstValue="(1)" />
</ScalarOperator>
</Row>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(2)">
<Const ConstValue="(2)" />
</ScalarOperator>
</Row>
</Values>
</ConstantScan>
</RelOp>
</Sort>
</RelOp>
<RelOp AvgRowSize="27" EstimateCPU="0.0001074" EstimateIO="0.01" EstimateRebinds="0" EstimateRewinds="39" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Lazy Spool" NodeId="83" Parallel="false" PhysicalOp="Table Spool" EstimatedTotalSubtreeCost="0.0260217">
<OutputList>
<ColumnReference Column="Union1162" />
<ColumnReference Column="Union1163" />
</OutputList>
<Spool>
<RelOp AvgRowSize="27" EstimateCPU="0.000432115" EstimateIO="0.0112613" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Sort" NodeId="84" Parallel="false" PhysicalOp="Sort" EstimatedTotalSubtreeCost="0.0117335">
<OutputList>
<ColumnReference Column="Union1162" />
<ColumnReference Column="Union1163" />
</OutputList>
<MemoryFractions Input="0" Output="0" />
<Sort Distinct="false">
<OrderBy>
<OrderByColumn Ascending="true">
<ColumnReference Column="Union1163" />
</OrderByColumn>
</OrderBy>
<RelOp AvgRowSize="27" EstimateCPU="4.0157E-05" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="40" LogicalOp="Constant Scan" NodeId="85" Parallel="false" PhysicalOp="Constant Scan" EstimatedTotalSubtreeCost="4.0157E-05">
<OutputList>
<ColumnReference Column="Union1162" />
<ColumnReference Column="Union1163" />
</OutputList>
<ConstantScan>
<Values>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(1)">
<Const ConstValue="(1)" />
</ScalarOperator>
</Row>
<Row>
<ScalarOperator ScalarString="newid()">
<Intrinsic FunctionName="newid" />
</ScalarOperator>
<ScalarOperator ScalarString="(2)">
<Const ConstValue="(2)" />
</ScalarOperator>
</Row>
</Values>
</ConstantScan>
</RelOp>
</Sort>
</RelOp>
</Spool>
</RelOp>
</NestedLoops>
</RelOp>
</QueryPlan>
</StmtSimple>
</Statements>
</Batch>
</BatchSequence>
</ShowPlanXML>'
);
```
Option 2 - Remote Scan
----------------------
By increasing the expense of the query and introducing a Remote Scan, the result is materialized.
```
with cte(guid,other) as (
select *
from OPENQUERY([TESTSQL\V2012], '
select newid(),1 union all
select newid(),2 union all
select newid(),3') x)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
``` |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | >
> *Is there ANY way to make the result come up with exactly 3 distinct guids and no more? I'm hoping to be able to better answer questions in
> future by including plan guides with CTE-type queries that are
> referenced multiple times to overcome some SQL Server CTE quirks.*
>
>
>
Not today. Non-recursive common table expressions (CTEs) are treated as in-line view definitions and expanded into the logical query tree at each place they are referenced (just like regular view definitions are) before optimization. The logical tree for your query is:
```
LogOp_OrderByCOL: Union1007 ASC COL: Union1015 ASC
LogOp_Project COL: Union1006 COL: Union1007 COL: Union1014 COL: Union1015
LogOp_Join
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
```
Notice the two View Anchors and the *six* calls to the intrinsic function `newid` before optimization gets started. Nevertheless, many people consider that the optimizer ought to be able to identify that the expanded sub-trees were originally a single referenced object and simplify accordingly. There have also been several [Connect requests](https://web.archive.org/web/20160914051638/https://connect.microsoft.com/SQLServer/feedback/details/218968/provide-a-hint-to-force-intermediate-materialization-of-ctes-or-derived-tables) to allow explicit materialization of a CTE or derived table.
A more general implementation would have the optimizer consider materializing arbitrary common expressions to improve performance (`CASE` with a subquery is another example where [problems](https://web.archive.org/web/20140329083016/https://connect.microsoft.com/SQLServer/feedback/details/546437/coalesce-subquery-1-may-return-null) can occur today). Microsoft Research [published a paper](https://web.archive.org/web/20120515085813/http://research.microsoft.com/en-us/um/people/jrzhou/pub/cse.pdf) (PDF) on that back in 2007, though it remains unimplemented to date. For the time being, we are limited to explicit materialization using things like table variables and temporary tables.
>
> *SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?*
>
>
>
This was just [wishful thinking](https://sql.kiwi/2011/12/forcing-a-parallel-query-execution-plan.html) on my part, and went well beyond the idea of modifying plan guides. It is possible, in principle, to write a tool to manipulate show plan XML directly, but without specific optimizer instrumentation using the tool would likely be a frustrating experience for the user (and the developer come to think of it).
In the particular context of this question, such a tool would still be unable to materialize the CTE contents in a way that could used by multiple consumers (to feed both inputs to the cross join in this case). The optimizer and execution engine do support multi-consumer spools, but only for specific purposes - none of which could be made to apply to this particular example.
>
> *While I'm not certain, I have a fairly strong hunch that the RelOps can be followed (Nested Loop, Lazy Spool) even if the query is not exactly the same as the plan - for instance if you added 4 and 5 to the CTE, it still continues to use the same plan (seemingly - tested on SQL Server 2012 RTM Express).*
>
>
>
There is a reasonable amount of flexibility here. The broad shape of the XML plan is used to *guide* the search for a final plan (though many attributes are ignored completely e.g. partitioning type on exchanges) and the normal search rules are considerably relaxed as well. For example, early pruning of alternatives based on cost considerations is disabled, the explicit introduction of cross joins is allowed, and scalar operations are ignored.
There are too many details to go into in depth, but the placement of Filters and Compute Scalars cannot be forced, and predicates of the form `column = value` are generalized so a plan containing `X = 1` or `X = @X` can be applied to a query containing `X = 502` or `X = @Y`. This particular flexibility can help greatly in finding a natural plan to force.
In the specific example, constant Union All can always be implemented as a Constant Scan; the number of inputs to the Union All does not matter. | I found traceflag 8649 (force parallel plan) induced this behaviour for the left-hand guid column on my 2008, R2 and 2012 instances. I didn't need to use the flag on SQL 2005 where the CTE behaved correctly. I tried using the plan generated in SQL 2005 in the higher instances but it wouldn't validate.
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
option ( querytraceon 8649 )
```
Either using the hint, using a plan guide including the hint or using the plan generated by the query with the hint on in a USE PLAN etc all worked.
 |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | >
> Is there *ANY* way ...
>
>
>
Finally in SQL 2016 CTP 3.0 there is a way, kind of : )
Using the trace flag and Extended Events as detailed by Dmitry Pilugin [here](http://www.queryprocessor.com/query-trace-column-values/), you can (somewhat arbitrarily) fish out three unique guids from the intermediate stages of the query execution.
NB This code is **NOT** intended for production or serious usage as regards CTE plan forcing, merely a light-hearted look at a new trace flag and a different way of doing things:
```
-- Configure the XEvents session; with ring buffer target so we can collect it
CREATE EVENT SESSION [query_trace_column_values] ON SERVER
ADD EVENT sqlserver.query_trace_column_values
ADD TARGET package0.ring_buffer( SET max_memory = 2048 )
WITH ( MAX_MEMORY = 4096 KB, EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS, MAX_DISPATCH_LATENCY = 30 SECONDS, MAX_EVENT_SIZE = 0 KB, MEMORY_PARTITION_MODE = NONE, TRACK_CAUSALITY = OFF , STARTUP_STATE = OFF )
GO
-- Start the session
ALTER EVENT SESSION [query_trace_column_values] ON SERVER
STATE = START;
GO
-- Run the query, including traceflag
DBCC TRACEON(2486);
SET STATISTICS XML ON;
GO
-- Original query
;with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
option ( recompile )
go
SET STATISTICS XML OFF;
DBCC TRACEOFF(2486);
GO
DECLARE @target_data XML
SELECT @target_data = CAST( target_data AS XML )
FROM sys.dm_xe_sessions AS s
INNER JOIN sys.dm_xe_session_targets AS t ON t.event_session_address = s.address
WHERE s.name = 'query_trace_column_values'
--SELECT @target_data td
-- Arbitrarily fish out 3 unique guids from intermediate stage of the query as collected by XEvent session
;WITH cte AS
(
SELECT
n.c.value('(data[@name = "row_id"]/value/text())[1]', 'int') row_id,
n.c.value('(data[@name = "column_value"]/value/text())[1]', 'char(36)') [guid]
FROM @target_data.nodes('//event[data[@name="column_id"]/value[. = 1]][data[@name="row_number"]/value[. < 4]][data[@name="node_name"]/value[. = "Nested Loops"]]') n(c)
)
SELECT *
FROM cte a
CROSS JOIN cte b
GO
-- Stop the session
ALTER EVENT SESSION [query_trace_column_values] ON SERVER
STATE = STOP;
GO
-- Drop the session
IF EXISTS ( select * from sys.server_event_sessions where name = 'query_trace_column_values' )
DROP EVENT SESSION [query_trace_column_values] ON SERVER
GO
```
Tested on version (CTP3.2) - 13.0.900.73 (x64), just for fun. | I found traceflag 8649 (force parallel plan) induced this behaviour for the left-hand guid column on my 2008, R2 and 2012 instances. I didn't need to use the flag on SQL 2005 where the CTE behaved correctly. I tried using the plan generated in SQL 2005 in the higher instances but it wouldn't validate.
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
option ( querytraceon 8649 )
```
Either using the hint, using a plan guide including the hint or using the plan generated by the query with the hint on in a USE PLAN etc all worked.
 |
27,719 | I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the query is not exactly the same. What is the right way of creating plan guides from scratch?
SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?
The specific instance in question is this CTE: [SQLFiddle](http://sqlfiddle.com/#!3/d41d8/5575/0)
```
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
```
Is there *ANY* way to make the result come up with exactly 3 distinct `guid`s and no more? I'm hoping to be able to better answer questions in future by including plan guides with CTE-type queries that are referenced multiple times to overcome some SQL Server CTE quirks. | 2012/10/27 | [
"https://dba.stackexchange.com/questions/27719",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/13073/"
] | >
> *Is there ANY way to make the result come up with exactly 3 distinct guids and no more? I'm hoping to be able to better answer questions in
> future by including plan guides with CTE-type queries that are
> referenced multiple times to overcome some SQL Server CTE quirks.*
>
>
>
Not today. Non-recursive common table expressions (CTEs) are treated as in-line view definitions and expanded into the logical query tree at each place they are referenced (just like regular view definitions are) before optimization. The logical tree for your query is:
```
LogOp_OrderByCOL: Union1007 ASC COL: Union1015 ASC
LogOp_Project COL: Union1006 COL: Union1007 COL: Union1014 COL: Union1015
LogOp_Join
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
```
Notice the two View Anchors and the *six* calls to the intrinsic function `newid` before optimization gets started. Nevertheless, many people consider that the optimizer ought to be able to identify that the expanded sub-trees were originally a single referenced object and simplify accordingly. There have also been several [Connect requests](https://web.archive.org/web/20160914051638/https://connect.microsoft.com/SQLServer/feedback/details/218968/provide-a-hint-to-force-intermediate-materialization-of-ctes-or-derived-tables) to allow explicit materialization of a CTE or derived table.
A more general implementation would have the optimizer consider materializing arbitrary common expressions to improve performance (`CASE` with a subquery is another example where [problems](https://web.archive.org/web/20140329083016/https://connect.microsoft.com/SQLServer/feedback/details/546437/coalesce-subquery-1-may-return-null) can occur today). Microsoft Research [published a paper](https://web.archive.org/web/20120515085813/http://research.microsoft.com/en-us/um/people/jrzhou/pub/cse.pdf) (PDF) on that back in 2007, though it remains unimplemented to date. For the time being, we are limited to explicit materialization using things like table variables and temporary tables.
>
> *SQLKiwi has mentioned drawing up plans in SSIS, is there a way or useful tool to assist in laying out a good plan for SQL Server?*
>
>
>
This was just [wishful thinking](https://sql.kiwi/2011/12/forcing-a-parallel-query-execution-plan.html) on my part, and went well beyond the idea of modifying plan guides. It is possible, in principle, to write a tool to manipulate show plan XML directly, but without specific optimizer instrumentation using the tool would likely be a frustrating experience for the user (and the developer come to think of it).
In the particular context of this question, such a tool would still be unable to materialize the CTE contents in a way that could used by multiple consumers (to feed both inputs to the cross join in this case). The optimizer and execution engine do support multi-consumer spools, but only for specific purposes - none of which could be made to apply to this particular example.
>
> *While I'm not certain, I have a fairly strong hunch that the RelOps can be followed (Nested Loop, Lazy Spool) even if the query is not exactly the same as the plan - for instance if you added 4 and 5 to the CTE, it still continues to use the same plan (seemingly - tested on SQL Server 2012 RTM Express).*
>
>
>
There is a reasonable amount of flexibility here. The broad shape of the XML plan is used to *guide* the search for a final plan (though many attributes are ignored completely e.g. partitioning type on exchanges) and the normal search rules are considerably relaxed as well. For example, early pruning of alternatives based on cost considerations is disabled, the explicit introduction of cross joins is allowed, and scalar operations are ignored.
There are too many details to go into in depth, but the placement of Filters and Compute Scalars cannot be forced, and predicates of the form `column = value` are generalized so a plan containing `X = 1` or `X = @X` can be applied to a query containing `X = 502` or `X = @Y`. This particular flexibility can help greatly in finding a natural plan to force.
In the specific example, constant Union All can always be implemented as a Constant Scan; the number of inputs to the Union All does not matter. | >
> Is there *ANY* way ...
>
>
>
Finally in SQL 2016 CTP 3.0 there is a way, kind of : )
Using the trace flag and Extended Events as detailed by Dmitry Pilugin [here](http://www.queryprocessor.com/query-trace-column-values/), you can (somewhat arbitrarily) fish out three unique guids from the intermediate stages of the query execution.
NB This code is **NOT** intended for production or serious usage as regards CTE plan forcing, merely a light-hearted look at a new trace flag and a different way of doing things:
```
-- Configure the XEvents session; with ring buffer target so we can collect it
CREATE EVENT SESSION [query_trace_column_values] ON SERVER
ADD EVENT sqlserver.query_trace_column_values
ADD TARGET package0.ring_buffer( SET max_memory = 2048 )
WITH ( MAX_MEMORY = 4096 KB, EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS, MAX_DISPATCH_LATENCY = 30 SECONDS, MAX_EVENT_SIZE = 0 KB, MEMORY_PARTITION_MODE = NONE, TRACK_CAUSALITY = OFF , STARTUP_STATE = OFF )
GO
-- Start the session
ALTER EVENT SESSION [query_trace_column_values] ON SERVER
STATE = START;
GO
-- Run the query, including traceflag
DBCC TRACEON(2486);
SET STATISTICS XML ON;
GO
-- Original query
;with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other
option ( recompile )
go
SET STATISTICS XML OFF;
DBCC TRACEOFF(2486);
GO
DECLARE @target_data XML
SELECT @target_data = CAST( target_data AS XML )
FROM sys.dm_xe_sessions AS s
INNER JOIN sys.dm_xe_session_targets AS t ON t.event_session_address = s.address
WHERE s.name = 'query_trace_column_values'
--SELECT @target_data td
-- Arbitrarily fish out 3 unique guids from intermediate stage of the query as collected by XEvent session
;WITH cte AS
(
SELECT
n.c.value('(data[@name = "row_id"]/value/text())[1]', 'int') row_id,
n.c.value('(data[@name = "column_value"]/value/text())[1]', 'char(36)') [guid]
FROM @target_data.nodes('//event[data[@name="column_id"]/value[. = 1]][data[@name="row_number"]/value[. < 4]][data[@name="node_name"]/value[. = "Nested Loops"]]') n(c)
)
SELECT *
FROM cte a
CROSS JOIN cte b
GO
-- Stop the session
ALTER EVENT SESSION [query_trace_column_values] ON SERVER
STATE = STOP;
GO
-- Drop the session
IF EXISTS ( select * from sys.server_event_sessions where name = 'query_trace_column_values' )
DROP EVENT SESSION [query_trace_column_values] ON SERVER
GO
```
Tested on version (CTP3.2) - 13.0.900.73 (x64), just for fun. |
13,550,821 | I'm making a method that take a list of arrays and finds the average of the numbers.
I know that my method works since I just moved it from my main method to the "average" method. I'm just having problems getting the array to work with the method.
I'm not sure if I'm wrong by calling the method by `average(a);`, or if it's because the method is written as `public static void average(double[] a){`
Could someone point me to the right direction?
```
public class Ass10{
public static void main(String[] args) {
System.out.println("asdf");
int a[] = {1, 2, 3,4};
average(a);
}
public static void average(double[] a){
int sum = 0;
for (int counter = 0; counter<a.length;counter++){
sum += a[counter];
}
System.out.println(sum/a.length)
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13550821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730056/"
] | From AutoSlugField documentation:
>
> always\_update – boolean: if True, the slug is updated each time the model instance is saved. Use with care because cool URIs don’t change (and the slug is usually a part of object’s URI). Note that even if the field is editable, any manual changes will be lost when this option is activated.
>
>
>
So this should work:
```
slug = AutoSlugField(populate_form='title', always_update=True, unique=True)
``` | The Better documentation is the own code:
[http://django-command-extensions.googlecode.com/svn/trunk/django\_extensions/db/fields/**init**.py](http://django-command-extensions.googlecode.com/svn/trunk/django_extensions/db/fields/__init__.py)
>
> slug = AutoSlugField(populate\_from='title', overwrite=True,
> unique=True)
>
>
> |
13,550,821 | I'm making a method that take a list of arrays and finds the average of the numbers.
I know that my method works since I just moved it from my main method to the "average" method. I'm just having problems getting the array to work with the method.
I'm not sure if I'm wrong by calling the method by `average(a);`, or if it's because the method is written as `public static void average(double[] a){`
Could someone point me to the right direction?
```
public class Ass10{
public static void main(String[] args) {
System.out.println("asdf");
int a[] = {1, 2, 3,4};
average(a);
}
public static void average(double[] a){
int sum = 0;
for (int counter = 0; counter<a.length;counter++){
sum += a[counter];
}
System.out.println(sum/a.length)
}
``` | 2012/11/25 | [
"https://Stackoverflow.com/questions/13550821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730056/"
] | From AutoSlugField documentation:
>
> always\_update – boolean: if True, the slug is updated each time the model instance is saved. Use with care because cool URIs don’t change (and the slug is usually a part of object’s URI). Note that even if the field is editable, any manual changes will be lost when this option is activated.
>
>
>
So this should work:
```
slug = AutoSlugField(populate_form='title', always_update=True, unique=True)
``` | use this code :
```
slug = AutoSlugField(max_length=500, populate_from='name', null=True, blank=True, always_update=True, unique=True)
``` |
613,808 | Consider the simplest case in quantum statistical mechanics, where we find the density of states in the case of a cuboidal 3 dimensional box. In the derivation we take only those states which are product seperable into wavefunctions along the three directions i.e. can be denoted by three quantum numbers $(n\_1, n\_2, n\_3)$ henceforth written as $|n\_1,n\_2,n\_3\rangle$ . However I feel that even states which are not product seperable should be considered. For example a particle in the system could be in the state $\frac{|1,0,0\rangle+|0,1,0\rangle}{\sqrt{2}}$. This will alter the counting of number of states. Why are such states excluded? | 2021/02/11 | [
"https://physics.stackexchange.com/questions/613808",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/287440/"
] | The point is not that there's a priori something special about separable states compared to non-separable states, the point is that you'd like to sum over a complete set of states -- that is, a basis for the Hilbert space. The separable states you describe happen to be particularly convenient states, because they are energy eigenstates. This is especially important when you want to derive something like the density of states. But if you wanted to calculate the partition function, for instance, you're technically free to choose any basis you'd like (although if you know the energy eigenstates, then those will usually be the most convenient).
One frequently confusing point when comparing quantum mechanics to classical mechanics is that every quantum system, no matter how small, has an infinite number of possible states. An easy example is a qubit: whereas a classical bit only has the states 0 and 1, a qubit has any linear superposition $\alpha | 0 \rangle + \beta | 1 \rangle$, of which there is a continuous infinity. But when you're calculating (say) a partition function of a Hamiltonian for a single qubit, you only need to sum over a complete basis, which will contain just two states. | The question that we are concerned with is the following, given a point in the $k$ space $(k\_{1},k\_{2},k\_{3})$ and an infinitesimal volume centred at this point, how many states can be found within this volume? The superposed state $$\frac{1}{\sqrt{2}}\left(|1,0,0 \rangle + |0,1,0\rangle\right)$$ is found in two different volumes at a finite separation from each other in the $k$ space and is therefore, of no relevance. |
613,808 | Consider the simplest case in quantum statistical mechanics, where we find the density of states in the case of a cuboidal 3 dimensional box. In the derivation we take only those states which are product seperable into wavefunctions along the three directions i.e. can be denoted by three quantum numbers $(n\_1, n\_2, n\_3)$ henceforth written as $|n\_1,n\_2,n\_3\rangle$ . However I feel that even states which are not product seperable should be considered. For example a particle in the system could be in the state $\frac{|1,0,0\rangle+|0,1,0\rangle}{\sqrt{2}}$. This will alter the counting of number of states. Why are such states excluded? | 2021/02/11 | [
"https://physics.stackexchange.com/questions/613808",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/287440/"
] | The point is not that there's a priori something special about separable states compared to non-separable states, the point is that you'd like to sum over a complete set of states -- that is, a basis for the Hilbert space. The separable states you describe happen to be particularly convenient states, because they are energy eigenstates. This is especially important when you want to derive something like the density of states. But if you wanted to calculate the partition function, for instance, you're technically free to choose any basis you'd like (although if you know the energy eigenstates, then those will usually be the most convenient).
One frequently confusing point when comparing quantum mechanics to classical mechanics is that every quantum system, no matter how small, has an infinite number of possible states. An easy example is a qubit: whereas a classical bit only has the states 0 and 1, a qubit has any linear superposition $\alpha | 0 \rangle + \beta | 1 \rangle$, of which there is a continuous infinity. But when you're calculating (say) a partition function of a Hamiltonian for a single qubit, you only need to sum over a complete basis, which will contain just two states. | It's essentially because you're counting dimensions or degrees of freedom, and not every possible state.
Just to give a different style of answer, when we get into the canonical ensemble, say, we will find that the system is described by a state matrix $$
\rho \propto \exp(-\beta \hat H)
$$
which will contain, as you say, a component that looks like
$$
|{1,0}\rangle\langle{1,0}| + |{0,1}\rangle\langle{0,1}|.\tag{1}
$$
(In 2D for simplicity.) They both have the same energy, so they both have the same prefactor, whatever that is.
As you say there is an alternative expression, in the basis $\sqrt{\frac12}\big(|{0,1}\rangle
\pm|{1,0}\rangle\big).$ These are new vectors that span the same plane, by the logic of “we count two dimensions” it is the same number of “states” we come to if we reckon this way. But, crucially, there is a consistency issue. Each of these states also has the same energy as the two we see above, but the contribution to the state matrix now looks like something different,$$
\frac12\big(|{0,1}\rangle+|{1,0}\rangle\big)\big(\langle{0,1}|+\langle{1,0}|\big)
+
\frac12\big(|{0,1}\rangle-|{1,0}\rangle\big)\big(\langle{0,1}|-\langle{1,0}|\big).\tag{2}
$$
If you expand these out, you may be relieved to find that the first term expands out into four terms, and the second term also expands out into four terms, but they are the same terms. Two cancel with minus signs, the remaining two sum together with $\frac12 +\frac12=1,$ and we recover equation (1) from equation (2). So it is indeed consistent!
In fact, I have been asserting that the prefactors in (1) and (2) are the same but this is not terribly physicist-y of me, for one crucial reason which is that as physicists we kind of get a pass to ignore degeneracy. Like, mathematicians cannot commute partial derivatives because there are degenerate cases where partial derivatives do not commute; they cannot invert matrices because there are degenerate cases where matrices have eigenvalues of 0 and Jordan blocks; we basically sweep this all under the rug and say that unless there is a conservation principle forcing some sort of equation that implies degeneracy, we don't have it, our world is noisy. (You can tell the quantum textbooks written by the mathematically inclined, because the very physical minded people have just one index of summation, but the mathematicians have separate indexes for things like spin or left and right traveling particles, because their model has a degeneracy there. The mathematician has to sum over all of the spin states because the Hamiltonian does not put them at different energies. And then a lazy physicist is instead like, I am going to perform this experiment somewhere on Earth, Earth has a magnetic field which is going to split the two different spin states, so this energy index that I am summing over secretly also has the spin index crammed into it because those different spin states don't have precisely the same energy level.)
And in some sense that is what we should do here. The question only really arises because you have chosen for the 2D box to be a perfect square. But if you let me say that there is noise in the box’s manufacture, then the one side is an angstrom longer than the other and there is a fine-structure splitting of the energy levels and there is no degeneracy.
Then I can just tell you that your provided state $\sqrt{\frac12}\big(|{0,1}\rangle+|{1,0}\rangle\big)$ is not actually a state of definite energy due to the fine structure, and we only “count” the states of definite energy. This is perhaps a clearer physicist-y answer. |
30,523,977 | I have two SQL Server tables below:
**Invoice**
```
InvoiceId Amount [Date]
1 10 2015-05-28 21:47:50.000
2 20 2015-05-28 21:47:50.000
3 25 2015-05-28 23:25:50.000
```
**InvoiceItem**
```
Id InvoiceId Cost
1 1 8
2 1 3
3 1 7
4 2 15
5 2 17
6 3 20
7 3 22
```
Now I want to `JOIN` these two tables `ON` **InvoiceId** and retrieve the following:
1. `COUNT` of `DISTINCT` **InvoiceId** from **Invoice** table `AS` **[Count]**
2. `SUM` of **Amount** from **Invoice** table `AS` **Amount**
3. `SUM` of **Cost** from **InvoiceItem** table `AS` **Cost**
4. `HOUR` part of **[Date]**
and `GROUP` them `BY` `HOUR` part of **[Date]**.
Desired Output wil be:
```
[Count] Amount Cost HourOfDay
2 30 50 22
1 25 42 23
```
How can I do this? | 2015/05/29 | [
"https://Stackoverflow.com/questions/30523977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1878010/"
] | one approach is to use a derived table:
```
SELECT CAST([Date] AS DATE) AS [Date],
DATEPART(HOUR,i.[Date]) AS HourOfDay,
COUNT(i.InvoiceId) AS NumberOfInvoices,
SUM(i.Amount) AS Amount,
SUM(it.Cost) AS Cost
FROM invoice i
INNER JOIN
(SELECT InvoiceId, SUM(Cost) AS Cost
FROM invoiceitem
GROUP BY InvoiceId) it ON i.InvoiceId = it.InvoiceId
GROUP BY [Date],DATEPART(HOUR,i.[Date])
```
or a CTE (Common Table Expression)
```
WITH InvoiceCosts (InvoiceId, Cost)
AS
(
SELECT InvoiceId, SUM(Cost) AS Cost
FROM invoiceitem
GROUP BY InvoiceId
)
SELECT CAST([Date] AS DATE) AS [Date],
DATEPART(HOUR,i.[Date]) AS HourOfDay,
COUNT(i.InvoiceId) AS NumberOfInvoices,
SUM(i.Amount) AS Amount,
SUM(ic.Cost) AS Cost
FROM invoice i
INNER JOIN
InvoiceCosts ic ON i.InvoiceId = ic.InvoiceId
GROUP BY [Date],DATEPART(HOUR,i.[Date])
``` | ```
SELECT COUNT (DISTINCT inv.InvoiceId) [Count],
SUM (Amount) Amount,
SUM (Cost) Cost,
datepart(HOUR, inv.[Date]) HourOfDay
FROM Invoice inv
INNER JOIN InvoiceItem itm
ON inv.InvoiceId = itm.InvoiceId
GROUP BY datepart(HOUR, inv.[Date]);
``` |
179,602 | [](https://i.stack.imgur.com/Fp1Lm.jpg)
This is a repost of my unsolved QGIS dilema. The image shows a single selected feature that consists of two polygons and the corresponding attribute table. Some nodes of the left poly have been added and moved to illustrate the boundary/ overlap problem. Before the nodes were moved and added the two polys were snapped together and I could not get rid of the line between them. Hovering over the nodes, pop ups identify the polys as either 0 or 1. How does one create a single polygon from the two? | 2016/02/05 | [
"https://gis.stackexchange.com/questions/179602",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/39243/"
] | As I understand your issue, you currently have a multipolygon feature which has an invalid geometry since one part of it overlaps another part. There is a 2-step procedure that should help you to merge your multipolygon into one simple polygon:
First, run the `v.clean` method which is located in the processing toolbox, GRASS section. Just select your layer and let the default options on. This should split your multipolygon into several features.
Then, select these new features and press the [Merge features button](https://gis.stackexchange.com/questions/102766/where-is-the-merge-selected-features-button-in-qgis-2-2) in the Advanced Editing Toolbar (which you may need to activate first). This will merge the features into one beautiful polygon. | I've just whiled away a few hours wrangling with just such a problem and couldn't solve it using any of the `v.clean` options using 2.18.2 for Mac.
I got lucky however, with trying the Multipart to singleparts geometry tool by choosing the attribute known to be unique resulting in a new temporary vector layer with three adjoining but separate features.
Select the adjoining features in edit mode and use the `Edit>Merge Selected Features` option to join the separate features into a single polygon.
Don't forget to save the temporary layer to disk using the `Layers>Save As` option otherwise the new layer will be lost even when saving the project. |
11,103,274 | I am trying to extract the below query:
```
select
'<tr><td>'||column1||'</td>',
'<td>'||column2||'</td>',
'<td>'||column3||'</td></tr>'
from table
```
In the above, column3 is a date field. When the output is printed, it is ignoring the time part. For example:
```
If columns 3 output is : 5/25/2011 3:03:17 AM
The above query returns : <tr><td>column1</td><td>column2</td><td>**25-JUN-11**</td></tr>
```
I have tried to\_date(column3,'yyyy/mm/dd HH24:MI:SS') and also, the normal query prints the time
```
select
column1,
column2,
column3,
from table
```
columns 3 prints time. Any help is appreciated.
**EDIT:**
I am using Oracle 10g. I have also tried it in Oracle 9i | 2012/06/19 | [
"https://Stackoverflow.com/questions/11103274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070422/"
] | Don't rely on implicit conversions, use [`TO_CHAR`](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions200.htm#i1009324) to display a date [to your liking](http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements004.htm#i34924):
```
select '<tr><td>'||column1||'</td>',
'<td>'||column2||'</td>',
'<td>'||to_char(column3, 'dd/mm/yyyy hh24:mi:ss')||'</td></tr>'
from table
``` | [TO\_DATE](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm) does exactly what it's supposed to do, format mask supplies it with the format it's primary input is in so it can transform it into a date. The format mask is not used to define output but input. What you need to use instead is [TO\_CHAR](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions180.htm)
```
TO_CHAR(column3,'yyyy/mm/dd HH24:MI:SS')
``` |
6,399,255 | I'm pretty good with MySQL, but this is something I have never done. What I want to do is make an SQL code to select 6 rows, each with their own WHERE clause.
What I am trying to do is get 6 rows, and each will be the most recent "video" that was posted. there are 6 categories, so that's why I have 6 rows. I want it to pull the most recent by it 'id' number.
I'd do it with 6 different SQL queries, but I assume that would be slower (unless this is the only way to do this?)

From that small snippet, I would like to end up with is this:
2 --> 21
6 --> 16
8 --> 14 (Picks 14 since it's largest.)
---
**Final Working Code**
```
$sql="SELECT video_category, MAX(video_id) AS video_id FROM videos GROUP BY video_category";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)) {
echo $rows['video_category'] . " --> " . $rows['video_id'] . "<br>";
}
``` | 2011/06/18 | [
"https://Stackoverflow.com/questions/6399255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118342/"
] | something like
```
select distinct category, video_id from table_name order by id DESC
```
If you have 6 categories in the db, you would get 6 rows, all having highest id in their category | You have two options:
1. Determine common WHERE clause that will result in what you need.
2. (probably preferred one) Make some query involving UNION (`SELECT ... FROM ... WHERE ... UNION SELECT ... FROM ... WHERE ...` etc.)
Let me know if you have any questions. I believe without your database structure it would be hard to help you more. |
6,399,255 | I'm pretty good with MySQL, but this is something I have never done. What I want to do is make an SQL code to select 6 rows, each with their own WHERE clause.
What I am trying to do is get 6 rows, and each will be the most recent "video" that was posted. there are 6 categories, so that's why I have 6 rows. I want it to pull the most recent by it 'id' number.
I'd do it with 6 different SQL queries, but I assume that would be slower (unless this is the only way to do this?)

From that small snippet, I would like to end up with is this:
2 --> 21
6 --> 16
8 --> 14 (Picks 14 since it's largest.)
---
**Final Working Code**
```
$sql="SELECT video_category, MAX(video_id) AS video_id FROM videos GROUP BY video_category";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)) {
echo $rows['video_category'] . " --> " . $rows['video_id'] . "<br>";
}
``` | 2011/06/18 | [
"https://Stackoverflow.com/questions/6399255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118342/"
] | Please share your table structure. Nevertheless, i think the following query should do the trick:
```
SELECT category_id, MAX(movie_id) most_recent_movie_for_category FROM movies GROUP BY category_id
``` | You have two options:
1. Determine common WHERE clause that will result in what you need.
2. (probably preferred one) Make some query involving UNION (`SELECT ... FROM ... WHERE ... UNION SELECT ... FROM ... WHERE ...` etc.)
Let me know if you have any questions. I believe without your database structure it would be hard to help you more. |
6,399,255 | I'm pretty good with MySQL, but this is something I have never done. What I want to do is make an SQL code to select 6 rows, each with their own WHERE clause.
What I am trying to do is get 6 rows, and each will be the most recent "video" that was posted. there are 6 categories, so that's why I have 6 rows. I want it to pull the most recent by it 'id' number.
I'd do it with 6 different SQL queries, but I assume that would be slower (unless this is the only way to do this?)

From that small snippet, I would like to end up with is this:
2 --> 21
6 --> 16
8 --> 14 (Picks 14 since it's largest.)
---
**Final Working Code**
```
$sql="SELECT video_category, MAX(video_id) AS video_id FROM videos GROUP BY video_category";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)) {
echo $rows['video_category'] . " --> " . $rows['video_id'] . "<br>";
}
``` | 2011/06/18 | [
"https://Stackoverflow.com/questions/6399255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118342/"
] | Thanks for posting the table structure. This is just a simple `GROUP BY` with a `MAX` aggregate on video\_id.
```
SELECT video_category, MAX(video_id) AS video_id FROM videos GROUP BY video_category;
``` | You have two options:
1. Determine common WHERE clause that will result in what you need.
2. (probably preferred one) Make some query involving UNION (`SELECT ... FROM ... WHERE ... UNION SELECT ... FROM ... WHERE ...` etc.)
Let me know if you have any questions. I believe without your database structure it would be hard to help you more. |
541,374 | How can I align my text in the table center then align it with the letter "M" ? Like the below it is right aligned but I want it center-right aligned. How ?
[](https://i.stack.imgur.com/NSOzD.png)
Like below, the text is center aligned with M.
[](https://i.stack.imgur.com/HIfba.png) | 2020/04/29 | [
"https://tex.stackexchange.com/questions/541374",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/109408/"
] | Assuming that is the first image the one you want to replicate, here's a MWE.
You can override the column alignment for a given cell by using `\multicolumn` for a single column (see also the last line - I added it to make it more clear).
In the first image you posted, the first cell from the top seems to be centered. This is obtained with `\multicolumn{1}{|c|}{\# Params}`.
The remaining ones appear to be simply right-aligned.
Since the content of every cell ends with an `M` (millions?), everything looks like to be aligned with the `M`.
```
\documentclass{standalone}
\begin{document}
\begin{tabular}{|r|}
\hline
\multicolumn{1}{|c|}{\# Params} \\
\hline
2.8M\\
15.4M\\
38.7M\\
\hline
2.9M\\
62M\\
12.9M\\
\hline
\multicolumn{1}{|c|}{x} \\ % to prove that you can override the column alignment
\end{tabular}
\end{document}
```
[](https://i.stack.imgur.com/Ne8Vl.png)
A better looking result can be achieved with the help of `siunitx`, assuming that `M` is a unit or a *Mega* prefix.
The package allows to define the `S` and `s` type of column.
You can play with the unit alignment with the `table-unit-alignment` key, that accepts values such as `left`, `right' or`center`.
```
\documentclass{standalone}
\usepackage{siunitx}
\begin{document}
\begin{tabular}
{|S[table-format=2.1]@{\,}s[table-unit-alignment = center]|}
\hline
\multicolumn{2}{|c|}{Parameters} \\
\hline
2.8 & \mega \\
15.4 & \mega \\
38.7 & \mega \\ \hline
2.9 & \mega \\
62 & \mega \\
12.9 & \mega \\
\hline
\end{tabular}
\end{document}
```
[](https://i.stack.imgur.com/IxMLN.png) | I'm not sure that I've understood your objective correctly, as the layouts in the two screenshots you've posted seem to be in direct conflict with each other. I've interpreted it as follows: (a) the numbers should be aligned on their decimal markers, (b) the `M` letters should be aligned, and (c) the number/`M` combinations should be centered horizontally within the column.
If this interpretation is correct, the following solution, which employs the `S` column type provided by the `siunitx` package, may be of relevance.
[](https://i.stack.imgur.com/X7pUj.png)
```
\documentclass{article}
\usepackage{siunitx}
\begin{document}
\begin{table}
\begin{tabular}{|S[table-format=3.1,table-space-text-post={M}]|}
\hline
{\# Params}\\
\hline
15.4M\\ 2.8M\\ 388.7M\\
\hline
\end{tabular}
\end{table}
\end{document}
``` |
17,574,559 | Is there a way to trigger an Error Event when HtmlLoader.load() fails?
When there is no internet connection, the COMPLETE Event never gets triggered. I want to be able to tell the user "there is no connection, close the current window and do someting else." | 2013/07/10 | [
"https://Stackoverflow.com/questions/17574559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1697071/"
] | Sure, but you have to listen instance of URLRequest for some events
```
//your code to load page in to HtmlLoader
var html:HTMLLoader = new HTMLLoader();
var urlReq:URLRequest = new URLRequest("http://www.adobe.com/");
configureListeners(urlReq);
html.width = stage.stageWidth;
html.height = stage.stageHeight;
html.load(urlReq);
addChild(html);
//add all listeners you need
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
``` | This code is working fine For Flex 4
```
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function creationCompleteHandler(event:FlexEvent):void
{
var html:HTMLLoader = new HTMLLoader();
var urlReq:URLRequest = new URLRequest("http://www.adobe.com/");
configureListeners(html);
html.width = 800;
html.height = 800;
html.load(urlReq);
conteiner.addChild(html);
}
//add all listeners you need
private function configureListeners(dispatcher:IEventDispatcher):void
{
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS,progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
.
.
.
.
.
.
]]>
</fx:Script>
<s:SpriteVisualElement id="conteiner">
</s:SpriteVisualElement>
</s:WindowedApplication>
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | ```
strcpy( x, (a == MACRO1)? "S" :
(a == MACRO2)? "K" : "error" );
```
Like your original code, this will copy either `"S"` or `"K"` to variable `x`.
If `a` is ***neither*** `MACRO1` nor `MACRO2`, it will copy `"error"` to buffer `x` with an assumption that `x` is large enough to hold `"error"` string.
*(You should figure out a better way to handle the case where `a` is neither of the two macros)* | it can be also
```
{
char *dummy;
dummy = a == MACRO1 ? strcpy(x, "TextA") : a == MACRO2 ? strcpy(x, "TextB") : strcpy(x, "error");
}
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | Setting aside this [beautiful answer](https://stackoverflow.com/questions/54443105/how-this-if-else-condition-can-be-replaced-by-ternary-operator/54443661#54443661), this cannot be written as a two "nested" ternary conditional operators since there is nothing to do for any value of `a` other than `MACRO1` and `MACRO2`, and it's not possible to trick `strcpy` into a no-op. (The behaviour of copying `x` to itself is *undefined*.)
So you are best off leaving the code as it is. Note that in terms of programming history, the ternary conditional operator was invented before the `if` `else` control block due perhaps to the deficiencies in the former, as epitomised in the case you present.
You could submit
```
strnpcy(x, a == MACRO1 ? "S" : "K", 2 * (a == MACRO1 + a == MACRO2));
```
to the next obfuscation contest though. | ```
strcpy( x, (a == MACRO1)? "S" :
(a == MACRO2)? "K" : "error" );
```
Like your original code, this will copy either `"S"` or `"K"` to variable `x`.
If `a` is ***neither*** `MACRO1` nor `MACRO2`, it will copy `"error"` to buffer `x` with an assumption that `x` is large enough to hold `"error"` string.
*(You should figure out a better way to handle the case where `a` is neither of the two macros)* |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | ```
strcpy( x, (a == MACRO1)? "S" :
(a == MACRO2)? "K" : "error" );
```
Like your original code, this will copy either `"S"` or `"K"` to variable `x`.
If `a` is ***neither*** `MACRO1` nor `MACRO2`, it will copy `"error"` to buffer `x` with an assumption that `x` is large enough to hold `"error"` string.
*(You should figure out a better way to handle the case where `a` is neither of the two macros)* | Simplest way, behaving like original, appending nothing if a doesn't match either MACRO1 or MACRO2:
```
strcpy(x, (a == MACRO1)?"S":(a == MACRO2)?"K":x);
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | Formally, it can be rewritten as equivalent
```
a == MACRO1 ? strcpy(x, "S") :
a == MACRO2 ? strcpy(x, "K") : 0;
```
but there's no meaningful reason to do so, unless it is just a puzzle (or unless there's a credible reason to [maintain expression semantics](https://stackoverflow.com/questions/1613230/uses-of-c-comma-operator/1618867#1618867)). | it can be also
```
{
char *dummy;
dummy = a == MACRO1 ? strcpy(x, "TextA") : a == MACRO2 ? strcpy(x, "TextB") : strcpy(x, "error");
}
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | Formally, it can be rewritten as equivalent
```
a == MACRO1 ? strcpy(x, "S") :
a == MACRO2 ? strcpy(x, "K") : 0;
```
but there's no meaningful reason to do so, unless it is just a puzzle (or unless there's a credible reason to [maintain expression semantics](https://stackoverflow.com/questions/1613230/uses-of-c-comma-operator/1618867#1618867)). | Simplest way, behaving like original, appending nothing if a doesn't match either MACRO1 or MACRO2:
```
strcpy(x, (a == MACRO1)?"S":(a == MACRO2)?"K":x);
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | ```
if(a == MACRO1)
strcpy(x,"S")
else
strcpy(x,"K");
```
can be :
```
strcpy(x, (a == MACRO1) ? "S" : "K");
```
but
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
```
has a missing else and to do
```
strcpy(x, (a == MACRO1) ? "S" : ((a == MACRO2) ? "K" : x));
```
is **not** correct because the argument of *strcpy* must not overlap but in that specific case not sure it is a true problem (even undefined behavior) , but also *x* is may be not yet initialized, and what about the performances ... | ```
strcpy( x, (a == MACRO1)? "S" :
(a == MACRO2)? "K" : "error" );
```
Like your original code, this will copy either `"S"` or `"K"` to variable `x`.
If `a` is ***neither*** `MACRO1` nor `MACRO2`, it will copy `"error"` to buffer `x` with an assumption that `x` is large enough to hold `"error"` string.
*(You should figure out a better way to handle the case where `a` is neither of the two macros)* |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | Setting aside this [beautiful answer](https://stackoverflow.com/questions/54443105/how-this-if-else-condition-can-be-replaced-by-ternary-operator/54443661#54443661), this cannot be written as a two "nested" ternary conditional operators since there is nothing to do for any value of `a` other than `MACRO1` and `MACRO2`, and it's not possible to trick `strcpy` into a no-op. (The behaviour of copying `x` to itself is *undefined*.)
So you are best off leaving the code as it is. Note that in terms of programming history, the ternary conditional operator was invented before the `if` `else` control block due perhaps to the deficiencies in the former, as epitomised in the case you present.
You could submit
```
strnpcy(x, a == MACRO1 ? "S" : "K", 2 * (a == MACRO1 + a == MACRO2));
```
to the next obfuscation contest though. | Simplest way, behaving like original, appending nothing if a doesn't match either MACRO1 or MACRO2:
```
strcpy(x, (a == MACRO1)?"S":(a == MACRO2)?"K":x);
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | Setting aside this [beautiful answer](https://stackoverflow.com/questions/54443105/how-this-if-else-condition-can-be-replaced-by-ternary-operator/54443661#54443661), this cannot be written as a two "nested" ternary conditional operators since there is nothing to do for any value of `a` other than `MACRO1` and `MACRO2`, and it's not possible to trick `strcpy` into a no-op. (The behaviour of copying `x` to itself is *undefined*.)
So you are best off leaving the code as it is. Note that in terms of programming history, the ternary conditional operator was invented before the `if` `else` control block due perhaps to the deficiencies in the former, as epitomised in the case you present.
You could submit
```
strnpcy(x, a == MACRO1 ? "S" : "K", 2 * (a == MACRO1 + a == MACRO2));
```
to the next obfuscation contest though. | it can be also
```
{
char *dummy;
dummy = a == MACRO1 ? strcpy(x, "TextA") : a == MACRO2 ? strcpy(x, "TextB") : strcpy(x, "error");
}
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | ```
if(a == MACRO1)
strcpy(x,"S")
else
strcpy(x,"K");
```
can be :
```
strcpy(x, (a == MACRO1) ? "S" : "K");
```
but
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
```
has a missing else and to do
```
strcpy(x, (a == MACRO1) ? "S" : ((a == MACRO2) ? "K" : x));
```
is **not** correct because the argument of *strcpy* must not overlap but in that specific case not sure it is a true problem (even undefined behavior) , but also *x* is may be not yet initialized, and what about the performances ... | Simplest way, behaving like original, appending nothing if a doesn't match either MACRO1 or MACRO2:
```
strcpy(x, (a == MACRO1)?"S":(a == MACRO2)?"K":x);
``` |
54,443,105 | Please help me to rewrite the below condition in a better way
This is a c code
```
if(a == MACRO1)
strcpy(x,"S")
else if (a == MACRO2)
strcpy(x,"K");
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54443105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9697921/"
] | Formally, it can be rewritten as equivalent
```
a == MACRO1 ? strcpy(x, "S") :
a == MACRO2 ? strcpy(x, "K") : 0;
```
but there's no meaningful reason to do so, unless it is just a puzzle (or unless there's a credible reason to [maintain expression semantics](https://stackoverflow.com/questions/1613230/uses-of-c-comma-operator/1618867#1618867)). | ```
strcpy( x, (a == MACRO1)? "S" :
(a == MACRO2)? "K" : "error" );
```
Like your original code, this will copy either `"S"` or `"K"` to variable `x`.
If `a` is ***neither*** `MACRO1` nor `MACRO2`, it will copy `"error"` to buffer `x` with an assumption that `x` is large enough to hold `"error"` string.
*(You should figure out a better way to handle the case where `a` is neither of the two macros)* |
65,015,110 | I have a table:
```
a b c
1 11 21
2 12 22
3 3 3
NaN 14 24
NaN 15 NaN
4 4 4
5 15 25
6 6 6
7 17 27
```
I want to remove all the rows in column `a` before the last row with the null value. The output that I want is:
```
a b c
NaN 15 NaN
4 4 4
5 15 25
6 6 6
7 17 27
```
I couldn't find a better solution for this but `first_valid_index` and `last_valid_index`. I think I don't need that.
---
**BONUS**
I also want to add a new column in the dataframe if all the values in a row are the same. The following rows should have the same value:
```
new a b c
NaN NaN 15 NaN
4 4 4 4
4 5 15 25
6 6 6 6
6 7 17 27
```
Thank you! | 2020/11/26 | [
"https://Stackoverflow.com/questions/65015110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2798218/"
] | you also know about comment like this "/\* ... bla bla ... */".
That must do not work on your mind, but it works.
Thus, I recommend you that change the comment from "/*... \*/" to "-- bla bla".
start of "--" comment can ignore that line without run.
ex>
/\*!40101 SET @OLD\_CHARACTER\_SET\_CLIENT=@@CHARACTER\_SET\_CLIENT \*/;
=>
-- 40101 SET @OLD\_CHARACTER\_SET\_CLIENT=@@CHARACTER\_SET\_CLIENT | Oh, found a solution...
```java
scriptRunner.setEscapeProcessing(false);
``` |
11,108 | $g(x) =\frac{3-5x}{5-x}$
I know that I am retarded for not being able to do this on my own. Algebraically you just have to solve for x. Even so, I can't do it. | 2010/11/20 | [
"https://math.stackexchange.com/questions/11108",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/2230/"
] | Hint: $y=\frac{3-5x}{5-x}$ so $y(5-x)=3-5x$. Now collect terms involving $x$ on one side and those not involving $x$ on the other and solve for $x$. | Maybe you could start with a less complicated example and build up from there. Why don't you try finding the inverse function of $f(x) = x + 3$ using the idea that Timothy gave you of putting $y = x + 3$ and then solving for $x$. Then you can try $f(x) = 7x - 2$ for instance. Now you could also try $f(x) = \frac{3}{x}$ for example.
Something that is sometimes very useful is to consider "easier" problems related to your original problem and trying to solve those.
I believe the point is to gain some experience on what the particular difficulty may be, and that the "harder" problem may combine some of the difficulties that you will have treated in the particular, less complicated examples that you considered. This advice is treated by Polya in his excellent book about problem solving. |
120,040 | I read the [r](/questions/tagged/r "show questions tagged 'r'") questions and answers.
I am trying to learn R and SO is a good source.
I would find it useful, to find all the [gem](/questions/tagged/gem "show questions tagged 'gem'") topics which were favourited by a lot of users.
Is there a way to search
>
> [r] isfavorinted:1 orderby:#\_of\_stars
>
>
> | 2012/01/23 | [
"https://meta.stackexchange.com/questions/120040",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/177436/"
] | Although the data does get stale you can use a Data.SE query for this
Here's one I wrote for you [GEM Questions by FavoriteCount](https://data.stackexchange.com/stackoverflow/query/59982/gem-questions-by-favoritecountt)
Here's the SQL code for it
```
SELECT p.id [Post Link],
p.favoritecount
FROM posts p
INNER JOIN posttags pt
ON p.id = pt.postid
INNER JOIN tags t
ON pt.tagid = t.id
WHERE tagname = 'gem'
AND p.favoritecount > 0
ORDER BY p.favoritecount DESC
```
Here's a query that takes in a tag name as an input [Questions by FavoriteCount](https://data.stackexchange.com/stackoverflow/query/59983/questions-by-favoritecount) | [Here's the query](https://data.stackexchange.com/stackoverflow/query/59981/favourite-by-tag) - insert any tag (for example, [r](/questions/tagged/r "show questions tagged 'r'")) and enjoy!
```
-- Get the ID of the tag:
DECLARE @tagName NVARCHAR(25) = '##Tag##'
DECLARE @tagId INT = (SELECT TOP(1) Id From Tags WHERE TagName = @tagName)
-- Fetch the results:
SELECT TOP(50)
'http://stackoverflow.com/q/' + CAST(Posts.Id AS VARCHAR) AS Url,
Posts.* FROM Posts
LEFT JOIN PostTags ON PostTags.PostId = Posts.Id
WHERE PostTags.TagId = @tagId
ORDER BY Posts.FavoriteCount DESC;
```
Dang, someone beat me to it :( |
7,949,818 | In Rails 3, when I write:
`@users = User.limit(10).sort_by(&:name)`
it is giving me 10 users in name order, but not the first 10 alphabetically like I want. What am I doing wrong?
Thanks! | 2011/10/31 | [
"https://Stackoverflow.com/questions/7949818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021325/"
] | Try:
`@users = User.limit(10).order('name ASC')` | The [`sort_by`](https://ruby-doc.org/core/Enumerable.html#method-i-sort_by) method is from Enumerable. So, in order to call `sort_by`, ActiveRecord has to retrieve the records from the database; ActiveRecord will first do this:
```
User.limit(10)
```
to get ten records from the database and then those records will be sorted (in Ruby) using their names. The end result is that the records will have been extracted from the database before they're sorted.
The solution is to listen to [Alex Peattie](https://stackoverflow.com/users/784858/alex-peattie) and use the `order` method. |
1,719,161 | This is the statement that needs to be proved: If $A⊈B∪C$ then $A-B⊈C$.
I want to proof using the contrapositive, so: If $A-B⊆C$ then $A⊆B∪C.$
And I don't know what to do from this point on. | 2016/03/29 | [
"https://math.stackexchange.com/questions/1719161",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294021/"
] | If A-B⊆C,
suppose $x \in A$.
If $x \in B$,
then
$x \in B \cup C$.
If $x \not\in B$,
then
$x \in A-B$,
so $x \in C$,
so $x \in B \cup C$.
Therefore
$x \in A
\implies x \in B \cup C$,
so
$A \subseteq B \cup C
$. | $A \not \subseteq B \cup C$ means there is an $x\_0 \in A$ where $x\_0 \not \in B \cup C$.
That means $x\_0 \not \in B$ and $x\_0 \not \in C$. But $x\_0 \in A$ and $x\_0 \not \in B$ means $x\_0 \in A - B$.
But $x\_0 \not \in C$. So $A - B \not \subseteq C$.
====
Furthermore, FWIW, this proves $A - (B \cup C) \subseteq A-B$. |
61,922,428 | I am generating arrays (technically they are row vectors) with a for-loop. a, b, c ... are the outputs.
Can I add the new array to the old ones together to form a matrix?
```
import numpy as np
# just for example:
a = np.asarray([2,5,8,10])
b = np.asarray([1,2,3,4])
c = np.asarray([2,3,4,5])
... ... ... ... ...
```
I have tried `ab = np.stack((a,b))`, and this could work. But my idea is to always add a new row to the old matrix in a new loop, but with `abc = np.stack((ab,c))` then there would be an error `ValueError: all input arrays must have the same shape`.
Can anyone tell me how I could add another vector to an already existing matrix? I couldn´t find a perfect answer in this forum. | 2020/05/20 | [
"https://Stackoverflow.com/questions/61922428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13100062/"
] | Based on some weird values, like `14:10 pm`, try this code:
```
from datetime import datetime as dt
def robust_strptime(txt):
try:
return dt.strptime(txt, '%H:%M')
except ValueError:
try:
return dt.strptime(txt, '%I:%M %p')
except ValueError:
return dt.strptime(txt, '%H:%M %p')
txt = ['11:58 am', '12:00', '13:32 pm', '13:31', '02:58 PM', '5:48 pm']
for hour in txt:
time = robust_strptime(hour)
print('{:10}'.format(hour) + 'was converted to: {}'.format(dt.strftime(time, '%H:%M:%S')))
```
output:
```
11:58 am was converted to: 11:58:00
12:00 was converted to: 12:00:00
13:32 pm was converted to: 13:32:00
13:31 was converted to: 13:31:00
02:58 PM was converted to: 14:58:00
5:48 pm was converted to: 17:48:00
``` | ```
%H - Hour (24-hour clock) as a decimal number [00,23].
```
find below link for more detail,
[enter link description here](https://docs.python.org/3/library/time.html#module-time) |
33,638 | I refer to "Sheaves in Geometry and Logic", by S. MacLane.
Let **C** be a category. Dealing with a *subobject* of an object $D \in \text{Ob}\_{\mathbf C}$, one defines an equivalence relation between morphisms towards *D*:
>
> Two monomorphisms $f:A\to D$, $g:B\to D$ with a common codomain *D* are called *equivalent* if there exists an isomorphism $h\colon A\to B$ such that *gh*= *f*.
> A *sbobject* of *D* is an equivalence class of monos towards *D*. The collection Sub**C**(*D*) of subobject of *D* carries a natural partial order [...].
> Then Sub**C**(*D*) is **the set** of all subobjects of *D* in the category **C**.
>
>
>
I can't figure out *why* Sub**C**(*D*) is a set, rather than a proper class! Indeed, we are considering something like an qeuivalence relation on
$\displaystyle \coprod\_{A\in \text{Ob}} \text{Hom}\_{\bf C}(A,D)$
which is not a set, as soon as **C** isn't small.
So, how can I avoid the problem? | 2010/07/28 | [
"https://mathoverflow.net/questions/33638",
"https://mathoverflow.net",
"https://mathoverflow.net/users/7952/"
] | For a general category the subobjects do indeed not have to form a set.
In the context of MacLane/Moerdijk you only look at toposes and there one has a natural isomorphism $Sub\_{\mathbf{C}}(D) \cong Hom\_{\mathbf{C}}(D,\Omega)$, where $\Omega$ is the subobject classifier.
So it follows from the axioms of a topos, *(edit, thanks Mike:) if it is locally small*, that $Sub\_{\mathbf{C}}(D)$ is a set. When you prove that the basic examples, sheaves, finite sets, products of those, etc. are toposes you exhibit an object $\Omega$ and establish the above bijection. Before that point the left hand side could a priori be a proper class but the right hand side is a set, since you know that your category is locally small, and your bijection then shows that subobjects form a set.
Knowing this you can conclude that objects in full subcategories *(edit, thanks again:) whose embedding preserves monos (e.g. if they are reflective)* of toposes also have a set of subobjects, e.g. in all locally presentable categories... | A reasonable reformulation of the question is, if there exists a set of representatives for subobjects; i.e. if there is a set of monomorphisms into our object $D$, such that every other monomorphism into $D$ is isomorphic to one of them.
This is, of course, false. Take a preorder $P$, which is a proper class, and has a maximal element $\infty$ (for example, the ordinals plus a maximal element). Then $\infty$ has no set of representatives for its subobjects.
However, it happens very often that there is a set of representatives. The category of sets or topological spaces are examples. If $C$ is a category which has the property, then the same is true for every algebraic finitary category over $C$. Thus, for example, the category of (topological) groups has the property. |
1,265,860 | This keeps happening to me all the time:
1) I write a script(ruby, shell, etc).
2) run it, it works.
3) put it in crontab so it runs in a few minutes so I know it runs from there.
4) It doesnt, no error trace, back to step 2 or 3 a 1000 times.
When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this:
```
ruby script.rb >& /path/to/output
```
I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there)
I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables.
Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**?
When debugging, I have to reset the timer and go back to waiting. Very time consuming.
How to test things in crontab better or avoid these problems? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1265860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96087/"
] | To find out the environment in which cron runs jobs, add this cron job:
```
{ echo "\nenv\n" && env|sort ; echo "\nset\n" && set; } | /usr/bin/mailx -s 'my env' [email protected]
```
Or send the output to a file instead of email. | If you really want to run it *as yourself*, you may want to invoke ruby from a shell script that sources your `.profile`/`.bashrc` etc. That way it'll pull in your environment.
However, the downside is that it's not isolated from your environment, and if you change that, you may find your cron jobs suddenly stop working. |
1,265,860 | This keeps happening to me all the time:
1) I write a script(ruby, shell, etc).
2) run it, it works.
3) put it in crontab so it runs in a few minutes so I know it runs from there.
4) It doesnt, no error trace, back to step 2 or 3 a 1000 times.
When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this:
```
ruby script.rb >& /path/to/output
```
I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there)
I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables.
Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**?
When debugging, I have to reset the timer and go back to waiting. Very time consuming.
How to test things in crontab better or avoid these problems? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1265860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96087/"
] | G'day,
One of the basic problems with cron is that you get a **minimal** environment being set by cron. In fact, you only get four env. var's set and they are:
* SHELL - set to /bin/sh
* LOGNAME - set to your userid as found in /etc/passwd
* HOME - set to your home dir. as found in /etc/passwd
* PATH - set to "/usr/bin:/bin"
That's it.
However, what you can do is take a snapshot of the environment you want and save that to a file.
Now make your cronjob source a trivial shell script that sources this env. file and then executes your Ruby script.
BTW Having a wrapper source a common env. file is an excellent way to enforce a consistent environment for multiple cronjobs. This also enforces the DRY principle because it gives you just one point to update things as required, instead of having to search through a bunch of scripts and search for a specific string if, say, a logging location is changed or a different utility is now being used, e.g. gnutar instead of vanilla tar.
Actually, this technique is used very successfully with The Build Monkey which is used to implement Continuous Integration for a major software project that is common to several major world airlines. 3,500kSLOC being checked out and built several times a day and over 8,000 regression tests run once a day.
HTH
'Avahappy, | If you really want to run it *as yourself*, you may want to invoke ruby from a shell script that sources your `.profile`/`.bashrc` etc. That way it'll pull in your environment.
However, the downside is that it's not isolated from your environment, and if you change that, you may find your cron jobs suddenly stop working. |
1,265,860 | This keeps happening to me all the time:
1) I write a script(ruby, shell, etc).
2) run it, it works.
3) put it in crontab so it runs in a few minutes so I know it runs from there.
4) It doesnt, no error trace, back to step 2 or 3 a 1000 times.
When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this:
```
ruby script.rb >& /path/to/output
```
I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there)
I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables.
Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**?
When debugging, I have to reset the timer and go back to waiting. Very time consuming.
How to test things in crontab better or avoid these problems? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1265860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96087/"
] | G'day,
One of the basic problems with cron is that you get a **minimal** environment being set by cron. In fact, you only get four env. var's set and they are:
* SHELL - set to /bin/sh
* LOGNAME - set to your userid as found in /etc/passwd
* HOME - set to your home dir. as found in /etc/passwd
* PATH - set to "/usr/bin:/bin"
That's it.
However, what you can do is take a snapshot of the environment you want and save that to a file.
Now make your cronjob source a trivial shell script that sources this env. file and then executes your Ruby script.
BTW Having a wrapper source a common env. file is an excellent way to enforce a consistent environment for multiple cronjobs. This also enforces the DRY principle because it gives you just one point to update things as required, instead of having to search through a bunch of scripts and search for a specific string if, say, a logging location is changed or a different utility is now being used, e.g. gnutar instead of vanilla tar.
Actually, this technique is used very successfully with The Build Monkey which is used to implement Continuous Integration for a major software project that is common to several major world airlines. 3,500kSLOC being checked out and built several times a day and over 8,000 regression tests run once a day.
HTH
'Avahappy, | To find out the environment in which cron runs jobs, add this cron job:
```
{ echo "\nenv\n" && env|sort ; echo "\nset\n" && set; } | /usr/bin/mailx -s 'my env' [email protected]
```
Or send the output to a file instead of email. |
1,265,860 | This keeps happening to me all the time:
1) I write a script(ruby, shell, etc).
2) run it, it works.
3) put it in crontab so it runs in a few minutes so I know it runs from there.
4) It doesnt, no error trace, back to step 2 or 3 a 1000 times.
When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this:
```
ruby script.rb >& /path/to/output
```
I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there)
I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables.
Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**?
When debugging, I have to reset the timer and go back to waiting. Very time consuming.
How to test things in crontab better or avoid these problems? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1265860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96087/"
] | >
> "Is there a way for me to just have crontab run a script as if I ran it myself from my terminal?"
>
>
>
Yes:
```
bash -li -c /path/to/script
```
From the man page:
```
[vindaloo:pgl]:~/p/test $ man bash | grep -A2 -m1 -- -i
-i If the -i option is present, the shell is interactive.
-l Make bash act as if it had been invoked as a login shell (see
INVOCATION below).
``` | If you really want to run it *as yourself*, you may want to invoke ruby from a shell script that sources your `.profile`/`.bashrc` etc. That way it'll pull in your environment.
However, the downside is that it's not isolated from your environment, and if you change that, you may find your cron jobs suddenly stop working. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.