qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
26,204,485 |
I am using gorilla mux for manage routing. What I am missing is to integrate a middleware between every request.
For example
```
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"strconv"
)
func HomeHandler(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "Hello home")
}
func main() {
port := 3000
portstring := strconv.Itoa(port)
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", r)
log.Print("Listening on port " + portstring + " ... ")
err := http.ListenAndServe(":"+portstring, nil)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}
```
Every incoming request should pass through the middleware. How can I integrate here a midleware?
**Update**
I will use it in combination with gorilla/sessions, and they say:
>
> Important Note: If you aren't using gorilla/mux, you need to wrap your
> handlers with context.ClearHandler as or else you will leak memory! An
> easy way to do this is to wrap the top-level mux when calling
> http.ListenAndServe:
>
>
>
How can I prevent this scenario?
|
2014/10/05
|
[
"https://Stackoverflow.com/questions/26204485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743843/"
] |
Just create a wrapper, it's rather easy in Go:
```
func HomeHandler(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "Hello home")
}
func Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("middleware", r.URL)
h.ServeHTTP(w, r)
})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", Middleware(r))
}
```
|
9,871,106 |
I would like to show boxplots for multiple variables, and rank them by column means in descending order, just like in the *Performance Analytics* package. I use the following code to generate the boxplots:
```
zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)
```
So far I have not been able to come up with a way to rank them as described above. I have tried using both *sort* and *order*, but without any satisfying results so far.
Any help would be much appreciated.
|
2012/03/26
|
[
"https://Stackoverflow.com/questions/9871106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1292820/"
] |
Use query
```
SELECT
id_cont, month, suma_lun, year
FROM
`your_table`
ORDER BY
id_cont
```
Your output will be
```
id_cont suma_lun month year
--------------------------------------------
FL28 2133 March 2012
FL28 2144 April 2012
FL28 2155 May 2012
FL29 2166 June 2012
FL29 2226 July 2012
FL29 2353 Aug 2012
```
then in PHP you can get desired output
```
<?php
$id=0;
while($row=mysql_fetch_array($records))
{
if($row['id_cont']) !=id)
{
echo" $row[id_cont] ";
id=$row['id_cont'];
}
echo "$row[month]";
echo "$row[suma_lun]";
echo "$row[year]";
}
?>
```
|
39,920,433 |
I'm looking at string manipulation in C and I don't understand why the statement `s1[i] = s1[++i];` won't replace the first `H` by the next character `e`. Take a look at the code :
```
#include <stdio.h>
main()
{
char s1[] = "Hello world !";
for(int i = 0; s1[i] != '\0'; ++i)
s1[i] = s1[++i];
printf("%s", s1);
}
```
It prints `Hello world !` instead of `el r`
|
2016/10/07
|
[
"https://Stackoverflow.com/questions/39920433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5730923/"
] |
Your program has [*undefined behaviour*](https://en.wikipedia.org/wiki/Undefined_behavior) because in this statement
```
s1[i] = s1[++i];
```
`i` is modified twice between sequence points (The assignment operator `=` doesn't introduce a sequence point).
gcc (`gcc -Wall -Wextra`) warns with:
```
warning: operation on ‘i’ may be undefined [-Wsequence-point]
```
similarly clang warns:
```
warning: unsequenced modification and access to 'i' [-Wunsequenced]
```
|
52,131,743 |
I have noticed a rather weird behaviour in my application I am creating;
I have a class I defined that has a static "instance" variable of the class type.
I would assume that (as per code attached) the constructor would be called.
Alas, it is not, unless I use the Void.get in a non-static field anywhere in my code.
```
public class Void : TilePrototype {
public static Tile get = new Tile((int)TileEntities.Void);
public static Void instance = new Void();
public Void() {
Debug.Log("created");
id = (int)TileEntities.Void;
isBlocking = true;
register();
}
public override RenderTile render(Tile tile){
return new RenderTile(0, new Color(0, 0, 0, 0));
}
```
So when I have something like :
```
public static TileStack empty = new TileStack(Void.get, Void.get);
```
the Void class constructor never gets called. But, if I have:
```
Tile t = Void.get;
```
Anywhere in my code it will be called.
Why?
Thanks.
|
2018/09/01
|
[
"https://Stackoverflow.com/questions/52131743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9373397/"
] |
This is a *really really* subtle and nuanced area of C#; basically, you've stumbled into "beforefieldinit" and the difference between a static constructor and a type initializer. You can reasonably ask "when does a static constructor run?", and MSDN will [tell you](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors):
>
> It is called automatically before the first instance is created or any static members are referenced.
>
>
>
Except... `public static TileStack empty = new TileStack(Void.get, Void.get);` isn't a static constructor! It is a static field initializer. And *that has different rules*, which basically are "I'll run when I must, no later, possibly sooner". To illustrate with an example: the following **will not** (probably) run your code, because *it doesn't have to* - there isn't anything demanding the field:
```
class Program
{
static void Main()
{
GC.KeepAlive(new Foo());
}
}
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
}
```
However, if we make a tiny tweak:
```
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
static Foo() { } // <=== added this
}
```
*Now* it has a static constructor, so it must obey the "before the first instance is created" part, which means it needs to *also* run the static field initializers, and so on and so on.
Without this, the static field initializer can be deferred until something *touches the static fields*. If any of your code *actually touches* `empty`, *then* it will run the static field initializer, and the instance will be created. Meaning: this would *also* have this effect:
```
class Program
{
static void Main()
{
GC.KeepAlive(Foo.empty);
}
}
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
}
```
This ability to defer execution of the static initialization until the static fields are **actually touched** is called "beforefieldinit", and it is enabled if a type has a static field initializer but no static constructor. If "beforefieldinit" isn't enabled, then the "before the first instance is created or any static members are referenced" logic applies.
|
11,919,061 |
We are developing a CMS and would like advice on the best way to handle user customizable themes. We have a couple ideas but are not really sure what the best approach is. The CMS will allow the user to customize every part of the site including colors, fonts, layout, etc, through a theme editor UI built into the CMS.
We were thinking writing a custom CSS parser that writes changes out to a CSS file for that theme. This approach seems like it may have a lot of point of failure and a lot of overheard.
The other way was to store all the CSS in a database and then just use inline CSS.
The CMS has been built using JQuery and PHP with MySQL database for user information and content, but not CSS.
Is there a more efficient way to parse/control/edit CSS properties of the theme?
Thanks
|
2012/08/12
|
[
"https://Stackoverflow.com/questions/11919061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1592878/"
] |
```
//your array
String[n] array;
//your button
Button b;
///your edittext
EditText e;
if(b.isPressed())
array[x]=edit.getText().toString();
```
OR using ArrayList
```
ArrayList<String> n= new ArrayList<String>();
//your button
Button b;
///your edittext
EditText e;
if(b.isPressed())
n.add(edit.getText().toString());
```
|
29,029,676 |
I'd like to use "is" operator in C# to check the runtime type of an object instance. But it doesn't seem to work as I'd expect.
Let's say we have three assemblies A1, A2 and A3 all containing just one class.
A1:
```
public class C1
{
public static void Main()
{
C2 c2 = new C2();
bool res1 = (c2.c3) is C3;
bool res2 = ((object)c2.c3) is C3;
}
}
```
A2:
```
public class C2
{
public C3 c3 = new C3();
}
```
A3:
```
public class C3
{
}
```
A1 needs to reference A2 and A3.
A2 needs to reference A3.
After running Main() res1 and res2 are set to true as expected. The problem occurs when I start versioning A3 as strongly named assembly and make A1 to reference one version
and A2 to reference another version of A3 (the source code of A3 remains the same). Btw. compiler allows this only if the version of A3 referenced by A2 is lower or equal than
the version of A3 referenced by A1. The outcome of this program is now different (res1 = true, res2 = false).
Is this behaviour correct? Shouldn't they be both false (or perhaps true)?
According to C# 5.0 specification (chapter 7.10.10) both res1 and res2 should end up with the same value. The "is" operator should always consider run-time type of the instance.
In IL code I can see for res1 the compiler made the decission that both C3 classes coming from different A3 assemblies are equal
and emitted the code without isinst instruction checking against null only. For res2 compiler has added isinst instruction which postpones the decision for run-time.
It looks like C# compiler has different rule on how to resolve this than CLR run-time.
```
.method public hidebysig static void Main() cil managed
{
.entrypoint
// Code size 36 (0x24)
.maxstack 2
.locals init ([0] class [A2]C2 c2,
[1] bool res1,
[2] bool res2)
IL_0000: nop
IL_0001: newobj instance void [A2]C2::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldfld class [A3]C3 [A2]C2::c3
IL_000d: ldnull
IL_000e: ceq
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: stloc.1
IL_0014: ldloc.0
IL_0015: ldfld class [A3]C3 [A2]C2::c3
IL_001a: isinst [A3_3]C3
IL_001f: ldnull
IL_0020: cgt.un
IL_0022: stloc.2
IL_0023: ret
} // end of method C1::Main
```
Could it be just trade-off for a faster and optimised implementation without using isinst (considering the compiler warning)?
Possible option to get around this is binding redirect (as suggested by the warning) but I can't use that as the versions may not always be backwards compatible (although C3 class always is). Changing the reference in A2 is also not an option for me.
EDIT: As it seems the easiest workaround is to always cast to object to get the correct result.
Anyway it would still be interesting to know if it's a bug in C# compiler (and possibly report it to MS) or not a bug per se (as compiler identifies a problem and reports a warning) although it could still generate a correct IL code.
|
2015/03/13
|
[
"https://Stackoverflow.com/questions/29029676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4666214/"
] |
Unfortunately, I don't have an answer to why the first result yields true. However, if the spec says that `is` is supposed to be based on the runtime type, Panagiotis is correct; the types are different and both should return false. GetType() and typeof behave as `is` should.
```
var res3 = c2.c3.GetType() == typeof(C3); // is false
var res4 = ((object)c2.c3).GetType() == typeof(C3); // is false
var localC3 = new C3();
var res5 = localC3 is C3; // is true
var res6 = ((object)localC3).GetType() == typeof(C3); // is true
```
My knee-jerk reation would be get rid of the object cast as that seems to work as you want.
However, as that may change if `is` is fixed. You could resort to the following. Since your code was compiled against signed assemblies, people won't be able to substitute a fake assembly.
```
var res7 = c3.GetType().FullName == typeof(C3).FullName
```
Hopefully, some of this helps.
|
47,376,733 |
I have noticed the `RecyclerView.Adapter` type is not generic in `Xamarin.Android`. Why is it so? It seems to be defined as generic in native Android according to the [documentation](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html). Is there an underlying reason for this? Or is it some kind of backward compatiblity scenario?
|
2017/11/19
|
[
"https://Stackoverflow.com/questions/47376733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/732221/"
] |
You need to wrap the function script inside **`<head>`** . Otherwise your script is not invoked.
Change the settings as
```
LOAD TYPE - Wrap in <Head>
```
**[WORKING DEMO](https://jsfiddle.net/76n5w9zr/)**
[](https://i.stack.imgur.com/jZXnk.jpg)
|
39,721,901 |
This probably may be a duplicate question, but I'm not able to do this correctly.
I have enabled CORS in my backend (reading [this](http://enable-cors.org/server_expressjs.html)). But, still, when I try to hit an API on my API server through my UI server, I get this:
`Request header field Authentication is not allowed by Access-Control-Allow-Headers in preflight response.`
Here are some relevant parts of my code:
### Backend
```
// enable CORS
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
```
### Frontend
```
$.ajax({
method: 'GET',
url: ...,
headers: {
Authentication: ...
},
...
});
```
|
2016/09/27
|
[
"https://Stackoverflow.com/questions/39721901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035469/"
] |
You need to allow that header explicitly
```
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authentication");
```
And you'd better use some existing CORS module, as I'm not sure your implementation is 100% correct.
I use this CORS middleware:
```
function (req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", YOUR_URL); // restrict it to the required domain
res.header("Access-Control-Allow-Methods", "GET,PUT,PATCH,POST,DELETE,OPTIONS");
// Set custom headers for CORS
res.header("Access-Control-Allow-Headers", YOUR_HEADER_STRING);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next();
};
```
|
24,151,727 |
I want to take some information created in a Joomla article into a separate system separate from Joomla. Here is an example value returned from a field I grabbed from a MySQL query (the column is "images" from the "com\_content" table):
```
{"image_intro":"images\/Capitol_-_D_C__-_Daytime.jpg","float_intro":"right","image_intro_alt":"","image_intro_caption":"","image_fulltext":"","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}
```
Now in PHP I want to convert this sucker into an array. Any ideas?
|
2014/06/10
|
[
"https://Stackoverflow.com/questions/24151727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988799/"
] |
`json_decode()` in PHP will be your friend, see the docs:
<http://docs.php.net/manual/de/function.json-decode.php>
Something like this:
```
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
```
|
558,014 |
If I want find command to stop after finding a certain number of matches, how do I do that?
Background is that I have too many files in a folder, I need to put them into separate folders randomly like:
```
find -max-matches 1000 -exec mv {} /path/to/collection1 \+;
find -max-matches 1000 -exec mv {} /path/to/collection2 \+;
```
is this possible to do with `find` alone? If not, what would be the simplest way to do this?
|
2019/12/19
|
[
"https://unix.stackexchange.com/questions/558014",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/27695/"
] |
As you're not using `find` for very much other than walking the directory tree, I'd suggest instead using the shell directly to do this. See variations for both `zsh` and `bash` below.
---
Using the `zsh` shell
```none
mv ./**/*(-.D[1,1000]) /path/to/collection1 # move first 1000 files
mv ./**/*(-.D[1,1000]) /path/to/collection2 # move next 1000 files
```
The globbing pattern `./**/*(-.D[1,1000])` would match all regular files (or symbolic links to such files) in or under the current directory, and then return the 1000 first of these. The `-.` restricts the match to regular files or symbolic links to these, while `D` acts like `dotglob` in `bash` (matches hidden names).
This is assuming that the generated command would not grow too big through expanding the globbing pattern when calling `mv`.
The above is quite inefficient as it would expand the glob for each collection. You may therefore want to store the pathnames in an array and then move slices of that:
```sh
pathnames=( ./**/*(-.D) )
mv $pathnames[1,1000] /path/to/collection1
mv $pathnames[1001,2000] /path/to/collection2
```
To randomise the `pathnames` array when you create it (you mentioned wanting to move random files):
```sh
pathnames=( ./**/*(-.Doe['REPLY=$RANDOM']) )
```
---
You could do a similar thing in `bash` (except you can't easily shuffle the result of a glob match in `bash`, apart for possibly feeding the results through `shuf`, so I'll skip that bit):
```bash
shopt -s globstar dotglob nullglob
pathnames=()
for pathname in ./**/*; do
[[ -f $pathname ]] && pathnames+=( "$pathname" )
done
mv "${pathnames[@]:0:1000}" /path/to/collection1
mv "${pathnames[@]:1000:1000}" /path/to/collection2
mv "${pathnames[@]:2000:1000}" /path/to/collection3
```
|
65,412,103 |
```js
<template>
<div
class=" d-flex flex-column my-5 align-items-center justify-content-center "
>
<div
v-for="(poste, id) in filterPost.slice().reverse()"
v-bind:key="id"
class="largeur80 d-flex align-items-center my-5 justify-content-center card bordurePost bordureRond border-primary shadow"
>
<div class="card-body p-3 container-fluid">
<div class="d-flex justify-content-between">
<div class="d-flex">
<img
v-if="
users
.map((user) => {
if (user.id === poste.user_id) return user.image_url;
})
.join('') !== (null || '')
"
:src="
users
.map((user) => {
if (user.id === poste.user_id) return user.image_url;
})
.join('')
"
width="100px"
height="100px"
class=" justify-content-left bordureProfil
rounded-circle"
/>
<img
v-else
src="../assets/image/icon.png"
width="100px"
class=" justify-content-left bordureProfil rounded-circle"
/>
<div class="ml-3 align-item-center justify-content-center">
<h5>
{{
users
.map((user) => {
if (user.id === poste.user_id) return user.email;
})
.join("")
}}
{{
users
.map((user) => {
if (user.id === poste.user_id) return user.id;
})
.join("")
}}
</h5>
<h6>Publié le: {{ poste.date_cree }}</h6>
</div>
</div>
<b-button
v-if="user_id == poste.user_id"
@click="deletePost(poste)"
size="sm"
variant="danger"
class="bg-light mb-2 minHeight30"
>
<b-icon
icon="trash-fill"
variant="danger"
aria-label="false"
></b-icon>
</b-button>
</div>
<h4 class=" largeur100 card-title">{{ poste.titre }}</h4>
<div class=" my-3">
<img
v-if="poste.image_link !== '' && poste.image_link !== null"
class="card-img-top"
height="400px"
:src="poste.image_link"
alt="img-or-video"
/>
</div>
<div>
<div class="text-left text-wrap py-3 card-text">
{{ poste.description }}
</div>
</div>
<div
v-for="(comment, id) in comments.filter((comment) => {
return comment.post_id == poste.id;
})"
v-bind:key="id"
class="d-flex mb-2 align-items-center justify-content-center align-content-center"
>
<img
v-if="
(comment.user_id = userConnect.id) &&
(!userConnect.image_url == null || '')
"
:src="userConnect.image_url"
width="60px"
height="60px"
class=" mr-3 justify-content-left bordurePost
rounded-circle"
alt=""
/>
<img
v-else
src="../assets/image/icon.png"
width="60px"
height="60px"
class=" mr-3 justify-content-left bordurePost
rounded-circle"
alt=""
/>
<div
class=" d-inline-flex flex-column align-items-start pl-3 largeur100 minHeight bordureRond bodurePost border border-primary backPrimaire"
min-heigth="60px"
>
<p class="stopOpac stopPadMarg text-dark">
{{
users.map((user) => {
if (user.id === comment.user_id) return user.prenom;
})
}}
{{ userConnect.nom }}
</p>
<p class="stopOpac text-left stopPadMarg text-secondary">
{{ comment.comment }}
</p>
</div>
<b-button
size="sm"
variant="danger"
class="d-flex justify-content-center bg-light ml-2 minHeight25 minwidth25"
>
<b-icon
icon="trash-fill"
variant="danger"
aria-label="false"
></b-icon>
</b-button>
</div>
<div class="mt-1 form-group">
<label class="text-primary" for="commentaire"
>Laisser un commentaire</label
>
<div
class="d-flex align-items-center justify-content-center align-content-center"
>
<img
v-if="
(poste.user_id = userConnect.id) &&
(userConnect.image_url !== null || '')
"
:src="userConnect.image_url"
width="50px"
height="50px"
class=" mr-3 justify-content-left bordurePost
rounded-circle"
alt=""
/>
<img
v-else
src="../assets/image/icon.png"
width="50px"
height="50px"
class=" mr-3 justify-content-left bordurePost
rounded-circle"
alt=""
/>
<input
type="text"
class="form-control"
name="commentaire"
placeholder="Commentaires..."
/>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "carte",
data() {
return {
postes: [],
users: [],
userDef: [],
userConnect: [],
comments: [],
user_id: localStorage.getItem("userId"),
};
},
computed: {
filterUser() {
return this.users.filter((user) => {
return user.id;
});
},
filterUserimage() {
return this.users.filter((user) => {
return user.image_url;
});
},
filterUsernom() {
return this.users.filter((user) => {
return user.nom;
});
},
filterPost() {
return this.postes.filter((poste) => {
return poste.user_id == this.userConnect.id;
});
},
filterComm() {
return this.comments.filter((comment) => {
return comment.user_id == this.userConnect.id;
});
},
},
async created() {
this.postes = [];
this.users = [];
this.userDef = [];
this.userConnect = [];
//this.postes = [];
await axios
.get("http://localhost:3000/postes")
.then(
(response) => ((this.postes = response.data), console.log(response))
)
.catch((error) => console.log(error));
await axios
.get("http://localhost:3000/users")
.then(
(response) => ((this.users = response.data), console.log(this.users))
)
.catch((error) => console.log(error));
await axios
.get("http://localhost:3000/users")
.then(
(response) => (
(this.userDef = response.data.find((user) => {
return user.id;
})),
console.log(this.userDef)
)
)
.catch((error) => console.log(error));
await axios
.get(`http://localhost:3000/user/${this.user_id}`)
.then(
(response) => (
(this.userConnect = response.data), console.log(this.userConnect.id)
)
)
.catch((error) => console.log(error));
await axios
.get("http://localhost:3000/commentaires")
.then(
(response) => (
(this.comments = response.data), console.log(this.comments)
)
)
.catch((error) => console.log(error));
},
methods: {
deletePost(poste) {
axios
.delete(`http://localhost:3000/poste/${poste.id}`, {})
.then((response) => {
//(this.submitStatus = "OK"),
console.log(response), this.$router.go("/post");
})
.catch((error) =>
// (this.submitStatus = "ERROR SERVEUR"),
console.log(error)
);
},
},
};
</script>
<style></style>
```
I am unable to link the comment.user\_id with the user.id I am unable to compare the user with the comment and display the name of the user in its comments.
I have already made a loop to have the number of comments in the posts linked with his comments, that's good. but I don't know how to link the rest anymore. I tried more than one function with fine map filter foreach ect. I have reached the end of the attempts.
can you help me ??
the data base is in mysql there are three tables linked together by a foreign key so everything is reier the data are there but I can't process them in front.
users is the array of users userConnect the user is currently connecting this for testing otherwise vuejs crashes.
So I want to compare user.id in users array with the comment.user\_id in the comments array and display the first name and last name of the one who has commented
[](https://i.stack.imgur.com/oVO25.png)
|
2020/12/22
|
[
"https://Stackoverflow.com/questions/65412103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14462293/"
] |
This is a data error. Somewhere in your DATUM column you have a string which cannot be cast to a date. This is always a risk when we store data as the wrong datatype.
If you are on Oracle 12c R2 or higher you can easily locate the errant row(s) with a query like this:
```
select * from your_table
where validate_conversion(datum as date, 'yyyymm') = 0
```
If you are on an earlier version of the database you can create a function which does something similar....
```
create or replace function is_date(p_str in varchar2
,p_mask in varchar2 := 'yyyymm' ) return number is
n pls_integer;
begin
declare
dt date;
begin
dt := to_date(p_str, p_mask);
n := 1;
exception
when others then
n := 0;
end;
return n;
end;
/
```
Like `validate_conversion()` this returns 1 for valid dates and 0 for invalid ones.
```
select * from your_table
where is_date(datum, 'yyyymm') = 0
```
This approach is safer because it applies Oracle's actual date verification mechanism. Whereas, using pattern matching regexes etc leaves us open to weak patterns which pass strings which can't be cast to dates.
|
336,702 |
OK, so I've been wracking my brain for the past hour trying to figure out how to calculate k in a problem like this:
>
> A mass of 10 kg is attached to a spring hanging from the ceiling. It is released, allowed to oscillate, and comes to rest at a new equilibrium point 10 meters below the spring's natural length. What is the value of the spring constant k for this spring?
>
>
>
There's two approaches that are giving me different answers:
1:
We can use forces: at equilibrium, the force of gravity will equal the spring force, so mg = kx. This gives a value of (10)(9.8) = k (10) or **k = 9.8.**
2: We can use potential energy. Before the mass is released, it has gravitational potential energy; at the new equilibrium, it has LESS gravitational PE, but more elastic PE, since it is now stretched. The elastic PE must have been converted from gravitational PE, so dPE (elastic) = dPE (gravitational). Since the change in height is the same as the change in stretch, the h in mgh = the x for spring stretch. So:
dPE (elastic) = dPE (gravitational), h = x
.5kx^2 = mgx
.5kx = mg
k = 2mg/x
Plugging in, we get
k = 2(10)(9.8)/10 or **k = 19.6**, which is twice as much as the k found through the other method.
I must be missing something here, why am I getting two different values for k depending on which approach I use?
|
2017/05/31
|
[
"https://physics.stackexchange.com/questions/336702",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/157819/"
] |
>
> What is the logic here if you were confronted with just the first
> diagram?
>
>
>
I recommend that you label all unique nodes (two junctions that are connected together by a wire are the same node) and redraw.
There are 5 unique nodes
A: the junction of the positive cell plate, R2, and R6
B: the junction of R2, R3, and R4
C: the junction of R4, R5, R6, R7, and R8
D: the junction of the negative cell plate, R7, and R8
E: the junction of R3 and R5
So, redraw the circuit in a sane way so that you can see the series and parallel connections. For example:
[](https://i.stack.imgur.com/OlvKg.png)
|
35,320,673 |
i want to select several random rows from database, something like this
```
select * from table order by rand limit 10
```
how to do it in Laravel eloquent model?
|
2016/02/10
|
[
"https://Stackoverflow.com/questions/35320673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5596825/"
] |
Do something like this:
```
User::orderBy(DB::raw('RAND()'))->take(10)->get();
```
|
261,401 |
```
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Header>
</SOAP-ENV:Header>
</SOAP-ENV:Envelope>
```
Please help me in building the XML Request Structure in apex.I have started like this Is this Correct?
|
2019/05/07
|
[
"https://salesforce.stackexchange.com/questions/261401",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/63272/"
] |
One way would be to create XML using String concatenation. This makes generated XML very much readable.
```
String requestInput = '?xml version="1.0" encoding="UTF-8"?>'+
'<SOAP-ENV:Envelope '+
' xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" '+
' xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> '+
' <SOAP-ENV:Header> '+
' </SOAP-ENV:Header>';
```
|
21,965,608 |
I clicked on the blue xcode project name in the TopLeft of the Project Navigator, and changed the name from "A" to "B", and now I'm getting an e-rror called :
```
ObjectiveChipmunk - 1 issue
cpSpaceQuery.c
! Lexical or Preprocessor Issue 'chipmunk/chipmunk_private.h' file not found
```
Please give some help and I will love you for this.
|
2014/02/23
|
[
"https://Stackoverflow.com/questions/21965608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Add the:
"[ProjectPath]/Libraries/Chipmunk/chipmunk/include"
or the path to chipmunk header fils.
to:
Target -> Building Settings -> Search Paths -> Header Search Paths
If it's not work, you should check the project folder in Finder make sure the folder of chipmunk in the right place.
|
89,562 |
i just bought my iPad mini for 2 weeks or more which has been jail broken. So since I'm using a weekly prepaid data plan, I need to renew the data plan again and again for every week. Hence I wanna know if I can use iMessages in order to apply my data plan again which I need to send it to '28882'.
Is that possible to use iMessages, or if it does not allow me to do so, do you have any idea how to send text messages as if 'normal messages' to especially non-apple devices?
Any idea what other apps do I need to use?
|
2013/04/23
|
[
"https://apple.stackexchange.com/questions/89562",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/47985/"
] |
Up until I did an update, I could email non Apple users without any problem. After the update, I couldn't. I spent over an hour with an Apple "genius" that finally fixed it. I just updated again and I have the same problem. This is ridiculous! I have customers that text me orders. I am so frustrated!! This is messing with my income!
|
53,020 |
In 1 Corinthians, Paul is writing to the church at Corinth after hearing reports over various matters. One of them is sexual immorality within the church at Corinth. Of this matter he says in 1 Corinthians 5: 11
>
> But now I am writing to you that you must not associate with anyone
> who claims to be a brother or sister but is sexually immoral or
> greedy, an idolater or slanderer, a drunkard or swindler. Do not even
> eat with such people.
>
>
>
Does this not contradict the gospels which document Jesus sitting with sinners?
>
> Now the tax collectors and sinners were all gathering around to hear
> Jesus. But the Pharisees and the teachers of the law muttered, “This
> man welcomes sinners and eats with them”. **Luke 15:1-2**
>
>
>
>
> Then Levi held a great banquet for Jesus at his house, and a large
> crowd of tax collectors and others were eating with them. But the
> Pharisees and the teachers of the law who belonged to their sect
> complained to his disciples, “Why do you eat and drink with tax
> collectors and sinners?” **Luke:5:29-30**
>
>
>
After this Jesus says:
>
> It is not the healthy who need a doctor, but the sick. I have not come
> to call the righteous, but sinners to repentance **Luke 5:31-32**
>
>
>
So Jesus on two separate occasions eats with sinners. Jesus then gives his reasoning, that he does so to save them. Paul on the other hand says not to associate with them, not even to eat with them, seemingly contradicting Jesus as far as I see it.
So does Paul contradict Jesus?
|
2020/11/14
|
[
"https://hermeneutics.stackexchange.com/questions/53020",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/19975/"
] |
In 1 Corinthians 5:11, Paul addresses the command to people who claim to be Christians.
>
> But now I am writing to you that you must not associate with anyone who **claims to be a brother or sister** but is sexually immoral or greedy, an idolater or slanderer, a drunkard or swindler. Do not even eat with such people.
>
>
>
Jesus ate with sinners who had not believed in the Messiah.
So does Paul contradict Jesus?
No, they are two different audiences.
|
49,807 |
How is it a fair trial if the senate does not allow new witnesses to testify? The only reason why they didn't testify in the first place was because President Trump forbade them from doing so - something which is a part of the Obstruction of Congress article in the impeachment.
I was under the impression that the House decides if Trump is impeached and the Senate decides whether or not to kick him out of office. Based on this assumption, the Senate would need more info - as they are the actually jury on the case, the house just said there is reason to send this case to the jury. So, how is it fair to ban new witnesses?
|
2020/01/29
|
[
"https://politics.stackexchange.com/questions/49807",
"https://politics.stackexchange.com",
"https://politics.stackexchange.com/users/28333/"
] |
You make an astute observation. This isn't something which would happen in a fair legal trial.
But legally this isn't a fair trial, it's a political process.
In a fair legal trial, [jurors who plan to work in total coordination with the defense](https://www.msnbc.com/rachel-maddow/watch/mcconnell-spurns-constitution-with-fealty-to-trump-on-impeachment-75068997517) would be dismissed, but [the chief justice presiding over the case can't do that either](https://politics.stackexchange.com/questions/49044/can-the-chief-justice-excuse-senators-from-the-jury-in-a-presidential-impeachmen).
Legal trials will have to wait until either Trump is removed from office, or [the DOJ memo against indicting a sitting president](https://www.justice.gov/olc/opinion/sitting-president%E2%80%99s-amenability-indictment-and-criminal-prosecution) is challenged/ignored.
|
68,270,954 |
After upgrading to net5 I'm getting obsoletion warning:
`[CS0618] 'HttpRequestMessage.Properties' is obsolete: 'Use Options instead.'`
however there seems to be no migration guide.
I.e. there's following code
```
httpRequestMessage.Properties.Add(Key, Value);
```
How exactly it should be migrated? Is
```
httpRequestMessage.Options.Set(new HttpRequestOptionsKey<TValue>(Key), Value);
```
correct?
|
2021/07/06
|
[
"https://Stackoverflow.com/questions/68270954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029276/"
] |
I struggled with the same thing and I found the solution.
Here is how you should use the new Options property.
Instead of `request.Properties.Add("foo", true);`
Write: `request.Options.Set(new HttpRequestOptionsKey<bool>("foo"), true);`
To read the key from response:
`response.RequestMessage.Options.TryGetValue(new HttpRequestOptionsKey<bool>("foo"), out bool foo);`
To be honest, I don't know why they changed it. It's strange we need to create a new HttpRequestOptionsKey object for each property. But it is what it is.
|
3,978 |
I asked [a question about my new HP Proliant](https://serverfault.com/q/454736/40159) and got [a very good answer](https://serverfault.com/a/454740/40159) but it was unclear to me if the answerer understood that I was using the server in production (although for home use). In other words, the load would be very small compared to anything in production for a business, but the data *is* ***critically important*** to *me*.
I asked a question to try to clarify whether the answerer correctly understood the situation, and another commenter decided to argue that the phrase "production quality" has some absolute meaning regardless of the purpose or context of the server. I explained and defended my use of the word "production" (if it's got *real* data and it's not QA, UAT, dev, etc., then it's *production*) since he didn't seem to understand this, and he became abusive, saying he was going to close the question "since [I] insist on being so appreciative of [his] answer".
This strikes me as a flagrant abuse of the power bestowed on him by his higher rep, but he also implied that the fact that my question is about a home server makes the question off topic. Is this true? Are our questions somehow invalidated by the fact that we're using the hardware at home rather than in an enterprise (or small business) setting? If so, why does that matter?
|
2012/12/08
|
[
"https://meta.serverfault.com/questions/3978",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/40159/"
] |
A couple of additional points to Iain's answer:
* Home use questions are off-topic because we don't want endless questions about how to host a website on a home computer, how to configure consumer routers on ADSL connections, etc.
* There's absolutely no "abuse of power" going on. The guy who commented on it being a home system didn't unilaterally close it, 4 other users agreed that it should be closed.
* I'd consider your question to be borderline: there are times when professionals cut corners and using a low-end server for a system where uptime isn't a big concern can be an appropriate decision. (I'd agree that it's not really a "production quality" system, however.)
* A closed question is not dead. The normal advice is that you can edit your question and flag it to ask a moderator to re-open. In this case, however, there's nothing in your actual question that says home use, so I'd suggest flagging it and asking a moderator to delete all the comments and re-open it.
(Actually, you don't need to flag it because I just did.)
|
354,662 |
Hi I am looking to step down a 10 volt DC to 5 DC with low output current (less then 1 amp)
Is it the best to build a buck converter or to buy it ready ?
thank you
---
Actually I am using an arduino,
I am not sure if using the 5 volt of the arduino is recommended ?
my circuit involve 4 L293D that requires 5 volt,
I have 10 volt available that I can step down to 5 volt,
This circuit is a design so will always be under power
I saw that a buck converter does not generate too much heat which is good for a circuit always power on
|
2018/02/07
|
[
"https://electronics.stackexchange.com/questions/354662",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/176656/"
] |
It really depends on what it is for.
If you are making yourself a one-time, or few-times, gizmo for a dedicated function buying an off-the shelf convertor is your best, and usually cheapest, bet. Though you may want to buy a few spares.
However, if you are designing a product, integrating a design is usually a safer approach. Using someone else's product puts you at the mercy of their standards and availability, both immediate, and long term. There is nothing worse than completing a year long design and qualification cycle, only to find out that the OEM part is no longer available, or has been changed.
Further, the assumption that the drop in part will "just work" is not always the case. With some, the "just" part has more emphasis than the "work" part.
There are numerous dubious suppliers out there. It is prudent to do your due diligence and find alternative suppliers, purchase samples, and compare them for compliance with what you expect them to do in the environments you expect them to handle.
|
26,824,576 |
I've been trying out the kmeans clustering algorithm implementation in scipy. Are there any standard, well-defined metrics that could be used to measure the quality of the clusters generated?
ie, I have the expected labels for the data points that are clustered by kmeans. Now, once I get the clusters that have been generated, how do I evaluate the quality of these clusters with respect to the expected labels?
|
2014/11/09
|
[
"https://Stackoverflow.com/questions/26824576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1315445/"
] |
I am doing this very thing at that time with Spark's KMeans.
I am using:
* The sum of squared distances of points to their nearest center
(implemented in [computeCost()](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel.computeCost)).
* The Unbalanced factor (see
[Unbalanced factor of KMeans?](https://stackoverflow.com/questions/39235576/unbalanced-factor-of-kmeans)
for an implementation and
[Understanding the quality of the KMeans algorithm](https://stackoverflow.com/questions/39240078/understanding-the-quality-of-the-kmeans-algorithm)
for an explanation).
Both quantities promise a better cluster, when the are small (the less, the better).
|
47,658,570 |
In order to illustrate a concept to use later for larger data types like `UInt128`, and `UInt256`, I'm trying to do the following function:
My function takes 2 `UInt8`s, shifts the first (theoretically the more significant bits), to the left 8 and then adds `int2`, (theoretically the lower bits)
```
func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
let x: UInt16 = (int1 << 8) + int2
return x
}
```
Is there something that I need to do to avoid the error: `(int1 << 8) + int2` isn't equal to the specified type `UInt16`?
|
2017/12/05
|
[
"https://Stackoverflow.com/questions/47658570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/602210/"
] |
You must explicitly convert the smaller to the larger type:
```
func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
let x: UInt16 = (UInt16(int1) << 8) + UInt16(int2)
return x
}
```
This also makes the explicit type annotation unnecessary:
```
func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
let x = (UInt16(int1) << 8) + UInt16(int2)
return x
}
```
and it can be shortened to:
```
func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
return UInt16(int1) << 8 + UInt16(int2)
}
```
The conversion to the larger type must be done *before* shifting/adding,
which might overflow otherwise.
|
50,032,490 |
I'm working on telephony PBX VOIP Project (call center suite)
along with Asterisk/Linux specialist.
I'm Intermediate PHP developer. I'm stuck on very First step.
I've to connect agents to Asterisk using HTML & PHP & Mysql.
Can any one guide me Step by Step ? How to login & maintain session with asterisk ?
I want to accomplish following tasks in first week
1) Login Agent/s & connection with asterisk
2) After login & maintain Agent Session
3) I want to Redirect user to Campaign Page with status "Pause" or "Not Ready"
|
2018/04/25
|
[
"https://Stackoverflow.com/questions/50032490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189512/"
] |
Asterisk is PBX, main goal is manage calls, not provide you "very simple" api for access it.
If you want work with asterisk, you HAVE understand how dialplan and channels works, so you need read general book like ORelly's "Asterisk the future of telephony".
After that you can use db-driven dialplan or **AGI** script(but still need dialplan).
You also can use **AMI** interface or **ARI**(very similar to REST you know).
But anyway for any control method you have understand dialplan, sorry.
<https://wiki.asterisk.org/wiki/display/AST/Getting+Started+with+ARI>
<https://wiki.asterisk.org/wiki/display/AST/Getting+Started+with+ARI>
<https://wiki.asterisk.org/wiki/display/AST/AMI+Libraries+and+Frameworks>
|
36,269,488 |
In Java, one can use the escape sequence `\0` to represent the [Null character](https://en.wikipedia.org/wiki/Null_character)
`\0` and `\0000` are not valid escape sequences in Kotlin, so I've been using a static java char and accessing that from Kotlin.
```
public class StringUtils{
public static char escapeChar = '\0';
}
```
Is there a Null character literal, or a better way of doing this in Kotlin?
|
2016/03/28
|
[
"https://Stackoverflow.com/questions/36269488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2104648/"
] |
These options will work:
* `'\u0000'` (Unicode escape syntax, as described in the [docs](https://kotlinlang.org/docs/reference/basic-types.html#characters))
* `0.toChar()` ([conversions](https://kotlinlang.org/docs/reference/basic-types.html#explicit-conversions) are optimized and have no function call overhead)
* `import java.lang.Character.MIN_VALUE as nullChar`, then use `nullChar` ([renaming import](https://kotlinlang.org/docs/reference/packages.html#imports))
|
102,717 |
In French we can use the prefix *re-* to mean *again* (*prendre* = *to take*, *reprendre* = *to take back/again*). It's sometimes a real verb (like *reprendre*), but it's not standard or semi-standard when we use it with certain verbs. But still we do and it.
So instead of saying *"j'ai **encore cassé** ce vase"* (formal), I could say *"j'ai **recassé** ce vase"* (informal), which means *"I **broke** this vase **again**"*.
I could even say *"j'ai **re-re-recassé** ce vase"* if it's the forth time I've broken it. It's only used in spoken French, (often to be funny).
Is there a comparable way in English to say "again for the n-th time"?
Note: I understand not every verb starting with *re* means *... again*, far from it.
|
2016/09/05
|
[
"https://ell.stackexchange.com/questions/102717",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/41294/"
] |
We can, at least with many verbs, prepend a second, or less commonly, a third or more *re* prefix. Some would consider it unacceptable in Standard English, and it would often be done informally, often playfully (apparently as you characterize such in French, to be funny), or for special effect (could be angry, etc.).
Bill: *They messed up my order again the second time, so I re-returned it!*
Susan: *Let's hope they get it right this time or you might have to re-re-return it!*
|
21,853,677 |
I want to build my application with a redis cache. but maybe redis is not available all the time in our case,
so I hope, it redis works well, we use it. if it can't work, just logging and ignore it this time.
for example:
```
try:
conn.sadd('s', *array)
except :
...
```
since there are many place I will run some conn.{rediscommand}, I don't like to use try/except every place.
so the solution maybe :
```
class softcache(redis.StrictRedis):
def sadd(key, *p):
try:
super(redis.StrictRedis, self).sadd(key, p)
except:
..
```
but since redis have many commands, I have to warp them one by one.
is it possible to custom a exception handler for a class to handle all the exceptions which come from this class ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21853677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1903880/"
] |
Silencing per default all exceptions is probably the worst thing you can do.
Anyway, for your problem you can write a generic wrapper that just redirects to the connection object.
```
class ReddisWrapper(object):
conn = conn # Here your reddis object
def __getattr__(self, attr):
def wrapper(*args, **kwargs):
# Get the real reddis function
fn = getattr(self.conn, attr)
# Execute the function catching exceptions
try:
return fn(*args, **kwargs)
# Specify here the exceptions you expect
except:
log(...)
return wrapper
```
And then you would call like this:
```
reddis = ReddisWrapper()
reddis.do_something(4)
```
This has not been tested, and will only work with methods. For properties you should catch the non callable exception and react properly.
|
10,330,723 |
I am trying to loop the data returned after ajax call is success and adding the result to [pagination plugin.](http://tympanus.net/codrops/2009/11/17/jpaginate-a-fancy-jquery-pagination-plugin/)
Here is my code:
```
var imagesPerPage = 2, pageNumber = 1;
var pagesContainer = $('#pagesContainer'),
imagesInPage = 0,
divPage = $("#p1");
$.ajax({
type: "POST",
url: "Default.aspx/GetImages",
data:{},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//Here goes my for loop
}
});
```
This is my for loop where I need to get the images from webmethod and loop them and add to the pagination.
```
for (i = 0; i < response.d.length; i++) {
if (imagesInPage >= imagesPerPage) {
imagesInPage = 1;
pageNumber += 1;
divPage = $('<div/>', { id: "p" + pageNumber }).addClass('pagedemo').hide().appendTo(pagesContainer);
} else {
imagesInPage += 1;
}
}
```
Here is my pagination default configuration:
```
$("#pagination").paginate({
count: pageNumber,
start: 1,
display: Math.min(7, pageNumber),
border: true,
border_color: '#fff',
text_color: '#fff',
background_color: 'black',
border_hover_color: '#ccc',
text_hover_color: '#000',
background_hover_color: '#fff',
images: false,
mouse: 'press',
onChange: function (page) {
$('#paginationdemo ._current').removeClass('_current').hide();
$('#p' + page).addClass('_current').show();
}
}); //pagination
```
Now my problem is when I try to get the response of one Image it is not showing me the image as well as the pagination.If it is more than one then it starts showing me the pagination and image.
**Screenshot**:

So can anyone say me where am I going wrong?
|
2012/04/26
|
[
"https://Stackoverflow.com/questions/10330723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944919/"
] |
There's no direct way of showing more than one field in `selectfield's` `displayField`.
So, you will need to create an extension based on the `selectfield`.
|
5,304,839 |
Hey, is there any way to determine is UIPickerView is scrolling currently, I really need that functionality for my app, it's really important. Thanks!
|
2011/03/14
|
[
"https://Stackoverflow.com/questions/5304839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493876/"
] |
There is a UIPickerViewDelegate method which is basically triggered every time you scroll the picker
```
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
```
Set the delegate for your picker, implement this method and see what happens...
[EDIT] ok now I understand what you need.
Implement a timer which checks the state of the picker.
```
checkTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(checkPicker) userInfo:nil repeats:YES];
```
in the above delegate method, store the last time the picker had been moved.
```
lastPickerDate = [[NSDate date] retain];
```
in the checkPicker method check how much time had elapsed from the last move
```
NSTimeInterval timeSinceMove = -[lastPickerDate timeIntervalSinceNow];
```
if timeSinceMove is bigger then some desired value i.e. 0.5 seconds, set your BOOL pickerMoving to false. else set it to true. This is not the most precise method to check for movement, but I think it should do the job...
|
13,197,733 |
I've got some crazy task, that sounds like mission impossible. I need to pass some data through stack of methods, which I can't modify (can modify only the last one). Example:
```
SomeData someData; //not passed in method1
obj1.method1(...);
```
here is obj1 class code
```
obj1 {
someReturnClass method1(...) {
...
obj2.method2(...);
...
}
}
```
obj2 and method2 call some more methods, before they get to objN.methodM(). It can even be run in separate thread (so, ThreadLocal won't help). I need to access someData inside methodM, which is not passed through this stack as parameter.
I've got some concepts to get it through exception and double running methodM, but it looks ugly.
Do you have any ideas, how to pass someData to methodM()?
|
2012/11/02
|
[
"https://Stackoverflow.com/questions/13197733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030113/"
] |
If you can't smuggle access any other way -- e.g. by adding a reference to `SomeData` into some other object that *is* passed through the call stack -- then you will eventually have to use a global variable. This is of course a poor design, but nothing else is possible given your constraints.
You mentioned in a comment that you may have several calls to your method "active" (is it recursive, or do you have multiple threads?) In that case, you will need to have a global collection instead, and have some way of inferring which element of the collection to select from the data that *is* passed through the call stack.
|
906,112 |
I want to show a UIPickerView on becoming FirstResponder of a UITextfield not the keyboard and fill the value in text field form the picker view.
any one knows this?
|
2009/05/25
|
[
"https://Stackoverflow.com/questions/906112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83905/"
] |
**Edit:** this answer was correct at the time of writing. Apple has since introduced `inputView`. Mafonya [answer](https://stackoverflow.com/a/10249439/1555903) is what you should be doing nowadays.
It is possible to prevent the keyboard from popping up. Set your class to be the delegate of the UITextField: `textField.delegate = self` and add: `<UITextFieldDelegate>` after your interface declaration (before the {) in the header file.
Now implement `textFieldShouldBeginEditing:`:
```
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
// Show UIPickerView
return NO;
}
```
If you want to be able to hide your pickerView this method won't work. What you could do then is create subclass of UITextField and override the `*trackingWithTouch:event:` selectors and do your magic in those. You probably still need to return NO from `textFieldShouldBeginEditting:` to prevent the keyboard from showing.
|
216,589 |
I'm thirteen years old (yes I was twelve when I signed up, but I had my parents make my account on my behalf and did not post any personal information, which I believe is legal :-P), and I am very passionate about programming. I have some questions regarding young programmers, and I'm wondering where to ask.
First I want to note a few things, before you say "nowhere; this doesn't fit with the q&a format" (which I do quite a bit :-P):
* I have a specific problem. I'm not going to ask "what should I do now;" there are specific things I want to know. For example, "how can a young programmer do xxx."
* My question applies to a general audience. I'm not going to ask "I've done xxx and want xxx, should I do xxx;" rather, it will apply to all young programmers in general.
Here are the sites I might ask it on:
* Programmers: I've considered asking here. I've seen the famous Venn diagram with "all people," "all careers," "all programmers," and "just you," and I believe that if I make my question general enough, it can apply to **all** young programmers. A question like this seems to be on-topic according to their "what can I ask" guidelines. However, their description says
>
> Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development.
>
>
>
It's not really about software development, and I'm *certainly* not professional, so that gives me doubts about asking there.
* The Workplace: I'm not sure about this one... it's not really about work, but I suppose it could be in a kind of abstract way ("the work of programming" or something). This seems like the wrong site though.
* Something else? Is there a better site perhaps?
Where on the SE network should I ask this, if at all? Or is this just not suitable to SE in general and I should find somewhere else to ask?
|
2014/01/17
|
[
"https://meta.stackexchange.com/questions/216589",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/180276/"
] |
As you have sufficient privileges, safe places for "drafting" questions like that are Programmers and Workplace [chat](/questions/tagged/chat "show questions tagged 'chat'") rooms ([Whiteboard](https://chat.stackexchange.com/rooms/21/the-whiteboard) and [Water Cooler](https://chat.stackexchange.com/rooms/3060/the-water-cooler), respectively).
Being free from topical / subjectivity limitations of Q&A sites, chat rooms allow one to discuss problems that might be not good fit for main site. Site regulars frequenting the rooms mentioned above can offer help and advice on how to "build" a question that would be topical and welcome at the main site.
|
22,551,090 |
![This is my code for find method in DBHelper].class[1]
```
public StringBuilder findData(String find)
{
StringBuilder output = new StringBuilder("Our data is:\n");
Cursor c = ourHelper.getReadableDatabase().rawQuery("SELECT abbrevaition FROM abbrtab WHERE acronym"+" = ? ;", new String[]{find});
String remarks=" ";
int iRemarks = c.getColumnIndex(KEY_ABBR);
if( c.moveToFirst() && c.getCount()>0 )
{
remarks= c.getString(iRemarks);
if(remarks.isEmpty())
{
Toast.makeText(ourContext, "not", Toast.LENGTH_LONG).show();
}
output.append(remarks);
}
c.close();
return output;
}
```
![This is code in Main.java for getting data from SQLite3. When i give the query select \* from abbrtab then it execute. and apply the where condition then i'm not get any thing. ][1]
```
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), String.valueOf("Hi"),Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
ASNDBAdapter info = new ASNDBAdapter(AllBranches.this);
info.open();
String data = et.getText().toString();
String result = info.findData(data).toString();
Intent i = new Intent(AllBranches.this, ViewData.class);
i.putExtra("my_data", result);
startActivity(i);
Toast.makeText(getApplicationContext(), String.valueOf(result),
Toast.LENGTH_LONG).show();
info.close();
}
```
|
2014/03/21
|
[
"https://Stackoverflow.com/questions/22551090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185056/"
] |
```
public StringBuilder findData(String find)
{
StringBuilder output = new StringBuilder("Our data is:\n");
Cursor c = ourHelper.getReadableDatabase().query("abbrtab", new String[] {"abbrevaition"},"acronym" +"="+find, null, null, null, null);
String remarks=" ";
int iRemarks = c.getColumnIndex(KEY_ABBR);
if( c.moveToFirst() && c.getCount()>0 )
{
remarks= c.getString(iRemarks);
if(remarks.isEmpty())
{
Toast.makeText(ourContext, "not", Toast.LENGTH_LONG).show();
}
output.append(remarks);
}
c.close();
return output;
}
```
Here "abbrtab" is table name and "abbrevaition" is name of field .
|
56,674,054 |
if i do a request to get some data from a database without sending any updates, however i'm marking the record in the database to say the data has been fetched, does that make it a PATCH request or a GET?
|
2019/06/19
|
[
"https://Stackoverflow.com/questions/56674054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669574/"
] |
So I would argue that these are two separate unit tests, one for function a and one for the dictionary \_actions.
\_actions is not just a simple dictionary but in a sense a dynamic function call. So if you are truly testing just function a then you need to patch the \_actions object and just test the functionality in the scope of the function.
\_actions is out of the testing scope and should be tested individually like any other method.
```
from unittest import TestCase
from unittest.mock import patch
from stack_overflow import a,b,c, _actions
class TestStack(TestCase):
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
@patch.dict('stack_overflow._actions',{'b':b})
def test_a(self):
self.assertEqual(5,a('b'))
def test__actions_def_b(self):
self.assertEqual(_actions['b'],b)
def test__actions_def_c(self):
self.assertEqual(_actions['c'],c)
```
```
def a(type):
current_actions = _actions
return _actions[type]()
def b():
return 5
def c():
return 7
_actions = { 'b': b, 'c': c}
```
|
68,340,593 |
I wanted to activate outlets at the same time without using the "ugly" auxiliary outlet URL syntax.
And after playing with it, I have been surprised with the activation mechanism.
* With this routing configuration:
```
{ path: 'test', component: Test1Component },
{ path: 'test', component: Test2Component, outlet: 'two' },
{ path: 'test', component: Test3Component, outlet: 'three' }
```
and this root template:
```
<router-outlet></router-outlet>
<router-outlet name="two"></router-outlet>
<router-outlet name="three"></router-outlet>
```
when navigating to `/test`, I thought the 3 outlets would be implicitly activated, but only the primary is.
* Now with all 3 empty paths:
```
{ path: '', component: Test1Component },
{ path: '', component: Test2Component, outlet: 'two' },
{ path: '', component: Test3Component, outlet: 'three' }
```
when navigating to `/`, the 3 outlets are activated!
* And with the 2 auxiliary routes only:
```
{ path: 'test', component: Test2Component, outlet: 'two' },
{ path: 'test', component: Test3Component, outlet: 'three' }
```
when navigating to `/test`, I get `Error: Cannot match any routes. URL Segment: 'test'`, I have to individually & explicitly target the outlets: `/(two:test//three:test)`, for the 2 outlets to be activated.
Could someone please explain all this?
|
2021/07/11
|
[
"https://Stackoverflow.com/questions/68340593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14100191/"
] |
Since you already have a `rank` column, i assumed it is in the order of `[date]`
```
select *,
repetitions = row_number() over(partition by id, [color], grp
order by [rank])
from
(
select *,
grp = [rank] - dense_rank() over (partition by id, [color] order by [rank])
from yourtable
) d
order by id, [rank]
```
EDIT : missed out the `id` in the `dense_rank()` part
|
51,551,091 |
I have a git repository and I am on branch `A`. How can I pull the latest code to my local master branch without checking out to master? I know that I can do below code:
```
git checkout master
git pull
```
but if I have changed files in my current branch `A`. I have to either commit or stash it before changing to the master branch. Is there a way for me to do that in my current branch `A`?
I don't have any local commits in master since I always work on the personal branch and I use master only for read-only purpose.
|
2018/07/27
|
[
"https://Stackoverflow.com/questions/51551091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5421539/"
] |
If the `master` does not have any local commits, then it points to the very same commit as `origin/master`. In this case, it does not make much sense to have it. For whatever purpose you need a master, use can use the `origin/master`, so that you don't have to maintain the local `master`:
```
$ git branch <feature> origin/master # make new feature branch
$ git log ..origin/master # see what is new in the upstream
$ git diff origin/master...HEAD # see your changes
```
...etc.
|
72,872,174 |
I am trying to read and then update the first comment on my pull request page on GitHub via the command line but it seems that the API that GitHub is providing doesn't read the first comment but only subsequent comments. I am trying to implement a functionality similar to [this GitHub Action](https://github.com/marketplace/actions/sticky-pull-request-comment) (I just don't want to do it via GitHub actions).
[](https://i.stack.imgur.com/Y057D.png)
I tried using the API mentioned here to get the list of comments: <https://docs.github.com/en/rest/issues/comments#list-issue-comments>
But it lists all the comments except for the first one. I wanted to list all the comments so that I could grab the ID of the first comment and then I would update it. Any idea on how to do this?
|
2022/07/05
|
[
"https://Stackoverflow.com/questions/72872174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4441211/"
] |
The GitHub action you are refering to uses a [GraphQL call to update comments](https://github.com/marocchino/sticky-pull-request-comment/blob/6ffe2e8205ffb59b9e44d042109a13511fe2ea88/src/comment.ts#L73-L103=). Same for [reading comments](https://github.com/marocchino/sticky-pull-request-comment/blob/6ffe2e8205ffb59b9e44d042109a13511fe2ea88/dist/index.js#L43-L92=).
That means you can call (`curl`) those graphQL, as [in here for update](https://stackoverflow.com/questions/65837496/how-to-update-a-issue-or-pr-comment-in-github-using-curl-and-a-graphql-updateiss), from command-line.
```bash
curl -H "Authorization: bearer <REPLACE WITH YOUR GITHUB PERSONAL ACCESS TOKEN>" -X POST -d \
"{ \
\"query\": \"mutation { \
updateIssueComment(input: { \
id: \\\"REPLACE WITH COMMENT NODE ID\\\", \
body: \\\"This is fantastic\\\" \
}) { \
issueComment { \
lastEditedAt \
} \
} \
}\"
} \
" https://api.github.com/graphql
```
To read comments though, you will need to take into account [pagination](https://stackoverflow.com/a/64140209/6309).
|
504,158 |
I have a custom keyboard layout located in `/usr/share/X11/xkb/symbols/us`. Every time an update happens, this file is updated to the standard keyboard layout. Is there either a way to change this permanently, or a way to change this in userspace away from distro-level config?
If there is a better way to approach custom keyboard layouts, please let me know. As far as I am aware, the best way to approach this is with xkb symbols files, and there is not much documentaion for these.
Thanks.
|
2019/03/03
|
[
"https://unix.stackexchange.com/questions/504158",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/339833/"
] |
Make a directory tree under `/home/<user>/` which has the same structure as `/usr/share/X11/xkb/`. In other words:
```
$ tree -L 1
.
├── compat
├── geometry
├── keycodes
├── rules
├── symbols
└── types
```
So put the relevant files in `compat`, `symbols`, etc. You obviously don’t need to make empty directories, just the directories for the files that you need.
Then consider renaming your symbols file to something different than `us`. There might be a way to disambiguate your own `us` symbols file from the one under `/usr/share/X11/xkb/`, but it is easier to just pick a new name which doesn’t appear in `/usr/share/X11/xkb/symbols/`. `mine` will do fine.
Let’s say that you put your custom Xkb directory at `/home/<user>/my-xkb` and that your custom symbols file is named `mine`.
If you use `setxkbmap(1)` to set your layout you simply need to change it to print its output and pipe it to `xkbcomp(1)`. So if this is your `setxkbmap` invocation:
```
setxkbmap mine
```
You will need to change it to this:
```
setxkbmap mine -print |
xkbcomp -I"/home/<user>/my-xkb" - "$DISPLAY"
```
|
674,888 |
I have a series of numbers: $1,2,3$
I'm calculating a simple average between, them $(2)$.
Now, I'm deleting the series and have no information regarding how many elements there were in the series or what the series item values are, but I keep the average value $(2)$.
Now, I have another series: $4,5,6$. I calculate the average $(5)$.
Is it correct to say that if I take the previous series average $(2)$ and do a new average between it and the new series average $(5)$, I will always get an accurate result for the average of the combination of the two series (series$[1]$ and series$[2]$)?
|
2014/02/13
|
[
"https://math.stackexchange.com/questions/674888",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128469/"
] |
Yes, if the series contain the same amount of numbers. No, otherwise.
* If the series contain the same amount of numbers, you have $a\_1,\dots, a\_n$ and $b\_1,\dots,b\_n$. Now the average of the first is $a=\frac{a\_1+\cdots+a\_n}{n}$ and the second $b=\frac{b\_1+\cdots b\_n}{n}$. The average of $a$ and $b$ is
$$\frac{a+b}{2} = \frac{\frac{a\_1+\cdots+a\_n}{n}+\frac{b\_1+\cdots+b\_n}{n}}{2}=\frac{a\_1+\cdots+a\_n + b\_1+\cdots+b\_n}{2n}$$ which is the average of $\{a\_1,a\_2,\dots,a\_n,b\_1,b\_2,\dots,b\_n\}$.
* If the series are unbalanced, the general answe is no. If one series is $\{0\}$ and the second series is $\{1,1,1,1,1,1,1,1,\dots,1\}$ ( a set of $k$ ones), then the average of averages is always $\frac12$, while the real average of the combination is $\frac{k}{k+1}$. As $k$ becomes large, this value approaches $1$.
In general, the average of the combination of the two series is a convex combination of the individual averages. This can be seen by manipulating the formulas for the averages. If the series are $a\_1,\dots, a\_m$ and $b\_1,\dots, b\_n$, then the average is
$$\frac{a\_1+\cdots+a\_m+b\_1+\cdots b\_n}{m+n} = \frac{a\_1+\cdots +a\_m}{m+n}+\frac{b\_1+\cdots +b\_n}{m+n} =\\= \frac{m}{m+n}\frac{a\_1+\cdots +a\_m}{m}+\frac{n}{m+n}\frac{b\_1+\cdots +b\_n}{n} = \alpha a + \beta b$$
where $alpha = \frac{m}{m+n}$ and $\beta = \frac{n}{m+n}$ and $a,b$ are the averages of the individual series.
|
175,962 |
My research supervisor wanted to produce a cost-benefit analysis for an infrastructure project (civil engineering). First he had someone else work on it, then he involved me. When I got involved, I noticed that the benefits were inflated and the costs downplayed to convince the reader of a massive benefit-cost ratio. I do not know if he stands to personally gain from this. I discussed it with him a few times, he pushed back with "I am experienced and I know I am right", and eventually in the final revision of the paper he changed my numbers. The way he changed the numbers is not even smart, he just changed the text, he didn't redo the calculations. Now I fear that if I bend under pressure, these bad numbers will be out there, forever! I am sure he will take the published paper and send it to every politician in the country trying to get this project approved. What can I do? I am still his PhD student so I can't get too confrontational.
|
2021/09/27
|
[
"https://academia.stackexchange.com/questions/175962",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/147433/"
] |
Make absolutely sure you understand the numbers correctly before suspecting, or even worse, accusing your advisor of dishonesty.
The following text only applies if you have satisfied yourself that there is no way these numbers could have been reached in an honest way.
If you are absolutely convinced of this, get out of there, under whatever pretext. You do not need to confront your supervisor, for which you have little power at this stage; but get out.
You are not only in danger of damaging your academic reputation. If the study enters policy, you may be indirectly or directly made responsible for wastage of public money and could face potential legal consequences stemming from that.
If your supervisor is really into shady practices, he may even deflect any potential fallout that might transpire to his "dishonest" student coauthor; i.e. you.
Do not accuse him of that. You have no proof and it is almost impossible to establish facts in the constellation you are in. Just get out of the paper, and ideally, out of the PhD relation. Find an excuse.
You have my sympathies for a situation which no one should be ever be in.
|
19,041,160 |
```
SELECT
prc.user_key,
percentile(P.price, 0.5) OVER (PARTITION BY P.user_key) as median_price
FROM
(
SELECT
vfc.user_key,
vfc.order_id,
MIN(vddo.cc) price
FROM
td_b.mv_a vfc
JOIN
td_b.dim_deal_option vddo
ON vfc.d_key = vddo.d_key
WHERE
vfc.action = 'sale'
GROUP BY vfc.user_key, vfc.order_id
) prc limit 100;
```
Gives the error "FAILED: Parse Error: line 4:13 mismatched input '(' expecting FROM near 'OVER' in from clause"
in Hive. When i remove the percentile and partition query works fine, any idea? I tried count() instead of percentile, still the same error.
|
2013/09/27
|
[
"https://Stackoverflow.com/questions/19041160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2242666/"
] |
the percentile / partition line aliases the subquery with "P" (P.price and P.user\_key) but the subquery is "prc". Sometimes bad aliases will throw that error
|
668,912 |
if $$4x^2 - y^2 = 64$$
show that:
$$ds^2 = \frac4{y^2}(5x^2 - 16)dx^2$$
I'm not sure what to do. Could someone explain it to me? I tried solving for y and then plugging it into the Arc Length formula to see if anything clicked, but nothing looked right to me.
|
2014/02/08
|
[
"https://math.stackexchange.com/questions/668912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/124243/"
] |
**Hint:** The basic intuition behind the arc length formula is that a small arc of any (well-behaved) curve is approximately straight, so an infinitely small arc of a curve can be considered exactly straight. So by the Pythagorean theorem, $dx^2 + dy^2 = ds^2$. Now just use $d(4x^2-y^2) = d(64)$ to write $dy$ in terms of $dx$.
|
56,449,474 |
I have a modal I am including in my app and during the the checkout process, I `show` the modal. If the transaction fails, I hide the modal using `$('#my-modal').modal('hide')` but my issue is that when the user goes to enter the checkout process again and it shows the modal, it still has the data that was there before. Is it possible to destroy the instance so that the data doesn't persist that?
|
2019/06/04
|
[
"https://Stackoverflow.com/questions/56449474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11397091/"
] |
This is pretty simple to do using `.join()` and `.decode()`:
```
lst = [b'897', b'7W', b'7W', b'018', b'0998', b'0000']
b" ".join(lst).decode("utf-8")
```
Output:
```
'897 7W 7W 018 0998 0000'
```
In the case you need to do multiple:
```
lsts = [[b'897', b'7W', b'7W', b'018', b'0998', b'0000'], [b'897', b'7W', b'7W', b'018', b'0999', b'0000']]
formatted = [b" ".join(lst).decode("utf-8") for lsts in list]
```
Output:
```
['897 7W 7W 018 0998 0000', '897 7W 7W 018 0999 0000']
```
|
49,966,243 |
I have this GridLayout:
```
<!--back-->
<GridLayout
android:id="@+id/back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="3"
android:columnCount="5">
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
<ImageView
android:src="@drawable/noTexture"/>
</GridLayout>
```
The images contained therein look like this:
[](https://i.stack.imgur.com/Op2Ed.png)
How to make the images distribute on the screen in a uniform way, ie, occupy all the space until the end so that both have the same size?
|
2018/04/22
|
[
"https://Stackoverflow.com/questions/49966243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9360882/"
] |
If you look at the documentation of Laravel at the Many to Many section <https://laravel.com/docs/5.6/eloquent-relationships#many-to-many> it's already explained in there. If you're planning to keep using Laravel I would recommend using the best practises of Eloquent. It's easier to understand and read for other developers. It's always worth to make your product the best you can. It also gives possibilities to quickly extend and maintain your application.
**All you need to do is to define a relationship in your model clinics**
```
// second, third and fourth parameter could also be optional
function departments(){
return $this->belongsToMany('App\Clinics', 'clinics_in_departments', 'department_id', 'clinic_id');
}
```
**To retrieve the data you can use**
```
$clinics = Clinics::with('departments')->get();
// this would hold a list of departments for each clinic
```
**To get exactly the same data extend the query to this**
```
$clinics = Clinics::with('departments')->whereIn('clinic_id',[1,2,3])->get();
```
Because it's a Many to Many relationship you could also define a relationship for the model **Departments** and do exactly the same as mentioned above.
|
47,625 |
I'm using SP2010, and am working at the moment in SPD 2010. I have a site, and am trying use a copy of v4.master as the site master page.
So, in SPD...
(I got two different books on SPD, and they basically describe the process as this)
* I create a copy of v4.master
* check it out
* rename it, leaving the extension as '.master'
* save it
* check it back in.
* right click on the renamed file, and pick 'Set as Default Master Page'\*.
So in the browser, I hop over to Site Settings > Master Page, and get "The site master page setting currently applied to this site is invalid. Please select a new master page and apply it" along with a big ol' yellow warning icon. And of course, the renamed master page is not availabe in the select menus for master pages.
* that last step in my instructions, I've tried 'Set as Custom Master Page', both, and neither. Basically exhausted the boolean possibilities there. No luck.
I'm stumped. I've looked at plenty of posts here, and on stackoverflow. Google has not been kind today, either.
So folks, how do I get my copy of v4.master to be the master page for my site? I'm at a loss.
|
2012/10/10
|
[
"https://sharepoint.stackexchange.com/questions/47625",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/5910/"
] |
Master pages need to be approved before use. Between the last 2 steps, you should approve the master page in the browser and then apply it as the default master page in SPD.
|
2,370,123 |
<http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/>
The dictionary does what I need but I do need to care about performance. Does anybody know if the Dictionary is implemented as a hashtable?
Or more specifically, does it perform in O(1)?
|
2010/03/03
|
[
"https://Stackoverflow.com/questions/2370123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85821/"
] |
it acts as a hashmap. in fact, every ActionScript object that is an instance of a dynamic class, acts as hashmap. of course keys can always collide with properties. this behaviour comes from JavaScript. I consider it a design failure.
Array is different in that it will perform some tricks on integer keys, and Dictionary is different in that it doesn't convert keys to strings, but uses any object value as key. Please note that Number and Boolean are both converted to String.
now why whould you care how it is implemented? if it is well implemented, you probably don't wanna know. You can benchmark it. It has O(1) for all operations and is reasonably fast (inserting costs a about twice as much time as an empty method call, deleting costs less). Any alternative implementation will be slower.
here a simple benchmark (be sure to compile it for release and run it in the right player):
```
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.utils.*;
public class Benchmark extends Sprite {
public function Benchmark() {
var txt:TextField = new TextField();
this.addChild(txt);
txt.text = "waiting ...";
txt.width = 600;
const repeat:int = 20;
const count:int = 100000;
var d:Dictionary = new Dictionary();
var j:int, i:int;
var keys:Array = [];
for (j = 0; j < repeat * count; j++) {
keys[j] = { k:j };
}
setTimeout(function ():void {
var idx:int = 0;
var out:Array = [];
for (j = 0; j < repeat; j++) {
var start:int = getTimer();
for (i = 0; i < count; i++) {
d[keys[idx++]] = i;
}
out.push(getTimer() - start);
}
txt.appendText("\n" + out);
start = getTimer();
for (var k:int = 0; k < i; k++) {
test();
}
txt.appendText("\ncall:"+(getTimer() - start));
idx = 0;
out = [];
for (j = 0; j < repeat; j++) {
start = getTimer();
i = 0;
for (i = 0; i < count; i++) {
delete d[keys[idx++]];
}
out.push(getTimer() - start);
}
txt.appendText("\n" + out);
},3000);//wait for player to warm up a little
}
private function test():void {}
}
}
```
|
7,249,829 |
When trying to commit changes in emacs (win32) and svn (vc mode) I got:
```
Error validating server certificate for ...:
- The certificate is not issued by a trusted authority. Use the
fingerprint to validate the certificate manually!
...
(R)eject, accept (t)emporarily or accept (p)ermanently?
```
That's OK, but how can I answer the question? When I press 'p' I got "No previous log message" line in minibuf. How to interact in emacs with running svn process?
|
2011/08/30
|
[
"https://Stackoverflow.com/questions/7249829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
When initialising neural networks, including the recurrent Hopfield networks, it is common to initialise with random weights, as that in general will give good learning times over multiple trials and over an ensemble of runs, it will avoid local minima. It is usually not a good idea to start from the same starting weights over multiple runs as you will likely encounter the same local minima. With some configurations, the learning can be sped up by doing an analysis of the role of the node in the functional mapping, but that is often a later step in the analysis after getting something working.
|
6,682,545 |
I need a Map container that contains either an
>
> `Item Object`
>
>
>
or
>
> `List<Item> Object`
>
>
>
as its value, and I can get it out without casting, is it possible?
|
2011/07/13
|
[
"https://Stackoverflow.com/questions/6682545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241824/"
] |
Short answer: No.
[Union types](http://en.wikipedia.org/wiki/Union_%28computer_science%29) don't exist in Java. The closest thing you could do in order to get compile-time type checking would be to create list of some custom wrapper class which contained *either* an `A` or a `List<A>`, something like the following:
```
public class UnionListWrapper<A> {
private final A item;
private final List<A> list;
public UnionListWrapper(A value) {
item = value;
list = null;
}
public UnionListWrapper(List<A> value) {
item = null;
list = value;
}
public Object getValue() {
if (item != null) return item;
else return list;
}
}
```
At least you wouldn't be able to *create* instances of this class that weren't either an `A` or a `List<A>`, but getting the value back out would still have to just be `Object`, with associated casting. This could get quite clumsy, and on the whole it's probably not worth it.
In practice I'd probably just have a `List<Object>` with some comments around being very careful about what data types are accepted. The problem is that even run-time checks (sub-optimal) aren't going to be possible, since Java's generic erasure means that you can't do an `instanceof A` check at runtime (doubly so on the generic parameter of the `List`).
|
73,041,304 |
I am trying to re-populate the saved form inputs after a submit/page reload. The problem I'm running into is the input field populates the saved value (or just any string) but then resets almost immediately. What am I missing? Thanks
**Flask (Server):**
```
@app.route("/code", methods=["GET", "POST"])
def code():
value = request.form["field1"]
return render_template(
"code.html",
saved_inputs = value
)
```
**Html:**
```
<form action="{{ url_for('code') }}" method="post" id="form">
<label for="field1">Test Input 1 </label>
<input type"text" name="field1" id="field1">
<button type="submit" class="btn btn-primary" id="btnSubmit">Submit</button>
</form>
```
**JS:**
```
<script>
$("#form").on('submit', function(event){
event.preventDefault();
// convert form to JSON
var formData = new FormData(document.getElementById('form'));
var formJSON = {};
for (var entry of formData.entries())
{
formJSON[entry[0]] = entry[1];
}
result = JSON.stringify(formJSON)
console.log("results is: "+result);
// set JSON to local Storage
sessionStorage.setItem('formObject', result);
// submit form
document.getElementById("form").submit();
// decode sessionstorage object
var decodedObj = JSON.parse(sessionStorage.getItem('formObject'));
console.log("sessionStorage object: "+decodedObj);
// alert("value is: "+decodedObj["field1"]);
// alert("jinja value is: "+"{{ saved_inputs }}");
// retrieve localStorage and populate input
// this is not working as expected
document.getElementById("field1").value = "WHY ISN'T THIS SAVING??";
// document.getElementById("field1").value = '{{ saved_inputs }}';
})
</script>
```
|
2022/07/19
|
[
"https://Stackoverflow.com/questions/73041304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3538178/"
] |
I think the issue you are facing is that you are not checking when the page loads--only when the form is submitted. To load the form on page load we can use sessionStorage to check if the record exists and then load the object to the form.
```
$(function() {
const formObj = sessionStorage.getItem('formObject');
// Load object
if (formObj != null) {
console.log("Previous form session exists")
let decodedObj = JSON.parse(formObj);
console.log("sessionStorage object: " + decodedObj);
console.log("value is: " + decodedObj["field1"]);
// retrieve sessionStorage and populate input
console.log("Loading previous session");
document.getElementById("field1").value = decodedObj["field1"];
}
});
```
[Proof of concept fiddle](https://jsfiddle.net/Lv5wqzkc/)
|
27,070,220 |
I'm trying to update the items of a recycleview using notifyDataSetChanged().
This is my onBindViewHolder() method in the recycleview adapter.
```
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
//checkbox view listener
viewHolder.getCheckbox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update list items
notifyDataSetChanged();
}
});
}
```
What I want to do is update the list items, after I check a checkbox. I get an illegal exception though: `"Cannot call this method while RecyclerView is computing a layout or scrolling"`
```
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:1462)
at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:2982)
at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:7493)
at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:4338)
at com.app.myapp.screens.RecycleAdapter.onRowSelect(RecycleAdapter.java:111)
```
I also used notifyItemChanged(), same exception. Any secret way to update to notify the adapter that something changed?
|
2014/11/21
|
[
"https://Stackoverflow.com/questions/27070220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850879/"
] |
You should move method 'setOnCheckedChangeListener()' to ViewHolder which is inner class on your adapter.
`onBindViewHolder()` is not a method that initialize `ViewHolder`.
This method is step of refresh each recycler item.
When you call `notifyDataSetChanged()`, `onBindViewHolder()` will be called as the number of each item times.
So If you `notifyDataSetChanged()` put into `onCheckChanged()` and initialize checkBox in `onBindViewHolder()`, you will get IllegalStateException because of circular method call.
click checkbox -> onCheckedChanged() -> notifyDataSetChanged() -> onBindViewHolder() -> set checkbox -> onChecked...
Simply, you can fix this by put one flag into Adapter.
try this,
```
private boolean onBind;
public ViewHolder(View itemView) {
super(itemView);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkboxId);
mCheckBox.setOnCheckChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!onBind) {
// your process when checkBox changed
// ...
notifyDataSetChanged();
}
}
...
@Override
public void onBindViewHolder(YourAdapter.ViewHolder viewHolder, int position) {
// process other views
// ...
onBind = true;
viewHolder.mCheckBox.setChecked(trueOrFalse);
onBind = false;
}
```
|
8,130,089 |
Environment: WinXP; PowerBuilder 11.5 (though probably not relevant because this portion is almost entirely WinAPI calls)
My application opens a COM port for writing using overlapped method calls. The port is opened when the application is opened. The app leaves the port open at all times.
Occasionally, the attached device stops receiving data even though the app is still sending data. The app receives no error messages. Stopping and restarting the app doesn't fix it. Rebooting the computer doesn't fix it. However, connecting via hyperterminal fixes it.
This particular device prints barcode labels. The app will be printing just fine, then suddenly, it won't print. Close the app; open and connect with hyperterminal; disconnect and close hyperterminal; open the app. It works just fine again... for a while. (I've had similar issues with other devices that also communicate via COM port, so I know it's not the device itself.)
The closest similar issue I can find on the web is at <http://www.eggheadcafe.com/microsoft/Windows-XP-Hardware/30829577/com1-not-behaving.aspx> which speaks of IRQ conflicts and offers no solution. I can only guess that my problem is similar.
Does anyone know what hyperterminal might be doing to clear things up?
|
2011/11/15
|
[
"https://Stackoverflow.com/questions/8130089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103701/"
] |
See my blog post for the working solution: <https://medium.com/cagataygurturk/load-a-bootstrap-popover-content-with-ajax-8a95cd34f6a4>
>
> First we should add a data-poload attribute to the elements you would
> like to add a pop over to. The content of this attribute should be the
> url to be loaded (absolute or relative):
>
>
>
```
<a href="#" title="blabla" data-poload="/test.php">blabla</a>
```
>
> And in JavaScript, preferably in a $(document).ready();
>
>
>
```
$('*[data-poload]').hover(function() {
var e=$(this);
e.off('hover');
$.get(e.data('poload'),function(d) {
e.popover({content: d}).popover('show');
});
});
```
>
> `off('hover')` prevents loading data more than once and `popover()` binds
> a new hover event. If you want the data to be refreshed at every hover
> event, you should remove the off.
>
>
> Please see the working [JSFiddle](https://jsfiddle.net/DTcHh/6415/) of the example.
>
>
>
|
34,917,932 |
Im trying to pass parameters through @Output but the fired function just receive 'undefined'. Can someone please show me the way to pass parameters through the EventEmitter of the @Output? For Example:
```
var childCmp = ng.core.Component({
selector:'child-cmp',
outputs: ['myEvent']
}).Class({
constructor: function(){
this.myEvent = new ng.core.EventEmitter();
this.myEvent.emit(false);
}
});
var parentCmp = ng.core.Component({
selector:'parent-cmp',
template:'<child-cmp (myEvent)="invoke()"'></child-cmp>',
directives: [childCmp]
}).Class({
constructor:function(){},
invoke: function(flag){
// here flag is undefined!!
}
});
```
|
2016/01/21
|
[
"https://Stackoverflow.com/questions/34917932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5774953/"
] |
You shoud use the following to get the value provided with the event:
```
<child-cmp (myEvent)="invoke($event)"'></child-cmp>'
```
This way the `invoke` method of your `childCmp` will receive as parameter the value you provide when emitting the `myEvent` custom event.
Hope it helps you,
Thierry
|
23,961 |
Coming from a denomination that doesn't subscribe to one earthly central Church authority, or a rigid structure, I find it very interesting to learn about denominations that do have such a structure. While browsing through the "Gospel Topics" section on the LDS website, I ran across the article on Tithing, which says this:
>
> Church members give their tithing donations to local leaders. These
> local leaders transmit tithing funds directly to the headquarters of
> the Church, where a council determines specific ways to use the sacred
> funds. This council is comprised of the First Presidency, the Quorum
> of the Twelve Apostles, and the Presiding Bishopric. Acting according
> to revelation, they make decisions as they are directed by the Lord.
> (See D&C 120:1.)
>
>
>
That's a very clear, understandable high-level explanation of the process including who makes the decisions.
Before getting to the question, here's a high-level explanation of my Church's process and who makes the decisions.
In my own Church (A Baptist one) it's handled in a more straightforward democratic fashion. Once per year, the Pastor puts together a budget of *anticipated* expenses (by category - Pastoral care, Sunday School Supplies, etc.) and *anticipated* income (based on last year's Tithes, growth trends, etc.), and presents it to the Church. The Church (meaning the voting (age 18+) members of the local Church) discuss and vote on the budgets. Usually we accept the Pastor's budget, but we may discuss and adjust certain line-items. Then, throughout the year, as needs arise, they are met if they fall within the budget. The Pastor has some leeway on certain items. For example, we have a line item for "Needs of others", and the Pastor can dole that out to individuals in need at his discretion.
One last thing before the actual question, I really am interested in how this is handled in other denominations, but I don't want to turn this into a "list" question. And I don't want to re-post the same question over and over naming different denominations in each. So I'm going to focus on one Church with a central authority and a well-defined structure that interests me, and ask about them.
---
Without further ado: In the Catholic Church, can someone provide an overview of who makes the broad financial decisions, and what is the process?
|
2013/12/20
|
[
"https://christianity.stackexchange.com/questions/23961",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/721/"
] |
The simple answer is: "it's very complicated". Individual churches, dioceses, national councils of bishops, religious orders, houses of those religious orders, the dicasteries of the Roman Curia, institutions like schools and hospitals: they are all to some extent independent and to some extent related. The Catholic Church is not a simple organisation, and it doesn't have a simple financial structure.
In particular, it is complicated because the exact pattern is not replicated in every country. The national Episcopal Conferences have some degree of autonomy in setting a pattern which will apply in each country, according to what is appropriate. Moreover, the *Vatican* finances are both complex and opaque. Some income comes directly from donations from the faithful (a system known as Peter's Pence), while other income comes from the surplus from the *Istituto per le Opere di Religione*, the Vatican Bank.
There isn't a simple organisational structure, with the Vatican at the top and the parishes at the bottom and a simple flow of money up and down the chain. This is because the basic structure of the Catholic Church is based around is that of the *particular church*. This is generally (though not always) a diocese. It is *local* (that is to say, defined by geography) and headed by a *bishop*. [(Code of Canon Law, Canon 368)](http://www.intratext.com/IXT/ENG0017/_P1B.HTM) If you want some of the theology behind this, the document [*Communionis Notio*](http://www.vatican.va/roman_curia/congregations/cfaith/documents/rc_con_cfaith_doc_28051992_communionis-notio_en.html) is relevant.
The diocese are institutionally independent of one another, though they are grouped in the national/regional Episcopal Conferences which have certain legislative powers in their region, and they are all subject to the Canon Law of the Catholic Church. Each diocese is divided into parishes. The priests in each parish are essentially "deputies" for the bishop.
The financial relationship that we might consider best, therefore, is between the diocese and the parish. (The financial organisation of the Vatican would take years to analyse fully!) The parish-diocese relationship is the most common financial relationship. It leaves a whole lot out, as you see from my opening paragraph. So let's look at one such example. I'm going to look at the Roman Catholic Diocese of Westminster and it's 2011 financial statement, for the simple reason that [I could find it online](http://rcdow.org.uk/att/files/diocese/2011+dow+annual+report+low-res+final+version.pdf).
The parishes receive income of various types (p19):
* collections, donations and legacies (by far the largest)
* parish activities
* investment income
* rent
* trading income
* disposal of assets
This is spent in various ways (p21). The largest are non-clergy salaries and parish assessments, which are in effect a diocesan tax: each parish provides a proportion of their income to the diocese. This proportion varies among Episcopal Conferences and possibly among dioceses: I haven't found any clear information.
In each parish, the parish priest is primarily in charge of finances:
>
> In all juridic affairs the pastor represents the parish according to the norm of law. He is to take care that the goods of the parish are administered according to the norm of cann. 1281-1288. [(Canon 532)](http://www.vatican.va/archive/ENG1104/_P1U.HTM#1CT)
>
>
>
On top of this, there is to be a finance council in each parish:
>
> In each parish there is to be a finance council which is governed, in addition to universal law, by norms issued by the diocesan bishop and in which the Christian faithful, selected according to these same norms, are to assist the pastor in the administration of the goods of the parish, without prejudice to the prescript of can. 532. [(Canon 537)](http://www.vatican.va/archive/ENG1104/_P1U.HTM#1V4)
>
>
>
So many decisions are taken on a local basis, by the priest with the advice of the finance council.
At a diocesan level, most income comes from the parish assessments mentioned above (p20 of the Diocese of Westminster report). In the diocese, there is again a finance council to manage finances:
>
> In every diocese a Finance council is to be established, offer which the diocesan bishop himself or his delegate presides and which consists of at least three members of the Christian faithful truly expert in Financial affairs and civil law, outstanding in integrity, and appointed by the bishop. [(Canon 492)](http://www.vatican.va/archive/ENG1104/__P1Q.HTM)
>
>
>
The function of this council is to provide "a budget of the income and expenditures which are foreseen for the entire governance of the diocese in the coming year".
---
So a short summary.
Most income comes to individual parishes. The parish priest is in charge of this, with the assistance of a finance council. A proportion of income goes from the parish to the diocese, where a finance council appointed by and presided over by the bishop is in charge of decisions concerning the governance of the diocese.
This is obviously not the whole picture. It covers only the parishes and diocese. These are the most significant aspect of the Church, but a lot more could be said about the various other aspects of the Church on local, national, regional and international levels. Moreover, to some extent these relationships vary significantly across the world.
|
38,362,973 |
When the `DebugTree` logs, I see the class name, however when I create a custom Tree, the tag is `null`. Here what my custom tree looks like:
```
public class CrashlyticsTree extends Timber.Tree {
private static final String CRASHLYTICS_KEY_PRIORITY = "priority";
private static final String CRASHLYTICS_KEY_TAG = "tag";
private static final String CRASHLYTICS_KEY_MESSAGE = "message";
@Override
protected boolean isLoggable(int priority) {
if (priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO) {
return false;
}
// only log WARN(Timber.w), ERROR(Timber.e), or WTF(Timber.wtf)
return true;
}
@Override
protected void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable t) {
if(User.CurrentUser.isLoggedIn()){
Crashlytics.setUserIdentifier(Long.toString(User.CurrentUser.getUserId()));
}
Crashlytics.setInt(CRASHLYTICS_KEY_PRIORITY, priority);
Crashlytics.setString(CRASHLYTICS_KEY_TAG, tag);
Crashlytics.setString(CRASHLYTICS_KEY_MESSAGE, message);
if (t == null) {
Crashlytics.logException(new Exception(message));
} else {
if(!TextUtils.isEmpty(message)){
Crashlytics.log(priority, tag, message);
}
Crashlytics.logException(t);
}
}
}
```
However even from the DebugTree, the tag that gets generated is `BaseActivity` because it does come from the `BaseActivity` however I was wondering if there was a way I can get the name of the class that extends BaseActivity
|
2016/07/13
|
[
"https://Stackoverflow.com/questions/38362973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113823/"
] |
According to Jake Wharton:
>
> The `tag` is null unless you call `tag(String)` at the log site or extend from `DebugTree` (which you shouldn't do for production logging).
>
>
>
Therefore you need to add `Timber.tag([class name])` before each call.
See [github.com/JakeWharton/timber/issues/122](https://github.com/JakeWharton/timber/issues/122)
|
52,206,667 |
In a DB2-400 SQL join, can the `USING()` clause be used with one or more AND ON clauses for a single join..? This is for a situation where *some* field names are the same, but *not all*, so USING() would only apply to *part* of the join.
I could have sworn I've done this before and it worked, but now it eludes me.
I've tried various combinations as shown below, but none of them work. Perhaps I'm simply mistaken and it's not possible:
```
SELECT * FROM T1 INNER JOIN T2 USING (COL1,COL2) AND ON (T1.COL3=T2.COL4)
SELECT * FROM T1 INNER JOIN T2 ON (T1.COL3=T2.COL4) AND USING (COL1,COL2)
SELECT * FROM T1 INNER JOIN T2 ON (T1.COL3=T2.COL4), USING (COL1,COL2)
SELECT * FROM T1 INNER JOIN T2 USING (COL1,COL2,(1.COL3=T2.COL4))
```
|
2018/09/06
|
[
"https://Stackoverflow.com/questions/52206667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2705042/"
] |
Try this:
```js
$(document).on("click", ".w3-modal",function(event) {
$(this).hide(); // hide when clicked
});
// if you want to hide when clicked outside try something like this
/*
$(document).on("click",function(event) {
var $tgt = $(event.target);
if (!$tgt.is(".w3-modal") && !$tgt.is(".modalbut")) $(".w3-modal").hide(); // hide when clicked outside
});
*/
// These are the new code for using the ESC key (keycode = 27), but I have not had any luck
$(document).keydown(function(e) {
var code = e.keyCode || e.which;
if (code == 27) $(".w3-modal").hide();
});
```
```css
#service1 {
display: none
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="modalbut button" onclick="document.getElementById('service1').style.display='block'"> Some Text
</button>
<div id="service1" class="w3-modal w3-margin-top">
<div class="w3-modal-content w3-card-4 w3-animate-top" style=" top:50px; width:61%; height:auto">
<header class="w3-container" style="height:auto;
background-color:#FE0565 ; color:#fff ;">
<span onclick="document.getElementById('service1').style.display='none'">
<i class="fa fa-close"></i></span>
<h2 style="text-align: center; font-size:34px; position:
relative;width:54%;margin-left:20%; top:0px;
text-decoration: underline"><b>Hard Drive</b></h2>
</header>
<div style="height:200px;">
<p></p>
</div>
<footer class="container" style="background-color:
#FE0565; color:#fff;">
<a href="/#">
<h3>For More Info Click Here</h3>
</a>
<span onclick="document.getElementById('service1').style.display='none'">
<i class="fa fa-close"></i></span>
</footer>
</div>
</div>
```
|
19,608,979 |
What is the best approach to creating elements in JavaScript? I know about creating element using:
string example:
```
var div="<div></div>"
```
And another way is using
```
document.CreateElement('div').
```
Which one is the best method to achieve high performance? Is there is any other way to achieve this?
|
2013/10/26
|
[
"https://Stackoverflow.com/questions/19608979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2510093/"
] |
There is no single "best" approach, the best thing to do varies with the situation.
You basically have two choices:
1. Use the DOM methods to create elements (`document.createElement('tagName')`) and append/insert them into the DOM (`appendChild`, `insertBefore`), or
2. Use `innerHTML` on an existing element, assigning an HTML string to it; the browser will parse and render the HTML.
It used to be, just a couple of years ago, that `innerHTML` was a lot faster. But modern versions of browsers have improved the speed of DOM access dramatically, so really it comes down to what works best for the overall task you're performing.
|
25,720,446 |
I have a question about the md5 hash from an image. I have already written an android app which generates the md5 hash from every image it takes and saves the image under this filename. When I compare the string with a program on my Windows PC it is exact the same string. Even online generators generate the same string. So I think everything works fine on Android.
Now it comes to iOS... I don't know what and how, but iOS7 changes every Image it gets. (I think).
For example:
If I make a photo, generate the hash from this picture and save it on my Android or Desktop it has an other hash then it had on the iPhone.
I even tried to save one of my images through safari on my iPhone and then sendet it back to my desktop. Tada, I got another hash then before. Even the size of the picture is different (about 300b).
Can someone tell me what Apple is doing here and how to avoid this? How can I compare images downloaded from a server on an android and iOS device if the hash will never be the same?
I'm using the hash to compare if the picture was correctly downloaded from my server, but under this circumstances it doesn't work under iOS.
I have read a similar article here: [IOS UIImage data differ with android image (for image downloaded from google)](https://stackoverflow.com/questions/24562540/ios-uiimage-data-differ-with-android-image-for-image-downloaded-from-google)
But there was no direct answer to this. I believe that the md5 Method from iOS works correct, but I think iOS does "things" with images so that the md5 is always different.
Thank you.
edit:
here is my code for generating a hash:
```
+(NSString*)getHash:(UIImage *)bild{
NSData *imageData = UIImagePNGRepresentation(bild);
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(imageData.bytes, imageData.length, md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
NSLog(@"Result: %@",output);
return output;
}
```
|
2014/09/08
|
[
"https://Stackoverflow.com/questions/25720446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2830759/"
] |
Author of the `maven-jaxb2-pugin` here.
`target/generated-sources/xjc` IS the proper directory. This is how generated code is handled in Maven builds, you never generate anything into `src/main/java`.
The `maven-jaxb2-plugin` also adds this directory to the Maven's sources directories. You just have to make sure that this directory is considered a source directory by your IDE. In Eclipse, m2eclipse plugin does this automatically when you do "Update project".
See [this part of the docs](http://confluence.highsource.org/display/MJIIP/User+Guide#UserGuide-AddingtargetdirectoryasMavensourcedirectory).
|
21,976,550 |
I'm making an Xpath as part of a scraping project I'm working on. However, the only defining feature of the text I want is the `title` attribute of the enclosing `<a>` tag like so:
```
<a href="lalala" title="This is what I want to refer to">This is what I want to scrape</a>
```
Is it at all possible to refer to that title and create a path like this?
```
//tr/td[style='vertical-align:top']/a[title='Vacancy details']
```
|
2014/02/24
|
[
"https://Stackoverflow.com/questions/21976550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424333/"
] |
Attributes in XPath expressions need to be prefixed with the `@` symbol...
```
//tr/td/a[@title='Vacancy details']
```
|
28,625,140 |
I have problems with dependencies in Maven-Java. My problem is that two modules have a dependency with different versions and these versions are incompatible. Can I solve it?
A example of the problem
I have three modules (MA, MB and MC) and two libraries (LA and LB), LA has two versions (v1 and v2) and they are incompatible
The first module, MA, contains the main class and It depends on MB and MC
MB module depends on LA v2.
MC module depends on LB version.
LB version depends on LA v1.
Finally, the tree of dependencies is the following:
```
MA
| - MB
| | - LA (v2)
| - MC
| | - LB
| | | LA (v1)
```
|
2015/02/20
|
[
"https://Stackoverflow.com/questions/28625140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3567642/"
] |
I do not know if you consider. In Maven exists one thing called **Exclusions**.
Extracted from the documentation:
>
> Since maven 2.x resolves dependencies transitively, it is possible for
> unwanted dependencies to be included in your project's classpath.
> Projects that you depend on may not have declared their set of
> dependencies correctly, for example. In order to address this special
> situtation, maven 2.x has incorporated the notion of explicit
> dependency exclusion. Exclusions are set on a specific dependency in
> your POM, and are targeted at a specific groupId and artifactId. When
> you build your project, that artifact will not be added to your
> project's classpath by way of the dependency in which the exclusion
> was declared.
>
>
>
Here the link, maybe it could help you to implement the configuration in your pom.xml --> [Maven Exclusions](http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html)
|
254,521 |
It is renowned that removing a point from an $\infty-$dimensional vector space $H$ preserves its contractibility (by Kuiper's theorem).
Is there any hope that $H\setminus A$ is not contractible, where $A$ is a disjoint union of points (possibly infinitely many, but still countable)?
|
2016/11/12
|
[
"https://mathoverflow.net/questions/254521",
"https://mathoverflow.net",
"https://mathoverflow.net/users/101032/"
] |
No, at least if $H$ is Banach. The argument is similar to [this MO post](https://mathoverflow.net/a/215930/40804) that proves $\Bbb R^3 \setminus S$, where $S$ is some countable set, is simply connected.
Let $S \subset H$ be a countable set. Fix a map $i: S^n \to H \setminus S$; let $X = F(D^n,\partial S^n; H)$ be the space of null-homotopies of $i$: the space of continuous maps $D^n \to H$ that restrict to $i$ on the boundary, equipped with the compact-open topology. As long as $H$ is at least an [F-space](https://en.wikipedia.org/wiki/F-space), $X$ is completely metrizable, so the Baire category theorem applies. Enumerating $S$, let $X\_k$ be the space of null-homotopies whose image does not contain $k$. if $H$ is Banach, we can use smooth approximation and the Sard-Smale transversality theorem to see that the $X\_k$ are open, dense, nonempty sets, and because Baire applies to $X$ the intersection $\bigcap\_k X\_k$ is nonempty, providing a null-homotopy of $i$. More generally we can delete the union of countably many finite-dimensional submanifolds of $X$ and preserve (weak!) contractibility.
It seems like an interesting question to ask which topological vector spaces always have $H \setminus S$ weakly contractible.
|
61,474,918 |
I have an assignment in which one of the methods of class creates a tree node of generic type T.
|
2020/04/28
|
[
"https://Stackoverflow.com/questions/61474918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12212507/"
] |
There is no such thing built in Redis.
But, Redis does support [keyspace notifications](https://redis.io/topics/notifications) which provides a way to register for `Expired` event.
You can register a client that will react on such event and refresh the cache.
Another option is to use [RedisGears](https://redisgears.io) and [register](https://oss.redislabs.com/redisgears/functions.html#register) on `expired`--> `register(eventTypes=['exired'])` event such that each time an expire event is triggered your function that runs embedded in Redis will refresh the data.
|
19,384,421 |
I want to simply return a value from sub report to main report, but always shows `null` when the report is executed. Using iReport 5.1.0.
Main report
===========
```
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report4" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ce028d85-f7e8-4abd-ad6b-e3b2ba04d14e">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
<defaultValueExpression><![CDATA["C:\\Users\\DellXFR\\"]]></defaultValueExpression>
</parameter>
<variable name="z" class="java.lang.Integer" calculation="System">
<variableExpression><![CDATA[8]]></variableExpression>
</variable>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch"/>
</title>
<detail>
<band height="125" splitType="Stretch">
<subreport>
<reportElement uuid="0c501730-d98a-4982-9953-2939f127ad9e" x="40" y="10" width="200" height="100"/>
<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
<returnValue subreportVariable="x" toVariable="z"/>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "report4_subreport1.jasper"]]></subreportExpression>
</subreport>
<textField evaluationTime="Band">
<reportElement uuid="9020a8d9-5799-4907-b8a3-704f41ffdcc0" x="399" y="73" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$V{z}]]></textFieldExpression>
</textField>
</band>
</detail>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
```
Subreport
=========
```
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report4_subreport1" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="78290b3a-34c2-496e-86ff-e213ca2c1039">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<queryString language="SQL">
<![CDATA[select * from ot;]]>
</queryString>
<field name="salscheme_id" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="ot_amount" class="java.lang.Double">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<variable name="x" class="java.lang.Integer">
<variableExpression><![CDATA[1]]></variableExpression>
</variable>
<group name="salscheme_id">
<groupExpression><![CDATA[$F{salscheme_id}]]></groupExpression>
</group>
<background>
<band splitType="Stretch"/>
</background>
<detail>
<band height="125" splitType="Stretch"/>
</detail>
</jasperReport>
```
|
2013/10/15
|
[
"https://Stackoverflow.com/questions/19384421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486322/"
] |
Pass variables from subreport to main report as follows:
1. In the main report, create a variable:
```xml
<variable name="subReportValue" class="java.lang.Integer"/>
```
Note: Do **not** set calculation value.
2. In the subreport, also create a variable:
```xml
<variable name="returnValue" class="java.lang.Integer" calculation="First">
<variableExpression><![CDATA[$F{myField}]]></variableExpression>
</variable>
```
Set the calculation and what you like to return. Note: Respect the **class value** of the main report variable, they need to be **same class**.
3. In the main report, set the subreport return value in the subreport tag:
```xml
<returnValue subreportVariable="returnValue" toVariable="subReportValue"/>
```
4. If you like to put the `subReportValue` in the detail band, just must set the `evalutationTime` of the `textField`, hence it needs to be after subreport (otherwise its still null).
```xml
<textField evaluationTime="Band">
<reportElement x="251" y="109" width="100" height="20"/>
<textElement lineSpacing="Single"/>
<textFieldExpression class="java.lang.Integer"><![CDATA[$V{subReportValue}]]></textFieldExpression>
</textField>
```
If it is not in the detail band set `evaluationTime="Report"` for grouping. To understand the different evaluationTime see [EvaluationTimeEnum](http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/type/EvaluationTimeEnum.html)
Re-compile the subreport when finished, since the main report references the compiled `.jasper` file, not the `.jrxml` source.
|
316,897 |
Let $\left(\Omega,\mathcal{A}\right)$ be a measurable space and let $\mathcal{B}$ be a sub-$\sigma$-algebra of $\mathcal{A}$. Let $g,f\_1,f\_2, f\_3,\dots$ be real-valued functions with domain $\Omega$ that are non-negative and measurable w.r.t. $\mathcal{A}$. Suppose each $f\_n$ is measurable w.r.t. $\mathcal{B}$ and that $f\_n\rightarrow g$ pointwise. Is $g$ measurable w.r.t. $\mathcal{B}$? If this is not generally the case, will it be so under stricter requirements e.g. that the space be $\sigma$-finite or finite relative to some measure?
P.S. The reason why i'm interested in this question is because i'm reading the article "Application of the Radon-Nykodim Theorem to the Theory of Sufficient Statistics" by Halmos and Savage ([link](https://projecteuclid.org/journals/annals-of-mathematical-statistics/volume-20/issue-2/Application-of-the-Radon-Nikodym-Theorem-to-the-Theory-of/10.1214/aoms/1177730032.full)), where a similar claim seems to be implied at the end of the proof of Lemma 12.
|
2013/02/28
|
[
"https://math.stackexchange.com/questions/316897",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/37058/"
] |
According to Rudin (Real and complex analysis), it is true. Because, you can show that the $\sup$, $\inf$, $\limsup$, $\liminf$ of a countable collection of functions is measurable. Limit is a special case of limsup or liminf since they are equal.
|
20,374,207 |
I was developed app, in this i have two activites one is PaintActivity and another one is TextActivity. when the user click the button in PaintActivity, TextActivity will be displayed along with the bitmap of PainActivity. In this user enter the text, and gives font style and color to the text after editing is done click the apply button to go to the paintactivity along with text and bitmap, i am using following code it works fine, except the one device,then i checked in different emulators, in one emulator(5.4"FWVGA(480\*854:mdpi)) i get outofmemory exception when clicking the apply button in TextAcitivty.
I am using following code
PaintActivity:
```
text.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
realPaint.setDrawingCacheEnabled(true);
Bitmap b2 = Bitmap.createBitmap(realPaint.getDrawingCache());
realPaint.setDrawingCacheEnabled(true);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b2.compress(Bitmap.CompressFormat.PNG, 100, bs);
byte[] byteArray = bs.toByteArray();
Intent i=new Intent(PaintActivity.this, TextActivity.class);
i.putExtra("bitT", byteArray);
realPaint.setDrawingCacheEnabled(false);
startActivityForResult(i,TEXT_BITMAP);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==TEXT_BITMAP && resultCode==RESULT_OK && data!=null){
byte[] byteArray=data.getByteArrayExtra("bittext");
BitmapFactory.Options opt=new BitmapFactory.Options();
opt.inSampleSize=3;
Bitmap bittext=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length,opt);
image.setImageBitmap(bittext);
}
}
```
TextACtivity:
```
apply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
loadBitmapFromView(real).compress(Bitmap.CompressFormat.PNG, 100, bs);
byte[] byteArray = bs.toByteArray();
i.putExtra("bittext", byteArray);
setResult(RESULT_OK,i);
finish();
}
});
```
|
2013/12/04
|
[
"https://Stackoverflow.com/questions/20374207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3064340/"
] |
Instead of `f.input :memberships` try this:
```
f.has_many :memberships do |pf|
pf.input :membership_type
end
```
and close your member object fields like this
```
f.inputs "Member Registration" do
f.input :forename
f.input :middlename
f.input :surname
...
end
```
So your form should look like this:
```
form do |f|
f.inputs "Member Registration" do
f.input :forename
f.input :middlename
f.input :surname
# .. the rest of your fields
end
f.has_many :memberships do |pf|
pf.input :membership_type
end
f.actions
end
```
|
27,365,466 |
I'm developing a simple web application in Java, but since I've changed my computer from win7 to mac os, i can't deploy my application.
Before the SO change my compiled code/war from intellij was deployed to debian with no problem. Now I get this (anoying) error:
```
An error occurred at line: [1] in the generated java file: [/var/lib/tomcat8/work/Catalina/localhost/chat/org/apache/jsp/index_jsp.java]
The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:199)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:438)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:405)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:349)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
```
In both machines I have installed JDK8 and Tomcat8. Debian CPU is a ARMv6, a raspberry pi. My Mac OS is x64 from mid 2012.
I already search over the web, try to update Tomca8, compile to java7 and deploy to a Tomcat7 instance, its driving me crazy!! I think this may be a cross platform problem, or something to do with class compilations, but I cannot find what!
Any help is much appreciated, Thanks
|
2014/12/08
|
[
"https://Stackoverflow.com/questions/27365466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3763828/"
] |
After many research and tests I couldn't solve this problem. My solution (that is not a real solution) for keep developing was replace all 8 version (jdk and tomcat) by version 7, both JDK and server (Tomcat).
An important note is to **use OpenJDK** and **NOT Oracle JDK**. I know, it seems contradictory but in the end it seems that OpenJDK install the necessary and right compilers. I didn't test with OpenJDK version 8 because my project only requires version 7, but for someone with the same problem, it worth to give a try with OpenJDK 8.
Hope this help someone and if anyone has any suggestion for the real solution, just past it.
|
32,858,353 |
I access the page `https://lazyair.co/specials/2015-09-25-02` correctly,
And I do have the template `specials.html.haml`
But it still show me the `ActionView::MissingTemplate`
How could it happen ? any direction ? Thanks
controller
==========
```
def specials
@specials = Special.all
end
```
exception
=========
```
An ActionView::MissingTemplate occurred in welcome#specials:
Missing template welcome/specials, application/specials with {:locale=>[:"zh-TW", :zh], :formats=>["image/webp", "image/*"], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}. Searched in:
-------------------------------
Request:
-------------------------------
* URL : https://lazyair.co/specials/2015-09-25-02
* HTTP Method: GET
* Parameters : {"controller"=>"welcome", "action"=>"specials", "token"=>"2015-09-25-02"}
* Process: 7573
```
|
2015/09/30
|
[
"https://Stackoverflow.com/questions/32858353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551273/"
] |
First try using the test id and then campaigns your project.And after add the campaigns ,wait for 20 miniut .Run your project you will get chartboost.For more detail [go this page](https://answers.chartboost.com/hc/en-us/articles/204930539-Creating-a-Publishing-Campaign)
|
53,453,112 |
I'm looking at the Google translate application on my phone (top image) and there's a line between each row of the settings that is very thin.
When I try to duplicate this line in Xamarin (bottom image 1 unit line)
```
<BoxView HeightRequest="1" HorizontalOptions="FillAndExpand"
BackgroundColor="{DynamicResource LineColor}" Margin="0" />
```
I cannot get this thickness. I thought the minimum line width was 1 so how can Google manage to make a line that appears thinner and can I somehow do this in Xamarin?
[](https://i.stack.imgur.com/MYZvp.jpg)
[](https://i.stack.imgur.com/TJrS0.jpg)
|
2018/11/23
|
[
"https://Stackoverflow.com/questions/53453112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422604/"
] |
I assume you want to use your extension only on one installation as local extension. So that's the way to go:
1. Create a directory, e.g. `packages` in your project's root directory.
2. Move your extension into this directory and name the folder `stsa-hellotypo3`. The part before the dash is your namespace, the part behind the package name.
3. Add to your `composer.json` of your extension the following entry:
```
"extra": {
"typo3/cms": {
"extension-key": "stsa_hellotypo3"
}
}
```
Now TYPO3 will use `stsa_hellotypo3` as extension key.
4. Change into your `composer.json` file in your TYPO3 project root the `repositories` entry:
```
"repositories": [
{
"type": "path",
"url": "packages/*"
},
{
"type": "composer",
"url": "https://composer.typo3.org/"
}
],
```
composer will look now into the `packages` folder for packages to install.
5. Now you can add your extension to the project:
```
composer require stsa/hellotypo3:@dev
```
The extension is symlink'ed as stsa\_hellotypo3 in typo3conf/ext/ directory. With the `@dev` the development version is installed (which you have). you can also add a version entry into your extension's `composer.json` file, then you can omit the `@dev`.
If you do it that way you don't have to add your extension's autoloading information to the root composer.json file.
|
51,654,120 |
I have a xib file of a table cell layout. I have 4 more cell layouts I need to create which are similar to layout 1 in structure, but not in content. The easiest, for me, would be if I could just copy the "layout" without the outlet references and modify the differences manually. Each different xib file will have a different corresponding swift file.
Is this possible?
|
2018/08/02
|
[
"https://Stackoverflow.com/questions/51654120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1034700/"
] |
I would do this using `stuff()` and some string manipulation:
```
select t.*,
stuff( ((case when c1 = 1 then ',campaign1' else '' end) +
(case when c2 = 1 then ',campaign2' else '' end) +
(case when c3 = 1 then ',campaign3' else '' end) +
(case when c4 = 1 then ',campaign4' else '' end)
), 1, 1, ''
) as campaigns
from t;
```
|
63,408,272 |
I tried to concatenate files created via snakemake workflow as the last rule. To separate and identify the contents of each file, I echo each file name first in the shell as a separation tag (see the code below)
```
rule cat:
input:
expand('Analysis/typing/{sample}_type.txt', sample=samples)
output:
'Analysis/typing/Sum_type.txt'
shell:
'echo {input} >> {output} && cat {input} >> {output}'
```
I was looking for the result as this format:
>
> file name of sample 1 content of sample 1 file name of sample
> 2 content of sample 2
>
>
>
>
>
>
>
>
>
instead I got this format:
>
> file name of sample 1 file name of sample 2 ... content of sample 1
> content of sample 2 ...
>
>
>
>
>
It seems snakemake execute echo command in parallel first then execute the cat command. What can I do the get the format I wanted?
Thanks
|
2020/08/14
|
[
"https://Stackoverflow.com/questions/63408272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14084148/"
] |
The output you get is consistent with the way bash works rather than with snakemake. Anyway, I think the snakemake way of doing it would be a rule to add the filename to the file content of each file and a rule to concatenate the output. E.g. (not checked for errors):
```
rule cat:
input:
'Analysis/typing/{sample}_type.txt',
output:
temp('Analysis/typing/{sample}_type.txt.out'),
shell:
r"""
echo {input} > {output}
cat {input} >> {output}
"""
rule cat_all:
input:
expand('Analysis/typing/{sample}_type.txt.out', sample=samples)
output:
'Analysis/typing/Sum_type.txt'
shell:
r"""
cat {input} > {output}
"""
```
|
53,959 |
"ADP and ATP are involved in energy transfer in cells."
I know what is ATP and I know how ADP is formed, but I don’t understand what “energy transfer in cells” means.
|
2016/12/02
|
[
"https://biology.stackexchange.com/questions/53959",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/27611/"
] |
>
> Is this DNA found in the mitochondria and chloroplasts coded for in the host's (animal's or plant's) DNA.
>
>
>
No, the DNA contained in these organelles it not a subset of the nuclear genome. However, part of the original genome of the prokaryote has been moved to nuclear DNA. That is why, as you cited, they "can no longer live independently."
>
> If not are there fully formed mitochondria and/or chloroplasts in all gametes (obviously chloroplasts only in the plant gametes) which were transferred directly from the parent who had them transferred directly from their parent and so on?
>
>
>
As the child organism would eventually need these organelles, and they can only be inherited, at least one of the gamete must contain them.
For the chloroplast, the general rule is that only one of the gamete provides it. For example, in gymnosperm it is the male gamete (pollen), in angiosperm, it is the female gamete (ovule). Either it is just not present in the other gamete, or a specific exclusion mechanism makes it mono-parentally inherited.
Mostly the same for the mitochondria, with the caveat that (motile) [spermatozoa](https://en.wikipedia.org/wiki/Spermatozoon) contain mitochondria for their metabolic functions (energy to move), but these are discarded when forming the zygote, and only the maternal mitochondria are inherited. (In plants, mostly maternal too with exceptions)
This does mean that there is a lineage of organelle on one of the parent's side, up to the [most recent common ancestor](https://en.wikipedia.org/wiki/Most_recent_common_ancestor) (approximately, the first individual of the species). In humans, this translates to a presumed [Mitochondrial Eve](https://en.wikipedia.org/wiki/Mitochondrial_Eve) from which all human mitochondrial DNA descends from.
>
> If so are all the mitochondria and chloroplasts of one type identical in a organism? Are they almost identicle in families (of organisms not the classifictaion Family)?
>
>
>
Every mitochondrion of an individual organism comes from the stock of mitochondria of the zygote, through replication. They are thus very similar, except for cell specialization (giving particular morphology to the organelles), and possible mutations. Same for the chloroplast.
Mitochondria (and chloroplasts) are basic components of the eukaryotic cell, providing essential functions which are highly conserved in a species, let alone related individuals.
However, this does not means the DNA of these organelle is the same for every individual : different sequences may give the same protein, or mutation may affect non-coding segment of the genome. This is the basis for [genetic genealogy](https://en.wikipedia.org/wiki/Genetic_genealogy), retracing family lineage though analysis of DNA, including mitochondrial DNA.
|
16,094,992 |
So, I have a form that posts to my php file using ajax, and succeeds. But the following query doesn't insert anything. Can someone help me understand what I'm doing wrong?
My php file:
```
<?php
include 'connect.php' ;
$type = mysql_real_escape_string($_POST['type']);
$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
if ($type == 'Just Text') {
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('".$title."', '".$type."', 0, '".$content."')")or die("MySQL Error: " . mysql_error());
}
?>
```
My connect.php:
```
<?php
$dbhost = "localhost";
$dbname = "example";
$dbuser = "test";
$dbpass = "test";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
```
|
2013/04/18
|
[
"https://Stackoverflow.com/questions/16094992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960065/"
] |
If you aren't receiving any errors and the `INSERT` just doesn't happen, it is most likely because the `if` statement fails to be true. Verify that `$type` actually matches `Just Text`.
You should also be inserting values using [*prepared statements*](http://j.mp/T9hLWi), and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which.
|
17,743,365 |
I'll try to keep it simple.
I have a list of similar rows like this:

HTML code:
```
<li ...>
<div ... >
<some elements here>
</div>
<input id="121099" class="containerMultiSelect" type="checkbox" value="121099" name="NodeIds">
<a ...>
<div ... />
<div ... >
<h2>Identified Text</h2>
<h3>...</h3>
</div>
</a>
</li>
```
I want to click the checkbox with a certain text, but I can't use any of its elements, because they are the same for all the list, and id is generated automatically. The only thing can be differentiated is the h2 text. I tried :
```
browser.h2(:text => /Identified/).checkbox(:name => "NodeIds").set
```
and I got UnknownException which is obvious because checkbox is not nested with a tag.
What can I do in this case?
Thanks
|
2013/07/19
|
[
"https://Stackoverflow.com/questions/17743365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1045780/"
] |
Use `BigInteger` in Java
That will satisfy your requirements.
Visit the following tutorial to learn [BigInteger in Java : TutorialPoint](http://www.tutorialspoint.com/java/math/java_math_biginteger.htm)
|
34,307,810 |
I am writing a program which gives me the letters containing only the consonants in a webpage address between www. and .com.
For example if I input www.google.com it should return me 'ggl' but that doesnt happen.
```
import re
x=int(raw_input())
for i in range(x):
inp1=raw_input()
y=re.findall('^www\.[^(aeiou)]+\.com',inp1)
print y
inp2=y[0]
print inp2
```
So what's the mistake in the line `y=re.findall('^www\.[^aeiou]+\.com',inp1)`?
|
2015/12/16
|
[
"https://Stackoverflow.com/questions/34307810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5685735/"
] |
try this one:
```
body{margin:0px;padding:0px;}
.boo {
position: absolute;
left: 10px;
top: 10px;
width: 100px;
height: 70px;
background-color: red;
}
.kah1 {
position: absolute;
left: 20px;
top: 30px;
width: 50px;
height: 40px;
background-color: green;
}
.kah2 {
position: absolute;
left: 30px;
top: 40px;
width: 50px;
height: 30px;
background-color: blue;
}
```
[**DEMO HERE**](https://jsfiddle.net/e0cpuarv/1/)
|
60,953,998 |
I have this function in views.py file that responsible for adding a record into the Database
```
def add_academy(request,pk):
child = get_object_or_404(Child_detail, pk=pk)
academic = Academic.objects.get(Student_name=child)
form = AcademicForm(request.POST, instance=academic)
if form.is_valid():
form.save()
return redirect('more',pk=pk) #it will redirect but can't create a new record
else:
form=AcademicForm()
context = {
'academic':academic,
'child':child,
'form':form,
}
return render(request,'functionality/more/academy/add.html',context)
```
And here is my form.py file
```
class AcademicForm(forms.ModelForm):
class Meta:
model=Academic
fields='Class','Date','Average_grade','Overall_position','Total_number_in_class'
labels={
'Average_grade':'Average Grade',
'Overall_position':'Overall Position',
'Total_number_in_class':'Total Number In Class'
}
Date = forms.DateField(
widget=forms.TextInput(
attrs={'type': 'date'}
)
)
```
And here is my model.py file
```
class Academic(models.Model):
Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE)
Class = models.CharField(max_length = 50)
Date = models.DateField()
Average_grade = models.CharField(max_length = 10)
Overall_position = models.IntegerField()
Total_number_in_class = models.IntegerField()
def __str__(self):
return str(self.Student_name)
```
And also this is my template will be used to display form
```
<div class="card-body">
<form action="" method="POST" autocomplete="on">
{% csrf_token %}
<div class="form-group">
{{form | crispy}}
<input type="submit" value="Save" class="btn btn-primary btn-block">
</form>
</div>
```
|
2020/03/31
|
[
"https://Stackoverflow.com/questions/60953998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11662460/"
] |
It looks like your Spring Boot app is expecting to configure a JPA DataSource, but it can't find the details it needs to do so. There's not a MarkLogic implementation of a DataSource, so you likely need to disable that aspect of Spring Boot. See <https://www.baeldung.com/spring-boot-failed-to-configure-data-source> for information on excluding DataSourceAutoConfiguration .
|
30,855,655 |
Using example from Andrew Ng's class (finding parameters for Linear Regression using normal equation):
With Python:
```
X = np.array([[1, 2104, 5, 1, 45], [1, 1416, 3, 2, 40], [1, 1534, 3, 2, 30], [1, 852, 2, 1, 36]])
y = np.array([[460], [232], [315], [178]])
θ = ((np.linalg.inv(X.T.dot(X))).dot(X.T)).dot(y)
print(θ)
```
Result:
```
[[ 7.49398438e+02]
[ 1.65405273e-01]
[ -4.68750000e+00]
[ -4.79453125e+01]
[ -5.34570312e+00]]
```
With Julia:
```
X = [1 2104 5 1 45; 1 1416 3 2 40; 1 1534 3 2 30; 1 852 2 1 36]
y = [460; 232; 315; 178]
θ = ((X' * X)^-1) * X' * y
```
Result:
```
5-element Array{Float64,1}:
207.867
0.0693359
134.906
-77.0156
-7.81836
```
Furthermore, when I multiple X by Julia's — but not Python's — θ, I get numbers close to y.
I can't figure out what I am doing wrong. Thanks!
|
2015/06/15
|
[
"https://Stackoverflow.com/questions/30855655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4231726/"
] |
Using X^-1 vs the pseudo inverse
--------------------------------
**pinv**(X) which corresponds to [the pseudo inverse](https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse#Applications) is more broadly applicable than **inv**(X), which X^-1 equates to. Neither Julia nor Python do well using **inv**, but in this case apparently Julia does better.
but if you change the expression to
```
julia> z=pinv(X'*X)*X'*y
5-element Array{Float64,1}:
188.4
0.386625
-56.1382
-92.9673
-3.73782
```
you can verify that X\*z = y
```
julia> X*z
4-element Array{Float64,1}:
460.0
232.0
315.0
178.0
```
|
27,077 |
When I start up my MacBookPro/osx/snow leopard , I get this error with yahoo messenger..
What is this keychain thing? Is this some Mac thing?
Any links to explain this concept and how to resolve it?
Thanks,
|
2011/10/09
|
[
"https://apple.stackexchange.com/questions/27077",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/10547/"
] |
For old versions of MacOS (prior to El Capitan) to fix this:
* Run Keychain Access (found in /Applications/Utilities)
* click "Keychain Access" in the menu bar at the top and select "Keychain First Aid".
* Run the repair and then run verify.
That should fix it!
|
5,009,194 |
I have two abstracted processes (e.g. managed within js objects using the revealing module pattern that do not expose their internals) that fire [custom events](http://api.jquery.com/trigger/) when they complete. I want to perform an action when both custom events have fired.
The new [Deferred](http://api.jquery.com/category/deferred-object/) logic in jQuery 1.5 seems like it would be an ideal way to manage this, except that the when() method takes Deferred objects that return a promise() (or normal js objects, but then when() completes immediately instead of waiting, which is useless to me).
Ideally I would like to do something like:
```
//execute when both customevent1 and customevent2 have been fired
$.when('customevent1 customevent2').done(function(){
//do something
});
```
What would be the best way to marry these two techniques?
|
2011/02/15
|
[
"https://Stackoverflow.com/questions/5009194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435241/"
] |
<http://jsfiddle.net/ch47n/>
I created a small plugin that creates a new jQuery.fn.when method.
Syntax is:
```
jQuery( "whatever" ).when( "event1 event2..." ).done( callback );
```
It uses jQuery.when() extensively internally and ensures that all events have been triggered on all elements in the collection before resolving.
---
Actual plugin code below:
```
( function( $ ) {
$.fn.when = function( events ) {
var deferred, $element, elemIndex, eventIndex;
// Get the list of events
events = events.split( /\s+/g );
// We will store one deferred per event and per element
var deferreds = [];
// For each element
for( elemIndex = 0; elemIndex < this.length; elemIndex++ ) {
$element = $( this[ elemIndex ] );
// For each event
for ( eventIndex = 0; eventIndex < events.length; eventIndex++ ) {
// Store a Deferred...
deferreds.push(( deferred = $.Deferred() ));
// ... that is resolved when the event is fired on this element
$element.one( events[ eventIndex ], deferred.resolve );
}
}
// Return a promise resolved once all events fired on all elements
return $.when.apply( null, deferreds );
};
} )( jQuery );
```
|
64,776,116 |
I have the following React app with a Slick carousel. I created a custom Next button and need to execute the `slickNext()` method to proceed to the next slide. The Slick carousel docs and some of the answers for questions have mentioned the following way to call `slickNext()` method.
**The problem is I'm getting the error** `slider.slick is not a function`.
This is what I have tried so far
```
gotoNext = () => {
var slider = document.getElementsByClassName("sliderMain")[0];
console.log("set", slider)
slider.slick("slickNext");
}
const SampleNextArrow = (props) => {
const { className, style } = props;
return (
<div
className={className}
onClick={this.gotoNext}
/>
);
}
const settings = {
dots: true,
infinite: false,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
swipe: false,
nextArrow: <SampleNextArrow className="customSlickNext" />,
};
<Slider
id="sliderMain"
{...settings}
className="sliderMain"
afterChange={this.changeSlide}
>{ /* slider goes here */}
</Slider>
```
How can I solve this?
|
2020/11/10
|
[
"https://Stackoverflow.com/questions/64776116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10638811/"
] |
With react-slick, you can add a `ref` prop on `<Slider>`. If you're using hooks, you can do that with `useRef()`:
```js
import React, { useRef } from 'react';
...
const sliderRef = useRef();
<Slider
ref={sliderRef}
...
>
</Slider>
```
You can then use `sliderRef` to call Slick methods in your function:
```js
gotoNext = () => {
sliderRef.current.slickNext();
}
```
The available methods for react-slick can be found at: <https://react-slick.neostack.com/docs/api/#methods>
|
215,896 |
[Further-developed followup to this question](https://codereview.stackexchange.com/questions/214221/allow-console-draw-poker-game-to-output-more-hands)
Python beginner here.
I created a command-line program that generates poker hands (5-52 cards) and compares their strength. On my Macbook Pro, it generates and compares 1m 5-card hands in ~2m.
Here's my code:
```
import copy
import distutils.core
from enum import Enum
from time import time
from random import shuffle
from math import floor
#Individual Cards
class Card:
def __init__ (self,value,suit):
self.value = value
self.suit = suit
self.vname = ''
self.sname = ''
def __str__(self):
return f'{self.sname}{self.vname}{self.sname}'
def __repr__(self):
if self.value <= 10:
return f'{self.value}{self.suit[0].lower()}'
if self.value > 10:
return f'{self.vname[0]}{self.suit[0].lower()}'
def vsname(self,value,suit):
if self.value == 2:
self.vname = 'Two'
elif self.value == 3:
self.vname = 'Three'
elif self.value == 4:
self.vname = 'Four'
elif self.value == 5:
self.vname = 'Five'
elif self.value == 6:
self.vname = 'Six'
elif self.value == 7:
self.vname = 'Seven'
elif self.value == 8:
self.vname = 'Eight'
elif self.value == 9:
self.vname = 'Nine'
elif self.value == 10:
self.vname = 'Ten'
elif self.value == 11:
self.vname = 'Jack'
elif self.value == 12:
self.vname = 'Queen'
elif self.value == 13:
self.vname = 'King'
elif self.value == 14:
self.vname = 'Ace'
if self.suit == "Hearts":
self.sname = '♥'
elif self.suit == "Spades":
self.sname = '♠'
elif self.suit == "Clubs":
self.sname = '♣'
elif self.suit == "Diamonds":
self.sname = '♦︎︎'
#All Decks
class Deck:
def __init__(self):
self.cards = []
self.create()
def create(self):
for _ in range(decks):
for val in (2,3,4,5,6,7,8,9,10,11,12,13,14):
for suit in ("Hearts", "Spades", "Clubs", "Diamonds"):
self.cards.append(Card(val,suit))
shuffle(self.cards)
def draw(self,x):
for y in range(x):
drawcards[y] = self.cards.pop()
drawcards[y].vsname(drawcards[y].value,drawcards[y].suit)
return drawcards
class BaseStrength(Enum):
ROYAL_FLUSH = 10000
STRAIGHT_FLUSH = 9000
QUADS = 8000
FULL_HOUSE = 7000
FLUSH = 6000
STRAIGHT = 5000
SET = 4000
TWO_PAIR = 3000
PAIR = 2000
HIGH_CARD = 1000
#Determine Values and Suits in Hand
def determine(hand):
values, vset, suits, all_cards = [], set(), [], []
for x in range(len(hand)):
values.append(hand[x].value)
vset.add(hand[x].value)
suits.append(hand[x].suit)
all_cards.append(hand[x])
return sorted(values,reverse=True),vset,suits,all_cards
#Message/Text Functions
def ss():
if show_strength: print(f'[{round(strength/10000,6)}]')
else: print()
def hnumber(max_v,msg):
while True:
try:
hn = input(msg)
if hn.lower() == 'm' or hn.lower() == 'max':
return max_v
elif 0 < int(hn) <= max_v:
return int(hn)
else:
print(f'Please enter an integer between 1 and {max_v}.')
except ValueError:
print('Please enter a positive integer.')
def decks(msg):
while True:
try:
d = int(input(msg))
if d > 0:
return d
else:
print('Please enter a positive integer.')
except ValueError:
print('Please enter a positive integer.')
def cph(msg):
while True:
try:
d = int(input(msg))
if 5 <= d <= 52:
return d
else:
print('Please enter a positive integer between 5 and 52.')
except ValueError:
print('Please enter a positive integer between 5 and 52.')
def sstrength(msg):
while True:
try:
ss = distutils.util.strtobool(input(msg))
if ss == 0 or ss == 1:
return ss
else:
print('Please indicate whether you\'d like to show advanced stats')
except ValueError:
print('Please indicate whether you\'d like to show advanced stats')
def get_inputs():
decks_ = decks('How many decks are there? ')
cph_ = cph('How many cards per hand? ')
max_v = floor((decks_*52)/cph_)
hnumber_ = hnumber(max_v,f'How many players are there (max {floor((decks_*52)/cph_)})? ')
sstrength_ = sstrength("Would you like to show advanced stats? ")
return (decks_,cph_,hnumber_,sstrength_)
def print_hand(user_hand):
print(f"\nPlayer {h_inc + 1}'s hand:")
print("| ",end="")
for c_x in user_hand: print(user_hand[c_x],end=" | ")
def post_draw():
hss = sorted(h_strength.items(), key=lambda k: k[1], reverse=True)
if not show_strength:
print(f'\n\n\nPlayer {hss[0][0] + 1} has the strongest hand!\nPlayer {hss[hnumber-1][0]+1} has the weakest hand :(')
if show_strength:
print(f'\n\n\nPlayer {hss[0][0]+1} has the strongest hand! [{round(hss[0][1]/10000,6)}]\nPlayer {hss[hnumber-1][0] + 1} has the weakest hand :( [{round(hss[hnumber-1][1]/10000,6)}]')
print('\n\n\n\n\nHand Occurence:\n')
for x in range(10): print(ho_names[x],hand_occurence[x],f'({round(100*hand_occurence[x]/len(hss),2)}%)')
print('\n\n\n\n\nFull Player Ranking:\n')
for x in range(len(hss)): print(f'{x+1}.',f'Player {hss[x][0]+1}',f'[{round(hss[x][1]/10000,6)}]')
print('\n\n\nComplete Execution Time:', "%ss" % (round(time()-deck_start_time,2)))
print('Deck Build Time:', '%ss' % (round(deck_end_time-deck_start_time,2)), f'({int(round(100*(deck_end_time-deck_start_time)/(time()-deck_start_time),0))}%)')
print('Hand Build Time:', '%ss' % (round(time()-deck_end_time,2)), f'({int(round(100*(time()-deck_end_time)/(time()-deck_start_time),0))}%)')
#Evaluation Functions
def valname(x):
if x == 2:
return 'Two'
elif x == 3:
return 'Three'
elif x == 4:
return 'Four'
elif x == 5:
return 'Five'
elif x == 6:
return 'Six'
elif x == 7:
return 'Seven'
elif x == 8:
return 'Eight'
elif x == 9:
return 'Nine'
elif x == 10:
return 'Ten'
elif x == 11:
return 'Jack'
elif x == 12:
return 'Queen'
elif x == 13:
return 'King'
elif x == 14 or x == 1:
return 'Ace'
def hcard(values):
global strength
strength = BaseStrength.HIGH_CARD.value + 10*values[0] + values[1] + .1*values[2] + .01*values[3] + .001*values[4]
return f'High-Card {valname(values[0])}'
def numpair(values):
global strength
pairs = list(dict.fromkeys([val for val in values if values.count(val) == 2]))
if not pairs:
return False
if len(pairs) == 1:
vp = values.copy()
for _ in range(2):
vp.remove(pairs[0])
strength = BaseStrength.PAIR.value + 10*pairs[0] + vp[0] + .1*vp[1] + .01*vp[2];
return f'Pair of {valname(pairs[0])}s'
if len(pairs) >= 2:
vps = values.copy()
pairs = sorted(pairs,reverse=True)
for _ in range(2):
vps.remove(pairs[0]); vps.remove(pairs[1])
strength = (BaseStrength.TWO_PAIR.value + 10*int(pairs[0]) + int(pairs[1])) + .1*vps[0]
return f'{valname(pairs[0])}s and {valname(pairs[1])}s'
def trip(values):
global strength
trips = [val for val in values if values.count(val) == 3]
if not trips:
return False
else:
vs = values.copy()
for _ in range(3):
vs.remove(trips[0])
strength = BaseStrength.SET.value + 10*trips[0] + vs[0] + .1*vs[1]
return f'Set of {valname(trips[0])}s'
def straight(vset,get_vals=False):
global strength
count = 0
if not get_vals:
straight = False
for rank in (14, *range(2, 15)):
if rank in vset:
count += 1
max_c = rank
if count == 5:
strength = BaseStrength.STRAIGHT.value + 10*min(vset)
straight = f'Straight from {valname(max_c-4)} to {valname(max_c)}'
break
else: count = 0
return straight
if get_vals:
sset = set()
for rank in (14, *range(2, 15)):
if rank in vset:
count += 1
sset.add(rank)
if count == 5:
return sset
else:
count = 0
sset = set()
raise Exception('No SSET')
def flush(suits,all_cards):
global strength
flushes = [suit for suit in suits if suits.count(suit) >= 5]
if flushes: flushes_vals = sorted([card.value for card in all_cards if card.suit == flushes[0]],reverse=True)
if not flushes:
return False
else:
strength = BaseStrength.FLUSH.value + 10*flushes_vals[0] + flushes_vals[1] + .1*flushes_vals[2] + .01*flushes_vals[3] + .001*flushes_vals[4]
flush = f'{valname(max(flushes_vals))}-High flush of {flushes[0]}'
return flush
def fullhouse(values):
global strength
trips = list(dict.fromkeys(sorted([val for val in values if values.count(val) == 3],reverse=True)))
if not trips:
return False
pairs = sorted([val for val in values if values.count(val) == 2],reverse=True)
if pairs and trips:
strength = BaseStrength.FULL_HOUSE.value + 10*trips[0] + pairs[0]
fh = f'{valname(trips[0])}s full of {valname(pairs[0])}s'
if len(trips) > 1:
if pairs:
if trips[1] > pairs[0]:
strength = BaseStrength.FULL_HOUSE.value + 10*trips[0] + trips[1]
fh = f'{valname(trips[0])}s full of {valname(trips[1])}s'
else:
strength = BaseStrength.FULL_HOUSE.value + 10*trips[0] + trips[1]
fh = f'{valname(trips[0])}s full of {valname(trips[1])}s'
if len(trips) == 1 and not pairs:
return False
return fh
def quads(values):
global strength
quads = [val for val in values if values.count(val) >= 4]
if not quads:
return False
else:
vq = values.copy()
for _ in range(4): vq.remove(quads[0])
strength = BaseStrength.QUADS.value + 10*quads[0] + vq[0]
return f'Quad {valname(quads[0])}s'
def straightflush(suits,vset,all_cards):
global strength
straight_= False
flushes = [suit for suit in suits if suits.count(suit) >= 5]
if flushes:
flushes_vals = sorted([card.value for card in all_cards if card.suit == flushes[0]],reverse=True)
if straight(flushes_vals):
straight_vals = straight(flushes_vals,True)
if {14,10,11,12,13} <= straight_vals: straight_ = "Royal"
if {14,2,3,4,5} <= straight_vals: straight_ = "Wheel"
else: straight_ = "Normal"
if straight_ == "Normal":
strength = BaseStrength.STRAIGHT_FLUSH.value + 10*max(flushes_vals)
sf = f'{valname(max(straight_vals))}-High Straight Flush of {flushes[0]}'
elif straight_ == "Wheel":
strength = BaseStrength.STRAIGHT_FLUSH.value
sf = f'Five-High Straight Flush of {flushes[0]}'
elif straight_ == "Royal":
strength = BaseStrength.ROYAL_FLUSH.value
sf = f'Royal Flush of {flushes[0]}'
else:
sf = False
return sf
def evalhand(values,suits,vset,all_cards):
x = straightflush(suits,vset,all_cards)
if not x: x = quads(values)
if not x: x = fullhouse(values)
if not x: x = flush(suits,all_cards)
if not x: x = straight(values)
if not x: x = trip(values)
if not x: x = numpair(values)
if not x: x = hcard(values)
return x
def count_hand_occurence(strength):
if strength < 2000: hand_occurence[0]+=1
elif strength < 3000: hand_occurence[1]+=1
elif strength < 4000: hand_occurence[2]+=1
elif strength < 5000: hand_occurence[3]+=1
elif strength < 6000: hand_occurence[4]+=1
elif strength < 7000: hand_occurence[5]+=1
elif strength < 8000: hand_occurence[6]+=1
elif strength < 9000: hand_occurence[7]+=1
elif strength < 10000: hand_occurence[8]+=1
elif strength == 10000: hand_occurence[9]+=1
hand_occurence = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
ho_names = ['High Card: ','Pair: ','Two-Pair: ','Three of a Kind: ','Straight: ','Flush: ','Full House: ','Four of a Kind: ','Straight Flush: ','Royal Flush: ']
drawcards, h_strength = {}, {}
decks, cards_per_hand, hnumber, show_strength = get_inputs()
deck_start_time = time()
deck = Deck()
deck_end_time = time()
#Hand Print Loop
for h_inc in range(hnumber):
user_hand = deck.draw(cards_per_hand)
print_hand(user_hand)
values,vset,suits,all_cards = determine(user_hand)
exact_hand = evalhand(values,suits,vset,all_cards)
print('\n'+exact_hand,end=" "); ss()
count_hand_occurence(strength)
h_strength[h_inc] = strength
post_draw()
```
|
2019/03/21
|
[
"https://codereview.stackexchange.com/questions/215896",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/193767/"
] |
* When you have a long if/elif chain in Python it's a good idea to use a dictionary instead. For example: `{1: 'one', 2: 'two', 3: ...}`. This also makes exception handling easier with the `.get()` method.
* Try to use proper names rather than just `x` or `y`.
* Instead of:
```
for indx in range(len(some_list)):
some_list[indx].do_something()
```
use:
```
for item in some_list:
item.do_something()
```
* Follow colons with a new line.
* The `while True ... try ... except ValueError` is a strange choice. Add a condition to your while loop and just increment some counter.
* Don't use exceptions to control the flow of the program. Exceptions are for catching exceptional behaviour, i.e. when something has gone wrong.
* Some of your lines are very long. Split up the printing if necessary.
* Try to be consistent with fstrings or `.format()`, not old formatting style (`%s`).
* Avoid using globals. There are various ways of getting rid of them such as wrapping hanging functions into a class and having the global as a class variable.
* Wrap your "worker" code (the code that does all the calling) in a function called something like `main()` (ideally more descriptive than that). Then use the standard:
```
if __name__ == '__main__':
main()
```
* Using a dictionary you can rewrite `count_hand_occurance()` to be a simple generator expression.
* Try to add doctrings; as a minimum for the classes if not the functions/methods as well.
* Consider logging all of these messages rather than printing them. Debugging is far easier with logged information. As a start, you could write a simple file writing function (open file in append mode, 'a+') that is called instead of print.
* in `post_draw()` you have `if not condition:` followed by `if condition:`. Just use `if`, `else`.
* More comments are needed in logic-dense areas.
**Edit, some explanations**
Using a dictionary instead of if/else, instead of:
```
if cond_a:
return a
elif cond_b:
return b
elif cond_c:
return c
```
create a dictionary where the conditions are the keys, and the return variables are the values:
```
some_dict = {cond_a: a, cond_b: b, cond_c: c}
```
then when it comes to using it, just do:
```
return some_dict[condition]
```
You can also add a default value for when the conditions isn't handled by the dictionary: `return some_dict.get(condition, default=None)`.
Class instead of globals:
The simplest example is to put the global into a class as you have done above with `Deck`:
```
class MyClass:
def __init__(self, some_var):
self.some_var = some_var
```
Then you can add your functions into that class as methods and they can all share `self.some_var` without putting it into the global scope.
There is almost always a way around using globals, try to narrow down exactly what you want to use the global for. Most of the time there'll be a design pattern to handle that case.
|
67,514,839 |
I need send the XML that vendor asked as below.
```
<Start>
<Ele extraAtt="123" extraAtt2="456">
<Field1>1</Field1>
<Field2>2/Field2>
<Field3>3</Field3>
</Ele>
</Start>
```
Here are my code:
```
Dim ms As MemoryStream = Nothing
Dim XMLWrt As XmlTextWriter = Nothing
Dim XMLDoc As XmlDocument = Nothing
ms = New MemoryStream()
XMLWrt = New XmlTextWriter(ms, Encoding.UTF8)
XMLWrt.Formatting = Formatting.Indented
XMLWrt.WriteStartDocument()
XMLWrt.WriteStartElement("Start")
XMLWrt.WriteStartElement("Ele")
AddElement(XMLWrt, "Field1", 1)
AddElement(XMLWrt, "Field2", 2)
AddElement(XMLWrt, "Field3", 3)
XMLWrt.WriteEndElement()
XMLWrt.WriteEndElement()
XMLWrt.Flush()
XMLDoc = New XmlDocument()
ms.Position = 0
XMLDoc.Load(ms)
XMLWrt.Close()
```
This code would generate the result as below.
As you can see, it missed "extraAtt="123" extraAtt2="456" on the Ele block.
I wonder how to modify code to generate what I want?
```
<Start>
<Ele> --> I need <Ele extraAtt="123" extraAtt2="456"> instead.
<Field1>1</Field1>
<Field2>2/Field2>
<Field3>3</Field3>
</Ele>
</Start>
```
|
2021/05/13
|
[
"https://Stackoverflow.com/questions/67514839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7651802/"
] |
Add a couple of calls on `XMLWrt.WriteAttributeString()`.
|
126,339 |
Where do I enable the CONFIG\_NO\_HZ\_FULL kernel configuration? Is it something I can set in conf files or is it something that has to be enabled when I build the kernel?
I am using CentOS with an upgraded kernel 3.10.
|
2014/04/24
|
[
"https://unix.stackexchange.com/questions/126339",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/66066/"
] |
If you would like to check if an option is configured into your current kernel, you can probably get the config via `gunzip -c /proc/config.gz > somefile`. So to check this one:
```
gunzip -c /proc/config.gz | grep HZ _FULL
```
You can search for options when configuring the kernel with `make menuconfig` via `/` -- the other TUI config apps should have a similar feature, and I presume the GUI ones something in a menu. The forward slash is a standard \*nix-ish hotkey for searching, used in (e.g.) the standard pager, `less`.
Anyway, a quick check of this for 3.13.3 turned up five different options, the first of which is `NO_FULL_HZ` and that option is set in the `menuconfig` hierarchy (the other config interface apps use the same one, I believe) by *General setup->Timers subsystem->Timer tick handling*.
Note that some options have prerequisites and will not appear unless those are satisfied. You can untangle these by looking at the output from the search, which indicates how your prereq values are currently set (in square brackets, e.g. `[=y]`) and uses logical operator notation:
* `!` indicates the option must not be set (so you would want `[=n]`)
* `&&` indicates the preceding requisite *and* the next one must be set.
* `||` indicates the preceding requisite *or* the next one must be set.
Conversely, some options are required by other ones which have been selected and clues about that will be in the search output too.
|
40,588 |
Rashi says that Korach saw with ruach hakodesh (divine inspiration) that the prophet Samuel would descend from him. Yet Rashi also implies he had the bad traits of jealousy and arrogance.
How could he have ruach hakodesh if he had the bad traits of jealousy and arrogance?
it seems one must be clean of all bad traits before reaching this level as explained in the book Mesilas Yesharim
|
2014/06/21
|
[
"https://judaism.stackexchange.com/questions/40588",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/1857/"
] |
Tiferes Tzion says that even though Korach lacked the refinement of character to receive prophecy, Ruach Hakodesh still rested upon him because he lived in a holy environment that was conductive to Ruach Hakodesh.
|
9,619,110 |
I am trying to display an ImageIcon of an object of class bishop. ImageIcon is retrieved using getImage(). Returned ImageIcon is stored in reference m but it is not getting displayed and another ImageIcon h, which is loaded directly, is getting displayed. What mistake I am making?
```
import javax.swing.*;
//Game.java
public class Game {
public static void main(String[] args) {
board b = new board();
bishop bis1 = new bishop();
bis1.setLocation(0, 0);
ImageIcon m = bis1.getImage();
b.squares[0][1].add(new JLabel(m));
ImageIcon h = new ImageIcon("rook.png");
b.squares[0][0].add(new JLabel(h));
}
}
//bishop.java
import javax.swing.*;
import java.awt.*;
public class bishop {
private ImageIcon img;
private int row;
private int col;
public void bishop() {
img = new ImageIcon("bishop.png");
}
public void setLocation(int i, int j) {
row = i;
col = j;
}
public int getX() {
return row;
}
public int getY() {
return col;
}
public ImageIcon getImage() {
return img;
}
}
// board.java
import javax.swing.*;
import java.awt.*;
public class board {
public JFrame frame;
public JPanel squares[][] = new JPanel[3][3];
public board() {
frame = new JFrame("Simplified Chess");
frame.setSize(900, 400);
frame.setLayout(new GridLayout(2,3));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
squares[i][j] = new JPanel();
if ((i + j) % 2 == 0) {
squares[i][j].setBackground(Color.black);
} else {
squares[i][j].setBackground(Color.white);
}
frame.add(squares[i][j]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
|
2012/03/08
|
[
"https://Stackoverflow.com/questions/9619110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021867/"
] |
You defined your constructor wrong way - with an unnecessary `void`. Therefore your `Bishop` class calls default empty constructor so your variable `img` is never set correctly. Remove it so that your constructor would be called correctly:
**Instead of this:**
```
public void bishop() {
img = new ImageIcon("bishop.png");
}
```
**Define it without void:**
```
public bishop() {
img = new ImageIcon("bishop.png");
}
```
|
258,933 |
**Round 1 (failed attempt)**
The current wiring was originally for an electric stove. I now have a gas stove, and would prefer to not run new cable or replace with a new 120v receptacle. My first attempt at this didn't work. Originally, I capped one of the hots at the outlet and grounded the the other side to the bus bar. Swapped out the Circuit for a single pole 15amp, replaced the receptacle with a 15amp GFCI. And it fried the outlet after a few weeks. I shut off the breaker, when I would flip it back on it would spark! (Im thinking because of the gauge of the wire? And a fried outlet?)
**Round 2, Here's what we got**
Id like to rewire it back to what it was since Im dealing with heavy wires. And try a 240v -> 120 v adapter.
* 6gauge wire (I think)... HOT(balck/red), HOT (Black), Neutral (White), No Green Ground.
* Both hots are connected to a 60amp Double pole circuit. I believe white is connected to the bus bar.
* 240v 50amp Power Outlet
<https://www.homedepot.com/p/Legrand-Pass-Seymour-50-Amp-125-250-Volt-NEMA-14-50R-Flush-Mount-Range-Dryer-EV-Charger-Power-Outlet-3894CC6/100576604>
* 240v --> 120V 15amp Adapter
<https://www.homedepot.com/p/Southwire-Gas-Range-Adapter-9042SW8801/302183109>?
* 120v 15amp Gas stove.
**QUESTIONS**
* How would you solve this if you didn't want to run new cable? (I have no problem changing the breaker/receptacle)
* Considering the 6 guage wire, Can I replace the outlet with a 240v 15amp and then use the 240v --> 120v 15amp adapter?
* Is that risker since the thicker wire supports higher current?
* Should I keep the double pole 60amp circut or a lower amp circuit since the adapter supports 120v 15amps to be plugged into it.
* Should I use 240v 50amp receptacle w/ a 60amp double pole?
|
2022/10/20
|
[
"https://diy.stackexchange.com/questions/258933",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/156070/"
] |
>
> And try a 240v -> 120 v adapter.
>
>
>
ONLY if it is UL-Listed. UL is the safety agency which writes the product safety rules and certifies equipment to be safe. Anything sold over-the-counter in reputable shops will be UL Listed.
Mail order bypasses the consumer safety agencies, and almost everything in the mail-order channels is dangerous cheap junk from you know where.
>
> My first attempt at this didn't work. Originally, I capped one of the hots at the outlet and grounded the the other side to the bus bar. Swapped out the Circuit for a single pole 15amp, replaced the receptacle with a 15amp GFCI. And it fried the outlet after a few weeks.
>
>
>
OK, *that should have worked*. The issue was clearly workmanship problems in the work that you did. **You should labor to improve your work quality until that thing works**. We can help.
You *absolutely should not* be flying off in a totally different direction and trying new things, least of all with *transformers*, when you have not mastered the basics yet.
So to start, put up photos of the work done so far, relating to the breaker and the receptacle, and we'll try to figure out what went wrong.
>
> I shut off the breaker, when I would flip it back on it would spark!
>
>
>
Might be a heavy load on the circuit (from a gas range? Unlikely) or it might be a workmanship problem. The photos will tell and then we can guide you.
>
> How would you solve this if you didn't want to run new cable? (I have no problem changing the breaker/receptacle)
>
>
>
I would sit at my desk and pigtail black, white, bare wires onto a 120V receptacle. Then I'd crawl down to the socket and use big red or tan wire nuts, and splice those #12 wires to the matching #6 wires coming out of the wall. I would cap off red.
If I did not have a ground wire, well, I'd have to see what you do have. You might have ground after all. If not, it can be retrofitted.
Then down at the breaker panel, I would swap out the 50A breaker for a 20A **2-pole** breaker or dual 20A singles. Why? To fill the empty hole. Can't leave a gaping hole in your panel!
Then I would cap off and insulate red in the panel, place black on the breaker, white to neutral bar and bare to ground bar. (which is sometimes the neutral bar, when in Rome do as the last guy did).
>
> Considering the 6 guage wire, Can I replace the outlet with a 240v 15amp and then use the 240v --> 120v 15amp adapter?
>
>
>
No, all that money on receptacle and adapter would be totally wasted. **Figure out why the 120V receptacle did not work**.
Even more than that, I have a funny feeling you might not have a proper ground wire. That is not the cause of it not working, but it would make it *illegal and dangerous* to stick the socket you picked, a NEMA 14-50, there. NEMA 14-50 requires a ground. (or a costly 2-pole GFCI breaker and a "No Equipment Ground" label at the socket).
>
> Is that risker since the thicker wire supports higher current?
>
>
>
No, that's not a risk. The risk is in the quality of work issues you are running into. We will work on those.
>
> Should I keep the double pole 60amp circut or a lower amp circuit since the adapter supports 120v 15amps to be plugged into it.
>
> Should I use 240v 50amp receptacle w/ a 60amp double pole?
>
>
>
If you insist on fitting a 50A "NEMA 14-50" receptacle, **then it is mandatory** to use a 40A or 50A breaker with that. NEC 210.21.
I hope I have talked you of dangerous mail-order adapters. If the adapter is stamped "UL Listed" with a *file number*, then it will have an internal fuse molded into the adapter (not replaceable) and that takes care of safety for the 15A outlet. UL requires that.
You better get your wiring right and sort out any problems with the appliance, because that fuse is NOT replaceable.
|
14,990,689 |
I understand that it is similar to the Fibonacci sequence that has an exponential running time. However this recurrence relation has more branches. What are the asymptotic bounds of `T(n) = 2T(n-1) + 3T(n-2)+ 1`?
|
2013/02/20
|
[
"https://Stackoverflow.com/questions/14990689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1533262/"
] |
After your insert query, use [mysql-insert-id](http://php.net/manual/en/function.mysql-insert-id.php).
```
<?php
...
$result = mysql_query("INSERT INTO orderdb(table_ID,MenuBook,order_status,order_date,order_receipt) VALUES('$table_ID', '$menuBook', '$order_status','$order_date','$order_receipt')");
$last_ID = mysql_insert_id();
...
?>
```
From the docs for mysql\_insert\_id():
>
> The ID generated for an AUTO\_INCREMENT column by the previous query on
> success, 0 if the previous query does not generate an AUTO\_INCREMENT
> value, or FALSE if no MySQL connection was established.
>
>
>
|
9,613,555 |
Can we consume our own C# dlls in metro style apps which is built using html & win Js?
|
2012/03/08
|
[
"https://Stackoverflow.com/questions/9613555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256244/"
] |
this works,
```
vi /srv/repos/hub/hooks/post-update
#!/bin/sh
cd /srv/www/siteA || exit
unset GIT_DIR
- git pull HUB master
+ git fetch HUB master
+ files=`git diff ..FETCH_HEAD --name-only --diff-filter=ACMRTUXB`
+ git merge FETCH_HEAD
+ for file in $files
+ do
+ sudo chown wwwrun:www $file
+ done
exec git-update-server-info
```
chown execs on only the files identified as being in the commit set -- small & fast.
|
612,024 |
I need to differentiate $x(t)=e^{2t}(4t^2-3t+1)$ to find velocity and acceleration at $3$ seconds.
I need to use the product rule.
I know $e^{2t} = u$ so $du(t)/dt = 2e^{2t}$
and $(4t^2-3t+1) = v$ and $dv= (8t-3)$
so $dy/dx = udv + vdu = (e^{2t})(8t-3)+(4t^2-3t+1)(2e^{2t})$
I am completely stuck where to go next
please help
|
2013/12/18
|
[
"https://math.stackexchange.com/questions/612024",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/116700/"
] |
You've done fine, now just factor out the factor $e^{2t}$ from each term and simplify! (It will make finding the second derivative, acceleration, easier if you simplify).
$$f'(t) = v(t) =(e^{2t})(8t-3)+(4t^2-3t+1)(2e^2t) = (e^{2t})\Big((8t-3)+(8t^2-6t+2)\Big) = e^{2t}(8t^2 + 2t - 1)$$
Evaluate at $t = 3$ to obtain velocity:
>
> $$v(3) = f'(3) = e^{6}(8(3)^2 + 2(3) - 1) = e^6(72 + 8 - 1) = 79e^6$$
>
>
>
Then, differentiate $f'(t)$ using the product rule again, and then evaluate at $t = 3$ to find acceleration at time = 3 seconds.
>
> $$f''(t) = a(t) = 2e^{2t}(8t^2 + 2t - 1) + 4e^{2t}(16t + 2)= 2e^{2t}\Big(8t^2 + 2t - 1 +32t + 4\Big) = 2e^{2t}(8t^2 + 34t + 3).\\$$ $$f''(3) = a(3) = 2e^6(72 + 102 + 3) = 354e^6$$
>
>
>
|
188,630 |
This post is an updated version of *[the original post](https://codereview.stackexchange.com/questions/162546/send-command-and-get-response-from-windows-cmd-prompt-silently)*, with the code examples below reflecting changes in response to very detailed inputs from user @pacmaninbw.
The updated source examples below also include the addition of a function that is designed to accommodate commands that do not return a response. The comment block describes why this function addition is necessary, and its usage.
I am interested in getting feedback with emphasis on the same things as before, so will repeat the preface of the previous post below.
>
> **The need:**
>
>
> I needed a method to programmatically send commands to the Windows 7
> CMD prompt, and return the response without seeing a console popup in
> multiple applications.
>
>
> **The design:**
>
>
> The environment in addition to the Windows 7 OS is an ANSI C (C99)
> compiler from National Instruments, and the Microsoft Windows Driver
> Kit for Windows 8.1. Among the design goals was to present a very
> small API, including well documented and straightforward usage
> instructions. The result is two
> exported functions. Descriptions for each are provided in their respective comment blocks. In its provided form, it is intended to be built as a DLL. The only header files used in this library are`windows.h` and `stdlib.h`.
>
>
> **For review consideration:**
>
>
> The code posted is complete, and I have tested it, but I am new to
> using `pipes` to `stdin` and `stdout`, as well as using Windows
> methods for `CreateProcess(...)`. Also, because the size requirements
> of the response buffer cannot be known at compile time, the code
> includes the ability to grow the response buffer as needed during
> run-time. For example, I have used this code to recursively read
> directories using `dir /s` from all locations except the `c:\`
> directory with the following command:
>
>
>
> ```
> cd c:\dev && dir /s // approximately 1.8Mbyte buffer is returned on my system
>
> ```
>
> I would especially appreciate feedback focused on the following:
>
>
> * Pipe creation and usage
> * `CreateProcess` usage
> * Method for dynamically growing response buffer (very interested in feedback on this)
> * Handling embedded `null` bytes in content returned from `ReadFile` function. (Credit to @chux, this is a newly discovered deficiency)
>
>
>
**Usage example:**
```
#include <stdio.h> // printf()
#include <stdlib.h> // NULL
#include "cmd_rsp.h"
#define BUF_SIZE 100
int main(void)
{
char *buf = NULL;
/// test cmd_rsp
buf = calloc(BUF_SIZE, 1);
if(!buf)return 0;
if (!cmd_rsp("dir /s", &buf, BUF_SIZE))
{
printf("%s", buf);
}
else
{
printf("failed to send command.\n");
}
free(buf);
/// test cmd_no_rsp
buf = calloc(BUF_SIZE, 1);
if(!buf)return 0;
if (!cmd_no_rsp("dir /s", &buf, BUF_SIZE))
{
printf("success.\n"); // function provides no response
}
else
{
printf("failed to send command.\n");
}
free(buf);
return 0;
}
```
**cmd\_rsp.h**
```
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Prototype: int int __declspec(dllexport) cmd_rsp(char *command, char **chunk, size_t size)
//
// Description: Executes any command that can be executed in a Windows cmd prompt and returns
// the response via auto-resizing buffer.
/// Note: this function will hang for executables or processes that run and exit
/// without ever writing to stdout.
/// The hang occurs during the call to the read() function.
//
// Inputs: const char *command - string containing complete command to be sent
// char **chunk - initialized pointer to char array to return results
// size_t size - Initial memory size in bytes char **chunk was initialized to.
//
// Return: 0 for success
// -1 for failure
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int __declspec(dllexport) cmd_rsp(const char *command, char **chunk, unsigned int chunk_size);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Prototype: int int __declspec(dllexport) cmd_no_rsp(char *command)
//
// Description: Variation of cmd_rsp that does not wait for a response. This is useful for
// executables or processes that run and exit without ever sending a response to stdout,
// causing cmd_rsp to hang during the call to the read() function.
//
// Inputs: const char *command - string containing complete command to be sent
//
// Return: 0 for success
// -1 for failure
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int __declspec(dllexport) cmd_no_rsp(const char *command);
#endif
```
**cmd\_rsp.c**
```
#include <windows.h>
#include <stdlib.h> // calloc, realloc & free
#include "cmd_rsp.h"
#define BUFSIZE 1000
typedef struct {
/* child process's STDIN is the user input or data entered into the child process - READ */
void * in_pipe_read;
/* child process's STDIN is the user input or data entered into the child process - WRITE */
void * in_pipe_write;
/* child process's STDOUT is the program output or data that child process returns - READ */
void * out_pipe_read;
/* child process's STDOUT is the program output or data that child process returns - WRITE */
void * out_pipe_write;
}IO_PIPES;
// Private prototypes
static int CreateChildProcess(const char *cmd, IO_PIPES *io);
static int CreateChildProcessNoStdOut(const char *cmd, IO_PIPES *io);
static int ReadFromPipe(char **rsp, unsigned int size, IO_PIPES *io);
static char * ReSizeBuffer(char **str, unsigned int size);
static void SetupSecurityAttributes(SECURITY_ATTRIBUTES *saAttr);
static void SetupStartUpInfo(STARTUPINFO *siStartInfo, IO_PIPES *io);
static int SetupChildIoPipes(IO_PIPES *io, SECURITY_ATTRIBUTES *saAttr);
int __stdcall DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
/* Respond to DLL loading by initializing the RTE */
if (InitCVIRTE (hinstDLL, 0, 0) == 0) return 0;
break;
case DLL_PROCESS_DETACH:
/* Respond to DLL unloading by closing the RTE for its use */
if (!CVIRTEHasBeenDetached ()) CloseCVIRTE ();
break;
}
/* Return 1 to indicate successful initialization */
return 1;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Prototype: int __declspec(dllexport) cmd_rsp(char *command, char **chunk, size_t chunk_size)
//
// Description: Executes any command that can be executed in a Windows cmd prompt and returns
// the response via auto-resizing buffer.
//
// Inputs: const char *command - string containing complete command to be sent
// char **chunk - initialized pointer to char array to return results
// size_t chunk_size - Initial memory size in bytes of char **chunk.
//
// Return: 0 for success
// -1 for failure
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int __declspec(dllexport) cmd_rsp(const char *command, char **chunk, unsigned int chunk_size)
{
SECURITY_ATTRIBUTES saAttr;
/// All commands that enter here must contain (and start with) the substring: "cmd.exe /c
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////
/// char cmd[] = ("cmd.exe /c \"dir /s\""); /// KEEP this comment until format used for things like
/// directory command (i.e. two parts of syntax) is captured
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////
const char rqdStr[] = {"cmd.exe /c "};
int len = (int)strlen(command);
char *Command = NULL;
int status = 0;
Command = calloc(len + sizeof(rqdStr), 1);
if(!Command) return -1;
strcat(Command, rqdStr);
strcat(Command, command);
SetupSecurityAttributes(&saAttr);
IO_PIPES io;
if(SetupChildIoPipes(&io, &saAttr) < 0) return -1;
//eg: CreateChildProcess("adb");
if(CreateChildProcess(Command, &io) == 0)
{
// Read from pipe that is the standard output for child process.
ReadFromPipe(chunk, chunk_size, &io);
status = 0;
}
else
{
status = -1;
}
free(Command);
return status;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Prototype: int __declspec(dllexport) cmd_no_rsp(char *command)
//
// Description: Variation of cmd_rsp that does not wait for a response. This is useful for
// executables or processes that run and exit without ever sending a response to stdout,
// causing cmd_rsp to hang during the call to the read() function.
//
// Inputs: const char *command - string containing complete command to be sent
//
// Return: 0 for success
// -1 for failure
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int __declspec(dllexport) cmd_no_rsp(const char *command)
{
/// All commands that enter here must contain (and start with) the substring: "cmd.exe /c
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////
/// char cmd[] = ("cmd.exe /c \"dir /s\""); /// KEEP this comment until format used for things like
/// directory command (i.e. two parts of syntax) is captured
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////
SECURITY_ATTRIBUTES saAttr;
const char rqdStr[] = {"cmd.exe /c "};
int len = (int)strlen(command);
char *Command = NULL;
int status = 0;
Command = calloc(len + sizeof(rqdStr), 1);
if(!Command) return -1;
strcat(Command, rqdStr);
strcat(Command, command);
SetupSecurityAttributes(&saAttr);
IO_PIPES io;
if(SetupChildIoPipes(&io, &saAttr) < 0) return -1;
status = CreateChildProcessNoStdOut(Command, &io);
free(Command);
return status;
}
static int SetupChildIoPipes(IO_PIPES *io, SECURITY_ATTRIBUTES *saAttr)
{
//child process's STDOUT is the program output or data that child process returns
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&io->out_pipe_read, &io->out_pipe_write, saAttr, 0))
{
return -1;
}
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (!SetHandleInformation(io->out_pipe_read, HANDLE_FLAG_INHERIT, 0))
{
return -1;
}
//child process's STDIN is the user input or data entered into the child process
// Create a pipe for the child process's STDIN.
if (!CreatePipe(&io->in_pipe_read, &io->in_pipe_write, saAttr, 0))
{
return -1;
}
// Ensure the write handle to the pipe for STDIN is not inherited.
if (!SetHandleInformation(io->in_pipe_write, HANDLE_FLAG_INHERIT, 0))
{
return -1;
}
return 0;
}
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
static int CreateChildProcess(const char *cmd, IO_PIPES *io)
{
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
SetupStartUpInfo(&siStartInfo, io);
// Create the child process.
bSuccess = CreateProcess(NULL,
cmd, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NO_WINDOW, // creation flags
//CREATE_NEW_CONSOLE, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if (!bSuccess)
{
return -1;
}
else
{
// Close handles to the child process and its primary thread.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
CloseHandle(io->out_pipe_write);
}
return 0;
}
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
static int CreateChildProcessNoStdOut(const char *cmd, IO_PIPES *io)
{
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
SetupStartUpInfo(&siStartInfo, io);
// Create the child process.
bSuccess = CreateProcess(NULL,
cmd, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NO_WINDOW, // creation flags
//CREATE_NEW_CONSOLE, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if (!bSuccess)
{
return -1;
}
else
{
// Close handles to the child process and its primary thread.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
CloseHandle(io->out_pipe_write);
}
return 0;
}
// Read output from the child process's pipe for STDOUT
// Grow the buffer as needed
// Stop when there is no more data.
static int ReadFromPipe(char **rsp, unsigned int size, IO_PIPES *io)
{
COMMTIMEOUTS ct;
int size_recv = 0;
unsigned int total_size = 0;
unsigned long dwRead;
BOOL bSuccess = TRUE;
char *accum;
char *tmp1 = NULL;
char *tmp2 = NULL;
//Set timeouts for stream
ct.ReadIntervalTimeout = 0;
ct.ReadTotalTimeoutMultiplier = 0;
ct.ReadTotalTimeoutConstant = 10;
ct.WriteTotalTimeoutConstant = 0;
ct.WriteTotalTimeoutMultiplier = 0;
SetCommTimeouts(io->out_pipe_read, &ct);
//This accumulates each read into one buffer,
//and copies back into rsp before leaving
accum = (char *)calloc(1, sizeof(char)); //grow buf as needed
if(!accum) return -1;
memset(*rsp, 0, size);
do
{
//Reads stream from child stdout
bSuccess = ReadFile(io->out_pipe_read, *rsp, size-1, &dwRead, NULL);
if (!bSuccess || dwRead == 0)
{
free(accum);
return 0;//successful - reading is done
}
(*rsp)[dwRead] = 0;
size_recv = (int)strlen(*rsp);
if(size_recv == 0)
{
//should not get here for streaming
(*rsp)[total_size]=0;
return total_size;
}
else
{
//New Chunk:
(*rsp)[size_recv]=0;
//capture increased byte count
total_size += size_recv+1;
//increase size of accumulator
tmp1 = ReSizeBuffer(&accum, total_size);
if(!tmp1)
{
free(accum);
strcpy(*rsp, "");
return -1;
}
accum = tmp1;
strcat(accum, *rsp);
if(total_size > (size - 1))
{ //need to grow buffer
tmp2 = ReSizeBuffer(&(*rsp), total_size+1);
if(!tmp2)
{
free(*rsp);
return -1;
}
*rsp = tmp2;
}
strcpy(*rsp, accum);//refresh rsp
}
}while(1);
}
// return '*str' after number of bytes realloc'ed to 'size'
static char * ReSizeBuffer(char **str, unsigned int size)
{
char *tmp=NULL;
if(!(*str)) return NULL;
if(size == 0)
{
free(*str);
return NULL;
}
tmp = (char *)realloc((char *)(*str), size);
if(!tmp)
{
free(*str);
return NULL;
}
*str = tmp;
return *str;
}
static void SetupSecurityAttributes(SECURITY_ATTRIBUTES *saAttr)
{
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr->nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr->bInheritHandle = TRUE;
saAttr->lpSecurityDescriptor = NULL;
}
static void SetupStartUpInfo(STARTUPINFO *siStartInfo, IO_PIPES *io)
{
siStartInfo->cb = sizeof(STARTUPINFO);
siStartInfo->hStdError = io->out_pipe_write;
siStartInfo->hStdOutput = io->out_pipe_write;
siStartInfo->hStdInput = io->in_pipe_read;
siStartInfo->dwFlags |= STARTF_USESTDHANDLES;
}
```
|
2018/03/01
|
[
"https://codereview.stackexchange.com/questions/188630",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/138048/"
] |
Handling embedded null bytes
----------------------------
`ReadFile(, lpBuffer,,,)` may read null characters into `lpBuffer`. Should this occur, much of code's use of `str...()` would suffer. Code instead needs to keep track of data as a read of "bytes" with a length and not as a *string*. I'd recommend forming a structure with members `unsigned char data[BUF_SIZE]` and `DWORD sz` or `size_t sz`. This affects code significantly. Effectively replace `str...()` calls with `mem...()` ones.
Minor: with using a "byte" buffer rather than a *string*, the buffer could start with `NULL`.
```
// char *accum;
// accum = (char *)calloc(1, sizeof(char));
char *accum = NULL;
```
Pipe creation and usage
-----------------------
Although there is much good error handling, `cmd_rsp()` fails to check the return value of `ReadFromPipe(chunk, chunk_size, &io);`.
```
// ReadFromPipe(chunk, chunk_size, &io);
if (ReadFromPipe(chunk, chunk_size, &io) == -1) TBD_Code();
```
Minor: Using `sizeof(char)` rather than `sizeof *accum` obliges a reviewer and maintainer to check the type of `accum`. In C, code can be simplified:
```
// accum = (char *)calloc(1, sizeof(char));
accum = calloc(1, sizeof *accum);
```
Minor: Unclear why code is using `unsigned` for array indexing rather than the idiomatic `size_t`. Later code quietly returns this as an `int`. I'd expect more care changing sign-ness. Else just use `int`.
```
// Hmmm
unsigned int total_size = 0;
int size_recv = 0;
```
CreateProcess usage
-------------------
Memory Leak:
```
if(SetupChildIoPipes(&io, &saAttr) < 0) {
free(Command); // add
return -1;
}
```
Minor: no need for `int` cast of a value in the `size_t` range.
```
// int len = (int)strlen(command);
// Command = calloc(len + sizeof(rqdStr), 1);
Command = calloc(strlen(command) + sizeof(rqdStr), 1);
```
Method for dynamically growing response buffer
----------------------------------------------
Good and proper function for `ReSizeBuffer( ,size == 0);`
Bug: when `realloc()` fails, `ReSizeBuffer()` and the calling code both free the same memory. Re-design idea: Let `ReSizeBuffer()` free the data and return a simple fail/success flag for the calling code to test. For the calling code to test `NULL`-ness is a problem as `ReSizeBuffer( ,size == 0)` returning `NULL` is O.K.
Unclear test: `if(!(*str)) return NULL;`. I would not expect disallowing resizing a buffer that originally pointed to `NULL`.
```
if(!(*str)) return NULL; // why?
if(!str) return NULL; // Was this wanted?`
```
Cast not needed for a C compile. Is code also meant for C++?
```
// tmp = (char *)realloc((char *)(*str), size);
tmp = realloc(*str, size);
```
For me, I would use the form below and let it handle all edge cases of zeros, overflow, allocation success, free-ing, updates. Be prepared for *large* buffer needs.
```
// return 0 on success
int ReSizeBuffer(void **buf, size_t *current_size, int increment);
// or
int ReSizeBuffer(void **buf, size_t *current_size, size_t new_size);
```
Tidbits
-------
Consider avoiding `!` when things work. This is a small style issue - I find a `!` or `!=` more aligns with failure than success.
```
// if (!cmd_no_rsp("dir /s", &buf, BUF_SIZE)) {
// printf("success.\n");
if (cmd_no_rsp("dir /s", &buf, BUF_SIZE) == 0) {
printf("success.\n");
```
With a change for handling piped data as a *string*, change variables names away from `str...`
|
24,157,940 |
I am having problems with my iframe. I really want the frame to auto adjust heights according to the content within the iframe. I really want to do this via the CSS without javascript. However, I will use javascript if I have too.
I've tried `height: 100%;` and `height: auto;`, etc. I just don't know what else to try!
Here is my CSS. For the frame...
```css
#frame {
position: relative;
overflow: hidden;
width: 860px;
height: 100%;
}
```
And then for the frame's page.
```css
#wrap {
float: left;
position: absolute;
overflow: hidden;
width: 780px;
height: 100%;
text-align: justify;
font-size: 16px;
color: #6BA070;
letter-spacing: 3px;
}
```
The page's coding looks like this...
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" �� "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>...</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="navigation">
<a href="/" class="navigation">home</a>
<a href="about.php" class="navigation">about</a>
<a href="fanlisting.php" class="navigation">fanlisting</a>
<a href="reasons.php" class="navigation">100 reasons</a>
<a href="letter.php" class="navigation">letter</a>
</div>
<div id="content" >
<h1>Update Information</h1>
<iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
```
Please note that the URL within the iframe is different then the website the iframe will be displayed on. However, I have access to both websites.
Can anyone help?
|
2014/06/11
|
[
"https://Stackoverflow.com/questions/24157940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493482/"
] |
I had this same issue but found the following that works great:
The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.
Here is what a typical YouTube embed code looks like, with fixed width and height:
```
<iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen></iframe>
```
It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):
```
<div class="container">
<iframe src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen class="video"></iframe>
</div>
```
And use the following CSS:
```
.container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
```
Here is the page I found the solution on:
<https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed>
Depending on your aspect ratio, you will probably need to adjust the `padding-bottom: 56.25%;` to get the height right.
|
1,459,739 |
I did a lot of searching and also read the PHP [$\_SERVER docs](http://php.net/reserved.variables.server). Do I have this right regarding which to use for my PHP scripts for simple link definitions used throughout my site?
`$_SERVER['SERVER_NAME']` is based on your web server's config file (Apache2 in my case), and varies depending on a few directives: (1) VirtualHost, (2) ServerName, (3) UseCanonicalName, etc.
`$_SERVER['HTTP_HOST']` is based on the request from the client.
Therefore, it would seem to me that the proper one to use in order to make my scripts as compatible as possible would be `$_SERVER['HTTP_HOST']`. Is this assumption correct?
**Followup comments:**
I guess I got a little paranoid after reading this article and noting that some folks said "they wouldn't trust any of the `$_SERVER` vars":
* <http://markjaquith.wordpress.com/2009/09/21/php-server-vars-not-safe-in-forms-or-links/>
* <http://php.net/manual/en/reserved.variables.server.php#89567> (comment: Vladimir Kornea 14-Mar-2009 01:06)
Apparently the discussion is mainly about `$_SERVER['PHP_SELF']` and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks.
My conclusion about my original question above is that it is "safe" to use `$_SERVER['HTTP_HOST']` for all links on a site without having to worry about XSS attacks, even when used in forms.
Please correct me if I'm wrong.
|
2009/09/22
|
[
"https://Stackoverflow.com/questions/1459739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142233/"
] |
That’s probably everyone’s first thought. But it’s a little bit more difficult. See [Chris Shiflett’s article *`SERVER_NAME` Versus `HTTP_HOST`*](http://shiflett.org/blog/2006/mar/server-name-versus-http-host).
It seems that there is no silver bullet. Only when you [force Apache to use the canonical name](http://httpd.apache.org/docs/2.2/mod/core.html#usecanonicalname) you will always get the right server name with `SERVER_NAME`.
So you either go with that or you check the host name against a white list:
```
$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
exit;
}
```
|
146,782 |
Tuberculosis was commonly called "consumption" for many years. When did "tuberculosis" or "TB" overtake "consumption" as the common term, in English, for the disease?
[This Ngram](https://books.google.com/ngrams/graph?content=Consumption,tuberculosis,T.B.&case_insensitive=on&year_start=1800&year_end=2000&corpus=17&smoothing=3&share=&direct_url=t4;,Consumption;,c0;,s0;;consumption;,c0;;Consumption;,c0;;CONSUMPTION;,c0;.t4;,tuberculosis;,c0;,s0;;tuberculosis;,c0;;Tuberculosis;,c0;;TUBERCULOSIS;,c0;.t4;,T.B.;,c0;,s0;;T.B.;,c0;;t.b.;,c0;;T.b.;,c0) isn't much use; it compares the use of the terms "consumption" and "tuberculosis" in American English from 1800 to 2000. Of course the problem is that "consumption" means many other things. The Ngram does show "tuberculosis" peaking between 1900 and 1920, but what I am interested in is roughly when a typical English speaker might have shifted from referring to the disease as "consumption," to "tuberculosis."
The dictionaries to which I have access simply state that "consumption" is an archaic term for the disease.
|
2014/01/18
|
[
"https://english.stackexchange.com/questions/146782",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/19894/"
] |
Expanding on Janus's excellent suggestion (make the search string more context-specific), the "switchover point is much clearer if you graph [**deaths from** consumption/tuberculosis](https://books.google.com/ngrams/graph?content=deaths%20from%20consumption,deaths%20from%20tuberculosis&case_insensitive=on&year_start=1800&year_end=2000&corpus=17&smoothing=3&share=&direct_url=t4;,deaths%20from%20consumption;,c0;,s0;;deaths%20from%20consumption;,c0;;deaths%20from%20Consumption;,c0;;Deaths%20from%20Consumption;,c0;;Deaths%20from%20consumption;,c0;.t4;,deaths%20from%20tuberculosis;,c0;,s0;;deaths%20from%20tuberculosis;,c0;;Deaths%20from%20tuberculosis;,c0;;Deaths%20from%20Tuberculosis;,c0;;DEATHS%20FROM%20TUBERCULOSIS;,c0)...

So we can reasonably say *tuberculosis* was already gaining currency before WW1, but by the *end* of the war it had almost completely displaced *consumption*. Perhaps because when a major protracted war ends, people want to make a fresh start in terms of language as well as politics and society.
---
My guess is that the actual cause of the disease (infection by [tubercle bacillus](http://www.thefreedictionary.com/tubercle+bacillus)) wasn't generally recognised until the turn of the century. The "germ theory" of disease is much associated with [Louis Pasteur, 1822 - 1895](http://inventors.about.com/od/pstartinventors/a/Louis_Pasteur.htm), but as it says in that link...
>
> During Louis Pasteur's lifetime it was not easy for him to convince others of his ideas, controversial in their time but considered absolutely correct today.
>
>
>
|
19,803,399 |
Say we have an iPhone that has mp3s synced to it that play normally with the built in ios music player. Can a webpage be coded in a way that if I surf to it using mobile safari, I can see my music library and play the files?
If so what APIs etc should I use?
|
2013/11/06
|
[
"https://Stackoverflow.com/questions/19803399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1640005/"
] |
On iOS, this is not possible. It *is* possible for Chrome Applications to get access to the local media library; however, iOS (even Chrome on Android right now, actually) do not support this.
|
4,624,748 |
How often do people use objects in PHP?
I have noticed it has not been used in any of the open source PHP projects I have looked into. It wasn't used in a web programming course at my Uni. I am just curious about how much objects are used by professional PHP developers.
|
2011/01/07
|
[
"https://Stackoverflow.com/questions/4624748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506565/"
] |
That's a very vague question, but OOP is used in the same way in PHP as it would be in any other scenario: as a way of modelling the interactions between discrete entities in your business logic.
A classic application for OOP in a web context would be a blog, where each post on the blog would be represented by an object, which in turn might have references to other objects representing the comments on that post.
As Jon said in his comment, though, OOP should be used only where it makes sense and logically fits into the system you're designing. Don't try to shoe-horn something into it just for the sake of it. Many PHP applications are simple enough not to require an OO approach, and are best implemented with a clean, straightforward procedural approach.
One caveat of OOP is that it can be quite difficult for beginners to learn, and is *very* easy to misunderstand. I started programming with PHP, and it took me a fair bit of trial and error to understand exactly how OOP should properly be used.
|
16,486 |
I've tried several times to get my head around this but failed everytime!!
I want to setup a working environment for creating websites that is efficient and straight forward to use. It needs to include version control and automatic backups as well as the ability to create and edit files.
The software list I have is:
1. Coda/Dreamweaver - for file editing.
2. Transmit - FTP client
The software I'm missing is:
1. Something for version control.
2. Something for automatic backups of both the files and database of the websites.
3. The ability to edit live files rather than FTP them down, edit, then FTP back up again.
Is there anything else that may be useful to include?
Ideally I'd like this as integrated as possible. I may also need some hand holding through the whole process!
**The most important aspect is that I'm on a Mac.**
Update:
One thing I forgot to mention is that I'm running several different sites with a mixture of static html and Wordpress.
UPDATE:
After taking Nick's advice I jumped straight in and tried his setup out, haven't looked back since! Amazing.
|
2011/07/06
|
[
"https://webmasters.stackexchange.com/questions/16486",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/7801/"
] |
Using [Coda,](http://www.panic.com/coda/) [Transmit,](http://www.panic.com/coda/) [Dropbox,](http://dropbox.com/) and Dropbox's [packrat](http://www.dropbox.com/help/113) feature, here's what I do:
### The workflow
1. Create a new folder in my local Dropbox directory for each new project.1
2. Create a new 'Site' in [Coda](http://www.panic.com/coda/), and set the folder from step 1 as the site's 'Local Root' folder.
3. Set the 'Remote Root' to the identical folder on the server.
4. Work on all files locally, and use Coda's 'Publish All' feature to push local file changes to the remote site periodically for testing.
### What this gives me
* **Automatic backups of all files to Dropbox with automatic unlimited versioning.** (Packrat gives you the unlimited versioning, but the standard 30 day versioning history might be enough for many). Every time I save a file it's automatically saved to Dropbox as a new version. I can rollback any file at any time via the Dropbox Web interface. I rarely use this, but it's nice to have it as it's saved my skin a few times.
* **'Proper' version control.** (Subversion support is now built into Coda, and there are Git [plugins](http://www.panic.com/coda/developer/community/plugins.php).)
* **Two-way syncing with Transmit.** If I suspect remote files have changed between edits, I use Transmit's mirroring features to sync remote changes from the server to my local machine. This is not a substitute for using more structured version control for code synchronisation and deployment, but for small projects and one-man jobs, it often suffices.
* **One-window general development** with Coda (which supports direct remote file editing without needing to set up a new Site if you need it, as does Transmit.)
From your wishlist, that gives you version control, automatic code backups, and remote file editing if you need it. (For safety I recommend working on the Dropbox-stored local copy and publishing changes to the server from time to time so that you maintain both a local and Dropbox backup automatically.)
### What about database backups?
Although I love [Navicat](http://www.navicat.com/) for MySQL database tinkering, I've not found a Mac-native automated database backup solution that I've been happy with. You could certainly hack together something using Automator/th3 aw3s0mE p0w3r of Unix, but I don't like to think that essential backups depend on my work machine being switched on (it's a laptop, after all!), so I found another solution.
I use Hostgator's [Site Auto Backup](http://siteautobackup.com/). It's a hosted service that lets you backup any website that uses the cPanel control panel (most shared hosting sites) with minimal configuration. It backs up files, databases, emails and logs every day. If your site doesn't use cPanel, it can back up via FTP and MySQL connections directly, which requires only a little more configuration.
Site Auto Backup costs about $20/year if you pay annually, and I think it's worth it for peace of mind. The admin interface could do with a bit of a refresh (see below), but it works as advertised and you can backup any site with it, not just Hostgator ones. There's no limit to the number of sites you can backup -- you just pay for storage over the provided 1GB -- so I backup all my client sites this way too. I don't charge for this as I consider it a basic essential service that's just part of the job, but you could bill clients for the service if you wanted to.

---
### Notes on Dropbox directory structure:
1: I have a single directory in my Dropbox folder called 'Sites', with subdirectories for each project named using the project's domain name: 'theproject.com' or 'beta.theproject.com' etc. If I'm starting a new site, the local site folder will be empty. If I'm working on an existing site, I will download the remote root directory to the local folder. (If I'm working on a WordPress site, I download only the `wp-content` or `themes` folder to save time.)
If I have multiple sites hosted on one server, I create several folders locally and several separate Sites in Coda (with the same FTP details).
|
18,118,923 |
Let's say I have multiple text boxes with array names, like:
```
<input type='text' name='test[]' class='test_tb' id='test1' value=''/>
<input type='text' name='test[]' class='test_tb' id='test2' value=''/>
```
Now if I was using a form, I could easily serialize it and send it, but I want to know how to build it manually. I tried something like
```
$.get('test.php',{
'test[]':$("#test1").val(),
'test[]':$("#test2").val()
},function(d){
console.log(d);
});
```
But since a object can't have repeating keys, obviously this didn't work...so what is the manual way of doing this?
PS: This is for learning purpose not any actual task.
|
2013/08/08
|
[
"https://Stackoverflow.com/questions/18118923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/510785/"
] |
Try
```
$.get('test.php',{
'test[]':[$("#test1").val(), $("#test2").val()]
},function(d){
console.log(d);
});
```
|
19,055,889 |
It seems the answers I searched online (including stackoverflow.com) get the image file id through gallery selection.
I have created my own file explorer.
Then how to do that?
I can create my own small size image; but I think it would be faster if we can make use of an exisiting thumbnail; and if it does not exist, I would prefer to create a thumbnail that is saved for later use.
[Update:]
OK, thanks for advice. So I will not create a thumbnail in the device, to avoid to use too much space.
Then is is better to do two steps:
Step 1: look for an exisiting thumbnail for the image file if it exists.
Step 2: if no thumbnail exists, then create my own small size bitmap (not save the it).
Then how to do Step 1, if I do not use the Gallery intent?
[Update 2:]
I also want to get the thumbnail of a video file.
I can use MediaMetadataRetriever to get a frame at any point of time, and rescale the image to a thumbnail. But I find it is very slow: I have 4 video files in the folder, and I can sense the delay.
So I think the better way to retrieve an existing thumbnail.
If I only know the file path and file name, how can I get it?
I think this question is the same as my original one, just it has more sense to do so.
|
2013/09/27
|
[
"https://Stackoverflow.com/questions/19055889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1914692/"
] |
You should use `if` instead of `for`:
```
fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "pepper"
if food_sought in fridge:
print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
else:
print("We couldn't find the food you were looking for")
```
---
If you really need to use `for .. in ..`, use different variable name. Or `food_sought` is overwritten.
```
fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "chicken"
for name in fridge:
if name == food_sought:
print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
break
else:
print("We couldn't find the food you were looking for")
```
|
1,250,983 |
When should one prefer object pool over dynamically allocated objects?
I need to create and destroy thousands of objects per second. Is it by itself enough to decide in favor of object pool?
Thanks.
|
2009/08/09
|
[
"https://Stackoverflow.com/questions/1250983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48461/"
] |
Yes, this is enough to decide in favor of object pool.
Quoting Boost documentation
>
> When should I use Pool?
>
>
> Pools are generally used when there is
> a lot of allocation and deallocation
> of small objects. Another common usage
> is the situation above, where many
> objects may be dropped out of memory.
>
>
>
See [Boost Pool](http://www.boost.org/doc/libs/1_39_0/libs/pool/doc/index.html) library
|
74,568,751 |
I am facing this issue from yesterday. This is the exact error: Failed to start feature-config: A e2-micro VM instance is currently unavailable in the us-central1-a zone. Alternatively, you can try your request again with a different VM hardware configuration or at a later time. For more information, see the troubleshooting documentation.
[](https://i.stack.imgur.com/yaLJj.png)
I had scheduled Google Compute Engine to TURN on & off at specific time using Instance scheduler but now I am locked out of it. I cannot even create a machine image to deploy on another zone
|
2022/11/25
|
[
"https://Stackoverflow.com/questions/74568751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337398/"
] |
I changed the Machine Configuration. As from your answer I could figure out that resources might not be available for the US Central Zone possibly due to traffic. I changed configuration to - n2-highcpu-2 vCPU 2 & Memory -2 GB
|
10,008,931 |
I have a list of rows in my datatable.
Now I wish to prioritize the rows not according to `DESC` or `ASC` but based on few similarities of my variables with the row values.
For example,
I have datatable with columns as below:
```
Name, Location, Age, Sex, Education..
```
And I already have some preferences of seeing those rows first which match my education and location, and those rows which doesn't match, can be after the first row.
How do I accomplish this?
I tried setting expression in `SELECT statement` with `OR` and `LIKE clause` but I didn't seem to be getting the right answer.
>
>
> ```
> DataRow[] row = ds.Tables[0].Select("Affiliations LIKE '%" + ftr2 + "%'OR Loc_city LIKE '%" + city1 + "%'OR Edu_Hist LIKE '%" + ftr + "%'OR Work_Hist LIKE '%" + ftr1 + "%' OR Priority='true'");
>
> ```
>
>
here i dont want to be strict that i want these values only but a preference setting that i want these values first, rest can be behind it..
|
2012/04/04
|
[
"https://Stackoverflow.com/questions/10008931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221463/"
] |
You get nullref because you don't set `_userRepository`. Set it in the `AdminController`s constructor and Niject will inject it happily:
```
public class AdminController : Controller
{
private readonly IRepository<User> _userRepository;
public AdminController(IRepository<User> userRepository)
{
_userRepository = userRepository;
}
//...
}
```
You can read here more about the [injection patterns with Ninject](https://github.com/ninject/ninject/wiki/Injection-Patterns) and [how injection works](https://github.com/ninject/ninject/wiki/How-Injection-Works).
|
60,612,562 |
I want to set the default value of 1 of my parameter using the other selected parameters dataset value.
for example, the content of the dataset is something like
```
[{'name': alex, 'id': 1},
{'name': bloom, 'id': 2},
{'name': kelly, 'id': 3},
{'name': david, 'id': 4},
{'name': lyn, 'id': 5}];
```
then in previous parameter, the user choose for name = alex, then how to set the next parameter value = 1, which the previous parameter's id.
|
2020/03/10
|
[
"https://Stackoverflow.com/questions/60612562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12638917/"
] |
Go to the parameter properties of the one you want to default > go to Default Values tab > Specify values > add 1 value and use this expression:
```
=Parameters!YourParameterName.Value
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.