text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Esseen's inequality for random series?
I am reading about convergence rates in the central limit theorem and have a question regarding Esseen's inequality.
Suppose $(X_j)_{j\in\mathbb{N}}$ is an independent sequence of random variables such that $\mathbb{E}X_j=0$ and $\mathbb{E}\lvert X_j\rvert^3<\infty$ for $j\in\mathbb{N}$. Define $\sigma^2_j:=\mathbb{E}X_j^2$ for $j\in\mathbb{N}$. As a reminder:
Esseen's inequality:. Let $n \in\mathbb{N}$. Put $B_n:=\sum_{j=1}^n\sigma_j^2$ and $F_n(x):=\mathbb{P}\left(B_n^{-1/2}\sum_{j=1}^n X_j<x\right)$ for $x\in\mathbb{R}$. Then for some absolute constant $c$
$$\sup_{x\in\mathbb{R}}\left\lvert F_n(x)-\Phi(x)\right\rvert \leq cB_n^{-3/2}\sum_{j=1}^n \mathbb{E}\lvert X_j\rvert^3 \tag{1},$$
where $\Phi$ denotes the cdf of the standard normal distribution.
Is then also the following true (with or without additional assumptions)?
Esseen's inequality for random series: Assume additionally that all the (random) series in the following converge and put $F(x):=\mathbb{P}\left(\left(\sum_{j=1}^\infty\sigma_j^2\right)^{-1/2}\sum_{j=1}^\infty X_j<x\right)$ for $x\in\mathbb{R}$. Then,
$$\sup_{x\in\mathbb{R}}\left\lvert F(x)-\Phi(x)\right\rvert \leq c\left(\sum_{j=1}^\infty\sigma_j^2\right)^{-3/2}\sum_{j=1}^\infty \mathbb{E}\lvert X_j\rvert^3,$$ where $c$ is the same constant as above.
Do we need that $F_n$ converges uniformly to $\Phi$, in order to interchange the limit and supremem on the LHS, when taking the limit as $n\to\infty$ in (1)?
EDIT: To clarify, I am additionally assuming here that $\sum_{j=1}^\infty\sigma_j^2<\infty$, $\sum_{j=1}^\infty \mathbb{E}\lvert X_j\rvert^3<\infty$, and the random series $\sum_{j=1}^\infty X_j$ converges almost surely.
A:
Fix a positive $\varepsilon$ and let $A_n$ be the event
$$
A_n:=\left\{\left\lvert \left(\sum_{j=1}^\infty\sigma_j^2\right)^{-1/2}\sum_{j=1}^\infty X_j-B_n^{-1/2}\sum_{j=1}^n X_j \right\rvert \gt \varepsilon\right\}.$$
Then for all $x\in\mathbb R$,
$$
F(x)-\Phi(x)\leqslant \mathbb{P}\left(\left(\left(\sum_{j=1}^\infty\sigma_j^2\right)^{-1/2}\sum_{j=1}^\infty X_j<x\right)\cap A_n^c\right)+\mathbb P(A_n)-\Phi(x)
$$
and the inclusion
$$
\left\{ \left(\sum_{j=1}^\infty\sigma_j^2\right)^{-1/2}\sum_{j=1}^\infty X_j<x\right\}\cap A_n^c \subset \left\{B_n^{-1/2}\sum_{j=1}^n X_j<x+\varepsilon \right\}
$$
hold hence
$$
F(x)-\Phi(x)\leqslant F_n(x+\varepsilon)-\Phi(x+\varepsilon)+
\Phi(x+\varepsilon)-\Phi(x)+\mathbb P(A_n).$$
Thus, Esseen's inequality gives that for all $n$,
$$
F(x)-\Phi(x)\leqslant cB_n^{-3/2}\sum_{j=1}^n \mathbb{E}\lvert X_j\rvert^3+
\sup_{x\in\mathbb R} \left(\Phi(x+\varepsilon)-\Phi(x)\right)+\mathbb P(A_n)
$$
and letting $n$ going to infinity gives
$$
F(x)-\Phi(x)\leqslant c\left(\sum_{j=1}^\infty\sigma_j^2\right)^{-3/2}\sum_{j=1}^\infty \mathbb{E}\lvert X_j\rvert^3+
\sup_{x\in\mathbb R} \left(\Phi(x+\varepsilon)-\Phi(x)\right) .
$$
The later supremum is reached for $x=-\varepsilon/2$ and is $\mathbb P\left(-\varepsilon/2\leqslant N\leqslant \varepsilon/2\right)$, where $N$ has a standard normal distribution and this goes to $0$ as $\varepsilon$ goes to $0$.
It remains to find an upper bound for $\Phi(x)-F(x)$. Here again, intersect with $A_n$ and control the difference between $F(x)$ and $F_n(x-\varepsilon)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
SCJP exam: Handle Exceptions
I'm studying for Java Programmer Certification (SCJP) exam. A question about exceptions, when handle exceptions is it best to handle a specific exception like NumberFormatException or catch all exceptions use the parent Exception class?
Base on my course unchecked exceptions are basically a RunTimeException which mostly result of a program bug. Does this mean that when I throw an exception manually I should rather use:
new Exception("... my message...")
and that I shouldn't handle RunTimeException?
Only handle checked exceptions?
A:
You should handle as specific Exceptions as possible. If you know when a RuntimeException may be thrown, you should usually fix your program so it doesn't throw that Exception.
As far as catching checked Exceptions go, you should handle as specific an Exception as you can so:
try {
} catch (FileNotFoundException fnfe){
} catch (IOException ioe){
} catch (Exception e){
}
When you are throwing Exceptions, you should almost never use throw new Exception().
Throw an exception that can give someone who sees it some more information about what happened when it was thrown. (i.e. IndexOutOfBounds or NullPointerExceptions. They give specific info w/out even looking at the message or stacktrace.)
If you want to throw an Exception, and you don't think the Java API has one that fits your case, it is best to subclass or extend the Exception giving it a very informative name.
| {
"pile_set_name": "StackExchange"
} |
Q:
Geth private network not starting
I am setting up a private ethereum network (which I have done before), then I noticed that the flags have changed on geth as well as the removal of the genesis flag all together.
I changed the flags accordingly to what is below but when it goes to load up I only get the following message without the console starting up properly.
geth init ./UTSGenesis.json networkid "1100" maxpeers 20 port 3000 console
I0816 09:34:47.826895 ethdb/database.go:82] Allotted 16MB cache and 16
file handles to /home/james/.ethereum/chaindata
I0816 09:34:47.894232 core/genesis.go:92] Genesis block already in
chain. Writing canonical number
I0816 09:34:47.894507 cmd/geth/main.go:300] successfully wrote genesis
block and/or chain rule set: f9deb7b6dc5fda52360cbab7f402b01ca4b76ff3112bdcce7f076d1b374d324c
As you can see, the console wont load up and it just quits out. What am I doing wrong?
A:
Using the geth init is a two part process.
The first is to initialise the blockchain with your parameters:
geth init ./UTSGenesis.json
The second is to run the node software on your newly created blockchain data. Note the -- before the options:
geth --networkid "1100" --maxpeers 20 --port 3000 console
See also:
Geth --genesis is giving Invalid Usage
geth init, what are the arguments?
| {
"pile_set_name": "StackExchange"
} |
Q:
I am stuck on a quiz in Udacity for JavaScript on Multi-dimensional arrays.
The quiz is about a multidimensional array and wants us to use a nested for loop to cycle through each element and replace the values that are divisible by 2 with the strings 'even' and 'odd' for even and odd numbers respectively. I cannot print out the array with the numbers divisible by 2 on to the console with the added string.
I have tried using .slice() and .splice() also but that did not get me the desired results either. Below is my latest attempt.
Programming Quiz - Multi-dimensional Arrays:
Question: Use a nested for loop to take the numbers array below and replace all of the values that are divisible by 2 (even numbers) with the string "even" and all other numbers with the string "odd".
var numbers = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
My code:
//create a nested for loop to cycle through each row and column
for(let row = 0; row < numbers.length; row++){
for(let col = 0; col < numbers.length; col++){
//if the even numbers in each row and column are divisible by 2, replace those
//numbers with the word even
if(numbers % 2 === 0){
numbers[row] += 'even';
}
}
}
console.log(numbers);
A:
You're real close! It comes down to how you're referencing the index in the 2-dimensional array. Iterating over it in a nested for loop requires first that we iterate through the rows, then the columns. In your example, you were actually iterating over the columns twice. In order to fix this, you would simply iterate over the row index of the numbers array in the nested for loop:
for(let row = 0; row < numbers.length; row++){
for(let col = 0; col < numbers[row].length; col++){
Then finally you will need to set the target index numbers[row][col] to even. In your example you used the addition assignment operator +=, which performs what is string concatenation. Instead of simply changing the index value to 'even', the += would actually add the word 'even' to the end of the number. So the index output would actually read something like 156even. Just drop the plus sign in order to reassign the index to even:
numbers[row][col] = 'even';
var numbers = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
for(let row = 0; row < numbers.length; row++){
for(let col = 0; col < numbers[row].length; col++){ //iterate over the n-th index of numbers[]
if(numbers[row][col] % 2 === 0){ //numbers[row][col] points to the nested index
numbers[row][col] = 'even'; //set index to 'even'
}
}
}
console.log(numbers);
This video is a nice explanation of how iterating over 2d arrays works: https://www.youtube.com/watch?v=qdT1P2qmsmU
The video is using Java, but the idea is exactly the same.
Hope this helps! Multi-dimensional arrays are tough to wrap your brain around!
| {
"pile_set_name": "StackExchange"
} |
Q:
How many hits can an armoured thug take?
In a beatdown attack, how many beatdown hits can an armoured thug take before being finished?
A:
14 hits as Catwoman (three samples).
10 hits as Batman (even while juicing, but not switching targets).
Two theories are that they either get more health as the fight goes on in Joker's Carnival and/or different armored thugs have different health, because—on at least one occasion—an armored thug took 36 hits.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access the window object from the document object
Is it possible to access the window object directly from the document object in Javascript?
For example:
// window.frames[0] returns the document object of the first frame or iframe found on the page
myFunc(window.frames[0]);
function myFunc(doc) {
// I want to do something along these lines:
var wnd = doc.getWindow();
alert("Found frame: " + wnd.name);
for (var i=0; i<wnd.frames.length; i++) {
myFunc(wnd.frames[i]);
}
}
I can't use jQuery for this, sorry.
A:
According to the MDN documentation you should already be getting the window with window.frames[0]. If you want the actual document you need to grab the actual frame element and dig into the document.
var firstFrame = document.getElementsByTagName( "iframe" )[ 0 ];
firstFrame.contentWindow; // The window
firstFrame.contentWindow.document; // The document
Note: I believe contentWindow isn't supported in very early versions of Safari (pre-3.0 IIRC)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass a string along with an injected dependency in ASP.NET Core v2
I have the below method in my Startup.cs class of my ASP.NET Core v2 project. My question is how to setup a class/service where a string value is passed to a class, along with an injected dependency.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add custom services.
services.AddSingleton<IMyAssistantClass, MyAssistantClass);
services.AddSingleton<MyClassManager>(s => new MyClassManager("connectionString", /* How to inject IMyAssistantClass? */);
// Other setup....
}
A:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyAssistantClass, MyAssistantClass);
services.AddSingleton<MyClassManager>(s =>
{
var imy = (IMyAssistantClass) s.GetService(typeof(IMyAssistantClass))
new MyClassManager("connectionString", imy);
}
);
}
// nice way to make it more convenient is to add extension method to IServiceCollection, like
public static T Resolve<T>(this IServiceProvider serviceProvider)
{
return (T) serviceProvider.GetService(typeof(T));
}
and then you could just call s.Resolve<IMyAssistantClass>();
| {
"pile_set_name": "StackExchange"
} |
Q:
List of structs - the value of the struct items is always null
i have a list of structs : user_stocks = new List<stock_Str>();
the struct is defined:
public struct stock_Str
{
public String name;
public int quote ;
public int chenge;
public bool quote_a;
public bool chenge_a;
public int[] rate_alarm;
public int[] chenge_alarm;
}
when i add item to the list i do:
stock_Str str = new stock_Str();
str.name = tbStockName.Text;
str.chenge_a = false;
str.quote_a = false;
str.quote = 0;
str.chenge = 0;
str.chenge_alarm = new int[2];
str.rate_alarm = new int[2];
for (int i = 0; i < 2; i++)
{
str.rate_alarm[i] = 0;
str.chenge_alarm[i] = 0;
}
_mainApp.user_stocks.Add(str);
my problems:
when i try to change values of the list items(of type struct), it don't change them!
my two arrays of two int's always set to null!
how can i fix it?
A:
a: that should not be a struct, at all
b: the "value" of a struct is never null; even Nullable<T>'s null is a bit of a magic-trick with smoke, mirrors and misdirection
Re the problem;
1: yes, that is because structs have copy semantics; you have altered a copy - not the same one
2: probably the same thing
Here's a more appropriate implementation; I imagine it'll fix most of your problems:
public class Stock
{
public string Name {get;set;}
public int Quote {get;set;}
public int Chenge {get;set;}
public bool QuoteA {get;set;}
public bool ChengeA {get;set;}
public int[] RateAlarm {get;set;}
public int[] ChengeAlarm {get;set;}
}
I'm unclear what the intent of the last 2 is, but personally I would prefer a list if it is a dynamic collection, for example:
private List<int> rateAlarms;
public List<int> RateAlarms {
get { return rateAlarms ?? (rateAlarms = new List<int>()); }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove/Destroy Function logic (Struct/Tries)
I've been working on a Trie program for practice and i'm running into some logic/coding issues when it comes to trying to create a method that removes or destroys words that are currently in the trie:
#include "trie.h"
/**************************************************************************/
/* Helper Functions
* trie_node_t * trie_new( void );
* Allocates memory for a new trie node
* Returns NULL if memory allocation was not possible or
* a memory address to a trie_node in the heap
/**************************************************************************/
trie_node_t * trie_new( void ){
trie_node_t * tmp = NULL;
int i;
if ( ( tmp = ( trie_node_t * ) malloc ( sizeof( trie_node_t ) ) ) == NULL )
return NULL;
for( i = 0; i < ALPHA_SIZE; i++ ) {
tmp->child[ i ] = NULL;
tmp->end = 1;
}
return tmp;
}
/**************************************************************************/
/* Functions functions
* int trie_size ( trie_node_t * root );
* Returns the number of words in the trie
* int trie_contains ( trie_node_t * root, char word[ ] );
* Returns 1 if a the word is in the trie
* 0 otherwise
* int trie_insert ( trie_node_t ** rootRef, char word[ ] );
* Returns 1 if the word is inserted in the trie
* 0 otherwise
* int trie_remove ( trie_node_t ** rootRef, char word[ ] );
* Returns 1 if the word is removed from the trie
* 0 otherwise
* int trie_destroy ( trie_node_t ** Tref );
* Returns 1 if the trie and all its node are destroyed
**************************************************************************/
int trie_size ( trie_node_t * root ) {
int i = 0;
int count = 0;
trie_node_t *temp = root; //Creates a temp variable (Because its being modified)
//if the reference does not exist(no more children)
if (temp == NULL){
return EXIT_FAILURE;
}
//loops through the child array
for (i = 0; i < ALPHA_SIZE; i++){
//if the reference to next child is not null
if(temp->child[i] != NULL){
//and the end character is '/0' (or not)
if(temp->child[i]->end == '/0'){
count += 1;
}
//add the return of trie_size to count, then run through the method again at the lower level.
count += trie_size(temp->child[i]);
}
}
return count;
}
/**************************************************************************/
int trie_contains ( trie_node_t * root, char word[ ] ){
trie_node_t *temp = root; //Create a temp variable, can't use the default root. (just a location).
int i = 0;
int length = strlen(word); //finds the length of array
int index = 0;
if (temp == NULL){
return EXIT_FAILURE;
}
if(!valid_word(word)){
return 0;
}
for (i = 0; i < length; i++){
index = charToInt(tlower(word[i]));
if (!temp->child[index]){
return 0;
}
temp = temp->child[index];
}
if (temp->end != '/0'){ //Checks if the end character at the last index is '/0' if it is not, it is not a word. Return 0 (not found)
return 0;
}
return 1;
}
/**************************************************************************/
int trie_insert ( trie_node_t ** rootRef, char word[ ] ){
trie_node_t *temp = *rootRef; //Create a temp variable, can't use the default rootRef. (just a location).
int i = 0;
int length = strlen(word); //finds the length of array
int index = 0;
if (temp == NULL){ //checks that the reference is not null
return EXIT_FAILURE;
}
if (!valid_word(word)){//checks if word is valid.
return 0;
}
for (i = 0; i < length; i++){
if (word[i] == '/0'){
index = 26;
} else if (word[i] >= 'A' || word[i] <= 'Z'){
index = charToInt(tolower(word[i])); //turns the word[i] into a usable integer.
}
else {
return EXIT_FAILURE;
}
if (!temp->child[index]){ //if there is not a child reference.
temp->child[index] = trie_new(); //create one.
}
temp = temp->child[index]; //move down to next level (next child)
}
temp->end = '\0';
return 1;
}
/**************************************************************************
* I'm pretty sure the majority of this method is incorrect, this was just an attempt I had. From what I understand I have to do is this:
* (1) Find the last character in the word (Found with the '/0' end char) and as long as there are no nodes connected at a lower level free the memory.
* (2) Move up (recursion is probably the easiest way to do this, but I haven't been able to figure out how) and check again.
* (3) Continue until the first letter of the word is reached, then exit.
* My question is how do I check to see if another node is connected? Also what would be the format of the recursive call?
**************************************************************************/
void trie_remove ( trie_node_t ** rootRef, char word[ ] ){
trie_node_t *temp = *rootRef;
int i = 0;
int index = 0;
int length = strlen(word);
if (temp == NULL){
return;
}
if (!valid_word(word)){
return;
}
//Code is incomplete, just an attempt.
for (i = 0; i < length; i++){
index = charToInt(tolower(word[i])); //not sure if this is necessary.
if (temp->child[i]->end == '/0'){
free(temp->child[i]);
}
}
return;
}
/**************************************************************************/
int trie_destroy ( trie_node_t ** rootRef ){
//issues with logic here, not exactly sure how to do this.
return 1;
}
/**************************************************************************/
int trie_init(trie_node_t **rootRef){
if ( *rootRef == NULL) {
*rootRef = trie_new();
}
return 1;
}
/**************************************************************************/
int valid_word (char word[]){
int length = 0;
int i = 0;
for (i = 0; i < length; i++){
if(charToInt(word[i]) > 26 || charToInt(word[i]) < 0){
return 0;
}
}
return 1;
}
/**************************************************************************/
int charToInt(char c){
return (int)c-(int)'a';
}
Trie.h: (Important stuff anyways) ALPHA_SIZE is 27.
typedef struct trie_node {
char end;
struct trie_node *child[ ALPHA_SIZE ]; //reference to trie node.
}trie_node_t;
I hope I formatted this question correctly, and I have looked on the site for possible solutions already but have yet to find any. If anyone can help me check my logic/ assist me in the coding of these methods that would be amazing. I don't just want the code I want to learn why it works!
Thanks in advance.
A:
for Remove, you need to remove free'd pointers from the trie:
for (i = 0; i < length; i++){
index = charToInt(tolower(word[i])); //not sure if this is necessary.
if (temp->child[i]->end == '/0'){
free(temp->child[i]);
temp->child[i]=0; // lets not point to free'd elements
}
}
For destroy - try recursion, roughly:
for (int i=ALPHA_MIN; i < ALPHA_MAX; ++i)
{
if (rootRef->child[i])
{
trie_destroy(rootRef->child[i]);
}
}
free (rootRef);
| {
"pile_set_name": "StackExchange"
} |
Q:
Is .NET Socket Send()/Receive() thread-safe?
Since a socket is full duplexed, meaning you can send and recieve simultaneously. So, is the .NET Socket Send()/Receive() thread-safe? I need to Send() and Receive() in 2 threads.
A:
Quote from the MSDN docs about the Socket class (under Thread Safety, towards the end of the page):
Instances of this class are thread
safe.
So I would suppose the answer is "yes".
| {
"pile_set_name": "StackExchange"
} |
Q:
Show that $\mathfrak{a}^n\not\subset\mathfrak{q}$.
Let $\mathfrak{a},\ \mathfrak{p}\subset R$ be two ideals, $\mathfrak{p}$ prime, with $\mathfrak{a}\not\subset\mathfrak{p}.$ Show that $\mathfrak{a}^n\not\subset\mathfrak{p}$.
I tried this by induction on $n$.
So $n=1$ is just the hypothesis, supose that $\mathfrak{a}^{n-1}\not\subset\mathfrak{p}$. We can consider all the $\alpha^2\in\mathfrak{a}^n$ such that $\alpha\in\mathfrak{a}^{n-1}$. If all the $\alpha^2$ were on $\mathfrak{p}$ we would have that $\alpha^2=\alpha\ · \alpha\ \in\mathfrak{p}$ but $\mathfrak{p}$ is prime so $\alpha\in \mathfrak{p},\ \forall\alpha\in\mathfrak{a}^{n-1},$ which is a contradiction.
Is my prove correct? Is there any other prove? Am i just trying to prove somethig trivial?
A:
Let's show the contrapositive: if $\mathfrak{a}^n \subseteq \mathfrak{p}$, let $a\in \mathfrak{a}$ and note that $a\cdot a^{n-1}=a^n\in \mathfrak{a}^n \subseteq \mathfrak{p}$. By primeness we have either $a\in \mathfrak{p}$ and/or $a^{n-1}\in \mathfrak{p}$. If the former is true we are done, if the latter holds we can, again conclude, by primeness, that either $a\in \mathfrak{p}$ and/or $a^{n-2}\in \mathfrak{p}$. Keep on applying this argument til you eventually have $a\in \mathfrak{p}$, showing that $\mathfrak{a} \subseteq \mathfrak{p}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does 'flavored English' mean here?
I came across this usage in the novel Lost Horizon by English writer James Hilton,Chapter 4.Here is the context.
Her concession evoked a formal bow from Chang. "But why not, madam?"
he replied in his precise and flavored English. "Must we hold that
because one religion is true, all others are bound to be false?"
A:
Flavour can mean a kind, variety, or sort.
Flavoured English refers to different types of English e.g. different dialects, or English that is influenced by another language, or accent of some type e.g. Dutch-flavoured, Finnish-flavoured, locally-flavoured, internationally-flavoured... I even found the expression full-flavoured English idiom in English Translation and Classical Reception: Towards a New Literary History
By Stuart Gillespie
Chang's English is described as being "precise and perhaps too accurate" and "perfect" in Chapter 3, and so that would be the flavour of his English - perfect, precise and too accurate, i.e. unnatural, probably too formal, most likely not including contractions and other features of connected speech.
The author never mentions what accent or dialect Chang speaks, and I've always assumed he spoke RP with a Chinese accent, but other readers may interpret perfect, precise and accurate as implying no Chinese accent at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
When is RF grounding necessary, and when is it not?
I've seen many installations, particularly at field day and also in second-floor installations, where RF grounding is ignored entirely. What are the drawbacks to this and when is it absolutely essential to have RF grounding?
A:
Two drawbacks to ignoring your grounding:
You will have a poor(er) signal.
You could become the ground and experience an RF burn first-hand.
That said, VHF antennas are often not grounded - handhelds and VHF radios in cars, for example.
A:
I think there might be confusion between RF ground, counterpoise, and electrical safety grounding. I am going to restrict my answer to RF ground (but, the word counterpoise is often used for the same thing).
In a perfectly balanced antenna, such as a Dipole at its resonant frequency, there is no need for an RF ground since no current would flow to the RF ground (like I said, in a perfect balanced antenna).
In a perfectly unbalanced antenna, such as a 1/4-wave vertical, an RF ground (aka counterpoise) is absolutely necessary to "complete" the antenna and make it whole. As they say, the ground image of your quarter wave antenna is the "other half" of the antenna and current will flow in this ground.
This is why a quarter wave antenna needs some sort of RF ground counterpoise made of conductors to make this current flow less lossy. Just relying on the ground itself results in a very lossy other half of your vertical and thus definitely not as efficient. In general, the more you can make the ground a good conductor (more radials, etc.) then the more efficient your antenna will be.
Given these two extremes, the need for an RF ground depends on all kinds of situations where the actual individual antenna geometry, height above ground, other nearby conductors, and so on come into play.
If your dipole antenna is not balanced for example, then common-mode current will flow down your feed line and radiate or enter into your shack and cause other problems. Making sure that your equipment is well grounded may help eliminate some of this RFI but it is best to eliminate the common-mode currents using an RF choke at the antenna feed point.
In summary, for good balanced antennas such as dipoles, Yagis, and similar geometries, RF grounding should not be necessary. If you have an unbalanced antenna like a vertical or a single long-wire antenna, or an inverted-L, or similar then a ground plane (RF ground) is required for efficient operating.
| {
"pile_set_name": "StackExchange"
} |
Q:
Differences between Dixit versions?
I'm concerned my niece, who's ten and has been raised on the likes of Hannah Montana, has little to no imagination or creativity. I want to find games we can play that will push her thinking out of the Disney drone-mold and I think that Dixit looks perfect for this. However, there's a problem; there are too many versions.
Amazon.co.uk stocks the following versions of Dixit:
Dixit
Dixit 2
Dixit 3
Dixit Odyssey
Dixit Journey
To me Odyssey looks the most random, but may be too far out for someone with little imagination, at least to start with. Common sense suggests starting with Dixit, as it's the first, but that also makes it the oldest; theoretically the newest would be the most stable and well made.
I'm not looking for opinions here, rather I'm after facts about the different games that may help decide which one is right for us.
So my question is: What makes each version of Dixit different, and what can you tell me about each that may help decide which version is best for my situation?
A:
I personally own all of the above apart from Dixit Journey (which I didn't even know existed).
You should know that, Dixit 2 and 3, aren't technically stand-alone games; they're only sets of additional cards.
Dixit Oddysey is nearly the same as original Dixit when it comes to rules. As far as I remember it has all the rules the original had, plus some additions for bigger number of players. It also has a set of pieces for greater number of players (up to 12, I think). The biggest difference are the actual cards - those are entirely new when compared to original.
My recommendation is to buy the Oddysey, as it contains the game pieces helpful* in playing a game and a manual. Then if your niece likes the game you could buy the others for additional cards.
*) As long as you have access to the game rules, you don't really need anything apart from the cards. All the other pieces in the boxes are used to keep track of players score, and to 'vote' for the cards - if you can manage this some other way (easiest and most crude would be pen&paper solution) you could buy only the cards.
A:
The concept of all the Dixit games are the same, they just have different images. The regular Dixit's images are definitely random. The Odyssey and Journey are more themed around travel and adventure. If you are a fantasy adventure person, I'd recommend Journey because there is Harry potter and Lord of the Rings references galore to be made. As for the regular Dixits (1,2, and 3) they all will be of the same quality of playing so if you have the chance to look at the cards, pick the pack with your favorite artwork. The whole point of the game is to see the creative things people see in each card. You and your niece may not think of the same idea for one card and that is the beauty and re-usability of the game.
A:
We bought the Journey version for our 8 year old a couple of years ago. We liked the concept of the game, but the images used in this version are dark and a bit disturbing. Almost all of them depict sad or angry characters in depressing or distressed scenes. I do not recommend this version as a family-friendly game.
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC 3 Selecting and deselecting checkboxes using jQuery
I have a view that displays a few images with checkboxes allowing the user to decide whether to save each image. I'm hiding the checkboxes, and instead using a checkmark or an X on top of the image to represent whether or not it is selected. This is all working fine. However, the value of the checkbox is not changing - it always remains unselected.
Here is my code in the view:
<div class="imgCheckBoxes">
<label for="MyImages_Cover" class="imgCheckBox">
<img src="http://example.com/image.jpg" alt="cover" />
</label>
@Html.CheckBoxFor(m => m.MyImages.Cover, new { @class = "check-box hideChkBx chkForImg" })
</div>
Which renders the following HTML:
<div class="imgCheckBoxes">
<label for="MyImages_Cover" class="imgCheckBox">
<img src="http://example.com/image.jpg" alt="cover" />
</label>
<input class="check-box hideChkBx chkForImg" id="MyImages_Cover"
name="MyImages.Cover" type="checkbox" value="true" />
<input name="MyImages.Cover" type="hidden" value="false" />
</div>
My jQuery code is as follows (removed some code dealing with positioning, etc):
var closeBtn = '../Content/img/close.png';
var okBtn = '../Content/img/ok.png';
$(document).ready(function (e) {
if ($('.imgCheckBox').html() != null && $('.imgCheckBox').html() != '') {
initializeOkCloseImg();
}
$('.chkForImg').change(function (e) {
initializeOkCloseImg();
});
});
function initializeOkCloseImg() {
var chkImg = '';
$('.chkForImg').each(function (index, element) {
chkImg = closeBtn;
if ($(this).is(':checked')) {
chkImg = okBtn;
}
});
}
Everything is working correctly in terms of switching the images denoting checked/unchecked, but when the form is posted the checkbox is always false. What am I missing here?
A:
Alright, I finally figured out the problem. The problem was actually not with the jQuery, but with my view model. Apparently this wasn't working because I was using a model inside my view model (MyImages.Cover). This for some reason threw everything out of wack. When I just use a standard bool in my view model, everything works perfectly. I have no idea why that is, but it kind of sucks since I need to reuse this logic on a few pages and defining individual properties in every view model seems tedious and unnecessary. Wish there was an easier way!
| {
"pile_set_name": "StackExchange"
} |
Q:
You've been signed in with a temporary profile windows 8.1
We've got roaming profiles from a Windows Server 2012 AD controller, and several windows 7 machines which log in and out fine.
We have one problem machine, a Windows 8.1 laptop which constantly brings up the error "You've been signed in with a temporary profile". I've followed the steps as listed here: http://www.eightforums.com/tutorials/38817-you-ve-been-signed-temporary-profile-fix.html but the issue returns after restarting the machine. The same profile signs in fine in Windows 7, but no matter which user we try, the same error comes up on the Windows 8.1 Machine
We've tried wiping the laptop and reinstalling windows 8.1 but the problem persists. This is very frustrating and Microsoft support has been terrible.
Anyone have any ideas what's causing this?
A:
Profiles from one version of Windows are not compatible with other versions. You need to create separate profile folders for each platform. Please see Microsoft article KB2890783 for a hotfix and needed registry entry.
| {
"pile_set_name": "StackExchange"
} |
Q:
Highest $n$ such that $2^n|a^{2012}+a^{2013}+a^{2014}+\cdots +a^{3012}$,$a=4k+2$
A question from BdMO 2013 Nationals:
Let $a$ be an integer divisible by 2 but not divisible by 4. What is the largest positive integer n such that $2^n|a^{2012}+a^{2013}+a^{2014}+\dots +a^{3012}$?
I simply rewrote $a^{2012}+a^{2013}+a^{2014}+\dots +a^{3012}$ as $a^{2012}(1+a+a^2+\dots +a^{1000})$. The second factor is odd.Therefore by Euclid's lemma,$2^n|a^{2012}$. We know that $a$ is of the form $4k+2$,$k=0,1,\dots$. This implies that $2^n|(4k+2)^{2012}$ and therefore $2^n|2^{2012}*(2k+1)^{2012}$. Again by Euclid's lemma,$2^n$ must divide $2^{2012}$. The largest value of $n$ is therefore $2012$. Am I correct?
A:
Note that $a=2(2k+1)$. Hence,
$$f(a) = a^{2012} + a^{2013} + \cdots + a^{3012} = a^{2012}\left(1+a+\cdots+a^{1000}\right)$$
Since $a$ is even, we have $1+a+\cdots+a^{1000}$ is odd. Hence, the highest power of $2$ that divides $f(a)$, is the highest power of $2$ that divides $a^{2012}$.
What you have done is absolutely correct. Pat yourself on your back.
| {
"pile_set_name": "StackExchange"
} |
Q:
Speech recognition issue in bot
I am working in bot framework and enabled speech in it.
When testing the speech functionality it is not recognizing few words like "HR".
I tried with different region's subscription key (Westus, eastus, common). In all the cases it is not recognizing word "HR".
How to make it recognize that word?
Is there any option?
speechOptions = {
speechRecognizer: new CognitiveServices.SpeechRecognizer({
subscriptionKey:
'*******************'
}),
speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
gender: CognitiveServices.SynthesisGender.Female,
subscriptionKey: '***********************',
voiceName: 'Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)'
})
};
A:
Unfortunately, I don't believe this is possible at the moment. There is currently an issue on the Web Chat repo to add support for Biased Word Lists for Speech. Hopefully, it should be prioritized in the 4.6 release. I know the development is beginning to focus on creating a better user experience for speech in Web Chat.
In the meantime, you could prompt your use to phrases like "Human Resources" instead of "HR."
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I avoid this inline Javascript?
I have a wordpress site. Under single.php, I have the following body tag
<body <?php body_class(); ?> onLoad="func(<?php echo $thePostID?>);" >
Reading articles on the web made me convinced of avoiding inline CSS and inline javascipt. So I made a restructuring of my site so that styles and scripts are contained now in external files. Except for this line of code since it really need the post id and I dont know how can I retrieve it outside of single.php.
Your usual help is appreciated.
A:
Use attributes:
<body data-post-id="<?php echo $thePostID?>">
You can then write
var postId = document.body.getAttribute('data-post-id');
| {
"pile_set_name": "StackExchange"
} |
Q:
What does this number theory statement mean?
I recently started studying number theory by myself and I am reading a book about number theory. There is one thing that I don't understand, the statement below:
If $a,b \in \mathbb{Z}$, then there is a $d \in \mathbb{Z}$ such that $(a,b)=(d)$.
I understand everything but the $(a,b)=(d)$. I know it has to do something with set theory probably, but what? Specifically why d is in parentheses and a pair is equal to a single variable?
A:
Notation. Let $R$ be a commutative ring and let $a_1,\ldots,a_n$ be elements of $R$, then the ideal generated by $a_1,\ldots,a_n$ is denoted by $(a_1,\ldots,a_n)$.
In your case, $(a,b)=\mathbb{Z}a+\mathbb{Z}b$ and $(d)=\mathbb{Z}d$.
A:
It's ring-theoretic ideal language for $\,a\Bbb Z + b \Bbb Z = d\Bbb Z,\ $ i.e. $\,|d| = \gcd(a,b).\ $
A:
$(a,b)$ means (in simple words) everything you get by multiplying and adding whatever is in $\mathbb{Z}$. More precisely, it is the ideal generated by $a$ and $b$. Similarly, $(d)$ is generated by $d$ single handedly, i.e., its multiples.
Two elements generate an ideal, which is "as fine as" their gcd. Indeed, this is what gcd means: it is the "finer mesh" that covers their union. The gcd is the "common nature" of them, which may also give this "joined mesh". For example, adding and multiplying whatever by 6 and 10, then you get all multiples of 2. Here, gcd(6,10)=2. This is why gcd is also notated as (6,10).
If you want a proof of this, you probably may find it in the section you ar reading, no matter what book you are referring to. Or you may want to show it yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
strtotime afternoon times reflecting 0
I've got an issue where strtotime returns my afternoon times as 0.
This is my code:
date_default_timezone_set('Africa/Johannesburg');
$from = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_start'] . ':00 ' . date('A',$_GET['meeting_start']));
$to = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_end'] . ':00 ' . date('A',$_GET['meeting_end']));
Basically, a user selects the date (2012-06-19) and types in a start time (filtered, 14:00) and end time (filtered, 15:00).
This piece then converts the strings given to seconds.
It works with anything I type before 13:00, but returns 0 when I type anything after 12:59
Some test cases:
User Input:
Date: 2012-06-19
Start: 10:00
End: 11:50
Result:
start: 1340092800
end: 1340099400
User Input:
Date: 2012-06-19
Start: 11:50
End: 13:00
Result:
start: 1340099400
end: 0
It's probably a stupid mistake again, but any help would be appreciated. Why does it return 0?
A:
You're mixing 12-hour and 24-hour formats together. Date format 'A' for AM and PM suffixes tells that 12-hour format is in use, so basically you can't deal with hour numbers greater than 12.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is an intuitive explanation for how PCA turns from a geometric problem (with distances) to a linear algebra problem (with eigenvectors)?
I've read a lot about PCA, including various tutorials and questions (such as this one, this one, this one, and this one).
The geometric problem that PCA is trying to optimize is clear to me: PCA tries to find the first principal component by minimizing the reconstruction (projection) error, which simultaneously maximizes the variance of the projected data.
When I first read that, I immediately thought of something like linear regression; maybe you can solve it using gradient descent if needed.
However, then my mind was blown when I read that the optimization problem is solved by using linear algebra and finding eigenvectors and eigenvalues. I simply do not understand how this use of linear algebra comes into play.
So my question is: How can PCA turn from a geometric optimization problem to a linear algebra problem? Can someone provide an intuitive explanation?
I am not looking for an answer like this one that says "When you solve the mathematical problem of PCA, it ends up being equivalent to finding the eigenvalues and eigenvectors of the covariance matrix." Please explain why eigenvectors come out to be the principal components and why the eigenvalues come out to be variance of the data projected onto them
I am a software engineer and not a mathematician, by the way.
Note: the figure above was taken and modified from this PCA tutorial.
A:
Problem statement
The geometric problem that PCA is trying to optimize is clear to me: PCA tries to find the first principal component by minimizing the reconstruction (projection) error, which simultaneously maximizes the variance of the projected data.
That's right. I explain the connection between these two formulations in my answer here (without math) or here (with math).
Let's take the second formulation: PCA is trying the find the direction such that the projection of the data on it has the highest possible variance. This direction is, by definition, called the first principal direction. We can formalize it as follows: given the covariance matrix $\mathbf C$, we are looking for a vector $\mathbf w$ having unit length, $\|\mathbf w\|=1$, such that $\mathbf w^\top \mathbf{Cw}$ is maximal.
(Just in case this is not clear: if $\mathbf X$ is the centered data matrix, then the projection is given by $\mathbf{Xw}$ and its variance is $\frac{1}{n-1}(\mathbf{Xw})^\top \cdot \mathbf{Xw} = \mathbf w^\top\cdot (\frac{1}{n-1}\mathbf X^\top\mathbf X)\cdot \mathbf w = \mathbf w^\top \mathbf{Cw}$.)
On the other hand, an eigenvector of $\mathbf C$ is, by definition, any vector $\mathbf v$ such that $\mathbf{Cv}=\lambda \mathbf v$.
It turns out that the first principal direction is given by the eigenvector with the largest eigenvalue. This is a nontrivial and surprising statement.
Proofs
If one opens any book or tutorial on PCA, one can find there the following almost one-line proof of the statement above. We want to maximize $\mathbf w^\top \mathbf{Cw}$ under the constraint that $\|\mathbf w\|=\mathbf w^\top \mathbf w=1$; this can be done introducing a Lagrange multiplier and maximizing $\mathbf w^\top \mathbf{Cw}-\lambda(\mathbf w^\top \mathbf w-1)$; differentiating, we obtain $\mathbf{Cw}-\lambda\mathbf w=0$, which is the eigenvector equation. We see that $\lambda$ has in fact to be the largest eigenvalue by substituting this solution into the objective function, which gives $\mathbf w^\top \mathbf{Cw}-\lambda(\mathbf w^\top \mathbf w-1) = \mathbf w^\top \mathbf{Cw} = \lambda\mathbf w^\top \mathbf{w} = \lambda$. By virtue of the fact that this objective function should be maximized, $\lambda$ must be the largest eigenvalue, QED.
This tends to be not very intuitive for most people.
A better proof (see e.g. this neat answer by @cardinal) says that because $\mathbf C$ is symmetric matrix, it is diagonal in its eigenvector basis. (This is actually called spectral theorem.) So we can choose an orthogonal basis, namely the one given by the eigenvectors, where $\mathbf C$ is diagonal and has eigenvalues $\lambda_i$ on the diagonal. In that basis, $\mathbf w^\top \mathbf{C w}$ simplifies to $\sum \lambda_i w_i^2$, or in other words the variance is given by the weighted sum of the eigenvalues. It is almost immediate that to maximize this expression one should simply take $\mathbf w = (1,0,0,\ldots, 0)$, i.e. the first eigenvector, yielding variance $\lambda_1$ (indeed, deviating from this solution and "trading" parts of the largest eigenvalue for the parts of smaller ones will only lead to smaller overall variance). Note that the value of $\mathbf w^\top \mathbf{C w}$ does not depend on the basis! Changing to the eigenvector basis amounts to a rotation, so in 2D one can imagine simply rotating a piece of paper with the scatterplot; obviously this cannot change any variances.
I think this is a very intuitive and a very useful argument, but it relies on the spectral theorem. So the real issue here I think is: what is the intuition behind the spectral theorem?
Spectral theorem
Take a symmetric matrix $\mathbf C$. Take its eigenvector $\mathbf w_1$ with the largest eigenvalue $\lambda_1$. Make this eigenvector the first basis vector and choose other basis vectors randomly (such that all of them are orthonormal). How will $\mathbf C$ look in this basis?
It will have $\lambda_1$ in the top-left corner, because $\mathbf w_1=(1,0,0\ldots 0)$ in this basis and $\mathbf {Cw}_1=(C_{11}, C_{21}, \ldots C_{p1})$ has to be equal to $\lambda_1\mathbf w_1 = (\lambda_1,0,0 \ldots 0)$.
By the same argument it will have zeros in the first column under the $\lambda_1$.
But because it is symmetric, it will have zeros in the first row after $\lambda_1$ as well. So it will look like that:
$$\mathbf C=\begin{pmatrix}\lambda_1 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & & \\ 0 & & & \end{pmatrix},$$
where empty space means that there is a block of some elements there. Because the matrix is symmetric, this block will be symmetric too. So we can apply exactly the same argument to it, effectively using the second eigenvector as the second basis vector, and getting $\lambda_1$ and $\lambda_2$ on the diagonal. This can continue until $\mathbf C$ is diagonal. That is essentially the spectral theorem. (Note how it works only because $\mathbf C$ is symmetric.)
Here is a more abstract reformulation of exactly the same argument.
We know that $\mathbf{Cw}_1 = \lambda_1 \mathbf w_1$, so the first eigenvector defines a 1-dimensional subspace where $\mathbf C$ acts as a scalar multiplication. Let us now take any vector $\mathbf v$ orthogonal to $\mathbf w_1$. Then it is almost immediate that $\mathbf {Cv}$ is also orthogonal to $\mathbf w_1$. Indeed:
$$ \mathbf w_1^\top \mathbf{Cv} = (\mathbf w_1^\top \mathbf{Cv})^\top = \mathbf v^\top \mathbf C^\top \mathbf w_1 = \mathbf v^\top \mathbf {Cw}_1=\lambda_1 \mathbf v^\top \mathbf w_1 = \lambda_1\cdot 0 = 0.$$
This means that $\mathbf C$ acts on the whole remaining subspace orthogonal to $\mathbf w_1$ such that it stays separate from $\mathbf w_1$. This is the crucial property of symmetric matrices. So we can find the largest eigenvector there, $\mathbf w_2$, and proceed in the same manner, eventually constructing an orthonormal basis of eigenvectors.
A:
There is a result from 1936 by Eckart and Young (https://ccrma.stanford.edu/~dattorro/eckart%26young.1936.pdf), which states the following
$\sum_1^r d_k u_k v_k^T = arg min_{\hat{X} \epsilon M(r)} ||X-\hat{X}||_F^2$
where M(r) is the set of rank-r matrices, which basically means first r components of SVD of X gives the best low-rank matrix approximation of X and best is defined in terms of the squared Frobenius norm - the sum of squared elements of a matrix.
This is a general result for matrices and at first sight has nothing to do with data sets or dimensionality reduction.
However if you don't think of $X$ as a matrix but rather think of the columns of the matrix $X$ representing vectors of data points then $\hat{X}$ is the approximation with the minimum representation error in terms of squared error differences.
A:
" which simultaneously maximizes the variance of the projected data." Have you hear of Rayleigh quotient? Maybe that's one way of seeing this. Namely the rayleigh quotient of the covariance matrix gives you the variance of the projected data. (and the wiki page explains why eigenvectors maximise the Rayleigh quotient)
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the PHP equivalent of this cookie code in jQuery/JavaScript?
I am new to PHP and I want to check the same condition as the given code which is in JavaScript using jQuery.
if ($.cookie('nwsubl') == 1) {
// Do something
}
A:
In PHP you can do as follow:
if(isset($_COOKIE['nwsubl']) && $_COOKIE['nwsubl'] == 1){
// Do something
}
isSet() is used to check whether variable exist or not. == loosely compares the values.
You can set cookie using setcookie() See here: http://php.net/manual/en/function.setcookie.php
| {
"pile_set_name": "StackExchange"
} |
Q:
file input type not being included in jquery FormData for AJAX send
I have a simple form that will be sent via AJAX to a php file for processing, this form includes a file upload, for some reason the file upload is not being included in the data to be sent.
My html form:
<form id="business-form">
<label for="business-name">Business Name:</label>
<input type="text" id="business-name" name="business-name">
<label for="business-location">Business Location:</label>
<input type="text" id="business-location" name="business-location">
<label for="business-description">Business Description:</label>
<input type="text" id="business-description" name="business-description">
<label for="fileToUpload">Business image:</label>
<input type="file" name="fileToUpload" id="fileToUpload">
<button id="create-business">Create New Business</button>
</form>
My jquery:
function createNewBusiness(){
var businessName = $('#business-name').val();
var businessLocation = $('#business-location').val();
var businessDescription = $('#business-description').val();
var file_data = $('#fileToUpload').prop('files')[0];
var sendAJAX = false;
if (businessDescription.length > 1 && businessLocation.length > 1 && businessName.length > 1) sendAJAX = true;
if (sendAJAX) {
var formData = new FormData($("#business-form")[0]);
var ft = $('#fileToUpload')[0].files[0];
formData.append("fileToUpload", ft);
console.log(ft);
console.log(formData);
$.ajax({
url: '/app/business/save_created', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
}
});
}else{
alert("Please fill in all fields to create a new business")
}
}
The php script returns:
Array ( [business-name] => fefe [business-location] => fe [business-description] => fe )
When a file is selected, but if the file is left blank i get:
Array ( [business-name] => dede [business-location] => eafrea [business-description] => aefad [fileToUpload] => undefined )
the (cake)php that currently handles the ajax:
public function app_save_created(){
$this->autoRender = false;
$this->layout = 'ajax';
print_r($this->request->data);
}
A:
Your needs use enctype='multipart/form-data'.
<form id="business-form" enctype='multipart/form-data'>
</form>
| {
"pile_set_name": "StackExchange"
} |
Q:
Facebook's like button inside a JQuery Tools' tab
I have added Facebook's like button inside the first tab of a JQuery Tools' tabs.
When the page is loaded the first tab opens and Facebook's like button appears, this works as expected, but when you click on the second/third/... tab and then return to the first tab, Facebook's like button does not appear any more...
The following is what I added to the first tab for the addition of the like button:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "http://connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
and placed the following code where I want the button to appear in the first tab:
<div class="fb-like" data-href="http://www.mysite.com/example/thisPage" data-send="false" data-layout="box_count" data-width="60" data-show-faces="false"></div>
Any idea what's happening here, and how to reload the like button every time the first tab is loaded?
A:
I'm guessing this has to do with AJAX and of course you need to reload the FB button after you call it in with AJAX. Add this to the end of your function to reinitialize Facebook and load the Like button:
FB.XFBML.parse();
| {
"pile_set_name": "StackExchange"
} |
Q:
XSLT adds unnecessary namespaces, how to get rid of them?
I process this XML file:
<z/>
by this XSLT 2.0 stylesheet:
<xsl:stylesheet
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:html = "http://www.w3.org/1999/xhtml"
xmlns:data = "http://portonvictor.org/ns/misc"
version = "2.0"
exclude-result-prefixes = "data html">
<xsl:template match="/">
<xsl:variable name="x">
<data:doc>
<xsl:copy-of select="*"/>
</data:doc>
</xsl:variable>
<xsl:copy-of select="$x/*/*"/>
</xsl:template>
</xsl:stylesheet>
Command line:
saxonb-xslt -xsl:error.xslt -s:error.xml
The resulting output is:
<?xml version="1.0" encoding="UTF-8"?><z xmlns:data="http://portonvictor.org/ns/misc"/>
It contains unnecessary xmlns:data namespace (even despite of I have exclude-result-prefixes). What is the easy way to get rid of such unnecessary namespaces?
The above toy example is a simplified real code of my free program, where I process an input XHTML file in several stages, first creating <data:doc> elements and then processing them.
A:
Well, your $x variable contains an element in the xmlns:data="http://portonvictor.org/ns/misc" namespace - and the element that you copy is a descendant of that element.
When you copy an element, you also copy all the namespaces that are in-scope for that element.
You'll see a different result if you change:
<xsl:copy-of select="$x/*/*"/>
to:
<xsl:copy-of select="$x/*/*" copy-namespaces="no"/>
Not sure how well this applies to your real problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
margin not overlap when the outer explicit set height
I wonder why the phenomenon will happen?
the inner div set margin-bottom 16px
As far as I know,the outer div contact with the inner div,no padding or border,if the outer div isn't set height css style,the under div will 16px away from the outer div, because the margin is overlap.However,if height css style is set on the outer div,the under div is close to the outer div.
so,can you explain how this phenomenon is caused?
.outer {
background: yellow;
height: 100px;
}
.inner {
height: 100px;
background: green;
margin-bottom: 16px;
}
.under {
background: red;
height: 10px;
}
<div class="outer">
<div class="inner"></div>
</div>
<div class="under"></div>
A:
So first things first, let's address this:
if you remove height css style on the outer div,you will find the under div is move down
This is due to Margin Collapsing:
If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.
Your child margin is collapsing with the parent margin, thus the 16px margin acts as part of the parent.
However by specifying a height, you negate margin collapsing.
From the W3 Box Model spec*:
Two margins are adjoining if and only if:
Both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
The bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height
Because the margins do not collapse, the child's margin will simply attempt to expand the height of the outer div (which won't be reflected, because the parent has a strictly set height of 100px).
But wait... what if we broke the collapse some other way? Would we see the height increase by 16px?
Two margins are adjoining if and only if:
no line boxes, no clearance, no padding and no border separate them
Seems easy enough. Let's add a border to break this rule.
.outer {
background: yellow;
border-bottom: 1px solid black;
}
.inner {
height: 100px;
background: green;
margin-bottom: 16px;
}
.under {
background: red;
height: 10px;
}
<div class="outer">
<div class="inner"></div>
</div>
<div class="under"></div>
Voila! As expected, the margins do not collapse, therefore the child's margin attempts to expand the height of the parent. With no height property on the parent to counter this, the height of the parent grows to 116px.
* This is pointing at an older spec, however this behavior has not changed. In fact, some of the newer spec documents I've found reference/link to this one.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between total recursive and primitive recursive functions
I am studying the theory of computation. Here are some terminologies that I am confused about.
Are total recursive function and primitive recursive function equivalent? I think they are equal because their domains are both total and they always generate output.
Can anyone tell me if there is some difference?
A:
They are not equivalent. The standard example is the Ackermann function, which is (total) recursive, but not primitive recursive. But if you are a programmer, here's another way to think of the difference between total recursive and primitive recursive functions. I'll discuss this in terms of an idealized imperative programming language running on an idealized computer (no memory or storage limits). You can think in terms of any standard imperative language, such as C or Java.
A total recursive function is any function you can write which always terminates.
A primitive recursive function is any function you can write where the only loops are those of the form "for i=1 to n do ..." Here $n$ is fixed in advance (before the loop starts), and you cannot (explicitly) change $i$ nor $n$ inside the loop. So the number of times the loop executes is determined in advance. This is the only looping structure allowed. You do not have a while loop, which terminates based on a condition, or a goto statement that can jump back to an arbitrary point in the code, or recursive function calls. These conditions make infinite loops impossible.
An example of a programming language that only supports primitive recursive functions is BlooP (this stands for Bounded Loop). It is impossible to write an infinite loop in BlooP, whereas it is undecidable whether a general program terminates.
However, even though all BlooP programs terminate, there are terminating programs that cannot be written in BlooP. The Ackermann function is one of them. The simplest example, though, is the BlooP interpreter. This is a program that takes as input a BlooP program plus any input the BlooP program requires, then runs the BlooP program, and produces its output. Since BlooP programs always terminate, the interpreter always terminates too. But it cannot be written in BlooP, by a diagonalization argument.
Roughly, the diagonalization argument goes as follows: For simplicity, we'll assume all functions map natural numbers to natural numbers. (Other types of inputs can be simulated by a Goedel encoding.) Let $B_1, B_2, \ldots$ be a recursive list of all BlooP programs, and set $f(n) = B_n(n) + 1$. Since every $B_n$ terminates, $f$ always terminates too, and is therefore total recursive. But $f \ne B_n$ for any $n$, since they differ at the value $n$ by construction. So $f$ is already an example of a total recursive function not primitive recursive (i.e. not expressible in BlooP). But since the only obstacle to calculating $f$ is the calculation of $B_n(n)$, which can be achieved by an interpreter, it follows that the BlooP interpreter cannot be written in BlooP.
A:
There is another example of a non-primitive-recursive but total computable function that explains better what the restricted definition of primitive recursion entails.
Each primitive recursive function is defined by a particular finite set of recursion equations, in terms of a fixed set of basic functions. We can use this to define an effective scheme for indexing all the primitive recursive functions. Let $(f_e : e \in \mathbb{N})$ be an effective indexing of the unary primitive recursive functions, meaning that
Every unary primitive recursive function is of the form $f_{e_f}(n)$ for some fixed $e_f$.
There is a single algorithm to compute $f_e(n)$ given $e$ and $n$.
Let $g(e,n)$ be the function that computes $f_e(n)$. We call $g$ a universal binary function. It is universal in the sense that it encapsulates all unary primitive recursive functions.
The function $g(e,n) = f_e(n)$ is certainly a total computable function. But it is not primitive recursive:
Suppose that $g(e,n)$ is primitive recursive. Then the function $f(n) = g(n,n)+1$ is also primitive recursive, as you can verify. But this function $f(n)$ cannot be of the form $g(e,n)$ for any fixed $e$, because for every $e$ we have $f(e) = g(e,e) + 1 \not = g(e,e)$, by the definition of $f$. Thus $g$ is total computable but not primitive recursive.
This diagonalization proof can be used in any system that is closed under a few basic operations. The moral of this construction is a key fact in computability theory:
A system of functions in which every function is total, and which has certain basic closure properties, cannot include a (total) universal binary function. The basic closure properties are the ones used in the proof above.
The point is that there is a fundamental incompatibility between the goal of making a system concrete enough that every function is total, and making a system strong enough that it includes universal functions for itself. Only one of these goals can be achieved at a time.
There is a universal binary partial function for the set of unary total computable functions. In fact there is a universal binary partial function for the set of unary partial computable functions, a larger class. This fact is essentially equivalent to the existence of a universal Turing machine.
A:
The Ackermann function, for example, is recursive, but is not primitive recursive. Indeed it "grows faster" than any primitive recursive function. From the definition in the link, it is not difficult to write an explicit program that computes the Ackermann function. There are many other concrete examples. The class of primitive recursive functions is a small subclass of the class of recursive functions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I add Multiple WHERE condtions
I am trying to Check and Insert record from ITEM to MIBOMD. I want to insert only if items in ItemID and partid fields in ITEM table exist in MIITEM table
I used the code below but I got this error message
Msg 4145, Level 15, State 1, Line 22
An expression of non-boolean type specified in a context where a condition is expected, near 'OR'.
USE [MITESTCO]
GO
INSERT INTO MIBOMD(bomItem, bomRev, bomEntry, partId, lead)
SELECT ItemID, rev, bomEntry, partid, qty
FROM ITEM WHERE (partid OR ItemID) IN (SELECT ItemId FROM MIITEM);
A:
You'll need to split out the WHERE clause from one OR condition to two.
USE [MITESTCO];
GO
INSERT INTO [MIBOMD]
([bomItem], [bomRev], [bomEntry], [partId], [lead])
SELECT [ItemID], [rev], [bomEntry], [partid], [qty]
FROM [ITEM]
WHERE [partid] IN (SELECT [ItemId] FROM [MIITEM])
OR [ItemID] IN (SELECT [ItemId] FROM [MIITEM]);
A:
Another way to do this is using EXISTS.
This will avoid using the Sub-Query twice
INSERT INTO [MIBOMD]
([bomItem],[bomRev],[bomEntry],[partId],[lead])
SELECT [ItemID],[rev],[bomEntry],[partid],[qty]
FROM [ITEM] I
WHERE EXISTS (SELECT 1
FROM [MIITEM] M
WHERE M.ItemId IN ( I.partid, I.ItemID ))
| {
"pile_set_name": "StackExchange"
} |
Q:
raster to polygon conversion
I 'm trying to automate the conversion of raster to polygon and the rasters files are in "TIF" format which is a "unsigned integer". I have the code below. However, I 'm getting an error while executing it. Could you have some suggestion please?
Code:
import arcpy, os
from arcpy import env
from arcpy.sa import *
#To overwrite output
arcpy.env.overwriteOutput = True
#Set environment settings
env.workspace = "C:/Subhasis/Test/Neshanic_Python/extract"
outws="C:/Subhasis/Test/Neshanic_Python/extract/clip/"
#checkout ArcGIS spatial analyst extension license
arcpy.CheckOutExtension("Spatial")
inraster = arcpy.ListRasters("*", "TIF")
for i in inraster:
filename=os.path.splitext(i)[0]
outPolygons= outws + str(filename) + '.shape'
field = "VALUE"
arcpy.RasterToPolygon_conversion(inraster, outPolygons, "NO_SIMPLIFY", field)
Error: Traceback (most recent call last): File
"C:\Subhasis\Test\Neshanic_Python\extract\Clip.py", line 23, in
arcpy.RasterToPolygon_conversion(inraster, outPolygons, "NO_SIMPLIFY", field) File "C:\Program Files
(x86)\ArcGIS\Desktop10.2\arcpy\arcpy\conversion.py", line 241, in
RasterToPolygon raise e
A:
For this line:
arcpy.RasterToPolygon_conversion(inraster, outPolygons, "NO_SIMPLIFY", field)
You are inserting a list not an individual raster file, trying changing it to:
arcpy.RasterToPolygon_conversion(i, outPolygons, "NO_SIMPLIFY", field)
| {
"pile_set_name": "StackExchange"
} |
Q:
Call Function only once in UIViewController, iOS Swift4.2, Xcode10.1
I have function call (pop view) in my 1st view controller which have to be called only once in app. Since then whenever I return back to 1st View controller the function need not to be called again.
func popView() {
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popView") as! popView
self.addChild(popOverVC)
popOverVC.view.frame = self.view.frame
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParent: self)
}
I have tried the following code and previous other sources in stack overflow, didn't work though..
///// Once Action in View Controller
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.isBeingPresented || self.isMovingToParent {
// Perform an action that will only be done once
popView()
}
}
A:
Maybe this works. In your ViewController, add a static property:
static var shouldPop = true
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if isBeingPresented || isMovingToParent {
// Perform an action that will only be done once
if (type(of: self).shouldPop) {
type(of: self).shouldPop = false
popView()
}
}
}
Of course, depending on your setup, this won't work if you have more than one instance of this viewcontroller that should keep their own state on whether popView should be called or not.
A:
If you want to call that PopView function only once in you App then try this,
In App delegate, set bool value
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UserDefaults.standard.set(true, forKey: "showPop") // like so
return true
}
Then, in first view controller try this,
func hasLaunchPop() {
let isshowPop: Bool = UserDefaults.standard.bool(forKey: "showPop")
if isshowPop == true {
popView()
UserDefaults.standard.set(false, forKey: "showPop")
}
}
then in viewdidload call like this,
override func viewDidLoad() {
super.viewDidLoad()
hasLaunchPop()
}
So that PopView appears only once in your app when its launched and will never show up again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Authenticate Xamarin forms app with username and password stored in a database table accessible via an Azure mobile app
I need to authenticate my Xamarin forms app with username and password stored in a database table accessible via an Azure mobile app.
We have an Asp.Net web app that users Forms authentication which has its data synched to an Azure SQL database (to user online/offline sync). I then use an Azure Mobile app to access the SQL data and use the Azure Mobile app as the backend for my Xamarin Forms app. We would like the users to log on to the Xamarin app with the same credential that they use for the web app.
Using walk throughs I have been able to get an app authenticating with Google, Azure active directory, etc. but is there a way of using the credentials stored in the Azure SQL database table? For the record I have very little experience with authentication.
I have found this https://github.com/HoussemDellai/CheapIdeas which uses the example of a Web API backend, will this work with an Azure Mobile App backend, aren't they essentially the same thing?
A:
I need to authenticate my Xamarin forms app with username and password stored in a database table accessible via an Azure mobile app.
According to your requirement, I assume that you could use App Service Authentication / Authorization and follow adrian hall's book about Custom Authentication to create the custom CustomAuthController endpoint in your Azure Mobile App backend project.
For your Xamarin client, you could use Azure Mobile Client SDK and login via the following code snippet:
MobileServiceClient.LoginAsync("custom", JObject.FromObject(new User { Username = "<userName>", Password = "<userPassword>" }));
For a quick way, you could follow Create a Xamarin.Forms app to download the Mobile Apps back end, then create your CustomAuthController ApiController and deploy to Azure.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hive: How to load data produced by apache pig into a hive table?
I am trying to load the output of pig into a hive table. The data are stored as avro schema on HDFS. In the pig job, I am simply doing:
data = LOAD 'path' using AvroStorage();
data = FILTER BY some property;
STORE data into 'outputpath' using AvroStorage();
I am trying to load it into a hive table by doing:
load data inpath 'outputpath' into table table_with_avro_schema parititon(somepartition);
However, I am getting an error saying that:
FAILED: SemanticException org.apache.hadoop.hive.ql.metadata.HiveException: MetaException(message:Invalid partition key & values; keys [somepartition, ], values [])
Can someone please suggests what I am doing wrong here? Thanks a lot!
A:
I just figured out that it is because LOAD operation does not deserialize the data. It simply acts like a copy operation. Thus, in order to fix it, you should follow these steps:
1. CREATE EXTERNAL TABLE some_table LIKE SOME_TABLE_WITH_SAME_SCHEMA;
2. LOAD DATA INPATH 'SOME_PATH' INTO some_table ;
3. INSERT INTO TARGET_TABLE SELECT * FROM some_table;
Basically, we should first load data into an external table and then insert it into the target hive table.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove dynamically created textboxes using jquery
I am creating textboxes dynamically on button click. I want to know to remove textboxes with another button click.
HTML
<table class="table-fill tbfill">
<thead>
<tr>
<th class="text-left" runat="server">Screen Name</th>
<th class="text-left" runat="server">Seats Available</th>
<th class="text-left"></th>
</tr>
</thead>
</table>
<input id="btnAdd" type="button" value="ADD"/>
jQuery
$("#btnAdd").bind("click", function ()
{
$("tbody.addScreen").append('<tr id="row0">' +
'<td class="text-left" name="screenName"> <input id="screenNameTextBox"/> </td>' +
'<td class="text-left"> <input id="seatsAvlTextBox" name="seatsAvl" /> </td>' +
'<td class="text-left"> <input type="button" value="Remove" id=Removebtn/> </td>' +
'</tr>');
});
I have a Remove button here. When I click the button I need to remove the textboxes from the corresponding row. How can I do this?
A:
You will have many items with the same ids Removebtn, row0, screenNameTextBox etc. which is incorrect. Use classes instead.
Change
<input type="button" value="Remove" id=Removebtn/>
and other ids to similar classes:
<input type="button" value="Remove" class="RemoveBtn"/>
Then, you will be able to use event delegation to assign a handler for all these buttons. For example, this code will remove the whole row on button click:
$(document).on('click', '.RemoveBtn', function() {
$(this).closest('tr').remove();
});
Here is the working JSFiddle demo.
If you want to remove textboxes only, then use:
$(document).on('click', '.RemoveBtn', function() {
$(this).closest('tr').find('input[type="text"]').remove();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to deal with a pugnacious user who regularly answers incorrectly?
I have been regularly coming across a new user recently; let's call "him" Bob?
Bob is absolutely convinced of his correctness on every topic. So convinced that he answers questions using completely invalid syntax because he knows how to solve a similar problem.
Commenting on the answer and pointing out the flaws sometimes results in a constructive response but more regularly not. Any downvotes (I haven't) normally results in a semi-unconstructive comment about '"experts"' or a small lecture on how people shouldn't downvote answers where someone was trying to help and that people should learn some manners.
So far, this has degenerated once, with a different user, and the community expressed themselves by downvoting more than usual.
I obviously don't know the particulars of the banning algorithm but it seems unlikely that Bob will be answer banned. He currently has 73 answers, 6 with a positive score and 6 with a negative. Five have been accepted, one an answer with positive score, which means only 10 of Bob's answers have been considered "helpful". People seem to be more wary of downvoting answers than questions, so Bob has escaped the worst. A significant minority of answers I would normally downvote as they're just wrong, but I can't and won't do that.
I am becoming extremely wary of commenting that Bob's answers are incorrect as I can't be bothered to have an argument over it. When combined with the volume of incorrect answers this is detrimental to the site. If wrong answers keep getting posted that people are unwilling to downvote or comment that they are incorrect then they stay around. I can't flag the answers as they're just technical inaccuracies.
Is there anything that an ordinary user can/should do in this situation? Bob is obviously acting in good faith and I don't think that he should be punished for doing so.
I am deliberately not posting Bob's identity as I'd rather Bob wasn't picked on.
A:
Commenting on incorrect answers is just that–it's only an argument if it's made in to one.
Comments regarding downvotes are just that; comments regarding downvotes– they don't need to be acted upon, but I'd tend towards flagging them as off-topic/not helpful.
IMO it's valuable to comment on incorrect answers, and I tend to downvote the more egregious.
People are wary about downvoting answers because it costs reputation, and can sometimes lead to silly retaliatory behavior. If it's serial retaliatory behavior the system will catch it.
Downvoting tends to push an answer down; if it's downvoted enough you can vote to delete. If it isn't, oh well: it's the internet, reacting to every "Someone is wrong on the internet!" hue and cry gets old fast.
A:
Downvote, downvote, downvote -- as you see new bad answers appear. I do not believe that you can achieve a rate here that will be mistaken for serial voting. If content is bad, downvote. Don't waste your time commenting.
| {
"pile_set_name": "StackExchange"
} |
Q:
why Linux diff utility produces output when contents are the same?
I don't know why when I run diff program on my workstation. It gave output differences while the file contents seem to be the same for me.
Here is my output result
But when I use vimdiff to open the files. They show nothing difference. Anyone knows the reason?
PS. I used the command of diff a.txt b.txt and vimdiff a.txt b.txt
Thanks for answering
A:
I usually find it has to do with the line endings. DOS-style files with have line endings of CR/LF (carriage return and line feed (a)) while UNIX-style files will just have LF.
While they may look the same, they're not. I would suggest you do a hex dump of the files to see what actual (but hidden) characters are there, with something like:
od -xcb file | less
A file with DOS-style line endings will have \r \n at the end of each line. UNIX-stle will have just \n (b).
(a) A throwback to typewriter days, when carriage return meant literally to slide the carriage to the left, and line feed meant to scroll the paper through one line, leaving the print head at the same position across the paper. Usually, these operations were combined but not always.
(b) Mac-style files, at least until they wised up and started using a decent OS under the hood, had just \r, the CR character.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get desired date object
I have a string:
NSString* string=@"2014-10-02 18:15:00 +0000";
How can I get date object with this string?
I tried:
NSString* string=@"2014-10-02 18:15:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *mydate = [dateFormatter dateFromString:string];
NSLog(@"mydate = %@",mydate);
mydate logs null value. I was expecting to log 2014-10-02 18:15:00 +0000.
All I want is to have date object which can be compared to another date object that displays 2014-10-02 18:15:00 +0000 when logged.
A:
You string is in 24 hour format but 'hh' is for 12 hour format. and 'HH' is for 24 hour format. Thats why it was returning null. Try this:
NSString* string=@"2014-10-02 18:15:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *mydate = [dateFormatter dateFromString:string];
NSLog(@"mydate = %@",mydate);
Hope this helps.. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the Catholic Church consider it sinful for couples who aren't able to conceive to have sex?
Say a married couple has sex, no babies are coming out, they go to a doctor, and they find out that they can't have children due to certain complications.
Given that the Catholic church takes a strong stand on the reproductive nature of sexual activity, if they have sex, is it sinful?
A:
I believe this to be a valid question because there can be confusion here.
HUMANEA VITAE
11. The sexual activity, in which husband and wife are intimately and chastely united with one another, through which human life is transmitted, is, as the recent Council recalled, "noble and worthy.'' (11) It does not, moreover, cease to be legitimate even when, for reasons independent of their will, it is foreseen to be infertile. For its natural adaptation to the expression and strengthening of the union of husband and wife is not thereby suppressed. The fact is, as experience shows, that new life is not the result of each and every act of sexual intercourse. God has wisely ordered laws of nature and the incidence of fertility in such a way that successive births are already naturally spaced through the inherent operation of these laws. The Church, nevertheless, in urging men to the observance of the precepts of the natural law, which it interprets by its constant doctrine, teaches that each and every marital act must of necessity retain its intrinsic relationship to the procreation of human life. (12)
The Church's position is that the married couple be open to procreation, not that procreation is mandatory.
Sarah had complications. Elizabeth had complications. Even our Blessed Mother had a missing element required for procreation.
Nothing is impossible For God.
A:
Marc's answer is correct. One might further add that Bible translations such as the New American Bible, which are respected by the Catholic Church, contain such verses as Mark 10: 7,8. "For this reason a man shall leave his Father and Mother, and the two shall become one flesh.....etc. This is a definition of marriage embedded within Jesus's teaching about divorce (which is sinful). Neither in this definition, nor in any other authoritative definition of marriage, are children even mentioned as being necessary, implying that the marriage is complete with or without children. Therefore, an inability to have children cannot be sinful.
Do not confuse religious cultural expectations with sinfulness. The two are not necessarily related.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is みつぎもの written 賜ぎ物 instead of 貢ぎ物 in this comic?
I was reading Hunter x Hunter volume 24, when suddenly this thing appeared:
賜{みつ}ぎ物{もの}
Just a bit of context: they are trying to infiltrate the enemy's base, and take advantage of one corrupt individual appetite for young women by sending in an undercover team member dressed up as a regular girl. The team leader (who thus sent the girl in) then uses the above phrase to say something along the lines of
Enjoy your present
I forgot the exact phrase but will add it later if necessary.
My question is why didn't the author use 貢{みつ}ぎ物 / 貢物 but this kanji ? Does it have to do with the current situation the character is in ?
I guess a related question is how do 貢ぐ and 賜る differ in sense ?
A:
This is a guess since I haven't read the series and the context you've given is rather fuzzy.
Mangaka sometimes use furigana to employ a spoken word / meaning difference. The usual example is adding the furigana あいつ to someone's name: [太郎]{あいつ}
The spoken word is あいつ but the kanji provide an explanation to the reader that the character means 太郎
I've also seen this example: [過去]{ゆめ}を見ていた。 (from 吸血姫 美夕)
In the situation you describe, from the speaker's point of view the meaning is 賜物 (fruit of our labour -- presumably the time it took to prepare the plan) while the audience (enemy) hears 貢ぎ物 (tribute).
Normally this would be written as [賜物]{貢ぎ物} but since Hunter x Hunter's target audience is rather young (primary school or thereabouts), they might not know how to read 貢ぎ物 and you typically can't add furigana to a furigana to clarify the pronunciation. The author or editor probably realised this, and in their search of a solution they ended up with the hybrid 賜ぎ物
For the dual meaning to work, the audience needs to notice that the word is not spelt with the usual kanji. You did notice it; I'm not so sure about the average reader.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding $f_x$ and and $f_y$ in a $f(x,y)$ function.
Let $f(x,y) = x^4y + 6xy^3 + 3x^4$.
(a) Find $f_x$.
(b) Find $f_y$.
I believe that I should make the equation equal to the function that I am looking for to solve the question. Would I be able to find the answer this way, and if not, how should I?
A:
Let $f(x,y) = x^4y + 6xy^3 + 3x^4$.
(a) We find $f_x$ by holding all the other variables (other than $x$) as constants. In this setting, we are holding $y$ as a constant. So we obtain:
$f_x = f_x (x,y)= 4x^3 y + 6y^3 +12 x^3$.
(b) Similarly, $f_y = f_y(x,y)=x^4 +18xy^2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Allow decimal value in numerator using matlab
Using Matlab, I want my output to have a decimal value in the numerator, but Matlab is automatically evaluating this into a fraction with integers in both numerator and denominator.
I am using symbolic math.
This is part of the output that's relevant:
residues =
-0.0016
0.0073
1.3684 - 1.0258i
1.3684 + 1.0258i
-1.5379 + 1.0363i
-1.5379 - 1.0363i
0.3333
poles =
-50.0000
-40.0000
-3.5000 + 9.3675i
-3.5000 - 9.3675i
-3.0000 + 9.0000i
-3.0000 - 9.0000i
0
directTerms =
[]
>> residues(1) / (s - poles(1))
ans =
-16/(10305*(s + 50))
I want the answer to be displayed as
-0.0016 / (s + 50)
Is there any way that I could prevent matlab from "simplifying" my expression.
A:
First you'll need to write the expression as:
expr=(-16/10305)/(s + 50)
then use vpa:
vpa(expr,3)
ans =
-0.00155/(s + 50.0)
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract only numbers from data in Jython
Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance:
[{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}]
(where xxx are the floating point numbers).
My question is how can I extract the numbers and put them in a more simple structure like a python list.
Thank you in advance.
A:
A PyJavaInstance is a Jython wrapper around a Java instance; how you extract numbers from it depends on what it is. If you need to get a bunch of stuff - some of which are strings and some of which are floats, then:
float_list = []
for item in instance_properties:
try:
float_list.append(float(item))
except ValueError:
pass
| {
"pile_set_name": "StackExchange"
} |
Q:
How to callback plugin thread on Safari 5.1 on OSX?
The Gecko functions NPN_PluginThreadAsyncCall / pluginthreadasynccall are not working for me on Safari 5.1 (Firefox works) - my function does not get called. I'm trying to make a function call back to JavaScript after performing a long-running task on another thread. How can I make this work?
A:
Yeah, we had the same problem with Safari 5.1 in FireBreath (which you should definitely look at if you're not familiar with it); NPN_PluginThreadAsyncCall no longer works. You haven't specified which platform you're on, so I'll show you what we use on both Mac and Windows.
On windows, we create a message HWND and we post a message to that HWND passing a void* in the event data as the LPARAM; the void* is converted back to a pointer to a data structure holding the params that pluginthreadasynccall would normally take, the call is made, and the data structure is freed. The message window class we use is here, and here is where the call is made. (Note that we use the same mechanism for cross-thread calls in IE)
On Mac, we basically just use the objective-c performSelectorOnMainThread; we wrapped it into a class to make it easier to use from c++. The scheduler class we use is here, and here is where the call is made. Note that you need to be really careful because there are lots of possible race conditions with these and occasionally you end up with re-entrant code. FireBreath has dozens of hours of work put into perfecting the cross-thread calls; it's a deceptively tricky problem.
Hopefully this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Am i using the logical operator OR (||) correctly, in javascript?
if ((typed_edge!='Either') || (typed_edge!='Walkable')){
alert("YES");
alert("type_edge"+ typed_edge + bus_stops_visited[$k]+ " " +bus_stops_visited[$k+1]);
}
if typed_edge has value Either,
The alert("YES") is displayed.
Isn't is supposed not to be displayed?
what i want is that when typed_edge has value "Either" or "Walkable", the alerts are not displayed. But this seems not to be the case!
A:
The way you have it above you need this:
if('Either' !== typed_edge && 'Walkable' !== typed_edge) {
// this means - it is NOT both of them
}
The way you have it right now, it says:
IF it's not Either
or
If it's not Walkable
Which means if it is 'Walkable', then the first condition evaluates to 'true'
That means the alert will fire.
Conversely, if it's 'Either', then the second condition will be 'true', and it will fire.
| {
"pile_set_name": "StackExchange"
} |
Q:
Вывести совпадения Laravel + MySql
Как вывести совпадения для пользователя -user_i = 1. Нужно вывести пользователей, которых лайкнул пользователь 1 и те пользователя, которые лайкнули этого пользователя
Например пользователь 12 подходит под условие, но не знаю как это вывести
$users = DB::table('likes')
->leftJoin('users','users.id','=','likes.like_user')
->leftJoin('user_attributes','user_attributes.user_id','=','likes.like_user')
->select('user_attributes.fullname','user_attributes.avatar','user_attributes.country','user_attributes.city','user_attributes.age',
'users.name','users.id','likes.created_at')
->where('likes.like_user','=', 'likes.user_id')
->where('likes.user_id','=', Auth::user()->id)
->paginate(15);
A:
SELECT t1.user_id
FROM likes t1
JOIN likes t2 ON t1.user_id = t2.like_user
AND t2.user_id = 1
AND t1.like_user = 1
и, если я верно понимаю синтаксис, то
$users = DB::table(DB:raw('likes t1'))
->join(DB:raw('likes t2'), 't1.user_id', '=', 't2.like_user ')
->where('t2.user_id', '=', '1')
->where(' t1.like_user', '=', '1')
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get auto-generated row primary key via Ruby PostgreSQL gem?
My table in PostgreSQL looks like this:
CREATE TABLE user (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL
)
I'm using Ruby pg gem to add a record to the table:
c = PG.connect(dbname: 'foo')
id = c.exec_params('INSERT INTO user (name) VALUES ($1)', ['Jeff']).oid_value
I'm getting nil back, instead of the auto-generated id of the new record. What is the right way to get it back?
A:
According to the docs, if the object id you're retrieving isn't set, thus nil.
You either have to set the object id yourself, or use returning like this:
res = conn.exec("INSERT INTO users (name) VALUES ('john') returning id")
res[0]['id']
#=> 1
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I force ggplot to show more levels on the legend?
I'm trying to create a complex ggplot plot but some things don't work as expected.
I have extracted the problematic part, the creation of points and its associated legend.
library(data.table)
library(ggplot2)
lev <- c("A", "B", "C", "D") # define levels.
bb <- c(40, 30,20,10,5)/100 # define breaks.
ll <- c("40%","30%","20%","10%","5%") # labels.
# Create data
nodos <- data.table(event = c("A", "B", "D", "C", "D"), ord = c(1, 2, 3, 3, 4),
NP = c(0.375, 0.25, 0.125, 0.125, 0.125))
ggplot() + geom_point(data=nodos,aes(x=ord,
y=event, size=NP), color="black", shape=16) +
ylim(lev) + scale_size_continuous(name="Prop.",
breaks=bb, labels=ll, range=c(0,6))+
scale_x_continuous(limits=c(0.5, 4.5),
breaks=seq(1,4,1))
As you can see, no matter what breaks and labels I use I'm not able to force ggplot to paint a legend containing 0% or 10%.
scale_size_continuous keeps creating just two elements.
And the smaller points are very badly scaled.
I have also tried with scale_scale_area, but it doesn't work either.
I'm using R 3.4.2 and ggplot2 2.2.1 (also tried the latest github version).
How can I get it?
A:
If you set the limits to encompass the breaks you'll be able to alter the legend. Current most of the breaks are outside the default limits of the scale.
ggplot() +
geom_point(data = nodos,
aes(x = ord, y = event, size = NP), color="black", shape = 16) +
scale_size_continuous(name = "Prop.",
breaks = bb,
limits = c(.05, .4),
labels = ll,
range = c(0, 6) )
| {
"pile_set_name": "StackExchange"
} |
Q:
Android: How can I create a layout within a layout ?
In my app I want to have a button that if the user clicks it
than a new layout is opened within the current (acually the main) layout.
the new layout should not fill all of the screen and parts of the previous layout
should be grayed out.
Any ideas on how to do this ?
A:
You can show a hidden layout within your button's onClick event by calling
view.setVisibility(View.VISIBLE)
You can also fade out view elements or whole views with
view.setAlpha(75);
view.setBackgroundColor(Color.GRAY);
Note that "view" in the first example is your layout element.. LinearLayout, RelativeLayout, etc. and in the 2nd example, "view" is the element(s) you're trying to gray out.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the user name of thr crm 2011?
how to Write the javascript function for getting the username(not a owner) in crm 2011.
A:
If you mean the FullName attribute of a SystemUser record you can use this function:
function getCurrentUserFullName() {
var serverUrl;
if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
} else {
serverUrl = Xrm.Page.context.getServerUrl();
}
var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var userRequest = new XMLHttpRequest();
userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false);
userRequest.setRequestHeader("Accept", "application/json");
userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
userRequest.send();
if (userRequest.status === 200) {
var retrievedUser = JSON.parse(userRequest.responseText).d;
var userFullName = retrievedUser.FullName;
return userFullName;
}
else {
return "error";
}
}
reference: CRM Answers - Get current user's full name with a synchronous call
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I optimise this mysql/php query?
My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
A:
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle sql inner join on dates range
I am trying to write join that joins on ids and date range:
SELECT * FROM C_INVOICE CI
INNER JOIN C_CONVERSION_RATE CCR
ON CCR.C_CURRENCY_ID=CI.C_CURRENCY_ID
AND CI.DATEINVOICED BETWEEN CCR.VALIDFROM AND CCR.VALIDTO
But the result I am getting is join from only from
ON CCR.C_CURRENCY_ID=CI.C_CURRENCY_ID
IN theory this should work just fine, and I don't get any errors, but result is not what I want
EDIT
--Full query
SELECT * FROM C_INVOICE CI
INNER JOIN C_CONVERSION_RATE CCR
ON CCR.C_CURRENCY_ID=CI.C_CURRENCY_ID
AND CI.DATEINVOICED BETWEEN CCR.VALIDFROM AND CCR.VALIDTO
WHERE CI.C_INVOICE_ID='1019748';
CI.DATEINVOICED = 15-FEB-16
CI.C_CURRENCY_ID = 100
There are many rows inside C_CONVERSION_RATE table with C_CURRENCY_ID = 100
but only one row falls into interval.
CI.DATEINVOICED(15-FEB-16) BETWEEN CCR.VALIDFROM(15-FEB-16) AND CCR.VALIDTO(15-FEB-16)
In this specific case CCR.VALIDFROM, CCR.VALIDTO are both equal to same date 15-FEB-16 but in other cases it can be few days interval
Anyway, the result I am expecting is single row where currency id and date interval matches. However, I am getting all the rows where currency id matches.
EDIT
Modified query a bit
SELECT
ci.dateinvoiced,
ccr.validfrom,
ccr.validto
FROM C_INVOICE CI
INNER JOIN C_CONVERSION_RATE CCR
ON CCR.C_CURRENCY_ID=CI.C_CURRENCY_ID
AND CI.DATEINVOICED BETWEEN CCR.VALIDFROM AND CCR.VALIDTO
WHERE CI.C_INVOICE_ID='1019748';
the result from this query I am getting
15-FEB-16 07-MAR-11 29-JAN-56
15-FEB-16 02-MAR-11 29-JAN-56
15-FEB-16 27-MAR-11 29-JAN-56
15-FEB-16 07-FEB-11 29-JAN-56
15-FEB-16 18-JAN-12 29-JAN-56
ccr.validto seem to be way off 29-JAN-56 there no such date in that column
don't know what causing this problem
A:
It looks like your C_CONVERSION_RATE table contains many rows with a VALIDTO date representative of an arbitrary end-of-time value of 29-JAN-59 (century unknown). If you are looking for the most recently valid conversion rate relative to the DATEINVOICED, you may need to use an analytic function to determine the next valid VALIDFROM value:
WITH CCR AS (
SELECT CCR.*
, LEAD(CCR.VALIDFROM,1,CCR.VALIDTO)
OVER (PARTITION BY CCR.C_CURRENCY_ID
ORDER BY CCR.VALIDFROM
, CCR.VALIDTO
) VALID_TO -- note the underscore ;)
FROM C_CONVERSION_RATE CCR
)
SELECT *
FROM C_INVOICE CI
INNER JOIN CCR
ON CCR.C_CURRENCY_ID=CI.C_CURRENCY_ID
AND CI.DATEINVOICED BETWEEN CCR.VALIDFROM AND CCR.VALID_TO -- note the underscore
AND CI.DATEINVOICED <> CCR.VALID_TO -- Make it a half open interval by not
-- including the exact end date since
-- it is actually the next start date.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery/CSS: count elements with certain classes, but without one specific class
I have label, which has classes status-label and unavailable.
I want to count all those containing it and exclude those, which have also class named "hide"
<label class="status-label unavailable"> should be selected
while
<label class="status-label unavailable hide"> shouldn't
I have tried to count the result like this:
var invalidConfigs=$("label.status-label.unavailable").not(".hide").length;
this didn't work either:
var invalidConfigs=$("label.status-label.unavailable:not(.hide)).length;
A:
var invalidConfigs = $("label.status-label.unavailable:not(.hide)")
.css("color", "red") // just for demo purposes
.length;
console.log(invalidConfigs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="status-label unavailable"> should be selected</label>
<label class="status-label unavailable hide"> shouldn't</label>
You are missing an end quote in your selector.
.css("color", "red") is just for the demo to make it visually apparent which element is selected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Obtain kMDItemKind on files inside bundles returns nil
For some reason I cannot do this on files inside bundles and files residing on different volumes.
Am I the only one experiencing this problem, and if not how do I solve it?
The Finder seems not having difficulties showing spotlight properties for the same files that I'm experiencing problems with.
I want to obtain the kMDItemKind of files as well as some other properties.
CFStringRef path = CFSTR("/Applications/Chess.app/Contents/Info.plist"); // bad
// CFStringRef path = CFSTR("/Applications/Chess.app"); // good
MDItemRef item = MDItemCreate(kCFAllocatorDefault, (CFStringRef)path);
if(!item) {
NSLog(@"MDItemCreate returned NULL for path: %@", path);
return nil;
}
CFStringRef kind = MDItemCopyAttribute( item, kMDItemKind );
if(kind) {
NSLog(@"file: %@ kind: %@", path, (NSString*)kind);
CFRelease( kind );
} else {
NSLog(@"file: %@ has no kMDItemKind attribute", path);
}
CFRelease( item );
OUTPUT:
file:
/Applications/Chess.app/Contents/Info.plist
has no kMDItemKind attribute
Same problem if I use the commandline tool mdls, like this
prompt> mdls /Applications/Chess.app/Contents/Info.plist
kMDItemFSContentChangeDate = 2009-05-19 08:09:03 +0200
kMDItemFSCreationDate = 2009-05-19 08:09:03 +0200
kMDItemFSCreatorCode = ""
kMDItemFSFinderFlags = 0
kMDItemFSHasCustomIcon = 0
kMDItemFSInvisible = 0
kMDItemFSIsExtensionHidden = 0
kMDItemFSIsStationery = 0
kMDItemFSLabel = 0
kMDItemFSName = "Info.plist"
kMDItemFSNodeCount = 0
kMDItemFSOwnerGroupID = 0
kMDItemFSOwnerUserID = 0
kMDItemFSSize = 3294
kMDItemFSTypeCode = ""
As you can see very little data is returned and no kMDItemKind
How would you obtain the metadata of the Info.plist ?
A:
Obtain kMDItemKind on files inside bundles returns nil
Correct. You can't get Metadata properties for files that Metadata hasn't indexed, and it doesn't index files inside bundles, in certain folders, and on any volume that has indexing disabled (including, but not limited to, read-only volumes, where Metadata can't write the index to the volume).
The Finder seems not having difficulties showing spotlight properties for the same files that I'm experiencing problems with.
How are you testing this? I Got Info on a PNG file, and on a PNG file inside an app bundle; the first had the usual image properties (e.g., dimensions), but the one inside a bundle showed nothing.
If you just want the Kind, use the LSCopyKindStringForURL function. Like most Core Services functions, it follows the CF memory-management rules.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift compiler "Fix It" error loop - Optionals
Swift's "Fix It" tool is complaining that an exclamation point is needed. After inserting one, it complains that it needs to be removed. What is the correct usage of "?" and "!" for this code?!
var debugLabel : SKLabelNode!
override func update(currentTime: NSTimeInterval) {
debugLabel!.text = "Ang: \(getFormattedNum(ball.physicsBody?.angularVelocity! ))"
}
func getFormattedNum( num:CGFloat ) ->String {
var formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
return formatter.stringFromNumber(num)!
}
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
debugLabel = childNodeWithName("deBugger") as SKLabelNode
...
}
The place Fix It is toggling back and forth is the exclamation point at the end of this property in the update func:
ball.physicsBody?.angularVelocity!
With ! or ? the error is "Operand of postfix ! should have optional type; type is "CGFloat".
Without optional indicator the error is "Value of optional type "CGFloat?" not unwrapped...
Note that "deBugger" is the name of a label in the sks.
A:
The problem is that you have an optional chain ball.physicsBody?.angularVelocity. This is going result in an optional because it is an optional chain. Unfortunately, you can't just unwrap that by adding a ! to the end because ball.physicsBody?.angularVelocity! is also an optional chain (the ! only unwraps the angularVelocity and not the entire chain). Also, in this case, angularVelocity is of type CGFloat so you can't unwrap it. You need to add parenthesis around the optional chain and then you can unwrap it:
debugLabel!.text = "Ang: \(getFormattedNum((ball.physicsBody?.angularVelocity)! ))"
| {
"pile_set_name": "StackExchange"
} |
Q:
Null-able foreign key; Entity Framework 5.0 model-first
I'm using Entity Framework 5.0 model-first approach using Visual Studio 2012 Express. I have a scenario to generate a nullable foreign key. For example, there are two entities – Organization and User. Not all users will belong to an organization. However, some users would belong to an organization. The User.Organization_ID column is always not null in spite of changing the multiplicity. Please help me to resolve this issue. Appreciate it.
A:
Changing the multiplicity 0..1 --> * (many) fixed this issue. i.e. 0 or 1 organization can have 0 or more users. This way, the organizatio_id in the user table is generated as nullable column! Thanks everyone for helping!
| {
"pile_set_name": "StackExchange"
} |
Q:
Domain not working after transfer from GoDaddy to AWS Route53
I have transferred my domain techhunters.net from GoDaddy to AWS Route53.
I have added hosted zone and created record set. Settings are given below.
Its been more than 48 hours still browser shows techhunters.net’s server IP address could not be found.
A:
You are still using Godaddy nameservers:
dig -t ns techhunters.net
Output:
;; ANSWER SECTION:
techhunters.net. 3600 IN NS ns73.domaincontrol.com.
techhunters.net. 3600 IN NS ns74.domaincontrol.com.
Quite likely, Godaddy will stop serving your domain name from the moment you transfer it away.
Basically, you defined your zone at AWS but you have yet to make it active.
See: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-name-servers-glue-records.html#domain-name-servers-glue-records-procedure
| {
"pile_set_name": "StackExchange"
} |
Q:
Database-Independent to_char Function in SQLAlchemy
I am using SQLAlchemy to make database-independent querys.
I am facing one issue with to_char function.
Consider the simple query like:
select to_char(id,'999') from xyz
It's working on Postgres but MySQL doesn't support it.
How can I make this query database-independent using SQLAlchemy?
A:
use the CAST function for simple type conversions. it is SQL standard and SQLAlchemy supports it directly via the cast() function: http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/expressions.html?highlight=cast#sqlalchemy.sql.expression.cast .
for date values, SQLA has an extract() function that produces the SQL EXTRACT function - a translation layer translates common fieldnames like "month", "day", "minute", etc. into the appropriate keyword for the backend in use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Risks of Microsoft Remote Desktop access behind a secure VPN
This is mostly for my own education, but a scenario has came up at work that has me skeptical. I'd like for the security experts to tell me if this policy is overbearing or not.
I remote into a VPN from my home PC, non-company issued. It installs Aventail onto the machine and destroys all cached data upon log off. It also does some sort of scanning via Sonicwall. My question is this: The VPN gives me full network access, which includes the ability to remote into my work PC. The company is now turning this off, citing a huge security risk. Is that really true? If someone already has my login to the VPN and it gives them full network access, isn't that already putting the company into DEFCON 1 mode? Is the whole RDP thing really a major additional risk after that? I'm not really seeing the reasoning behind it, but hopefully someone can shed some light on it.
A:
It's strict, but I wouldn't say it's overbearing.
Let's say there are two ends of the pool, with corporate networks. On the shallow end it's wide open, with no internal firewalls between desktops and servers. You can go to any app, any server, any port, from anywhere. On the deep end, networks are segmented and access controls enforced. Only Finance can go to the Finance servers. Everybody can go to port 443 on the Wiki server, only the admin network can go to port 22. Things like that.
In all but the shallowest networks, remote access users are considered the least trusted. Any filters in place will be in place for them. The company doesn't have physical control over those systems, so they don't get the fullest set of access.
Allowing RDP to desktop users is a way of negating that control. Someone on an untrusted remote PC who can RDP to an internal desktop gains, in essence, trusted access. And that can be a big problem. I can remember how Xerox took themselves off the Internet for a week back in the mid-90s because someone broke into an engineer's home in order to sit in front of his PC which had ISDN access to the Xerox internal network. Took them a week to clean up, and they just shut off the pipes until it was clean.
Now, you'll argue, the fact that secondary credentials is necessary to RDP after you've VPNed is a compensating control. That's a true point. But the fact of the matter is, if ACLs of some sort are in place to limit access from VPN users, then RDP is a way to circumvent those limits. That's why you run into this sort of policy with some regularity.
| {
"pile_set_name": "StackExchange"
} |
Q:
Backbone.js with a url to nested collections
I'm looking to build out my site using backbone.js. My API returns a url to other various resources (not strict HAL, otherwise maybe this would be ok) but I'm having a little difficulty creating aggregate pages (e.g. pages with content from multiple models/collections.
For example, I have a 'Deals' pages which displays a list of deals. Each deal displays the number of tickets for that particular deal. It is bad practice to perform fetches during a render of the page and Backbone-Relational looks promising but I'm not sure how I can use it with url references to related collections. Sorry if this is a dumb question, I'm new to these frameworks.
Partial example of 'Deal':
{
"_id": "526a6f520188d9c0e300002a",
"name": "test",
"description": "",
"isPublished": false,
"images": [],
"dealType": "group",
"tickets": "http://[host]/1/deals/526a6f520188d9c0e300002a/tickets"
}
Any advice would be greatly appreciated!
A:
Looks like this is what your looking for.
var DealModel = Backbone.Model.extend({
initialize:function(){
var self = this;
self.ticketsCollection = new (Backbone.Collection.extend({
url:self.get('tickets')
}))
self.listenTo(self.ticketCollection, 'all', function (sourceEventName) {
self.trigger.apply(self, ['ticket:' + sourceEventName].concat(_.rest(arguments)));
})
this.ticketsCollection.fetch(); //this can be done only when you want tickets details
}
})
var DealCollection = Backbone.Collection.extend({
model:DealModel,
url:'urltoDeals'
})
var dealCollection = new DealCollection();
dealCollection.fetch();
| {
"pile_set_name": "StackExchange"
} |
Q:
Can my tomato plant move indoors?
I have a potted tomato plant on my porch. The temperature is starting to drop as we move into fall; will it adapt well to being an indoor plant? My windows don't get a ton of sun I'm afraid. The plant is about four feet tall, of the variety "Watermelon Beefsteak". It's got a few flowers that are just starting to develop fruits; will this be interrupted if I bring it inside? Should I bring it in now or wait until it gets cold properly?
A:
You can move a tomato indoors, but the problem will be that it will grow spindly and thin, crawl along the ground, and will not set new fruit. Existing fruit won't ripen quickly. But if it survived until Spring you would probably get tomatoes starting in April/May depending on your climate.
A:
I can not come up with a good reason why you couldn't, but depending on size, soil, inside temp/sunlight, ect, it could be a bad idea. Also of interest is your location. If it was me I would try, but I would not expect a good outcome. On a plus side if it did do well you would have a great start next year.
I do have a couple of suggestions. I have an acquaintance who has a very large hydroponic greenhouse in Kentucky. He told me that the important things for tomatoes is temperature, water, and nutrients. So I would use a balanced miracle grow type product, keep it well, but not overly watered, and most of all WARM. According to him, light was not as important to tomatoes as heat.
I hope that it helps some.
-Bruce
Sorry I almost forgot all about my last thought: Prune the sucker vines!! They take too much energy from the rest of the plant. I'm sure you can find some Google some good info on how to ID and prune sucker vines on tomato plants. Good Luck -Bruce
| {
"pile_set_name": "StackExchange"
} |
Q:
Get category id in wordpress
I want to get category id from wp_terms where name is say "services".
I do so:
$myrows = $wpdb-> query("SELECT * FROM wp_terms WHERE name='services' " );
if(!$myrows){
echo "wrong".mysql_error();
}
else{
echo $myrows ->ID;
}
But it does not print anything. WHat is wrong here?
A:
It depends on what you want to do, but can you try this?
echo get_cat_ID('services');
See http://codex.wordpress.org/Function_Reference/get_cat_ID
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if Window is already open? Duplicate Windows
I have a button that opens a Window.
If the button is pressed again, it opens a duplicate of the same window.
info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
How do you check if the Window is already open, and deny a duplicate from being opened again?
I can't use info.ShowDialog() because it disables the Main Window.
Solutions that have not worked:
Info info = new Info();
if (!info.IsActive)
{
info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
}
Info info = new Info();
if (info.Visibility != Visibility.Visible)
{
info.Owner = Window.GetWindow(this);
info.Show();
}
public static bool IsWindowOpen<T>(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType<T>().Any()
: Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
}
private void buttonInfo_Click(object sender, RoutedEventArgs e)
{
if (!IsWindowOpen<Window>("Info"))
{
Info info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
}
}
A:
You could use .IsLoaded field or bind the .ContentRendered event
Edit 1 -
Window1:
public class Window1 : Window
{
private Info info = null;
private Boolean IsInfoOpened = false;
protected void OpenInfo()
{
if (this.IsInfoOpened) return;
this.info = new Info();
this.info.ContentRendered += delegate { this.IsInfoOpened = true; };
this.info.Closed += delegate { this.IsInfoOpened = false; }
this.info.Show();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the method signature for passing an async delegate?
I've recently moved back to C# from being in Objective-C land, and the async/await keywords in C# 5 look cool. But I'm still trying to get a handle on the proper syntax.
I want to declare a method that takes an asynchronous delegate as a parameter, but I am having trouble getting both the caller and the callee syntax correct. Can someone provide a code sample showing the method declaration, the call, and a call to the delegate?
I'm thinking the declaration would be something like the following. Note that this function isn't asynchronous; i.e. its asynchronicity is independent of the delegate.
void DoSomethingWithCallback(async delegate foo(int))
{
...
foo(42);
...
}
The call would be something like:
DoSomethingWithCallback(async (int x) => { this.SomeProperty = await SomeAsync(x); });
Of course none of this compiles and most of the samples I've seen assume that one has a field or property that's the delegate, rather than the anonymous delegate I'd like to use.
A:
A function that takes a delegate as a parameter must use a named delegate type; unlike in Objective-C you can't declare an anonymous delegate type inline in the function definition. However, the generics Action<> and Func<> are provided so that you don't have to declare a new type yourself. In the code below I'm assuming the delegate takes a single int as a parameter.
void DoSomethingWithCallback(Func<int,Task> callbackDelegate)
{
Task t = callbackDelegate(42);
}
If this function doesn't actually do anything with the Task object returned (as with the code shown above), you can instead use Action<int> as the delegate type. If you use Action, you can still declare the delegate async (below) but the implicit Task object returned is ignored.
The lambda syntax for calling the above function is straightforward and the syntax you used in the question is correct. Note that the parameter type doesn't need to be specified here since it can be inferred:
DoSomethingWithCallback(async (intParam) => { this.myint = await Int2IntAsync(intParam); });
You can also pass a method or delegate variable, if you wish, instead of using the lambda syntax:
async Task MyInt2Int(int p) { ... }
Func<int,Task> myDelegate;
void OtherMethod()
{
myDelegate = MyInt2Int;
DoSomethingWithCallback(myDelegate); // this ...
DoSomethingWithCallback(MyInt2Int); // ... or this.
}
A:
The return type of the method signatue is Task if there is no return type, or Task<T> if there is a return type.
Tho, I'm not 100% certain if you can have async lambdas like that.
In the method that is consuming the task, you would either 'await' the task or use the properties and methods on Task to get the result.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP - Is there a NOT-complicated way to determine the position of a link on page?
I would like to write a script which determines the position of hyperlinks from other domains which link to my website. For example I want to know if the link comes from "inside an article", "inside a sidebar (left / right)", "inside the footer". The only way I can think of is to check the CSS classes which wrap the link. For example a link is inside the class "left_sidebar", then it's likely inside the left sidebar :)
But this seems like a buggy way to determine this. This may work with well designed Wordpress themes, but will fail with many other sites.
So is there a better way to do this? Thanks!
A:
There are more creative ways to achieve what I think you're driving at. Instead of thinking in terms of section think of context. If a link resides in a p tag with a fair amount of additional text we can infer it's part of an article and not a set of links.
Combine a set of these inferences, add weight and you start building something that you can fine-tune.
| {
"pile_set_name": "StackExchange"
} |
Q:
Foreign key constraint error with code first...working fine with model-first
I'm trying to create a school base applicaiton using code first approach but getting "Foreign key constraint error" on my Result table...tried making the same applicaiton with model-first approach and its working fine...
this is the error im getting
An exception of type 'System.Data.SqlClient.SqlException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: Introducing FOREIGN KEY constraint
'FK_dbo.Semestersubjects_dbo.Semesters_semesterId' on table
'Semestersubjects' may cause cycles or multiple cascade paths. Specify
ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN
KEY constraints.
Could not create constraint or index. See previous errors.
This is what my context class look like
public class student
{
public student()
{
this.SemesterStudents = new HashSet<Semesterstudent>();
}
public int id { get; set; }
public string Name { get; set; }
public virtual ICollection<Semesterstudent> SemesterStudents { get; set; }
}
public class Semester
{
public Semester()
{
this.SemesterStudents = new HashSet<Semesterstudent>();
this.Semestersubjects = new HashSet<Semestersubject>();
}
public int id { get; set; }
public string Name { get; set; }
ICollection<Semesterstudent> SemesterStudents { get; set; }
ICollection<Semestersubject> Semestersubjects { get; set; }
}
public class Semesterstudent
{
public Semesterstudent()
{
this.Results = new HashSet<Result>();
}
public int id { get; set; }
public int studentId { get; set; }
public int semesterId { get; set; }
public virtual student students { get; set; }
public virtual Semester semesters { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Semestersubject
{
public Semestersubject()
{
this.Results = new HashSet<Result>();
}
public int id { get; set; }
public int semesterId { get; set; }
public string Title { get; set; }
public virtual Semester semesters { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Result
{
public int id { get; set; }
public int SemesterstudentId { get; set; }
public int SemestersubjectId { get; set; }
public int Marks { get; set; }
public virtual Semesterstudent SemesterStudents { get; set; }
public virtual Semestersubject SemesterSubjects { get; set; }
}
A:
As the comments have stated, you should show your OnModelCreating method for better answers. But to decipher the error message for you, it's saying there's a problem with the delete action - that it is cascading (eg. if you delete one entity it also deletes the related entities). The problem with this, is that if you were to delete a SemesterSubject the cascade would then also delete the Semester which would then (assuming the Semester delete action is also cascade) also delete the related SemesterSubjects which to quote the error may cause cycles or multiple cascade paths
Again if you show your OnModelCreating you will get better information on how to fix the error, but the short answer is to configure your foreign key to change the OnDelete behaviour so this doesn't cascade eg. (may be different depending on which version you are using etc.)
builder.Entity<SemesterSubject>(entity =>
{
entity.HasOne(e => e.semesters)
.WithMany(e => e.Semestersubjects)
.HasForeignKey(e => e.semesterId)
.OnDelete(DeleteBehavior.Restrict);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a difference in these declarations?
Both of these are declaring Jagged Lists correct?
//Declare 'Jagged' List
//Version 1
private List<string>[] fieldInfoArray = new List<string>[7];
//Version 2
private List<string>[][] fieldInfoArray = new List<string>[7][];
There is no difference between these two declarations right? They are both essentially doing the same thing correct? Declaring a Jagged List?
A:
Both declare arrays. When you will try to access the elements of either array, you will be returned List<string>.
First one is a 1-D array of size 7. All the 7 elements are List<string>s.
The second array is also a 1-D array of size 7 but each of those 7 elements is another "1-D array of List<string>" (and not just "List<string>").
| {
"pile_set_name": "StackExchange"
} |
Q:
Stopping Local Communication in android hotspot
How can I stop two devices from communicating among themselves if they are connected to my Hot Spot.(for eg I want them to not be able to ping eachother)
A:
You want to enable Wireless Isolation mode.
On the Linksys this is called AP Isolation.
From WirelessIsolation.com:
Wireless Isolation, sometimes called client isolation, is a setting on
a wireless router. When this setting is enabled it prevents a computer
that is connected to the network by a wireless connection from
accessing computers and resources that are connected to the network by
a wired connection. It will also prevent one wirelessly connected
device from connecting to another wirelessly connected device. In
essence Isolating that device on the wireless network.
This is used as a method of security so that you can provide both
wired and wireless connection through the same network without opening
up secured computers and resources to potentially unwanted visitors.
This can be very helpful in businesses that have a wireless hotspot
located in their lobby for example.
Without Wireless Isolation anyone on a wireless internet connection in
a wifi hotspot would not only have full access to the computers and
resources in the company’s network, but also to the various wireless
devices that were using the wifi hotspot at that time.
Most wireless router makers will support wireless isolation in one
form or another, if you already have a router and are curious to see
if it comes with wireless isolation or not you can check your products
manual, or log into your router and check the security tab.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swap two values on a stack
I want to swap the two values on the top of a std::stack<double>. Is there a better way than the following to do that ?
void swap_top(std::stack<double>& stack)
{
double a = stack.top();
stack.pop();
double b = stack.top();
stack.pop();
stack.push(a);
stack.push(b);
}
A:
With a plain stack, there's no better way.
Interestingly, the stack adapter actually exposes the underlying container as a protected member. This means that you can do this:
template <typename T, typename Container = std::deque<T>>
class stack_ex : public std::stack<T, Container> {
public:
using stack_ex::stack::stack;
void swap_top() {
auto last = c.rbegin();
auto before_last = std::prev(last);
std::iter_swap(last, before_last);
}
};
A:
You can do it with less stack operations but using std::swap, though I doubt it will be faster:
double a = stack.top();
stack.pop();
std::swap(a, stack.top());
stack.push(a);
Or just don't use stack, use the underlying container (such as deque, vector, or list) directly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does passing an unsigned int to a function make it lose bits?
My question is quite similar to the one here except that I’m working with C.
I wrote some code to rotate an unsigned int; that is, the function bitRotate() (code below).
The function works very well when, instead of the printfs and scanfs, I directly put the literals I want to use, e.g. bitRotate(0xabcdef00,8);in the main function.
However, when I pass x as an argument as in the following code, abcdef00 that was got from the user, the x gets corrupted to ab000000. I checked and double checked and debugged my code multiple times and I am pretty sure the error is in this part but I don’t understand why.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define WIDTH sizeof(unsigned int)*CHAR_BIT
unsigned int bitRotate(unsigned int, char );
int main()
{
unsigned int x;
char n;
while(1)
{
printf("Enter x: ");
scanf("%x", &x);
printf("Enter n: ");
scanf("%d", &n);
printf("%x\n", bitRotate(x,n));
}
return 0;
}
unsigned int bitRotate(unsigned int value, char n)
{
char un = abs(n);
unsigned int fallen = ~(0u);
if(un == WIDTH)
return value;
else if (un < WIDTH)
{
if (n < 0)
{
fallen >>= (WIDTH - n);
fallen = value & fallen;
fallen <<= (WIDTH - n);
value >>= n;
}
else
{
fallen <<= (WIDTH - n);
fallen = value & fallen;
fallen >>= (WIDTH - n);
value <<= n;
}
value |= fallen;
return value;
}
else
return 0;
}
A:
The bitRotate function is fine and so is the way you call it.
The actual culprit is here:
char n;
scanf("%d", &n); // <<<<<
You provide the wrong format specifier to scanf which results in undefined behaviour. Your compiler most likely warned you about this.
The %d format specifier needs an pointer to an int (which usually takes 32 bits), but you provide the pointer to a char which takes 8 bits. Therefore scanf most likely clobbers the memory adjacent to the address of n.
You want this:
int n;
scanf("%d", &n);
| {
"pile_set_name": "StackExchange"
} |
Q:
Associate Protractor with TFS (MTM)
I was wondering whether it is possible to connect my protractor tests with TFS and run it from Microsoft Test Manager.
A:
Integration will be very limited. You can create a Generic Test in Visual Studio and associate that to your Test Case in MTM. The Generic Test can run the actual commandline that will trigger Protractor.
The only test runner that can currently directly integrate into MTM is MsTest, any other test runner needs to be wrapped by a Generic Test in order to integrate into MTM.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to execute an Ingest PipeLine in an ElasticSearch Update?
I'm using NEST to comunicate with ElasticSearch.
In an Index operation I can especify the PipeLine to execute:
var insertDocument = client.Index<Document>(docInsert,
s => s.Index(idxName)
.Pipeline("attachments"));
Is it possible to execute an Ingest PipeLine in an ElasticSearch Update?
Thanks in advance,
A:
No. Pipelines can only be specified on index and bulk (index operations).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the need of Neutral and Phase Metering?
I'm working on a project where I have to implement a metering IC to measure Voltage,
Current and Power on 230v power lines.
I have to use Atmel's 90E24 single phase metering IC. This IC has two channels one for
Phase and another for Neutral current metering.
Since, all the current drawn by the load will flow on both phase and neutral (return path)
then what is the significance of using two line metering?
A:
You would typically monitor the neutral as part of an anti-tampering technique. People might bypass only the line , in which case the return current through the neutral would be different (higher) than what is on the Line. If both the L and N were by-passed then the neutral voltage might change (depending upon when the ground connection is made).
On Edit: looking at the datasheet it says " In anti-tampering mode, the power difference threshold between L line and N line can be: 1%, 2%,... 12%, 12.5%, 6.25%, 3.125% ..." on page 13.
| {
"pile_set_name": "StackExchange"
} |
Q:
Limiting the size of an audio buffer
Currently I am using pat of Apple's script "iPhoneMixerEQGraphTest" to playback audio in my app, however they do not "buffer" they send all the data to the buffer at once which I believe is causing my app to overload. I get a memory of over 100 MB and then a crash. The memory is usually less than 20MB. How would I be able to call on the audio read to only buffer part of the audio and not the whole thing. The crash happens on the callback : memcpy(out, &in[sample], ioData->mBuffers[0].mDataByteSize);.
I load my audio with this method:
- (void)setPlayerItem:(PlayerItem *)item{
mUserData.frameNum = 0;
mUserData.maxNumFrames = 0;
for (int i = 0; i < 1 && i < MAXBUFS; i++) {
printf("loadFiles, %d\n", i);
ExtAudioFileRef xafref = 0;
OSStatus result = ExtAudioFileOpenURL((__bridge CFURLRef)[item url], &xafref);
if (result || 0 == xafref) { printf("ExtAudioFileOpenURL result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
// get the file data format, this represents the file's actual data format
// for informational purposes only -- the client format set on ExtAudioFile is what we really want back
CAStreamBasicDescription fileFormat;
UInt32 propSize = sizeof(fileFormat);
result = ExtAudioFileGetProperty(xafref, kExtAudioFileProperty_FileDataFormat, &propSize, &fileFormat);
if (result) { printf("ExtAudioFileGetProperty kExtAudioFileProperty_FileDataFormat result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
printf("file %d, native file format\n", i);
fileFormat.Print();
// set the client format to be what we want back
// this is the same format audio we're giving to the the mixer input
result = ExtAudioFileSetProperty(xafref, kExtAudioFileProperty_ClientDataFormat, sizeof(mClientFormat), &mClientFormat);
if (result) { printf("ExtAudioFileSetProperty kExtAudioFileProperty_ClientDataFormat %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
// get the file's length in sample frames
UInt64 numFrames = 0;
propSize = sizeof(numFrames);
result = ExtAudioFileGetProperty(xafref, kExtAudioFileProperty_FileLengthFrames, &propSize, &numFrames);
if (result || numFrames == 0) { printf("ExtAudioFileGetProperty kExtAudioFileProperty_FileLengthFrames result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
// keep track of the largest number of source frames
if (numFrames > mUserData.maxNumFrames) mUserData.maxNumFrames = numFrames;
// set up our buffer
mUserData.soundBuffer[i].numFrames = numFrames;
mUserData.soundBuffer[i].asbd = mClientFormat;
UInt32 samples = numFrames * mUserData.soundBuffer[i].asbd.mChannelsPerFrame;
mUserData.soundBuffer[i].data = (AudioSampleType *)calloc(samples, sizeof(AudioSampleType));
// set up a AudioBufferList to read data into
AudioBufferList bufList;
bufList.mNumberBuffers = 1;
bufList.mBuffers[0].mNumberChannels = mUserData.soundBuffer[i].asbd.mChannelsPerFrame;
bufList.mBuffers[0].mData = mUserData.soundBuffer[i].data;
bufList.mBuffers[0].mDataByteSize = samples * sizeof(AudioSampleType);
// perform a synchronous sequential read of the audio data out of the file into our allocated data buffer
UInt32 numPackets = numFrames;
result = ExtAudioFileRead(xafref, &numPackets, &bufList);
if (result) {
printf("ExtAudioFileRead result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result);
free(mUserData.soundBuffer[i].data);
mUserData.soundBuffer[i].data = 0;
return;
}
// close the file and dispose the ExtAudioFileRef
ExtAudioFileDispose(xafref);
}
}
It gets played with:
// create a new AUGraph
result = NewAUGraph(&mGraph);
if (result) { printf("NewAUGraph result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
// create three Audio Component Descriptons for the AUs we want in the graph using the CAComponentDescription helper class
// output unit
CAComponentDescription output_desc(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO, kAudioUnitManufacturer_Apple);
// iPodEQ unit
CAComponentDescription eq_desc(kAudioUnitType_Effect, kAudioUnitSubType_AUiPodEQ, kAudioUnitManufacturer_Apple);
// multichannel mixer unit
CAComponentDescription mixer_desc(kAudioUnitType_Mixer, kAudioUnitSubType_MultiChannelMixer, kAudioUnitManufacturer_Apple);
printf("add nodes\n");
// create a node in the graph that is an AudioUnit, using the supplied AudioComponentDescription to find and open that unit
result = AUGraphAddNode(mGraph, &output_desc, &outputNode);
if (result) { printf("AUGraphNewNode 1 result %lu %4.4s\n", result, (char*)&result); return; }
result = AUGraphAddNode(mGraph, &eq_desc, &eqNode);
if (result) { printf("AUGraphNewNode 2 result %lu %4.4s\n", result, (char*)&result); return; }
result = AUGraphAddNode(mGraph, &mixer_desc, &mixerNode);
if (result) { printf("AUGraphNewNode 3 result %lu %4.4s\n", result, (char*)&result); return; }
// connect a node's output to a node's input
// mixer -> eq -> output
result = AUGraphConnectNodeInput(mGraph, mixerNode, 0, eqNode, 0);
if (result) { printf("AUGraphConnectNodeInput result %lu %4.4s\n", result, (char*)&result); return; }
result = AUGraphConnectNodeInput(mGraph, eqNode, 0, outputNode, 0);
if (result) { printf("AUGraphConnectNodeInput result %lu %4.4s\n", result, (char*)&result); return; }
// open the graph AudioUnits are open but not initialized (no resource allocation occurs here)
result = AUGraphOpen(mGraph);
if (result) { printf("AUGraphOpen result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
// grab the audio unit instances from the nodes
result = AUGraphNodeInfo(mGraph, mixerNode, NULL, &mMixer);
if (result) { printf("AUGraphNodeInfo result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
result = AUGraphNodeInfo(mGraph, eqNode, NULL, &mEQ);
if (result) { printf("AUGraphNodeInfo result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
// set bus count
UInt32 numbuses = 2;
printf("set input bus count %lu\n", numbuses);
result = AudioUnitSetProperty(mMixer, kAudioUnitProperty_ElementCount, kAudioUnitScope_Input, 0, &numbuses, sizeof(numbuses));
if (result) { printf("AudioUnitSetProperty result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
for (UInt32 i = 0; i < numbuses; ++i) {
// setup render callback struct
AURenderCallbackStruct rcbs;
rcbs.inputProc = &renderInput;
rcbs.inputProcRefCon = &mUserData;
printf("set AUGraphSetNodeInputCallback\n");
// set a callback for the specified node's specified input
result = AUGraphSetNodeInputCallback(mGraph, mixerNode, i, &rcbs);
if (result) { printf("AUGraphSetNodeInputCallback result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
printf("set input bus %d, client kAudioUnitProperty_StreamFormat\n", (unsigned int)i);
// set the input stream format, this is the format of the audio for mixer input
result = AudioUnitSetProperty(mMixer, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, i, &mClientFormat, sizeof(mClientFormat));
if (result) { printf("AudioUnitSetProperty result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
}
printf("get EQ kAudioUnitProperty_FactoryPresets\n");
// get the eq's factory preset list -- this is a read-only CFArray array of AUPreset structures
// host owns the retuned array and should release it when no longer needed
UInt32 size = sizeof(mEQPresetsArray);
result = AudioUnitGetProperty(mEQ, kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &mEQPresetsArray, &size);
if (result) { printf("AudioUnitGetProperty result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
/* this code can be used if you're interested in dumping out the preset list
printf("iPodEQ Factory Preset List:\n");
UInt8 count = CFArrayGetCount(mEQPresetsArray);
for (int i = 0; i < count; ++i) {
AUPreset *aPreset = (AUPreset*)CFArrayGetValueAtIndex(mEQPresetsArray, i);
CFShow(aPreset->presetName);
}*/
printf("set output kAudioUnitProperty_StreamFormat\n");
// set the output stream format of the mixer
result = AudioUnitSetProperty(mMixer, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &mOutputFormat, sizeof(mOutputFormat));
if (result) { printf("AudioUnitSetProperty result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
printf("set render notification\n");
// add a render notification, this is a callback that the graph will call every time the graph renders
// the callback will be called once before the graph’s render operation, and once after the render operation is complete
result = AUGraphAddRenderNotify(mGraph, renderNotification, &mUserData);
if (result) { printf("AUGraphAddRenderNotify result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
printf("AUGraphInitialize\n");
// now that we've set everything up we can initialize the graph, this will also validate the connections
result = AUGraphInitialize(mGraph);
if (result) { printf("AUGraphInitialize result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
CAShow(mGraph);
OSStatus result = AUGraphStart(mGraph);
if (result) { printf("AUGraphStart result %ld %08X %4.4s\n", result, (unsigned int)result, (char*)&result); return; }
mIsPlaying = true;
Finally I receive a callback from:
static OSStatus renderInput(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData)
{
SourceAudioBufferDataPtr userData = (SourceAudioBufferDataPtr)inRefCon;
AudioSampleType *in = userData->soundBuffer[inBusNumber].data;
AudioSampleType *out = (AudioSampleType *)ioData->mBuffers[0].mData;
UInt32 sample = userData->frameNum * userData->soundBuffer[inBusNumber].asbd.mChannelsPerFrame;
// make sure we don't attempt to render more data than we have available in the source buffers
// if one buffer is larger than the other, just render silence for that bus until we loop around again
if ((userData->frameNum + inNumberFrames) > userData->soundBuffer[inBusNumber].numFrames) {
UInt32 offset = (userData->frameNum + inNumberFrames) - userData->soundBuffer[inBusNumber].numFrames;
if (offset < inNumberFrames) {
// copy the last bit of source
SilenceData(ioData);
memcpy(out, &in[sample], ((inNumberFrames - offset) * userData->soundBuffer[inBusNumber].asbd.mBytesPerFrame));
return noErr;
} else {
// we have no source data
SilenceData(ioData);
*ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
return noErr;
}
}
memcpy(out, &in[sample], ioData->mBuffers[0].mDataByteSize);
//printf("render input bus %ld from sample %ld\n", inBusNumber, sample);
return noErr;
}
A:
Don't read the whole audio file at once. Instead, read only a few seconds at a time into a circular buffer or fifo, and keep filling the buffer from the file (in another thread) to roughly keep up with the rate that the audio render callback is emptying it. The memory required for the buffer can be quite small (maybe a few seconds worth, or even less, to be safe).
Another alternative is to memory map the entire file (mmap), which doesn't dirty memory, and thus doesn't count against an apps memory allowance (until it gets close to the gigabyte range).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to change depth of field in RAW images?
I am beginner to photography, and I've learnt that we can do a lot of post-production in images by using RAW format. I'm looking for options to change/modify the depth of field in the RAW images - is this possible?
A:
No - the aperture is set by the physical blades in the lens when you take the photo; a RAW "image" contains the readings from the sensor when the photo was taken, so there's no way you can go back and modify the light which was captured by the sensor. While it's not as obvious, this is equivalent to asking "Can I modify what the camera was pointing at from a RAW image?"
The closest that we have at this point in time is a Light-field camera which does allow you to modify things like the depth of field and the focal plane after the shot has been taken.
A:
For the purpose that you are asking the answer is "No". Sort of.
Unless you are using what is known as a Light Field Camera such as the Lytro, you can't change the aperture at which the shot was taken after the fact any more than you can change the shutter speed.
There are editing tools that allow you to artificially create blur to parts of an image, but at present they don't look very natural as the blur isn't applied gradually to things closer and further away from the point of focus. There is also the problem of the edge between what is and what isn't blurred being very abrupt in much the same way as how subjects cloned into another background look.
There are, however, many things we do to an image after taking the picture that can affect the Depth of Field (DoF). Any time you crop an image and display the crop at the same size as the original you are altering the Depth of Field. Any time you increase or decrease the display size at the same viewing distance you alter the DoF. Anytime you change the viewing distance of the same photo you alter the DoF!
Understanding what DoF is and what it is not is important here.
In a way, depth-of-field is an illusion. There is only one plane of focus. Everything in front of or behind the point of focus is out of focus to one degree or another. What we call DoF is the area where things look, to our eyes, like they are in focus. This is based on the ability of the human eye to resolve certain minute differences at a particular distance. If the slightly out-of-focus blur is smaller than our eye's capability to resolve the detail then it appears to be in focus. When you magnify a portion of an image by making it larger or moving closer to it you allow your eye to see details that before were too close together to be seen by your eyes as separate pieces of the image. There is no magic barrier beyond which everything is equally blurry and inside of which everything is equally in focus!
Since things are gradually blurrier the further they are from the point of focus, as you gradually magnify the image the perceived depth of field gets narrower as the near and far points where your eyes can resolve fine details moves closer to the focal plane.
A:
No, its not possible with a single photo.
But you could take multiple photos, at different focus points or apertures. Then they can be combined in post processing, to give the effect of a different depth of field. You would have to keep the camera in the same position between shots, and it wouldn't work for moving subjects. This could work for either RAW or JPEG images.
It would be possible for a camera can do this automatically. eg some of the Panasonic Lumix models are due to get a Post Focus feature. This takes a burst of 4K photos at up to 30 frames per second, while shifting the lens to different focus areas. So you can choose afterwards where you want the focus to be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mapping an ArrayList of Object with XSD file
I'm working with Java/Eclipse/Spring to create a Web Services. I'm writing a XSD file with the structure for the Java Classes for the Web Services (Request, Response, etc).
I used the option "Generate Jaxb Classes", over the XSD file, to create the Java classes.
It is working fine for data types like int, string, long, etc, but, when my property is an ArrayList of Objects, the Java class generated doesn't have the "SET" method of the property. It only have the "GET" method.
This is an example:
XSD file:
<element name="GetPrizesAndCatalogsResponse">
<complexType>
<sequence>
<element name="answerCode" type="int" />
<element name="prizes" type="tns:SW_Prize" maxOccurs="unbounded"></element>
<element name="prizesCatalog" type="tns:SW_Catalog" maxOccurs="unbounded"></element>
<element name="pagination" type="tns:SW_Pagination"></element>
</sequence>
</complexType>
</element>
Java class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"answerCode",
"prizes",
"prizesCatalog",
"pagination"
})
@XmlRootElement(name = "GetPrizesAndCatalogsResponse")
public class GetPrizesAndCatalogsResponse {
protected int answerCode;
@XmlElement(required = true)
protected List<SWPrize> prizes;
@XmlElement(required = true)
protected List<SWCatalog> prizesCatalog;
@XmlElement(required = true)
protected SWPagination pagination;
/**
* Obtiene el valor de la propiedad answerCode.
*
*/
public int getAnswerCode() {
return answerCode;
}
/**
* Define el valor de la propiedad answerCode.
*
*/
public void setAnswerCode(int value) {
this.answerCode = value;
}
/**
* Gets the value of the prizes property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prizes property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrizes().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SWPrize }
*
*
*/
public List<SWPrize> getPrizes() {
if (prizes == null) {
prizes = new ArrayList<SWPrize>();
}
return this.prizes;
}
/**
* Gets the value of the prizesCatalog property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prizesCatalog property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrizesCatalog().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SWCatalog }
*
*
*/
public List<SWCatalog> getPrizesCatalog() {
if (prizesCatalog == null) {
prizesCatalog = new ArrayList<SWCatalog>();
}
return this.prizesCatalog;
}
/**
* Obtiene el valor de la propiedad pagination.
*
* @return
* possible object is
* {@link SWPagination }
*
*/
public SWPagination getPagination() {
return pagination;
}
/**
* Define el valor de la propiedad pagination.
*
* @param value
* allowed object is
* {@link SWPagination }
*
*/
public void setPagination(SWPagination value) {
this.pagination = value;
}
}
Is my definition of the XSD file correct? Is it necessary to add another tag on the XML?
A:
Solved:
there is a new method (I don't know if is it a new one) called "addAll".
You can get your collection and then use addAll to add another collection.
Code:
getPrizesAndCatalogsResponse.getPrizes().addAll(newPrizes);
| {
"pile_set_name": "StackExchange"
} |
Q:
XMLStarlet - UTF-8 Nordic characters
Using XMLStarlet (windows) to edit an RSS feed, but got a few issues with norwegian characters 'ÆØÅ'.
I'm using an example I found at this site ( https://stackoverflow.com/a/14397390/3168446 )
This is my feed.xml. (Notepad++ says it's encoded in UTF-8)
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
<title>My RSS Feed</title>
<description>This is my RSS Feed</description>
</channel>
</rss>
I'm not using the following example as it's for a linux script, but my long command line below does the same-ish..
#!/bin/sh
TITLE="Test title ÆØÅ"
LINK="http://www.example.com"
DATE="`Sat, 26 Jul 2014 01:14:30 +0200`"
xmlstarlet ed -L -a "//channel" -t elem -n item -v "" \
-s "//item[1]" -t elem -n title -v "$TITLE" \
-s "//item[1]" -t elem -n link -v "$LINK" \
-s "//item[1]" -t elem -n pubDate -v "$DATE" \
-d "//item[position()>10]" feed.xml ;
Windows command line (what I'm using):
xml.exe ed -L -a "//channel" -t elem -n item -v "" -s "//item[1]" -t elem -n title -v "Test title ÆØÅ" -s "//item[1]" -t elem -n link -v "http://www.example.com" -s "//item[1]" -t elem -n pubDate -v "Sat, 26 Jul 2014 01:14:30 +0200" -d "//item[position()>10]" feed.xml
'ÆØÅ' is giving me issues when I add the second item containing 'ÆØÅ', well, actually the first item gives me problems, but doesn't produce an error message until second item is added:
feed.xml:8.23: Input is not proper UTF-8, indicate encoding !
Bytes: 0xC6 0xD8 0xC5 0x3C: Bytes: 0xC6 0xD8 0xC5 0x3C
<title>Test title ãÏ┼</title>
Anyone got any tips? I guess it's an encoding issue, but I don't understand why because feed.xml is UTF-8 and encoding is set to utf-8 in the feed.
A:
I can confirm this problem is solved in XMLStarlet version 1.6.1+ win32 build!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ge the data rows which is belonging to one date
I have table like.
ID | startdatetime
1 | 2013-08-30 22:30:00
2 | 2013-08-29 12:00:00
3 | 2013-08-29 13:30:00
4 | 2013-08-27 11:30:00
5 | 2013-08-27 13:30:00
6 | 2013-08-26 09:30:00
I want to get the the data which are belonging to a date (for example rows 2 and 3 are belonging to 2013-08-29 )
How could I write in Doctrine?
$em = $this->getDoctrine()->getEntityManager();
$items = $em->getRepository("UserBundle:Table")->findBy('startdatetime' => '*****'));
A:
You have two options:
1 - the quick and dirty one is to use the MySQL SUBSTRING to get the date out of the datetime:
WHERE SUBSTRING(dateTimeField,1,10) = '2013-08-29'
2 - Use DoctrineExtensions and then you can select data like this:
$q->select('p')
->where('YEAR(startdatetime) = :year')
->andWhere('MONTH(startdatetime) = :month')
->andWhere('DAY(startdatetime) = :day');
$q->setParameter('year', $year)
->setParameter('month', $month)
->setParameter('day', $day);
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I have multiple copies of an object that are identical update while instantiated as separate objects in different view controllers?
I'm trying to have multiple copies of a single product objects in different view controllers (i.e. you have a product in a shopping list and when you search queries web-service and returns searched products). There is a symbol on search tableviewCell if that product is in the shopping list.
I thought of two ways to do this:
Have an array in a singleton class that caches the products in a NSMutableDictionary by their id numbers and every time a products is created it check to see if there is one in its place. If so it just uses the product already there. I can have a setting in the product that states if it is on the shopping list or not.
Use core data. I tried to implement it but not sure how I can exactly do this. I was thinking of using core data so that when i update a product object it is also updated in other parts of the app using NSFetchedResultsController.
What is "standard practice" for this situation?
Let me know what you think and how you would approach this. Thanks!
A:
You can use singleton pattern for your data manager class, which will hold your data in an array of Models (For e.g.: Product)
If you use singleton data manager (for e.g.: ProductManager) then your data (for e.g.: Product entities) would be persistent for all your class files in application life cycle mode.
Here you can find more information:
Objective C Singleton Class
http://www.galloway.me.uk/tutorials/singleton-classes/
Hope this is what you are looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get pointer to object from pointer to some member
Suppose there's a structure
struct Thing {
int a;
bool b;
};
and I get a pointer to member b of that structure, say as parameter of some function:
void some_function (bool * ptr) {
Thing * thing = /* ?? */;
}
How do I get a pointer to the containing object? Most importantly: Without violating some rule in the standard, that is I want standard defined behaviour, not undefined nor implementation defined behaviour.
As side note: I know that this circumvents type safety.
A:
If you are sure that the pointer is really pointing to the member b in the structure, like if someone did
Thing t;
some_function(&t.b);
Then you should be able to use the offsetof macro to get a pointer to the structure:
std::size_t offset = offsetof(Thing, b);
Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<char*>(ptr) - offset);
Note that if the pointer ptr doesn't actually point to the Thing::b member, then the above code will lead to undefined behavior if you use the pointer thing.
A:
void some_function (bool * ptr) {
Thing * thing = (Thing*)(((char*)ptr) - offsetof(Thing,b));
}
I think there is no UB.
A:
X* get_ptr(bool* b){
static typename std::aligned_storage<sizeof(X),alignof(X)>::type buffer;
X* p=static_cast<X*>(static_cast<void*>(&buffer));
ptrdiff_t const offset=static_cast<char*>(static_cast<void*>(&p->b))-static_cast<char*>(static_cast<void*>(&buffer));
return static_cast<X*>(static_cast<void*>(static_cast<char*>(static_cast<void*>(b))-offset));
}
First, we create some static storage that could hold an X. Then we get the address of the X object that could exist in the buffer, and the address of the b element of that object.
Casting back to char*, we can thus get the offset of the bool within the buffer, which we can then use to adjust a pointer to a real bool back to a pointer to the containing X.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to update a record in a trigger with value from a REST API?
When an account is saved I need to update it with value from a REST API. I though my approach would work but I'm getting the following compilation errors.
Method does not exist or incorrect signature: void getTicker() from the type tickerClass
What's the proper way to make a REST API callout in a trigger to update the trigger records?
I tried getting it to work like this, but got stuck on the compilation error.
Person clicks New Account, and fills in the appropriate fields. Person clicks Save.
triggerTicker on Account is triggered.
triggerTicker calls tickerClass.
tickerClass uses REST API to grab the 'high' value.
tickerClass adds the 'high' value in the valueHigh variable and then assigns valueHigh to the Ticker_Start__c field.
Record is saved.
My trigger.
trigger triggerTicker on Account (before insert) {
tickerClass.getTicker();
// convert the output of ticker.getTicker() from String to Decimal
Decimal newTicker = Decimal.valueOf(tickerClass.getTicker());
// create new Account record and include required fields
for (Account newAcc : Trigger.new) {
Account a = new Account();
a.Name = 'Ticker Test';
a.Ticker_Start__c = newTicker;
}
}
It calls a class (tickerClass) method getTicker(). I am getting the following Problem in the on triggerTicker LINE 'Decimal newTicker = Decimal.valueOf(ticker.getTicker());:
Here is tickerClass.getTicker():
public class tickerClass {
@future(callout=true)
public static void getTicker() {
String retVal = null;
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://www.bitstamp.net/api/ticker/');
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
system.debug(results);
retVal = string.valueof(results.get('high'));
Decimal valueHigh = decimal.valueOf(retVal);
}
}
}
UPDATE: UPDATED THE TRIGGER AND THE CLASS BUT STILL GETTING ERRORS. I AM HAVING ISSUES WITH JUST PASSING THE ACCOUNT FROM THE TRIGGER TO THE CLASS. IDEAS? CAN'T FIND ANYTHING IN TRAILHEAD.
Trigger (updated)
trigger triggerTicker on Account (after insert) {
tickerClass.getTicker(Trigger.new);
}
Class (updated)
public class tickerClass {
// have to call future method if you are going to pull the method in a trigger
@future(callout=true)
// because we are looking for the accountId we need to make the trigger an after trigger
public static void getTicker(Account[] accounts) {
// do callout stuff
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://www.bitstamp.net/api/ticker/');
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
String retVal = null;
retVal = string.valueof(results.get('high'));
Decimal valueHigh = decimal.valueOf(retVal);
for (Account acct : accounts) {
acct.Ticker_Start__c = valueHigh;
}
}
// save the changes
update accounts;
}
}
tickerClass Error
'public static void getTicker(Account[] accounts) {'
Future methods do not support parameter type of List
Ok, I'm thinking I need to pass over the Account Id, right? How do I do that?
triggerTicker Error
'tickerClass.getTicker(Trigger.new);'
Method does not exist or incorrect signature: void getTicker(List) from the type tickerClass
I get one of these errors no matter what I do it seems. I have no idea how to properly pass data to the Class it seems...
A:
Specific Issues
Your method signature is
public static void getTicker(String retVal) {
but you are passing it Trigger.new, a List<sObject>. The compiler is looking for
public static void getTicker(List<sObject> retVal) {
which does not exist.
Edit: per your comments and discussion, what you are aiming at is to have a method
@future
public static void getTicker(List<Id> accountIds) {
which you can call like this from your trigger:
tickerClass.getTicker(new List<Id>(Trigger.newMap.keySet()));
This is a simple one-liner to get a list of Ids for all of the Accounts that are in your trigger context.
Then, within your method, you'll need to create a list of Account sObject instances to update, something like this:
List<Account> toUpdate = new List<Account>();
for (Id thisId : accountIds) {
toUpdate.add(new Account(Id = thisId, Ticker_Start__c = valueHigh));
}
update toUpdate;
When you update sObjects, you only need to populate the Id field and those fields whose values you wish to change.
More General Issues
You seem very uncomfortable with core Apex syntax and type infrastructure, and I'm going to go out on a limb and guess this is your first programming language. Trailhead is a great resource, but it's not comprehensive in providing an introduction to computer programming.
The Apex Developer Guide is somewhat more systematic in introducing the Apex language and how it works. It's not easy, but the ADG provides more detail and conceptual guidance, I think, than does Trailhead. But that might be another valuable resource for you, and I'd suggest going through the first several chapters in their entirety. Concepts like typing, parameters, and syntax are things you absolutely need in order to progress, and I'm afraid you'll find yourself quite frustrated if you don't establish that foundation.
If Trailhead and the ADG don't provide enough support, you may want to consider learning another programming language alongside Apex, like Python or JavaScript or Java, that have more breadth in introducing these core CS concepts, which you can then apply back to Apex.
Limits and Robustness
This is a more architectural commentary that you may want to keep in mind for the future.
In general, you need to be wary about @future callouts in triggers, because the future limit (50) is significantly lower than the maximum number of records you can receive in one invocation of the trigger (not one transaction, note!) - 200. If somebody inserts 51 Accounts in bulk, and you fire a future method per object, your code will throw an uncatchable LimitException.
One quick fix is to pass a collection, as above, to the future method, so that you only invoke it once. Then, the next limit you have to worry about is how many callouts you can make (100) in the future method. Again, if you're making one call-out per record, you're in trouble. Luckily, here it looks like you only need to make one call-out in total, so you're probably okay.
Another strategy to manage these limits issues, especially if you do need to call out for each record, is to pass a List of Account Ids to a Queueable Apex class, which runs asynchronously and can chain itself into a new Queueable invocation when it's done.
You can loop over the Ids in your Queueable and make callouts for the first N of them, and then chain into a new Queueable to process the remaining records. You'd have to tune N based on the callout limit (100) as well as the performance of your remote API, since there is a total callout time limit as well.
This will allow you to guarantee that all of your Accounts get processed, without burdening your triggers with a low limit on records.
A:
Thanks everyone for the help. Solution is posted below. The trigger and class work together to pull the data from the API and put into Salesforce.
Errors I was making:
Not appropriately creating the recordId List no the Trigger.
Not seeting the acct.Id to the a.Id on the Class.
NOT calling and creating acct List via SOQL query on the Class.
If you have any suggestions to tighten the code up, I'm all ears! :D
trigger
trigger Account on Account (before update, after insert) {
if (Trigger.isAfter) {
// create list to hold the Account Record ID
List<String> recordId = new List<String>();
// create new Account to pull the Account ID
for (Account acct : Trigger.new) {
// new instance of the account is set to a
Account a = new Account();
// set the Id to the Id of the new Account
a.Id = acct.Id;
// add the Account ID to the recordId List
recordId.add(a.Id);
// call the processRecords method and pass the recordId List
AccountClass.processRecords(recordId);
}
}
if (Trigger.isBefore) {
// develop in future
}
}
class
public class AccountClass {
@future(callout=true)
public static void processRecords(List<ID> recordId) {
// external callout to the api
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://www.bitstamp.net/api/ticker/');
request.setMethod('GET');
HttpResponse response = http.send(request);
// if callout is successful (code: 200)
if (response.getStatusCode() == 200) {
// parse the JSON
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
// create empty string variable
String retVal = null;
// change the api value (high) to a string and assign to string variable
retVal = string.valueof(results.get('high'));
// create a new decimal variable and change the retVal variable to decimal
Decimal valueHigh = decimal.valueOf(retVal);
// get record based on ID; can also put SOQL in place of acct in for loop
List<Account> acct = [SELECT Name
FROM Account
WHERE Id IN :recordId];
// for all of accounts that have the Account ID recordId
for (Account a : acct) {
// set the Ticker Start field to the external callout value for 'high'
a.Ticker_Start__c = valueHigh;
// update the record
update a;
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
In Rails 5, is setup called each time test is run?
Let's say I have the code below in my model test.
def setup
@object = Object.new(name: "test")
end
test "test 1" do
@object.age = 25
assert @object.valid?
end
test "test 1" do
...
end
...
Is the setup method called for before each test is done or it is just called once and proceeds to run all the tests?
A:
The setup method will be run before each test case. The minitest documentation says:
Runs before every test. Use this to set up before each test run.
| {
"pile_set_name": "StackExchange"
} |
Q:
ExtJS - dependent combobox
i had a problem with the loadData() function in my dependent combobox.
I'm doing a desk where I can create shortcuts and modify them.
The problem occurs when trying to modify the shortcut and pass "Tab con URL" to "Tab con Info de sistema".
Detects an error in the loadData function when I choose the combo with id="sistemas". No data load brings me function GetMenu in the store.
The data that returns the GetMenu function isn't loaded to the store.
I dont know why. Here is my code, can anyone lend me a hand?
The store:
var cmb_menu = new Ext.data.SimpleStore({
fields : ['id', 'menu'],
data : menu
});
Code:
{
xtype : "radio",
boxLabel : "Tab con Info de sistema",
value : "oneway",
tabIndex : 1,
id :'IdCheck',
name : "rt_rt_radiobutton",
listeners: {
check: function(){
Ext.getCmp("sistemas").enable();
Ext.getCmp("iconUrl").disable();
}
}
},
{
xtype:"radio",
boxLabel:"Tab con URL",
value:"twoway",
id: 'idCheckedUrl',
tabIndex:1,
name:"rt_rt_radiobutton",
listeners: {
check: function (ctl, val) {
if(val){
Ext.getCmp("iconUrl").enable();
Ext.getCmp("sistemas").disable();
Ext.getCmp("sistemas").clearValue();
Ext.getCmp("menus").clearValue();
Ext.getCmp("items").clearValue();
Ext.getCmp("subMenu").clearValue();
Ext.getCmp("menus").disable();
Ext.getCmp("items").disable();
Ext.getCmp("subMenu").disable();
}
}
}
},
{
xtype : 'combo',
store : cmb_sistemas,
hiddenName : 'id_sistema',
allowBlank : false,
value : sistemId,
mode : 'local',
fieldLabel : 'Sistemas',
disabled : true,
name : 'sistemas',
id : 'sistemas',
anchor : '90%',
displayField : 'sistema',
triggerAction: 'all', //rdiaz
emptyText : 'Seleccione un sistema',//rdiaz
editable : false, //rdiaz
valueField : 'id',
listeners : {
select: function (){
idSistema = this.getValue();
nombreSistema= this.getRawValue();
var menu = Ext.getCmp("menus");
iMenu = getMenu(idSistema);
//menu.store.clear();
menu.store.loadData(iMenu, true);
menu.enable();
var items = Ext.getCmp("items");
//menu.clearValue();
//menu.store.removeAll();//rdiaz
items.clearValue();
items.disable();
var subMenues= Ext.getCmp("subMenu");
subMenues.clearValue();
subMenues.disable();
}
}
},
{
xtype : 'combo',
store : cmb_menu,
hiddenName : 'id',
valueField : 'id',
value : menuID,
mode : 'local',
allowBlank : false,
fieldLabel : 'menu',
disabled : true,
triggerAction: 'all',//rdiaz
emptyText : 'Seleccione un menu',//rdiaz
editable : false, //rdiaz
name : 'menus',
id : 'menus',
anchor : '90%',
displayField : 'menu',
listeners : {
select: function () {
selectedMenu = this.getValue();
Ext.getCmp("subMenu").clearValue();
//alert(selectedMenu);
idSistema = Ext.getCmp("sistemas").getValue();
mItems = getItemsMenu(selectedMenu, idSistema);
if($.trim(selectedMenu) == "000060000000010000"){
var subMenues= Ext.getCmp("subMenu");
subMenues.store.loadData(mItems);
subMenues.enable();
var items = Ext.getCmp("items");
items.clearValue();
items.enable();
}else{
var subMenues= Ext.getCmp("subMenu");
subMenues.store.loadData(mItems);
subMenues.disable();
var items = Ext.getCmp("items");
//alert(mItems);
items.store.loadData(mItems);
items.clearValue();
items.enable();
}
}
}
},
Thank you!
A:
Store load methods are asynchronous meaning that the code after loadData is executed immediately but the data is not yet loaded.
You need to either perform the rest of your logic in the call back of loadData or separately in a load event listener.
| {
"pile_set_name": "StackExchange"
} |
Q:
why these two classes have the same size, does the method constitutes no size to a class?
I am trying to check the size of a class. Also, I am new to C++. I have two classes,
the difference between two classes is just that one has 8 methods in it. How come there is no difference in size of class in both of it. Can you please explain me with the concepts?
#include <iostream>
using namespace std;
class A
{
int b;
char c[2];
int func(int x, int y)
{
return x+y;
}
int func1(int x, int y)
{
return x+y;
}
int func2(int x, int y)
{
return x+y;
}
int func3(int x, int y)
{
return x+y;
}
int func4(int x, int y)
{
return x+y;
}
int func5(int x, int y)
{
return x+y;
}
int func6(int x, int y)
{
return x+y;
}
int func7(int x, int y)
{
return x+y;
}
};
class B
{
int b;
char c[2];
};
int main()
{
cout<<"Size of class A is "<< sizeof(A)<<endl;
cout<<"Size of class B is "<< sizeof(B)<<endl;
return 0;
}
The output is the following -
$ ./class_size.out
Size of class A is 8
Size of class B is 8
A:
Exactly. Methods do not contribute to the size of an object. There is only one copy of each function, and this is passed as a hidden argument.
You will notice an increase in size when you add your first virtual function, because objects with virtual functions will need at least an extra pointer to resolve virtual calls dynamically.
| {
"pile_set_name": "StackExchange"
} |
Q:
php error : Trying to get property of non-object
Not able to process this error as I am getting this as my output
enter code here
Notice: Trying to get property of non-object in
C:\xampp\htdocs\seo\seo.php on line 161 Notice: Trying to get property
of non-object in C:\xampp\htdocs\seo\seo.php on line 162
and
Notice:Trying to get property of non-object in C:\xampp\htdocs\seo\seo.php on
line 163 Page Authority:0 Domain Authority:0 External Links:
and this is the code
$accessID = " xxxx ";
$secretKey = " xxxxxxxx";
$domain = "$sig";
$expire_in = time() + 500;
$SignIn = $accessID."n".$expire_in;
$binarySignature = hash_hmac('sha1', $SignIn, $secretKey, true);
$urlSafeSignature = urlencode(base64_encode($binarySignature));
$data = "103079215140";
$curlURL = "http://lsapi.seomoz.com/linkscape/url-metrics/?Cols=".$data."&AccessID=".$accessID."&Expires=".$expire_in."&Signature=".$urlSafeSignature;
$Domains = array($domain);
$Domai = json_encode($Domains);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $Domai
);
$ch = curl_init($curlURL);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close( $ch );
$result = json_decode($response,true);
$pageAuthority=round($result[0]->upa,0);
$domainAuthority=round($result[0]->pda,0);
$externalLinks=$result[0]->ueid;
echo "Page Authority:".$pageAuthority."<br/>";
echo "Domain Authority:".$domainAuthority."<br/>";
echo "External Links:".$externalLinks."<br/>";
A:
You are using:
$result = json_decode($response,true);
^^^^ here
According to the manual:
When TRUE, returned objects will be converted into associative arrays.
So the result will be an array and there will be no objects.
So you need:
$result[0]['upa']
// etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
VB dll doesnt work in python with ctypes (function * not found)
I struggle to create dll in VB which will be visible for python,
none of VB functions are visible when I import dll into python
Here's what I do:
Simplest ever VB class
Public Class MyFunctions
Public Function AddMyValues(ByVal Value1 As Double, ByVal Value2 As Double)
Dim Result As Double
Result = Value1 + Value2
Return Result
End Function
End Class`
I save it as a dll (Build from Visual Studio 2010)
I try if it works by importing it into othoer VB project (it works fine):
Imports ClassLibrary1
Module Module1
Sub Main()
Dim Nowa As New ClassLibrary1.MyFunctions
Dim Result As String
Result = Nowa.AddMyValues(123, 456.78).ToString
Console.WriteLine(Result)
Console.ReadLine()
End Sub
End Module
I load it into python and try to use it:
from ctypes import *
MojaDLL = cdll.LoadLibrary("E:\\ClassLibrary1.dll")
MojaDLL.MyFunctions
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python25\lib\ctypes\__init__.py", line 361, in __getattr__
func = self.__getitem__(name)
File "C:\Python25\lib\ctypes\__init__.py", line 366, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'MyFunctions' not found
instead of MyDll.MyFunctions i also tried: MyDll.MyFunctions() , MyDll.MyFunctions.AddMyValues(1,2) , MyDll.MyFunctions.AddMyValues.
What's wrong here? I don't understand it.
PS. there's similar unsolved problem: calling vb dll in python
A:
You cannot do this. The DLL you’re producing is a .NET assembly, or, if you expose a COM interface, it’s a COM component.
Python’s ctypes module only supports C ABI DLLs.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a volatile table in this case?
sel *A union all sel * B union all sel * C
I need this statement result in a table for calculation
A,B,C contains same columns but different values
A:
I don't know what you mean by volatile but if you are looking for the results of your query in one table you can use something like the below
INSERT INTO TARGET_TABLE
SELECT * FROM A
UNION ALL
SELECT * FROM B
UNION ALL
SELECT * FROM C;
If you dont want duplicate values you can replace UNION ALL by UNION
| {
"pile_set_name": "StackExchange"
} |
Q:
Webpack is displaying empty pages, but files are being shown in terminal
partially going insane right now. I have been trying to fix this problem for over a week, but still can not seem to fix it.
Currently I am trying to make a React application that utilizes React-Router, however I am NOT using Redux or Flux. I took the code from the react-redux-starter-kit. I had experimented around with it a bit and all was working fine, but when I started changing things heavily is when I ran into issues.
The problem is, when the pages loads NOTHING is being displayed. When I say nothing I mean no HTML, JS, or CSS. All that is being displayed is the original base HTML file that consists of a <header> and <body> tag. When starting up the terminal I can see that the files are being loaded by webpack, here is what it looks like:
Server is now running at http://192.168.0.9:3000.
webpack built 928ca955f4efc3417ea7 in 11490ms
Hash: 928ca955f4efc3417ea7
Version: webpack 1.13.2
Time: 11490ms
Asset Size Chunks Chunk Names
2abdf22181eb309fd513564971a12163.png 70.2 kB [emitted]
148e6bc6eabab75f3e18eddc2d99a10f.png 34 kB [emitted]
app.928ca955f4efc3417ea7.js 1.04 MB 0 [emitted] app
1.charities.928ca955f4efc3417ea7.js 2.31 kB 1 [emitted] charities
vendor.928ca955f4efc3417ea7.js 405 kB 2 [emitted] vendor
app.928ca955f4efc3417ea7.js.map 1.29 MB 0 [emitted] app
1.charities.928ca955f4efc3417ea7.js.map 3.53 kB 1 [emitted] charities
vendor.928ca955f4efc3417ea7.js.map 487 kB 2 [emitted] vendor
favicon.ico 30.9 kB [emitted]
index.html 491 bytes [emitted]
Child html-webpack-plugin for "index.html":
Asset Size Chunks Chunk Names
index.html 565 kB 0
webpack: bundle is now VALID.
When I load the page though, none of those items are being displayed. I thought html-webpack-plugin was suppose to inject the necessary files, but it is not doing so. I can not figure out why none of the necessary files are being loaded in to my HTML file. My webpack config is as so:
import webpack from 'webpack'
import cssnano from 'cssnano'
import postcssNested from 'postcss-nested'
import postcssSimpleVars from 'postcss-simple-vars'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import config from '../config'
const paths = config.utils_paths
const {__PROD__} = config.globals
const webpackConfig = {
name: 'client',
target: 'web',
devtool: config.compiler_devtool,
resolve: {
root: paths.client(),
extensions: ['', '.js', '.json']
},
module: {}
}
const APP_ENTRY_PATHS = [
'babel-polyfill',
paths.client('main.js'),
`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`
]
webpackConfig.entry = {
app: APP_ENTRY_PATHS,
vendor: config.compiler_vendor
}
webpackConfig.output = {
filename: `[name].[${config.compiler_hash_type}].js`,
path: paths.dist(),
publicPath: config.compiler_public_path
}
webpackConfig.plugins = [
new webpack.DefinePlugin(config.globals),
new HtmlWebpackPlugin({
template: paths.client('index.html'),
hash: false,
favicon: paths.client('static/favicon.ico'),
filename: 'index.html',
inject: 'body',
minify: {
collapseWhitespace: true
}
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor']
})
]
if (__PROD__) {
webpackConfig.plugins.push(
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true,
warnings: false
}
})
)
}
webpackConfig.module.loaders = [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'react', 'stage-1']
}
},
{
test: /\.json$/,
loader: 'json'
}
]
const BASE_CSS_LOADER = 'css?sourceMap&-minimize'
const cssModulesRegex = new RegExp(
`(${paths.client().replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&')})`
)
const cssModulesLoader = [
BASE_CSS_LOADER,
'modules',
'importLoaders=1',
'localIdentName=[name]__[local]___[hash:base64:5]'
].join('&')
webpackConfig.module.loaders.push({
test: /\.css$/,
include: cssModulesRegex,
loaders: [
'style',
cssModulesLoader,
'postcss'
]
})
webpackConfig.module.loaders.push({
test: /\.css$/,
exclude: cssModulesRegex,
loaders: [
'style',
BASE_CSS_LOADER,
'postcss'
]
})
webpackConfig.postcss = [
cssnano({
autoprefixer: {
add: true,
remove: true,
browsers: ['last 2 versions']
},
discardComments: {
removeAll: true
},
discardUnused: false,
mergeIdents: false,
reduceIdents: false,
safe: true,
sourcemap: true
}),
postcssNested(),
postcssSimpleVars({
variables: function () {
return require(paths.client('styles/variables'));
}
})
]
webpackConfig.module.loaders.push(
{ test: /\.woff(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
{ test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
{ test: /\.otf(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
{ test: /\.ttf(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
{ test: /\.eot(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
{ test: /\.svg(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
{ test: /\.(png|jpg)$/, loader: 'url?limit=8192' }
)
export default webpackConfig
Please help me figure out why my index.html is not being injected with ANY of the files needed. All that is being displayed is the original index.html. If you would like all of the files I am currently using you can view them here. Thank you, please help!!
A:
It looks like all that's being served is the fallback and static handlers you have configured in server/main.js
app.use(express.static(root));
app.use(fallback('index.html', { root }));
If you delete that the request hangs indefinitely. That's not the only necessary fix but that will hopefully help you get to the root of the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cassandra default column value cqlsh
I am very new to Cassandra, and using the cqlsh to try out basic queries. I want to alter a table by inserting a new column with a default value (say 0). This is same as this SO question, the difference being I am trying to do it from cqlsh, so can't run an insert command on 50,000 rows. Is there a "cqlish" way to achieve this?
A:
There are no cqlsh/cql driver ways to this at the moment without executing on all of your rows. The simplest way may be to use a Spark and the Cassandra Connector.
There you could do something like
case class RowObj( oldValue1: Type, ..., newDefaultValue: Type)
sc.cassandraTable[RowObj]("keyspace","table")
.map(row -> row.copy(newDefaultValue = default)
.saveToCassandra("keyspace","table")
| {
"pile_set_name": "StackExchange"
} |
Q:
SQLite: Multiple select statements vs one select statement
In my Android project, I have a SQLite table data containing two rows, id and name. It has +/- ten records. Note that records may have been deleted, so the ids could be non-sequential.
In an activity I need the corresponding names of +/- 100 ids (obviously with lots of duplicate values).
I could do this by executing the SQLite query SELECT name FROM data WHERE id = x a hundred times.
Another option is executing the SQLite query SELECT id,name FROM data one time, then store the ids and the names in an array, and then get the names of the ids by java (String name = namesArray[Arrays.binarySearch(idsArray, x)];
Which method should I use? Or is there even a better solution?
A:
The second option is much faster.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Call child function from parent component in React Native functional component?
Hello I want to call showModal() in AddModalBox.js from App.js by using useRef() to access AddModalBox.js into App.js but is doesn't work it said:
showmodal.showMdal() is not a function...
Thanks for help...
App.Js
import React ,{useRef,useState} from 'react'
import {View,Text,StyleSheet,Image,Button,FlatList, Alert } from 'react-native'
import data from './components/Data'
import Swipeout from 'react-native-swipeout'
import AddModalBox from './components/AddModalBox'
const App=()=>{
const showmodal =useRef()
const callModal=()=>{
showmodal.showModal()
}
return(
<>
<View style={{backgroundColor:'red',height:10,flex:1,flexDirection:'row',marginTop:10}}>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'flex-end'}}>
<Button title="+" onPress={callModal}/>
</View>
</View>
<FlatList data={data} renderItem={({item,index})=> <Mydata item={item} index={index} parentFlatList={refreshFlatList}/>}
keyExtractor={item=>item.id}
/>
<AddModalBox ref={showmodal}/>
</>
)
}
export default App;
AddModalBox.js
I want to call showModal() function from App.js …
import React,{useRef}from 'react'
import {Text,View,Button,Dimensions} from 'react-native'
import Modal from 'react-native-modalbox'
import { useState } from 'react'
//import data from './components/Data'
var screen=Dimensions.get('window')
const AddModalBox=(props)=>{
let isOpen=false
// I want call this function in App.js
const showModal=()=>{
isOpen=true
}
return(
<>
<Modal style={{width:screen.width-80,height:200,justifyContent:'center'}}
position='center'
backdrop={true}
onClosed={()=>isOpen=false}
ref={show}
isOpen={isOpen}
>
<Text>hello from modal</Text>
</Modal>
</>
)
}
export default AddModalBox;
A:
Let me show you an example to use parameters between child and parent components.
This example is about variable visibility, but you can see and get insight to use on your code:
//Parent component
class Parent extends Component {
state = {
viewClhild: false
}
goToChild = (task) => {
this.setState({viewChild: true})
}
onShowClhildChange(viewChild) {
this.setState({ viewChild });
}
render() {
<View>
{
this.state.viewChild
? <ChildScreen onShowClhildChange={this.onShowClhildChange.bind(this)} />
: <Text>Show Parent</Text>
}
<Button
onPress={() => {this.goToChild()}}
>
<Text style={button.text}>Entrar</Text>
</Button>
</View>
}
}
//Child Component
class ChildScreen extends Component {
isChildVisible = (isVisible) => {
this.setState({ viewChild: isVisible })
if (this.props.onShowClhildChange) {
this.props.onShowClhildChange(isVisible);
}
}
constructor (props) {
super(props);
this.state = {
viewChild: this.props.viewChild
}
}
render() {
return (
<View>
<Button
onPress={() => this.isChildVisible(false)}
>
<Text>CLOSE CHILD SCREEN</Text>
</Button>
</View>
)
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I simplify this this code [VBA]
My current code
With PT.PivotFields("Year")
.PivotItems("2012").Visible = False
.PivotItems("2013").Visible = False
.PivotItems("2014").Visible = False
.PivotItems("2011").Visible = False
.PivotItems("2015").Visible = False
End With
is there a way to set a variable = to the current year so that I can use an If/Then statement to format this pivot table instead?
A:
see if this works
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Set pt = ActiveSheet.PivotTables(1)
' change field as needed
Set pf = pt.PivotFields("Year")
For Each pi In pf.PivotItems
If pf.Value <> "2016" Then pi.Visible = False
Next pi
| {
"pile_set_name": "StackExchange"
} |
Q:
postfix mailserver auth failed
I have an postfix + amavis mailserver, everything works fine except that somehow I will receive an spam email from me to me... so I dig and I make the following mods:
vi /etc/postfix/main.cf
smtpd_recipient_restrictions = permit_sasl_authenticated, reject_unauth_destination, check_sender_access hash:/etc/postfix/access/sender_access, reject_unknown_sender_domain, warn_if_reject reject_unverified_sender
mkdir /etc/postfix/access
vi /etc/postfix/access/sender_access
gigi.com 550 YOU ARE NOT ME.
postmap /etc/postfix/access/sender_access
/etc/init.d/postfix restart
Now I have to see if I receive mails from me :)
Anyway, in the /var/log/mail.log I have the following messages that are annoying to me in the security manner, will be good, wrong?
Can I make something to stop those requests from outside? Are too many... Could be an security breach? I mean, those request are minute by minute... wt#?
I attach some of the mail.log
Oct 13 22:06:34 mail postfix/smtpd[8698]: warning: unknown[191.96.249.61]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:06:34 mail postfix/smtpd[8698]: disconnect from unknown[191.96.249.61]
Oct 13 22:06:34 mail postfix/verify[8777]: close database /var/lib/postfix/verify_cache.db: No such file or directory (possible Berkeley DB bug)
Oct 13 22:06:35 mail postfix/smtpd[8722]: warning: unknown[191.96.249.26]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:06:35 mail postfix/smtpd[8722]: disconnect from unknown[191.96.249.26]
Oct 13 22:06:35 mail postfix/smtpd[8702]: connect from unknown[191.96.249.13]
Oct 13 22:06:43 mail postfix/smtpd[8702]: warning: unknown[191.96.249.13]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:06:43 mail postfix/smtpd[8702]: disconnect from unknown[191.96.249.13]
Oct 13 22:06:56 mail postfix/smtpd[8703]: connect from unknown[191.96.249.61]
Oct 13 22:06:57 mail postfix/smtpd[8698]: connect from unknown[191.96.249.13]
Oct 13 22:06:58 mail postfix/smtpd[8702]: warning: hostname radheengineering.info does not resolve to address 191.96.249.26
Oct 13 22:06:58 mail postfix/smtpd[8702]: connect from unknown[191.96.249.26]
Oct 13 22:07:00 mail postfix/smtpd[8703]: warning: unknown[191.96.249.61]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:07:00 mail postfix/smtpd[8703]: disconnect from unknown[191.96.249.61]
Oct 13 22:07:06 mail postfix/smtpd[8698]: warning: unknown[191.96.249.13]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:07:06 mail postfix/smtpd[8698]: disconnect from unknown[191.96.249.13]
Oct 13 22:07:07 mail postfix/smtpd[8702]: warning: unknown[191.96.249.26]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:07:07 mail postfix/smtpd[8702]: disconnect from unknown[191.96.249.26]
Oct 13 22:07:20 mail postfix/smtpd[8722]: connect from unknown[191.96.249.13]
Thanks guys!
A:
Oct 13 22:07:07 mail postfix/smtpd[8702]: warning: unknown[191.96.249.26]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
Oct 13 22:07:07 mail postfix/smtpd[8702]: disconnect from unknown[191.96.249.26]
Oct 13 22:07:20 mail postfix/smtpd[8722]: connect from unknown[191.96.249.13]
It just means that someone from IP 191.96.249.26 is trying to authenticate on your mailserver but he fails, because he is using wrong password. According to whois on this IP, this IP belongs to hosting provider dmzhost.co - you could try contact them and report abuse, say that on of their IPs is trying to hack into your mail server.
Beside that, you could block this IP address via iptables for example, on the long run you could integrate something as fail2ban on your server to block IP after X amount of failed tries. Or use something like CSF (ConfigServer Security & Firewall) instead of fail2ban. Or you could limit authentication tries directly in the postfix as suggested here:
# RATE THROTTLING
smtpd_client_connection_rate_limit = 20
smtpd_error_sleep_time = 10s
smtpd_soft_error_limit = 3
smtpd_hard_error_limit = 5
| {
"pile_set_name": "StackExchange"
} |
Q:
Asset Storeに繋がらなくなった。
タイトル通り以下のようになりました。
どうすれば繋がるのか教えてください。
調べたところ,「edit > project settings > player, untick ‘use direct3d 11′」のチェックを外せばいいとありましたが,どこなのかわかりません。それらしいところのチェックを外しても繋がりませんでした。
http://hidex97.hotcom-web.com/wordpress/?p=212
試した画像は以下です。
Unityのバージョンは5.4.2f2です。
A:
私の環境でも、同様の現象が発生しました。
動作環境: Unity 5.4.2f2
MacOS - Sierra
メニューからAssetStoreを開くと、Editor内のウインドウに結合されますが、外した状態(フロート状態)にすると、これまでと同様のAssetStoreが表示されました。
| {
"pile_set_name": "StackExchange"
} |
Q:
Scala inheritance best practices using a container classes
I have architected some code like this:
A "HandlerArguments" class which will take in a bunch of factories and other helpers needed for all the handler subclasses:
class HandlerArguments(
val a: A,
val b: B,
val c: C) {
/* nothing here */
}
A Handler superclass that will take in HandlerArguments:
class Handler(val args: HandlerArguments) {
def subHandler1 = new SubHandler1(args)
def subHandler2 = new SubHandler2(args)
def subHandler3 = new SubHandler3(args)
var message: Message = null
/* code here that invokes subHandler1, 2, or 3 based on a matcher */
def invokeCommand(msg: Message) = {
message = msg
someCommand match {
case command1 => subHandler1.something()
case command2 => subHandler2.something()
case command3 => subHandler3.something()
}
}
}
And the subHandlers, or subClasses:
class subHandler1(args: HandlerArguments) extends Handler(args) {
...
args.something.somethingElse(message.x)
...
}
class subHandler2(args: HandlerArguments) extends Handler(args) { ... }
class subHandler3(args: HandlerArguments) extends Handler(args) { ... }
And in another file, I am initializing the Handler:
/* initializing Handler */
val args = new HandlerArguments(a, b, c)
val handler = new Handler(args)
handler.invokeCommand(someMsg)
My questions are,
is this the best way to do this? The main thing I want to achieve is not having to pass 'message' around a lot between the superclass Handler and the subclasses, (i.e. subHandler1.something(message)).
How is my use of HandlerArguments? I thought about using traits or abstract classes but this is something that needs to be set once and then used by the Handler class.
It seems weird that I'm passing args from Handler to the SubHandlers, only to pass it back to Handler in the extends clause. Is there a better way to do this?
Thoughts? Thanks!
A:
What you have here is an example of a command/lookup-table pattern.
A few things that I can offer off the top of my head are:
make HandlerArguments a case class. That way, it's a bit less verbose and you get a lot of added benefits.
case class HandlerArguments(a: A, b: B, c: C)
and you are done. The arguments to case class constructors are automatically considered vals.
Another problem that I can see is that the construction of subclass instances from the super-class would result in a stack-overflow (as subclass construction also constructs a super class instance, and the cycle goes on indefinitely).
However, according to your use case, there probably shouldn't be a superclass-subclass relationship between your Handler and the SubHandler* classes. The subHandler* classes are the actual handlers, that is, they are the ones that handle the messages. Your Handler class simply dispatches messages to them. What you can do here would be something like the following.
case class HandlerArgs(a: A, b: B, c: C)
trait MessageHandler {
val args: HandlerArgs
def handle(msg: String)
}
class Handler1(val args: HandlerArgs) extends MessageHandler {
override def handle(msg: String) = ???
}
class Handler2(val args: HandlerArgs) extends MessageHandler {
override def handle(msg: String) = ???
}
class Handler3(val args: HandlerArgs) extends MessageHandler {
override def handle(msg: String) = ???
}
class MessageDispatcher(args: HandlerArgs) {
private val messageHandler1 = new Handler1(args)
private val messageHandler2 = new Handler2(args)
private val messageHandler3 = new Handler3(args)
def dispatch(message: String) {
val someCommand: Command = ???
someCommand match {
case Command("command1") => messageHandler1.handle(message)
case Command("command2") => messageHandler2.handle(message)
case Command("command3") => messageHandler3.handle(message)
}
}
}
val dispatcher = new MessageDispatcher(HandlerArgs(new A, new B, new C))
dispatcher.dispatch("<some command>")
Update after comment
If you want the messages to be shared by all the instances, one option is to add the template pattern to the existing code:
trait MessageHandler {
val args: HandlerArgs
private var message: Option[String] = None
// Save the message in a common implementation, and...
private def saveMessage(msg: String) {
message = Option(msg)
}
def handle(msg: String) {
saveMessage(msg)
doSomethingWithMessage(msg)
}
// let the subclasses handle the the actual message handling
protected def doSomethingWithMessage(msg: String)
}
class Handler1(val args: HandlerArgs) extends MessageHandler {
override def doSomethingWithMessage(msg: String) = ???
}
// rest of the message handlers
Of course, there are several ways of doing this.
Another way, as discussed in the comments, was to use a single element container. For ex.
class MessageHolder {
var message: Option[String] = None
}
trait MessageHandler {
val args: HandlerArgs
val messageHolder: MessageHolder
def handle(msg: String)
}
class Handler1(val args: HandlerArgs,
val messageHolder: MessageHolder) extends MessageHandler {
override def handle(msg: String) = ???
}
class MessageDispatcher(args: HandlerArgs) {
private val mh = new MessageHolder
private val messageHandler1 = new Handler1(args, mh)
private val messageHandler2 = new Handler2(args, mh)
private val messageHandler3 = new Handler3(args, mh)
def dispatch(message: String) {
val someCommand: Command = ???
mh.message = Option(message)
// ...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't mount CIFS through fstab
Trying to mount a CIFS share (from Freenas) at boot, but I can't seem to get it to work.
//freenas/mast/ /media/plexshare cifs guest,uid=1000 iocharset=utf8 0 0
I've tried using an IP rather than 'freenas' but that doesn't help
What's weird is that this worked twice, then on the third reboot, stopped working, and now won't mount with
sudo mount -a
It just returns :
mount: /etc/fstab: parse error: ignore entry at line 13
I can access the share perfectly when browsing the network through the file manager. The path when accessing it that way is: smb://freenas.local/mast/ I've also tried adding the .local to the line in fstab, but again to no avail.
A:
I see an issue but it may just be a misprint ..
the line should be :
//freenas/mast/ /media/plexshare cifs guest,uid=1000,iocharset=utf8 0 0
you have a space after uid and iocharset and it should be a comma
As you mentioned you are getting an error about only being able to mount as root. I also suggested trying
//freenas/mast/ /media/plexshare cifs defaults 0 0
If that doesn't help I can tell you the way I was able to get a network share drive to automount.
first you need to create a file in your users home directory
open terminal ... it should be at the users home directory
touch .smbcredentials
then
sudo chmod 600 .smbcredentials
open the file and add the following information
username=<user name needed to access the share>
password=<password needed to access the share>
once you have that file in place you will need to change or add the line to your etc/fstab at the end after all other lines.
//freenas/mast/ /media/plexshare cifs credentials=/home/<username>/.smbcredentials,iocharset=utf8,sec=ntlm 0 0
This should allow it to login and mount correctly to the share.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get value from Objects in an Array Wordpress
I am trying to add a voting functionality to a Wordpress website, the available plugins do not meet my requirements.
I have this array wich contains another array with wp_post objects (these are users who voted) what I need to do is compare the current_user_ID with all the post_author ids in the array objects. I need to do this so I can show different content to users who already have voted. Just knowing how to get post_author value from the objects in the array and compare it to the current_user_id would help out alot. I hope you guys can help me, thanks in advance.
This is how I get the array:
<?php $my_post_meta = get_post_meta($post->ID, 'supporters', false);
echo print_r($my_post_meta); ?>
And this is the array that shows:
Array ([0] => Array
(
[0] => WP_Post Object
(
[ID] => 750
[post_author] => 46
)
[1] => WP_Post Object
(
[ID] => 749
[post_author] => 47
)
[2] => WP_Post Object
(
[ID] => 748
[post_author] => 1
)
))1
A:
Try this:
<?php
$my_post_meta = get_post_meta($post->ID, 'supporters', false);
$current_user_ID = get_current_user_id();
foreach( $my_post_meta[0] as $post_object ) {
if( $post_object->ID == $current_user_ID ) {
// The current user has voted
}
}
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Find a matrix (in a base $B$) the projection operator of space $V$ on the subspace $\ker(F-I_{v})$ along the subspace $\ker(f-2I_{v})$
$$ B = (v_{1}, v_{2}, v_{3}, v_{4})$$ - basis of the vector space V, F - linear operator on the $V$
$$M^{B}_{B} = \left[\begin{array}{ccc}3&1&-1&1\\2&4&-1&-3\\2&2&0&-2\\2&2&-1&-1\end{array}\right]$$
Find a matrix (in a base $B$) the projection operator of space $V$ on the subspace $\ker(F-I_{v})$ along the subspace $\ker(f-2I_{v})$.
I need help how to do it. Thanks in advance
A:
If I understood your question right then we should have the following. Let $P$ be the required projection operator and $x\in V$ be an arbitrary point. Then $Px\in\ker (F-I_v)$ and $x-Px\in\ker (F-2I_v)$. Then $(F-I_v)Px=0$ and $(F-2I_v)(x-Px)=0$. Hence $FPx=Px$ and $Fx-FPx-2x+2Px=0=Fx-2x+Px$. So $P=2I_v-F$.
| {
"pile_set_name": "StackExchange"
} |
Q:
R fill in data value based on data range and variable combinations
I have 2 data frames which have been merged together, 1. with fine scale GPS position data along with datetimes and a site id; and 2. observations from each site inlcluding site id, individual id, and when the monitoring began and ended at a given site. In the merged data frame some of the individual id values are NA because the two tables didn't match on the date times and site id. However, I want to fill in individual id where the site ids match and the date time is between the start and end dates associated with that monitoring event. All these fields are available one table. I am currently using a loop to fill in the missing individual ids, but I have millions of rows and it's very inefficient. Any suggestions for improved efficieincy?
MWE
library(tidyverse)
dates = seq(as.Date('2020/01/01'), as.Date('2020/05/01'), by="day")
df1 = data.frame(site = rep(1:2,each = 5),
date_time = c(dates[1:5], dates[10:14]),
lat = rnorm(10,0,20),
lon=rnorm(10,150,180))
df2 = data.frame(site = c(1,2), id = c('A','B'),
start = c(dates[1], dates[10]),
date_time = c(dates[2], dates[11]),
end=c(dates[5], dates[14]) )
dat = merge(df1,df2,all=T)
For loop used to solve this problem (inefficiently)
for(i in 1:nrow(dat)){
tmp = dat[i,]
if(!is.na(dat[i,'id'])){next}
dat[i,'id'] = df2 %>% filter(site==tmp$site, start<=tmp$date_time, end>=tmp$date_time) %>% pull(id)
}
A:
Thanks to @thelatemail this solution worked:
df2[df1, on=c("site","start<=date_time","end>=date_time")]
| {
"pile_set_name": "StackExchange"
} |
Q:
What happens behind the git command "git merge pr --squash"
Say you have a master branch to which you want to merge your feature branch onto with a merge --squash that will happen if you setup a pull request as squash merge.
To my understanding in a 'high level' explanation the feature branch would get copied by checking out a temp branch on the head of the feature branch. Now onto this temp feature branch all the commits would be rebased interactively so all the commits that diverged from the ancestor commit would be squashed onto this temp feature branch.
Then that temp feature branch gets rebased onto master so after that the master can just fast forward merge to that new sqaushed commit and the temp feature branch gets deleted.
Leaving the master branch with that new commit that includes all changes on the feature branch but has no 'merge connection/relationship' to the last commit on that feature branch.
Normally in the pull request the source branch, in this case the feature branch, will also be deleted. If you don't do that you would still have a unmerged feature branch with the same state as before the pull request.
Is my 'high level' understanding correct or is the process of a squash merge different behind the curtains?
Thanks in advance!
A:
You're mixing together several concepts that must be kept separate. In particular, a pull request is a GitHub (or other web service provider) feature. This is not something Git does.1 Meanwhile git merge is a Git command-line command that operates within your own repository located on your own computer (laptop or whatever). When working with GitHub pull requests, you—or whoever agrees to the request, at least—may manipulate some browser button(s) to do a "merge", a "rebase and merge", or a "squash and merge", and those make changes in a repository hosted on GitHub. These are related, but different in several important ways, the biggest one being who actually has the repository. Once you have more than one Git repository, it's crucial to keep in mind which one has which commits pointed-to by which branch names, because your branch names are yours, and theirs are theirs: they need not have anything to do with each other, even if they're both called master or topic or feature/short or whatever.
1Git has a git request-pull command, which generates (but does not send) email messages. This is clearly not the same as a GitHub-style pull request.
The word merge, in Git, is both a noun and a verb
The gitglossary defines merge this way:
As a verb: To bring the contents of another branch (possibly from an external repository) into the current branch. In the case where the merged-in branch is from a different repository, this is done by first fetching the remote branch and then merging the result into the current branch. This combination of fetch and merge operations is called a pull. Merging is performed by an automatic process that identifies changes made since the branches diverged, and then applies all those changes together. In cases where changes conflict, manual intervention may be required to complete the merge.
As a noun: unless it is a fast-forward, a successful merge results in the creation of a new commit representing the result of the merge, and having as parents the tips of the merged branches. This commit is referred to as a "merge commit", or sometimes just a "merge".
There is a lot packed into these two paragraphs, and I'm not a fan of wedging the definition of "pull" into that of the verb merge—especially since git pull can be told to run git rebase instead of git merge as its second Git command—but the verb/noun distinction is here. When you do the action—the verb as a merge part—you often get the noun-or-adjective, i.e., the merge commit, as the result.
With this in mind, let's look at the anatomy of actual merges
Ignoring git pull (which just runs git merge for you, unless you tell it otherwise), the way you invoke the main merge-as-a-verb operation is to run:
git merge <thing-to-specify-a-commit>
from the command line. The commit specifier argument can be a branch name, a tag name, a raw commit hash ID, or anything that allows Git to find one particular commit.
Commits, in Git, exist in the form of a graph, specifically a Directed Acyclic Graph or DAG. Each commit is identified by its own unique hash ID—the hash ID is essentially the true name of the commit, and this one particular name is used in every Git repository everywhere to mean that one particular commit, if that commit is in that Git repository at all. Meanwhile, each commit contains, as part of its metadata, the actual hash ID(s) of its parent(s).
Mathematically, the definition of a graph is G = (V, E) where V is a set of vertices (or nodes) and E is a set of edges connecting those nodes. In Git, the nodes are commits—identified by their hash IDs—and the edges are one-way links or arcs, pointing from the child commit to its parent(s). These one-way links let Git move about, starting at the child-most commits. This gives us a bunch of ways to draw the graph. For StackOverflow postings, the way I like is to write them down like this, with newer commits towards the right:
... <-F <-G <-H
Here each letter stands in for an actual hash ID, and the arrows coming from a letter are the edges / arcs: if H is a commit, it holds the hash ID of its parent G, so H points to G. G holds the hash ID of F, so G points to F, and so on. These arrows all go backwards—a typical DAG has the arrow going from the parents, to the children, but Git prefers to work backwards (for various good reasons).2 For our own convenience, though, we can just start drawing them without any arrow-direction at all, and just remember that Git does things backwards:
...--F--G--H
In the forward direction—the one Git doesn't actually do—commit F has one child G, and G has one child H. From here, let's have H acquire two children, each of which has one of its own children:
I--J
/
...--F--G--H
\
K--L
For Git to find these commits, it needs some branch names. The branch names hold the actual hash ID of the last commit in the branch—which implies that every time we add a new commit to the branch, the value associated with the name changes—but let's just draw this in now:
I--J <-- br1
/
...--F--G--H
\
K--L <-- br2
In order to make a merge—to run the verb kind of merge—we'll pick one branch to check out, such as br1, and then run git merge on the other one:
git checkout br1
git merge br2
This will kick off the merge-as-a-verb process. If all goes well, it will make a merge commit, which is simply a commit with at least two parents:3
I--J
/ \
...--F--G--H M <-- br1 (HEAD)
\ /
K--L <-- br2
This new merge commit M gets added as the last commit on the current branch br1, so that the name br1 now points to new merge commit M.
Git actually computes the contents—the merged files—for merge commit M using three inputs: the two tip commits—here, J and L—and the merge base commit, which is defined as the best common ancestor of the other two commits. In this particular case, the best common ancestor is easy to see: it's commit H.4 You can think of the way Git handles this as:
run git diff --find-renames hash-of-H hash-of-J to see what we changed;
run git diff --find-renames hash-of-H hash-of-L to see what they changed;
combine these two diff outputs, applying the combined changes to the files from commit H.
Ignoring all the mechanics of conflict resolution, and the various special non-merge cases that git merge can do, this is really the key to any merge. Git finds the common starting-point commit, makes two sets of diffs, combines them, and applies the combined diffs to the common starting point snapshot. This forms the snapshot for the merge result.
2In particular, everything inside the main Git object database—commits and files, plus various glue objects—is frozen for all time. Git needs this to make its hash IDs work. A commit knows its parent or parents at the time it gets created: their hash IDs already exist. The commit does not know its children yet. The commit has just been born! Its memory is now frozen. Eventually, later, it acquires its first child. The parent cannot learn its child's hash ID, because the commit is already frozen for all time. The same holds if and when the parent gets a second child, third child, and so on. The children know their parents, but the parents don't know their children.
3Git calls a merge commit with three or more parents an octopus merge. There's nothing you can do with an octopus merge that you cannot do with a series of ordinary merges—in fact, the opposite is true: you can do things with ordinary merges that Git will refuse to do as a single octopus merge. The fact that an octopus merge is weaker than regular merges is somewhat useful, when you're examining a new-to-you repository, in that you can be reasonably assured that this merge doesn't introduce secret changes, nor have any conflict resolutions. But other version control systems that only allow pair-of-commit merges are just as powerful as Git.
4Technically, the merge base is the Lowest Common Ancestor of the two commits, using a generalized form of the LCA algorithm. LCAs are well defined on trees—the graph fragment I show above is actually a tree rather than a DAG—but in DAGs there may be more than one LCA. In this particular answer I'm not going to go into how Git handles the multiple-LCA case.
The squash merge is now trivial
Once you understand all of the above, git merge --squash becomes ridiculously simple. Git does everything it would do for a real merge, and then, at the end, it makes a commit that has one parent instead of two.5
That is, we start out with:
I--J <-- br1
/
...--F--G--H
\
K--L <-- br2
and run git checkout br1; git merge --squash br2. Git finds merge base H, performs two diffs, combines the diffs, and applies those to the contents of H. Then Git makes—well, makes you make; see footnote 5—the new merge commit, but instead of M with parents J and L, Git makes a commit we might want to call S (for squash) with one parent, J:
I--J--S <-- br1
/
...--F--G--H
\
K--L <-- br2
Had Git made merge M—and we can in fact still make M, the hashes wouldn't match, but the snapshots of M and S would. You can confirm this by making M:
git checkout -b experiment <hash-of-J>
git merge br2
which results in:
I--J--S <-- br1
/ \
...--F--G--H M <-- experiment (HEAD)
\ /
K--L <-- br2
The contents of M and S will match:
git diff br1 experiment
will show nothing at all.
5When you run git merge --squash, Git makes you run git commit yourself. The --squash flag turns on the --no-commit flag. This is a leftover from an ancient version of Git where --squash simply made git merge exit before running git commit—a true merge actually invokes git commit at the end, unless you use --no-commit or the merge has conflicts.
| {
"pile_set_name": "StackExchange"
} |
Q:
Responsive flash?
EDIT: I believe its safe to say that Flash is finally being discontinued.
A client recently ask for a flash background, ie, the flash had to be on the background.
How do I give a flash object 100% width while the height is defined?
And since the animation will stretch across the screen, is it possible to make the animation repeat itself within the window?
I hope the following image will clarify what I mean -
(sorry for the half-witted title.)
A:
You should be able to set the flashObject at 100% width and a static height in html. Any tiling would have to be done within flash itself. You'd probably have to make heavy use of events that relate to the size of the stage changing.
http://swffit.millermedeiros.com/ would be a good resource to go to as well. It does allow you to use 100% width and specify a max/min height. Unfortunately, the script is no longer in active development, and may have to be modified for modern browsers.
I agree with David's suggestion to go another route, but I know how clients can be sometimes...
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.