source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0005643140.txt"
] | Q:
Weird behavior merging 2 class functions and passing variables by reference
I have the following two class functions which I'm attempting to merge into one because they are very similar:
void Camera::UpdateCameraPosition(void) {
if(cameraMode == CAMERA_MODE_THIRD_PERSON) {
float alpha = Math::DegreesToRadians(Rotation.y);
float beta = Math::DegreesToRadians(Rotation.x);
Position.SetValue(
Player.x + CAMERA_ORBIT_OFFSET * cos(beta) * sin(alpha),
Player.y + CAMERA_ORBIT_OFFSET * sin(-beta),
Player.z + CAMERA_ORBIT_OFFSET * cos(beta) * cos(alpha)
);
} else {
Position = Player;
}
}
void Camera::UpdatePlayerPosition(void) {
if(cameraMode == CAMERA_MODE_THIRD_PERSON) {
float alpha = Math::DegreesToRadians(Rotation.y);
float beta = Math::DegreesToRadians(Rotation.x);
Player.SetValue(
Position.x - CAMERA_ORBIT_OFFSET * cos(beta) * sin(alpha),
Position.y - CAMERA_ORBIT_OFFSET * sin(-beta),
Position.z - CAMERA_ORBIT_OFFSET * cos(beta) * cos(alpha)
);
} else {
Player = Position;
}
}
As you can see, Player and Position are two private variables of the class. They're data type is Vector3D, another class.
I'm trying to merge them like this:
void Camera::UpdateCameraOrPlayerPosition(Vector3D &target, Vector3D reference) {
if(cameraMode == CAMERA_MODE_THIRD_PERSON) {
float alpha = Math::DegreesToRadians(Rotation.y);
float beta = Math::DegreesToRadians(Rotation.x);
target.SetValue(
reference.x - CAMERA_ORBIT_OFFSET * cos(beta) * sin(alpha),
reference.y - CAMERA_ORBIT_OFFSET * sin(-beta),
reference.z - CAMERA_ORBIT_OFFSET * cos(beta) * cos(alpha)
);
} else {
target = reference;
}
}
This compiles and such but it doesn't behave the same. While the other two functions are working, when I replace those function calls to this one instead, it doesn't work as it should.
The replacements I did are these:
UpdatePlayerPosition() -> UpdateCameraOrPlayerPosition(Player, Position)
UpdateCameraPosition() -> UpdateCameraOrPlayerPosition(Position, Player)
I also tried with a pointer instead of reference, the result was the same. Am I missing something here?
A:
You'll notice that target.SetValue uses + for Camera and - for Player when adjusting the X Y and Z coordinates.
|
[
"math.stackexchange",
"0002799578.txt"
] | Q:
Pivoting in the Bareiss algorithm
I'm learning about the Bareiss algorithm to compute determinants over integral domains from Chee Yap, Fundamental Problems of Algorithmic Algebra (see also this question). The naive version of the algorithm suffers from zero divisions, i.e. it will not work if there are some leading principal minors that are 0.
As mentioned briefly in the text - and also more extensively in this paper (p. 34) - the workaround is to exchange rows (or columns, I guess this should be equivalent): If I'm in the k-th outermost step and the (k,k) entry is zero, I find a row i with i > k, such that the (i,k) entry is non-zero (and then multiply the determinant by -1).
Now my question is: What if I can't find any such row?
There is some hint later on in the Yap text about this meaning that the matrix has dependent rows (so the determinant would be 0). But I don't have a proof for this.
Additionally, it would be useful if somebody knew a concrete example of a matrix that exhibits this behaviour. The only one I can think of is the zero matrix which, trivially, does have determinant 0.
A:
I believe I have now found a proof:
First, let's assume wlog that no row exchanges have happend up to the point where we cannot find a suitable row for the row exchange (because one can show that this would be equivalent to computing the determinant of the same matrix with the rows exchanged initially; that matrix has determinant 0 iff the original one has determinant 0). If, at the beginning of the $k$-th outermost iteration of the algorithm on a matrix $A$, we encounter an entry $a_{ik}$ mit $i \geq k$, then this is the determinant of the $(i,k)$-bordered matrix of order $k$ of $A$, i.e. of a $k\times k$ matrix (this can be shown by induction). Now assume $a_{ik} = 0$ for all $i\geq k$.
If $k=1$, the matrix $A$ would have a zero column, so the determinant must be zero. Otherwise, we look at the matrix $B$, which consists of the first $k$ columns of $A$. The first $k-1$ rows of $B$ can't be linearly dependent because otherwise they would also be dependent if we dropped the $k$-th column, so the leading principal minor of order $k-1$ would be zero - but that would mean that the $(k-1,k-1)$ entry of the modified matrix, after $k-1$ iterations, would be zero, which is impossible because then the algorithm would have been aborted before.
By assumption, the rows $1,\ldots,k-1,i$ of $B$ are dependent for any $i\geq k$. Since rows $1,\ldots,k-1$ are independent, this means that their span contains all other rows of $B$. Therefore, $B$ has rank $k-1$. But then $A$ can have rank at most $(k-1) + (n-k) = n-1$, which implies $|A| = 0$.
|
[
"stackoverflow",
"0036099471.txt"
] | Q:
How to set a range of values in numpy to nan?
My dataset looks like following:
>>> difference
array([[ -1, 0, 4],
[-20, 2, -1],
[ 2, -20, 0]])
I want values ranging from +2 to -2 to be replace by nan.
the resultant array should look like following.
>>> difference
array([[ nan, nan, 4.],
[-20., nan, nan],
[ nan, -20., nan]])
A:
Using np.abs(difference)<=2 to get the True values of the range, one way would be with np.where, like so -
np.where(np.abs(difference)<=2,np.nan,difference)
Sample run -
In [5]: difference
Out[5]:
array([[ -1, 0, 4],
[-20, 2, -1],
[ 2, -20, 0]])
In [6]: np.where(np.abs(difference)<=2,np.nan,difference)
Out[6]:
array([[ nan, nan, 4.],
[-20., nan, nan],
[ nan, -20., nan]])
For completeness, a more explicit way to get such a mask would be with (difference <=2) & (difference >=-2) instead of np.abs(difference)<=2.
|
[
"stackoverflow",
"0011015898.txt"
] | Q:
How to detect that UIScrollView is scrolling or that is is dragging
I need to know on a continuous basis when my UIScrollView is scrolling or dragging.
A:
Implement these two delegate methods..
- (void)scrollViewDidScroll:(UIScrollView *)sender{
//executes when you scroll the scrollView
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// execute when you drag the scrollView
}
A:
Better use isTracking to detect if the user initiated a touch-drag.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isTracking {
// ...
}
}
A:
This answer is deprecated. See @ober's isTracking solution instead
- (void)scrollViewDidScroll:(UIScrollView *)sender{
if(sender.isDragging) {
//is dragging
}
else {
//is just scrolling
}
}
|
[
"stackoverflow",
"0044937017.txt"
] | Q:
Element.classList Cannot read property 'toggle'
I'm getting this error:
Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLTableCellElement.toto
Can someone help?
var comments = document.getElementsByClassName('organisation');
var numComments = comments.length;
function toto(e){
/*this.style.cssText='background-color:white';*/
comments.classList.toggle('.maClasse');
}
for (var i = 0; i < numComments; i += 1) {
comments[i].addEventListener('click', toto, false);
}
A:
It's good!
var comments = document.getElementsByClassName('organisation');
var numComments = comments.length;
//function toto(e){
//this.style.cssText='background-color:white';
//comments.classList.toggle('.maClasse')
function myFunction() {
this.classList.toggle("maClasse");
};
//}
for (var i = 0; i < numComments; i += 1) {
comments[i].addEventListener('click', myFunction, false);
}
|
[
"stackoverflow",
"0016639865.txt"
] | Q:
Construct AND query if parameter is empty
I'm allowing my user to search by 10 different criteria. I'm picking that from url. But problem is if some of that criteria is/are empty. Then it will search record in database where is empty record.
$pretrazi_drzava=quote_smart($_GET["pretrazi_drzava"]);
$pretrazi_broj=quote_smart($_GET["pretrazi_broj"]);
$pretrazi_spol=quote_smart($_GET["pretrazi_spol"]);
$pretrazi_boja=quote_smart($_GET["pretrazi_boja"]);
$pretrazi_rasa=quote_smart($_GET["pretrazi_rasa"]);
$pretrazi_ime=quote_smart($_GET["pretrazi_ime"]);
$pretrazi_godina=quote_smart($_GET["pretrazi_godina"]);
$pretrazi_status=quote_smart($_GET["pretrazi_status"]);
$pretrazi_otac=quote_smart($_GET["pretrazi_otac"]);
$pretrazi_majka=quote_smart($_GET["pretrazi_majka"]);
It is easy to do with OR
...AND (mg_drzava.drzava='$pretrazi_drzava'
OR mg_golub.brojgoluba='$pretrazi_broj'
OR mg_golub.spol='$pretrazi_spol'
OR mg_golub.boja='$pretrazi_boja'
OR mg_golub.rasa='$pretrazi_rasa'
OR mg_golub.ime='$pretrazi_ime'
OR mg_golub.godina='$pretrazi_godina'
OR mg_status.status='$pretrazi_status'
OR O.brojgoluba='$pretrazi_otac'
OR M.brojgoluba='$pretrazi_majka')...
But if instead OR u put AND and if for example only mg_golub.brojgolub='' is empty, then it will search every record in database where brojgolub is empty and it won't find nothing and it won't show nothing as result.
How to solve that situation?
A:
You could use a foreach and iterate the $_GET array for construct your SQL statement
$sql = "SELECT * FROM table";
if(count($_GET) > 0)
{
// Append WHERE clause
$sql .= " WHERE ";
// Construct WHERE
foreach($_GET as $key => $value)
{
if($value != '')
{
$sql .= ' '.$key.' = '.$value.' AND ';
}
}
// Remove last "AND"
$sql = trim( $sql, 'AND ');
}
I didn't test this code, is just for reference how to ignore a emtpy value in your SQL statement. hope this help.
Updated: avoid 1=1 in query
|
[
"superuser",
"0000477071.txt"
] | Q:
Is it possible to make the motherboard log instant random shutdowns?
My computer randomly shuts down instantly. It even happens sometimes in the bios. And sometimes it runs for days under load without any problem.
I checked and it is not a temperature issue.
What I'm wondering is if it's somehow possible to log what caused the instant shutdown. I was thinking that only the motherboard could log it since sometimes it even happens when in the bios.
My motherboard is an Asus p8p67 pro rev 3.1.
A:
The motherboard will not keep logs like this.
This sort of failure could be caused by RAM though.
Run memtest from http://www.memtest.org/ overnight and see if it throws up errors.
The other thing it's likely to be is a power supply on its way out, but this is harder to test without installing a spare.
Outside of that, you could see if there's an updated BIOS you could flash.
|
[
"stackoverflow",
"0035363672.txt"
] | Q:
python code for inserting "N" in genome
I am having problem in my code I am trying to read a fasta file i.e. "chr1.fa", then I have a mutation file which looks like this
chr1 822979 822980 CLL6.08_1_snv 88.2 +
chr1 1052781 1052782 CLL6.08_2_snv 388.9 +
chr1 1216196 1216197 CLL6.08_3_snv 625 +
chr1 5053847 5053848 CLL6.08_4_snv 722.2 +
chr1 5735093 5735094 CLL6.08_5_snv 138.9 +
this is a tab delimited file with chr1 as first column and + as last. I want to insert a N in the chr1.fa file the using the location from the second column.My code looks like this
#!/usr/bin/python
# Filename: mutation.py
import sys , os
import numpy as np
import re
#declaring the variables
lst = ''
chr_name = ''
first_cord = ''
second_cord = ''
lstFirstCord = []
sequence = ''
human_genome = ''
seqList = ''
# Method to read the Genome file (file contains data for only one chromosome)
def ReadgenomeCharacter():
header = ' '
seq = ' '
try:
human_genome = raw_input("Enter UCSC fasta file of human genome:")
human_seq = open(human_genome, 'rw+')
line = human_seq.readline()
except:
print 'File cannot be opened, wrong format you forgot something:', human_genome
exit()
while line:
line = line.rstrip('\n')
if '>' in line:
header = line
else:
seq = seq + line
line = human_seq.readline()
print header
print "Length of the chromosome is:",len(seq)
print "No. of N in the chromosome are:", seq.count("N")
return seq
#Method to replace the characters in sequence string
def ReplaceSequence():
seqList = list(sequence)
for index, item in enumerate(lstFirstCord):
if seqList[index] != "N":
seqList[index] = "N"
newSequence = ''.join(seqList)
return newSequence
#Method to write to genome file
def WriteToGenomeFile(newSequence):
try:
with open("chr1.fa", 'rw+') as f:
old_human_seq = f.read()
f.seek(0)
f.write(newSequence)
print "Data modified in the genome file"
print "Length of the new chromosome is:",len(newSequence)
print "No. of N in the new chromosome are:", newSequence.count("N")
except:
print 'File cannot be opened, wrong format you forgot something:', human_genome
exit()
sequence = ReadgenomeCharacter()
print "Here is my mutaiton file data"
data = np.genfromtxt("CLL608.txt",delimiter ="\t", dtype=None,skip_header=0) #Reading the mutation file CLL608.txt
#Storing the mutation file data in a dictionary
subarray = ({'Chr1' : data[data[:,0] == 'chr1'],'Chr2': data[data[:,0] == 'chr2'],'Chr3': data[data[:,0] == 'chr3'],
'Chr4': data[data[:,0] == 'chr4'], 'Chr5': data[data[:,0] == 'chr5'],'Chr6': data[data[:,0] == 'chr6'],
'Chr7': data[data[:,0] == 'chr7'], 'Chr8': data[data[:,0] == 'chr8'],'Chr9': data[data[:,0] == 'chr9'],
'Chr10': data[data[:,0] == 'chr10'] , 'Chr11': data[data[:,0] == 'chr11'],'Chr12': data[data[:,0] == 'chr12'],
'Chr13': data[data[:,0] == 'chr13'], 'Chr14': data[data[:,0] == 'chr14'],'Chr15': data[data[:,0] == 'chr15'],
'Chr16': data[data[:,0] == 'chr16'],'Chr17': data[data[:,0] == 'chr17'],'Chr18': data[data[:,0] == 'chr18'],
'Chr19': data[data[:,0] == 'chr19'], 'Chr20': data[data[:,0] == 'chr20'],'Chr21': data[data[:,0] == 'chr21'],
'Chr22': data[data[:,0] == 'chr22'], 'ChrX': data[data[:,0] == 'chrX']})
#For each element in the dictionary, fetch the first cord and pass this value to the method to replace the character on first chord with N in the genome file
for the_key, the_value in subarray.iteritems():
cnt = len(the_value)
for lst in the_value:
chr_name = lst[0]
first_cord = int(lst[1])
second_cord = int(lst[2])
lstFirstCord.append(first_cord)
#Call the method to replace the sequence
newSeq = ReplaceSequence()
print "length :", len(newSeq)
#Call the method to write new data to genome file
WriteToGenomeFile(newSeq)
`
I am getting output like this
Enter UCSC fasta file of human genome:chr1.fa
chr1
Length of the chromosome is: 249250622
No. of N in the chromosome are: 23970000
Here is my mutaiton file data
length : 249250622
File cannot be opened, wrong format you forgot something:
we can download the chr1.fa by typing the following command directly
rsync -avzP
rsync://hgdownload.cse.ucsc.edu/goldenPath/hg19/chromosomes/chr1.fa.gz .
Somehow I am not able to insert the N in the sequence and also not able to wirte the new sequence.
I will be glad if any valuable suggestion for improving the code :)
A:
To make your life a bit easier, you may want to consider using Biopython to read in your fasta and do your converting.
Here's some documentation to get you started http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc16
Here is some starter code.
from Bio import SeqIO
handle = open("example.fasta", "rU")
output_handle = open("output.fasta", "w")
for record in SeqIO.parse(handle, "fasta"):
print record.seq
handle.close()
output_handle.close()
|
[
"stackoverflow",
"0016680524.txt"
] | Q:
Call REGEXP_LIKE using LINQ to Entities with Oracle
So if I have an Oracle query like this:
SELECT * FROM xyz WHERE REGEXP_LIKE(col1, '^[0-9]+$');
How can I call REGEXP_LIKE using LINQ to Entities with the Oracle.DataAccess client:
var q = from x in collection
where ??Oracle.REGEXP_LIKE(x.col1, "^[0-9]+$")??
select x;
Is something like this supported with the Oracle.DataAccess client?
A:
So the solution for me was just to open up a connection to the DB (ADO.NET) and execute the raw SQL...I dabbled with trying to create a custom LINQ function, but it would've taken too long to figure out given the relative simplicity of just "hacking" it.
|
[
"tex.stackexchange",
"0000042318.txt"
] | Q:
Removing a backslash from a character sequence
For indexing I wanted to write a macro \macroname that removes leading backslashes from macro names but leaves the names of environments untouched. That is
\macroname{\relax} --> relax
\macroname{itemize} --> itemize
where the --> is meant to be read as "expands to".
From my understanding, the following should work:
\newcommand\removebs[1]{\if#1\char92\else#1\fi}
\newcommand\macroname[1]{%
\expandafter\removebs\detokenize{#1}}
However, its outcome is
\macroname{\relax} --> \relax % literally
\macroname{itemize} --> itemize
By chance, actually, I found out that if I change the catcode of the backslash to "other" during the definition of the \removebs macro, it works:
{
\catcode`\|=0
|catcode`|\=12
|global|def|removebs#1{|if#1\|else#1|fi}
}
\newcommand\macroname[1]{%
\expandafter\removebs\detokenize{#1}}
Why is that? From TeX by Topic I'd expect that the comparison made by \if is what Philipp Lehman calls "category code agnostic".
Thanks for your answers!
A:
Joseph has given a working solution. I'd like to explain what goes wrong with your code.
First attempt
\newcommand\removebs[1]{\if#1\char92\else#1\fi}
\newcommand\macroname[1]{%
\expandafter\removebs\detokenize{#1}}
With \macroname{\relax} you get
\expandafter\removebs\detokenize{\relax}
and then (using • to separate tokens and <space> do denote a space token)
\removebs • \ • r • e • l • a • x • <space>
which becomes
\if • \ • \char • 9 • 2 • \else • \ • \fi • r • e • l • a • x • <space>
and the comparison is between a category code 12 backslash and the token \char, which of course leads to false.
The code \char92 are instruction to print character 92 from the current font.
One might correct the code by checking against a real category code 12 backslash:
\makeatletter
\newcommand{\removebs}[1]{\if#1\@backslashchar\else#1\fi}
\makeatother
but the space produced by \detokenize after \relax would remain.
Second attempt
{
\catcode`\|=0
|catcode`|\=12
|global|def|removebs#1{|if#1\|else#1|fi}
}
This works because it just implements the check against a category code 12 backslash, but it's not necessary, as the token is already available as \@backslashchar in the LaTeX kernel.
An alternative way, without global definitions and category changes, can be
\begingroup\lccode`\|=`\\
\lowercase{\endgroup\def\removebs#1{\if#1|\else#1\fi}}
where the only token that is converted to its lowercase equivalent is | (to a backslash).
Proposed code
% \makeatletter
% \newcommand{\removebs}[1]{\if#1\@backslashchar\else#1\fi}
% \makeatother
\begingroup\lccode`\|=`\\
\lowercase{\endgroup\def\removebs#1{\if#1|\else#1\fi}}
\newcommand{\macroname}[1]{\expandafter\removebs\string#1}
Since all you want is to get the argument letters, it doesn't matter if the first letter in \macroname{itemize} has category code 12.
A:
TeX works with tokens, and what you need to know is that a control sequence such as \foo is not tested by \if as a series of characters, but as a single 'unit'. There a a few primitives that will turn control sequences back into single tokens: \detokenize does this for a set of tokens, while \string does so for a single token. The latter is also available in all TeX versions (\detokenize requires e-TeX).
As you observe, detokenizing the input allows you to do a comparison to a category code 'other' \. An alternative approach would be to test if #1 is a control sequence, using the fact that \ifcat treats all (unexpanded) control sequences as identical. You can then use \string to convert to multiple tokens, and \@gobble to remove the very first character:
\documentclass{article}
\makeatletter
\newcommand{\removeabs}[1]{%
\ifcat\relax\noexpand#1%
\expandafter\expandafter\expandafter\@gobble\expandafter\string
\fi
#1%
}
\makeatother
\begin{document}
\removeabs{foo}
\removeabs{\bar}
\end{document}
The above is all fine as long as \escapechar is printable and not a space. Using some code from LaTeX3 'translated' back to primitives, you can set things up to be robust for all escape characters:
\documentclass{article}
\makeatletter
\newcommand{\removeabs}[1]{%
\ifcat\relax\noexpand#1%
\expandafter\removeabs@aux@i
\fi
#1%
}
\newcommand*{\removeabs@aux@i}{%
\romannumeral
\if\string\ \removeabs@aux@ii\fi
\expandafter\removeabs@aux@iii\string
}
\newcommand{\removeabs@aux@ii}{}
\long\def\removeabs@aux@ii#1\removeabs@aux@iii{%
-\number\fi\expandafter\z@
}
\newcommand{\removeabs@aux@iii}[1]{\z@}
\makeatother
\begin{document}
\removeabs{foo}
\removeabs{\bar}
\end{document}
(See the implementation of \cs_to_str:N in the LaTeX3 docs for what is going on here!)
|
[
"stackoverflow",
"0036493494.txt"
] | Q:
Mouse events for captured element stop firing while dragging
I have some code that draws some points on the screen and then allows them to be dragged while holding the left mouse button. This kinda works except constantly the mouse events stop firing and the point being dragged stops moving.
Because all of the events stop being caught(for some unknown reason), that means the user can release the left mouse button without anything happening.
The weird thing is that the user can then reposition the mouse over the point and it will start dragging again without holding the left mouse button down. It makes for a very poor user experience.
What is going on?
pinPoint.MouseLeftButtonDown += Point_MouseLeftButtonDown;
pinPoint.MouseLeftButtonUp += Point_MouseLeftButtonUp;
pinPoint.MouseMove += Point_MouseMove;
.
.
.
void Point_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
((UIElement)sender).CaptureMouse();
if (_isDragging == false)
{
_isDragging = true;
}
}
void Point_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
_isDragging = false;
((UIElement)sender).ReleaseMouseCapture();
}
void Point_MouseMove(object sender, MouseEventArgs e)
{
//where the point gets moved and some other logic
//possibly this logic takes too long?
}
A:
I've found a solution that works. I've still got no idea why it is continually losing the MouseCapture though.
pinPoint.LostMouseCapture += Point_LostMouseCapture;
.
.
.
void Point_LostMouseCapture(object sender, MouseEventArgs e)
{
//if we lost the capture but we are still dragging then just recapture it
if (_isDragging)
{
((UIElement)sender).CaptureMouse();
}
}
|
[
"stackoverflow",
"0018802757.txt"
] | Q:
How to delay instantion of a specific controller(not a route)?
I would like to have a directive which behaves as typical ng-controller, but I want it to be called once a promise is resolved, not sooner.
In HTML this could be written like this:
<div ng-controller="myCtrl" ctrl-promise="p">
p could be any promise on parent scope.
I know there is a way to delay instantiation of a controller for a route(as answered here: Angular.js delaying controller initialization), but I would much prefer to specify this per controller rather than per route.
I know I could use ng-if with p as atribute, but is there other way?
A:
So you want the stuff inside the div to exist, just without the controller controlling it, until the promise is resolved?
Here is a directive which will create a controller when a promise is resolved:
angular.module('myApp')
.directive('delayController', function($controller, $q) {
return {
scope: true,
link: function(scope, elm, attr) {
$q.when(scope.$parent.$eval(attr.delayControllerPromise)).then(function() {
var ctrl = $controller(attr.delayController, {
$scope: scope
});
elm.children().data('$ngControllerController', ctrl);
});
}
};
});
You can use it like this:
<div delay-controller="MyCtrl" delay-controller-promise="myPromiseExpr()">
</div>
|
[
"stackoverflow",
"0035111725.txt"
] | Q:
changing the image src attr
Looking for some direction with this.
At this current iteration, I have it where if a user clicks on an image thumbnail, the thumbnail image displays in a different div (the main div) and in doing so, it rewrites the main div img src attr *update: with the thumbnail img attr minus the "-thumbnail". This part is good, or at least I believe it is.
With that said, after the user clicks on a thumbnail and the main div img appears, it lingers...and what I mean by lingers is that for example, if a user closes the div and re-opens it or another div just like it, the last image shows (stays) when it shouldn't in the main div. Instead, it should be showing the first thumbnail img in the main div...
Any suggestions is appreciated and below is what I currently have (or at least a portion of it). There is a lot more, but below is the main stuff that's giving me troubles...
*update: The HTML part is within a div class called "t_1". I have 24 of these..."t_1", "t_2", "t_3" respectively. And within this class, I have what is posted below in all using the same div classes. The only difference is the folder names in the img tag.
So, when a user clicks on that thumbnail and that thumbnail image gets rewritten so that it can be displayed in the main div "t_main_screenshot", all is good...but then, if the user clicks out of the "t_1" etc. divs, and opens up another "t_2", that last image thumbnail that was clicked previously shows in the main div (t_main_screenshot) instead of the first image thumbnail for what should be in "t_2"...
Hopefully this is a bit better in clarity...It's kind of hard to explain.
HTML:
<div class="t_main_screenshot">
<img src="_framework/images/slides/simplicity/2.png" alt="" title="" />
</div>
<div class="t_thumbnail_wrapper">
<div class="t_thumbnail active">
<img src="_framework/images/slides/simplicity/2-thumbnail.png" alt="" title="" />
</div>
<div class="t_thumbnail">
<img src="_framework/images/slides/simplicity/4-thumbnail.png" alt="" title="" />
</div>
<div class="t_thumbnail">
<img src="_framework/images/slides/simplicity/6-thumbnail.png" alt="" title="" />
</div>
</div>
JS / JQuery:
$('.t_thumbnail').click(function() {
$('.t_thumbnail').removeClass('active');
$(this).addClass('active');
var thumbNail = $(this).find('img').attr('src');
$('.t_main_screenshot img').fadeOut(0, function() {
$(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = thumbNail.replace('-thumbnail', '');
});
});
A:
Finally figured out the answer to this:
$('.t_thumbnail').click(function() {
$('.t_thumbnail').removeClass('active');
$(this).addClass('active');
var thumbNail = $(this).find('img').attr('src');
$(this).parent().parent().siblings().find('.t_main_screenshot').children('img').fadeOut(0, function() {
$(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = thumbNail.replace('-thumbnail', '');
});
});
|
[
"salesforce.stackexchange",
"0000047881.txt"
] | Q:
Invalid Cross Reference Key : Record Type ID value isn't valid for User: 012v00000008f4nuBB
I am having some issues. The below is a code snipet of my test class. The class complies and produces 96% of coverage with no errors. When deploying in production it throws the above error.
Salesforce says the error is on the first bolded line. However the recordtypeid it throws at me is a recordtype for the second bolded line: which in itself is a legit recordtype.
User me = TestUtil.createUser();
RecordType accountrec = [select id from RecordType where sObjecttype ='Account' and DeveloperName='prop'];
RecordType opprec = [select id from RecordType where sObjecttype ='Opportunity' and DeveloperName='full'];
RecordType goalrec = [select id from RecordType where sObjecttype ='Goals__c' and DeveloperName='Manager'];
System.runAs(me){
Account acc = new Account(recordtypeid=accountrec.id, Name='TestAccount');
insert acc;
Contact cont = new Contact(FirstName='Test', lastName = 'Contact', phone='(888) 888-8888', AccountId=acc.id);
insert cont;
Group__c Group = new Group__c(Name='Group', Ownerid = me.id);
insert Group; //**ERROR THROWN IS AT THIS LINE**
Group_Goal__c GroupGoal = new Group_Goal__c(Name ='testGroupgoal', Group__c=Group.id);
insert GroupGoal;
Goals__c goal = new Goals__c(recordtypeid=goalrec.id, Ownerid = me.id, EFM_Group_Goal__c=efmGroupGoal.id, Fiscal_Year__c='FY2015');
insert goal; //**RECORD TYPE PROVIDED IS FOR THIS RECORD**
}
A:
Profiles have record type settings. This error means that the user has a profile for which that record type is not enabled. You need to make sure the profile you're using has access to the desired record type, or that the value is being set in a "without sharing" class.
|
[
"math.stackexchange",
"0001588944.txt"
] | Q:
Divisibility set of problems
It may seem as a begginer question, but i was wondering if there exist a certain method to solve problems like the following :
$$1) \text{ if } n ∈ \Bbb N \\ n(n^2+5)\,⋮\,6$$
$$2) \text{ if } n ∈ \Bbb N \\n^4+6n^3+11n^2+6n\,⋮\,24$$
$$3)\text{ if } n=2k \text{ then } \frac{n}{12}+\frac{n^2}{8}+\frac{n^3}{24}∈ \Bbb Z $$
NOTE:I havent dont this types of problems in a long time and it would be useful to see a detailed solution.Thanks!a
A:
Another possible method is to write these numbers in terms of binomial coefficients which are always integers :
1) $$\frac{n(n^2+5)}{6}=\frac{n^3+5n}{6}=n+\frac{n^3-n}{6}=n+\frac{n(n+1)(n-1)}{3!}=n+\binom{n+1}{3}$$ which is an integer so $6 \mid n(n^2+5n)$
2) $$n(n+1)(n+2)(n+3)=n^4+6n^3+11n^2+6n$$ so $$\frac{n^4+6n^3+11n^2+6n}{24}=\frac{n(n+1)(n+2)(n+3)}{4!}=\binom{n+3}{4}$$ which is an integer .
3) $$\frac{k}{6}+\frac{k^2}{2}+\frac{k^3}{3}=\frac{2k^3+3k^2+k}{6}=\frac{k(k+1)(2k+1)}{6}$$
This can be seen either by this method :
This number is actually :
$$2\binom{k+1}{3}+\binom{k+1}{2}$$
Or you can do this in an awesome way noticing it's actually :
$$1^2+2^2+3^2+\ldots+k^2$$ (if you know this formula ) .
|
[
"stackoverflow",
"0001095774.txt"
] | Q:
How can I eliminate left recursion in the following grammar?
Here's the grammar, which is supposed to describe a language of nested braces with commas as delimiters:
L ::= {L} | L,L |
A few more examples of strings I'd expect the grammar to accept and reject:
Accept:
{,{,,{,}},,{,}}
{{{{}}}}
{,{}}
Reject:
{}{}
{,{}{}}
{{},{}
A:
Done by hand:
L ::= { L } | { L } , | , L | ε
Or, instead of just winging it we could use a more systematic approach and apply the algorithm from Wikipedia on removing immediate left recursion:
L ::= { L } L1 | L1
L1 ::= ε | , L L1
|
[
"stackoverflow",
"0000159846.txt"
] | Q:
UnsatisfiedLinkError: The specified procedure could not be found
I'm writing some JNI code in C++ to be called from an applet on Windows XP. I've been able to successfully run the applet and have the JNI library loaded and called, even going so far as having it call functions in other DLLs. I got this working by setting up the PATH system environment variable to include the directory all of my DLLs are in.
So, the problem, is that I add another call that uses a new external DLL, and suddenly when loading the library, an UnsatisfiedLinkError is thrown. The message is: 'The specified procedure could not be found'. This doesn't seem to be a problem with a missing dependent DLL, because I can remove a dependent DLL and get a different message about dependent DLL missing. From what I've been able to find online, it appears that this message means that a native Java function implementation is missing from the DLL, but it's odd that it works fine without this extra bit of code.
Does anyone know what might be causing this? What kinds of things can give a 'The specified procedure could not be found' messages for an UnsatisifedLinkError?
A:
I figured out the problem. This was a doozy. The message "The specified procedure could not be found" for UnsatisfiedLinkError indicates that a function in the root dll or in a dependent dll could not be found. The most likely cause of this in a JNI situation is that the native JNI function is not exported correctly. But this can apparently happen if a dependent DLL is loaded and that DLL is missing a function required by its parent.
By way of example, we have a library named input.dll. The DLL search order is to always look in the application directory first and the PATH directories last. In the past, we always ran executables from the same directory as input.dll. However, there is another input.dll in the windows system directory (which is in the middle of the DLL search order). So when running this from a java applet, if I include the code described above in the applet, which causes input.dll to be loaded, it loads the input.dll from the system directory. Because our code is expecting certain functions in input.dll which aren't there (because it's a different DLL) the load fails with an error message about missing procedures. Not because the JNI functions are exported wrong, but because the wrong dependent DLL was loaded and it didn't have the expected functions in it.
|
[
"stackoverflow",
"0015624978.txt"
] | Q:
Does current OpenCL implimentions of Java offer cross-platform support as well as stability to be used in projects?
Background:
Our school entered in a competition where my team (based on 3 people including me) is assigned the task to do navigation and image processing. It's an year long project but I want to get started as soon as possible and see what are the options I have. University and other firms are funding in this research as well. I am no computer science major, we are building an engineering application that highly depends on navigation and image processing for basis of intense calculation purposes on top.
Question:
I understand we will be needing algorithms and smart data structure choices to cut down the processes and split the work in threads to harness the power of the device. Anyhow, I have been reading a lot regarding OpenCL implementations for Java that I found namely, LWJGL, JOCL, JavaCL. The problem is, they all do the same thing but some does it better in their own unique ways. I am looking for something simple with fair amount of community and cross-platform support. Because, the microcontrollers we will buy most probably run Linux (I am thinking Arduino and SMARTGPU).
Anyways, this is very early so I need some pointers as to where to go from here. I will probably need to look up some guides, tutorials, and manuals as well to understand more on OpenCL.
A:
I have been using JavaCL for nearly a year now and have found it to be easy to use and reliable. The one bug that I did find was fixed within 24 hours (admittedly a very simple bug). I did try using JOCL but found their API to be a little difficult to use compared to JavaCL. I have no experience with LWJGL, but would point out that LWJGL is more general as it is intended for games.
If you decide to use Java, then I would suggest starting with JavaCL.
However, I would suggest that you consider OpenCV as it provides a lot of image processing functions that have already been heavily optimised. It may not be as fast as using OpenCL and a fancy embedded GPU but it could cut your development time.
|
[
"stackoverflow",
"0040017011.txt"
] | Q:
I want to create a Y/N flag. If one of the same accounts ends in M then mark as N else Y if all ends with D
SELECT
CASE WHEN SUBSTR(ACCOUNT,6,1) = 'M' THEN 'N' ELSE 'Y' END AS POSTING_FLAG
FROM ALL_QUEUES
Desired Output:
Account Flag
12345D N
12345D N
12345D N
12345M N
22222D Y
22222D Y
22222D Y
22222D Y
A:
You can use analytic function; this uses a CTE to provide your base data with just the account:
with all_queues (account) as (
select '12345D' from dual
union all select '12345D' from dual
union all select '12345D' from dual
union all select '12345M' from dual
union all select '22222D' from dual
union all select '22222D' from dual
union all select '22222D' from dual
union all select '22222D' from dual
)
select account,
case max(substr(account, -1))
over (partition by substr(account, 1, length(account) - 1))
when 'M' then 'N' else 'Y' end as posting_flag
from all_queues;
ACCOUNT POSTING_FLAG
------- ------------
12345D N
12345D N
12345D N
12345M N
22222D Y
22222D Y
22222D Y
22222D Y
8 rows selected.
If the account is really always seven characters then you can simplify the partition substring.
|
[
"stackoverflow",
"0060111688.txt"
] | Q:
How to assert that app sends correct data to API server with POST request
I am writing React.js application talking to API server. I have read tons of articles on how to mock these calls and send some fake response from API. I can do testing using @testing-library/react, I can easily mock axios with axios-mock-adapter and test fetch requests using HTTP GET method. But I cannot find anywhere how to make sure that my app, when it sends some POST request, sends correct data to API, i.e. that my app sends json payload with e.g. "id" field, or "name" field set to "abc", or something like this.
I am new to React.js. Please advise how to make tests asserting what the app sends to API. Is it possible?
Let's say that I have a function named doSomething, like below, called with onClick of some button.
const doSomething = async (userId, something) => {
try {
await REST_API.post('doSomething', {
user_id: userId,
something: something
});
return true;
} catch (error) {
window.alert(error);
return false;
}
};
REST_API above is axios instance.
How can I ensure that the I (or some other developer) didn't make a typo and didn't put "userId" instead of "user_id" in the payload of the request?
A:
If you have to be sure you call correctly the api, I'd use jest as follow:
jest.mock('axios', () => ({
post: jest.fn(),
}));
describe('test', () => {
it('doSomething', () => {
const userId = 123;
const something = 'abc';
doSomething(userId, something);
expect(axios.post).toBeCalledWith(
'doSomething', {
user_id: userId,
something,
},
);
});
});
or if you use instance, define it in another file (axios_instance.js) and using the follow test:
jest.mock('./axios_instance', () => ({
instance: {
post: jest.fn(),
},
}));
describe('test', () => {
it('doSomething', () => {
const userId = 123;
const something = 'abc';
doSomethingInstance(userId, something);
expect(instance.post).toBeCalledWith(
'doSomething', {
user_id: userId,
something,
},
);
});
});
|
[
"stackoverflow",
"0022288494.txt"
] | Q:
margin-top in percentage not working as expected
I know what you're thinking, but the parent container(s) are all positioned with pixels.
I have a div with a height and width in pixels, inside that div I have a youtube iframe that has (for this example) it's margin-top in percentage.
This the HTML:
And this is the result:
I know it's a ridiculously small frame (right bottom of selected div) but it's just an example :)
As you can see, in code I have the margin-top set to 99% but it's actually positioned a lot lower. What could be the cause of this?
A:
The point is that a percentage value for top/bottom margin/padding properties is relative to the width of the box's containing block. It doesn't respect the height of the parent element.
8.3 Margin properties: 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', and 'margin'
<percentage> The percentage is calculated with respect to the width
of the generated box's containing block. Note that this is true for
margin-top and margin-bottom as well. If the containing block's
width depends on this element, then the resulting layout is undefined
in CSS 2.1.
As you are using absolute positioning, try using top: 99% instead in which a percentage value refers to the height of the box's containing block.
|
[
"ux.stackexchange",
"0000086173.txt"
] | Q:
What is the rationale behind the design to bring "everything" ahead of the lock screen?
On Android Lollipop, even with a PIN-enabled lock screen, it is possible to:
Turn on/off Flight mode
Turn on/off Location
Turn on/off WiFi, Bluetooth, Mobile Data
See all available WiFi and Bluetooth connections
Enable/Disable Hotspot
Turn on/off the torch
Turn on/off phone sounds, and/or all interruptions.
etc, from the Quick Settings pull-down menu.
I can think of so many security risks this poses that I cannot justify that the reason for having this is purely for user convenience.
What is the rationale behind this design?
A:
You will note that all of the items that are accessible from in front of the lock screen are interactions with the hardware. They are also hardware interactions that commonly take place whilst the user is busy using his or her hands for something else.
What isn't in front of the security lock is the user's data. Even the network related items are focussed around turning on and off the hardware. No where does the OS allow access to actuall user data or functionality that has a cost associated with it without that access being secured if the user has setup a lock.
A:
My initial reaction to this is that it's 100% for convenience.
If you're in a dark room looking for something it's great to be able to quickly turn on the light without needing to authenticate one way or another.
If you're late for a flight, you rush to get on the plane & sit down, it's great to be able to quickly put it in airplane mode without needing to authenticate.
You can do almost the exact same actions on iOS as well by default, but there is an option to disable these from the lock screen if desired. I'm not sure if Android has this or not, but I would assume so.
I do see the security implications that you mentioned, but I think these are not a concern for most people (however it should be something to think about!). If you are security conscious & it's possible in the OS it would be a good idea to disallow these features from being accessed on the lock screen.
|
[
"es.stackoverflow",
"0000164096.txt"
] | Q:
Limitar numero de datos a insertar en base de datos mysql
Inserto un nombre desde un formulario a una base de datos que representa los participantes de un taller. En el taller solo hay espacio para 30 personas y trate de limitar eso con la funcion COUNT(*). Mi problema es que el formulario sigue enviando datos aun que la base de datos ya tenga 30 entradas. Gracias por su ayuda.
<?php
$link = mysqli_connect("localhost", "user", "pass", "base");
if($link === false){
die("ERROR: No se puede conectar. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$res = mysqli_query("SELECT COUNT(*) as cnt FROM `taller1` ");
$row = mysqli_fetch_assoc($res);
if($row['cnt']<30){
$sql = "INSERT INTO taller1 (name) VALUES ('".$name."')";
if(mysqli_query($link, $sql)){
echo "Su registro se ha realizado correctamente.";
}
else{
echo "ERROR: no se pudo añadir $sql. " . mysqli_error($link);
}
}
else{
echo "Taller lleno";
}
mysqli_close($link);
?>
A:
Te coloco un ejemplo, ya solo debes adaptarlos a tus necesidades:
<?php
$link = mysqli_connect("localhost", "root", "", "demo");
$res = mysqli_query($link, "SELECT * FROM alumnos ");
$fila = mysqli_num_rows($res);
printf($fila);
if($fila <= 2){
$sql = "INSERT INTO alumnos (nombre, edad, sexo) VALUES ('dato1', 34, 'dato1')";
mysqli_query($link, $sql);
}
else{
echo "Taller lleno";
}
Te hago los siguientes comentarios
Para leer el número de filas hago uso del método mysqli_num_rows, la cual recibe como parámetro la variable que contiene la query
Gracias a la función que te menciono en el punto 1, ya no necesito hacer un count de los registros; basta con que haga un select * from
tabla y va a funcionar
|
[
"pt.meta.stackoverflow",
"0000002263.txt"
] | Q:
Não é preferível "Alô, Mundo" do que o "Olá, Mundo" que aparece nos anúncios do site em Português?
Ainda não tenho reputação para enviar uma pergunta para o Meta, que é onde acho que esta pergunta deveria estar, mas desde a primeira vez que vi o "Olá, Mundo." eu achei estranho.
Talvez esta seja a forma usada em Portugal, e então nesse caso o site poderia ter dois anúncios diferentes conforme a região.
A:
Porque isto seria um problema?
Isto vem do famoso programa inicial que alguém faz quando vai iniciar em alguma tecnologia. Ele é chamado originalmente "Hello World" e que foi consagrado em português como "Olá Mundo". Sim, existe versões como "Alô Mundo" mas a minha experiência de brasileiro é o uso do "Olá" na maioria dos exemplos.
O importante é que passou a mensagem. Se alguém não conseguir entender a mensagem, terá dificuldade para se comunicar com coisas mais complexas que vão aparecer no site.
"Alo Mundo" não seria bom também já que tem um erro ortográfico.
|
[
"stackoverflow",
"0030452208.txt"
] | Q:
Removing "Loading..." from PFQueryTableViewController
After upgrading my Parse Library for iOS (obj-c) to v. 1.7.1 I got rid off the old activityIndicator that showed up every time the tableview was initializing. INSTEAD I now got a black text in the center (x,y) of the tableview and I cannot remove it. The text says "Loading...".
Does someone now a trick like this in the old version?
A:
Just for others in the same situation
In parse's SDK v1.7.5 the "loading..." is customizable via the storyboard. Just click on the PFQueryTableViewController and set the "Loading view.." in the Attributes Inspector.
|
[
"stackoverflow",
"0007570969.txt"
] | Q:
Getting the most played track out of the iPod library (MPMediaQuery)
I need to get out the 25 most Played Songs out from my iPod Library with my iPhone app. i am using a MPMediaQuery.
One solutions would be to loop through all tracks and them comparing by MPMediaItemPropertyAlbumTrackCount. But i think thats a bit unefficient. Is there a way to directly get the Most Played items playlist?
A:
I think you are looking for MPMediaItemPropertyPlayCount not MPMediaItemPropertyAlbumTrackCount. MPMediaItemPropertyAlbumTrackCount is the track number of the song as it appears in its album.
MPMediaItemPropertyPlayCount unfortunately cannot be used for making queries with MPMediaQuery since it is a user-defined property.
Your best option is to store all the play counts in a database like Core Data when your app is opened for the first time and update it by registering for notifications when the user's library changes.
|
[
"magento.stackexchange",
"0000074634.txt"
] | Q:
Dashboard chart - show last seven days by default
Magento admin dashboard chart shows last 24 hours stats by default.
How to show last 7 days by default instead?
Is this possible without overriding core files?
A:
You need to rewrite the method Mage_Adminhtml_Block_Dashboard_Graph::_prepareData.
by default it looks like this:
protected function _prepareData()
{
$availablePeriods = array_keys($this->helper('adminhtml/dashboard_data')->getDatePeriods());
$period = $this->getRequest()->getParam('period');
$this->getDataHelper()->setParam('period',
($period && in_array($period, $availablePeriods)) ? $period : '24h'
);
}
You need to replace 24h with 7d.
|
[
"stackoverflow",
"0024677275.txt"
] | Q:
Need help fixing top bar inside another div with scroll
everybody! I'm trying to create a template as shown in the image below.
I will explain you what it does:
The left and right menus will toggle between 150 and 50 px (I've already made this part of the script using jQuery). When the toggle script runs from 150 to 50, the content of the page will expand (already done that too).
The side menus have "fixed position" written on them in the pictures, but I won't need this anymore because I will use overflow-y: scroll on the content instead of page scroll.
What I don't know how to do: I really can't get that top bar to be fixed and expand the same time content expands.
Image
Here is what I've done 'till now:
Fiddle
CSS:
*{
margin: 0px;
padding: 0px;
}
body, html{
height: 100%;
}
#container {
display: table;
width: 100%;
height: 100%;
}
#left, #middle, #right {
display: table-cell;
height: 100px;
}
#left, #right {
width: 150px;
background: #1f1f1f;
height: 100%;
color: white;
}
#middle {
background: white;
}
A:
you could use position fixed for your top bar:
Html
<div id="top">top bar</div>
Css
#top {position:fixed; background:lightblue; top:0; left:150px; right:150px; }
jQuery
var top = $('#top');
$('#middle').css('padding-top', top.outerHeight());
$('#left').click(function(){
width = $(this).width();
if(width == 150){
$(this).css('width', 50);
top.css('left', 50);
} else {
$(this).css('width', 150);
top.css('left', 150);
}
});
$('#right').click(function(){
width = $(this).width();
if(width == 150){
$(this).css('width', 50);
top.css('right', 50);
} else {
$(this).css('width', 150);
top.css('right', 150);
}
});
Example
|
[
"math.stackexchange",
"0000592133.txt"
] | Q:
Aid solving logical puzzle
I have a logical puzzle here that I need to solve. I'm not after just the answer of this puzzle, but also the reasoning and thought-process behind solving it. Any assistance is greatly appreciated.
What number between 1 and 7 do the following equal? A=, B=, C=, D=, E=, F=, G=
Given that:
1. A ≠ 2
2. A + B = F
3. C – D = G
4. D + E = 2F
5. E + G = F
The rules are:
1. All the variables (A, B, C, D, E, F, G) are equal to integer values between 1 and 7
2. None of the variables (A, B, C, D, E, F, G) are equal to each other i.e. all seven values will be used, no repeat use of integers
A:
Notice that if you have positive numbers, the relation $x+y=z$ implies $x<z$ and $y<z$. So properties 2., 3., 5. give $A<F$, $B<F$, $D<C$, $G<C$, $E<F$, $G<F$.
Moreover since $D+E = 2F$ and $E<F$ you get $F<D$.
So $A,B,E,G < F < D < C$ which means that $F = 5, D = 6, C = 7$.
Then from 4. $E=4$, from 3. $G=1$ from 1. $A=3$, $B=2$.
|
[
"stackoverflow",
"0061081512.txt"
] | Q:
Concatenating string and int in printf - C
I have the following code:
#define ERROR_MSG "Error: there was an error "
#define IN_LINE_MSG "in line"
int line = 0;
how can I concatenate those 3 using printf so I will get the following printed:
"Error: there was an error in line 0"
A:
Take a look at format specifiers for printf
This should be it: printf("%s%s %d", ERROR_MSG, IN_LINE_MSG, line)
Here, %s stands for string and %d stands for a digit. Then those three arguments after the string are passed in to take the place of those specifiers, in order.
|
[
"stackoverflow",
"0026772158.txt"
] | Q:
Unable to load ArrayList data to spinner in android
I am parsing data from server using json. Then storing them in Arraylist and loading them in to spinner in android. But I am getting same value for all the spinner data. For example I am geting json data as following:
[{"pricing":"500,600,700,800,900,1000"}]
Now I am comma seperating them and adding them in arraylist like this :
List<String> items = Arrays.asList(Pricing.split(","));
for(int j=0;j<items.size();j++)
{
r.add(items.get(i));
}
Then loading this arraylist in spinner.
Here's my full code:
try
{
json = new JSONArray(data);
for (int i = 0; i < json.length(); i++)
{
JSONObject obj = json.getJSONObject(i);
String Pricing = obj.getString("pricing");
List<String> items = Arrays.asList(Pricing.split(","));
List<String> r = new ArrayList<String>();
for(int j=0;j<items.size();j++)
{
r.add(items.get(i));
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
ArrayAdapter cd = new ArrayAdapter(this,android.R.layout.simple_spinner_item,r);
cd.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin2.setAdapter(cd);
}
But spinner has 500 500 500 500 500 500 instead of 500 600 700 800 900 1000.
Anything wrong I'm doing in this code..?? I'm new to android. Please suggest me solution.
A:
Try this way,hope this will help you to solve your problem.
You are using wrong index variable (i) which is for outer loop but your data accessing using inner loop so just replace (i) index variable with (j) index variable.
r.add(items.get(i));
Replace
r.add(items.get(j));
|
[
"stackoverflow",
"0042368594.txt"
] | Q:
Why did crawling errors regarding App Indexing increase instantly?
we experienced an instant app indexing error increase from 0 to more than 100k. We cannot explain the spontaneous increase of errors especially cause each error refers to the HTTP schema of deep links that we do not support at all.
We have established a custom schema which is successfully online since years now. Strange thing is also that despite the error reports, the search traffic seems to be okay. It has not dropped since, what we would have expected if there is a real problem.
What is even more confusing is that the deep links generated by the SearchConsoles help page are faulty. Regardless that they are generated with the HTTP schema the generated ADB command is correct but the generated intent URL for browsers is defininetly wrong.
See this example for the site
http://www.finanzen.net/Kursziele/CEWE_Stiftung:
SearchConsole Help: intent://<OURPACKAGE>/http/www.finanzen.net/Kursziele/CEWE_Stiftung#Intent;scheme=android-app;package=undefined;end
Firebase TestConsole Help: intent://www.finanzen.net/Kursziele/CEWE_Stiftung#Intent;scheme=http;package=<OURPACKAGE>;end
So for the moment we suspect an update of SearchConsole to be responsible for this behaviour. If not we are completely puzzled.
Anyone else experiencing this?
A:
I was seeing similar error reporting anomalies and reached out. I've heard from the App Indexing support team that this is a known issue and they are working on it. No ETA yet.
Copy of email from App Indexing support
|
[
"security.stackexchange",
"0000227478.txt"
] | Q:
Can I pre-register an SSL certificate with validity in the near future?
Can I register an SSL certificate that will only start to be valid in the near future and not right away?
A:
Ordinarily, the validity of period of the certificate is not determined by the requestor, and is not specified in the CSR. The validity period is determined by the CA (most CA's offer various durations according to price). So, you would have to find a CA that has a mechanism in place for what you are trying to do.
See CSR expiry date / validity date for more info.
|
[
"math.stackexchange",
"0001360753.txt"
] | Q:
If $A$, $B$ are $3\times 3$ matrices, and all elements are different from each other and greater in their absolute value than 3, then is $AB \ne 0$?
Let $A$ and $B$ be two $3\times 3$ matrices. All entries of $A$ are distinct and all entries of $B$ are distinct. All entries in both matrices are greater in their absolute value than 3. Then $AB \ne 0$.
Is this true or false, and why?
A:
$$\begin{pmatrix} 4 & 8 & 12 \\ 5 & 10 & 15 \\ 7 & 14 & 21 \end{pmatrix}
\begin{pmatrix} -28 & -35 & -49 \\ 8 & 10 & 14 \\ 4 & 5 & 7 \end{pmatrix}
=
\begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix}$$
The idea was to start with
$$\begin{pmatrix} 1 & 2 & 3 \\ 1 & 2 & 3 \\ 1 & 2 & 3 \end{pmatrix}
\begin{pmatrix} -7 & -7 & -7 \\ 2 & 2 & 2 \\ 1 & 1 & 1 \end{pmatrix} $$
and then experiment multiplying rows and columns respectively by constants until the elements in each respective matrix is distinct. You can read of those constants from the first column and last row: $4, 5, 7$.
|
[
"stackoverflow",
"0038526618.txt"
] | Q:
Signaling mechanism for one thread waiting on several
I'm designing a system where a pool of workers pop jobs out of a queue, and I want the main thread to wait for all that to be done. This is what I've come up with so far (pseudocode):
// Main
launch_signal();
for (auto &worker : pool) {
// create unique_lock
if (!worker.done)
worker.condition_variable.wait(lock, worker.done);
}
// Worker
if (queue.empty()) {
mutex.lock();
this->done = true;
mutex.unlock();
this->condition_variable.notify_one();
// wait for launch signal from Main
} else {
mutex.lock();
auto job = queue.pop();
mutex.unlock();
job.execute();
}
So Main signals that jobs are available, then waits for every worker to signal back. Worker meanwhile keeps popping jobs off the queue until empty, then signals done and goes into waiting for launch signal.
My question: What is a more efficient algorithm for doing this?
A:
The existing code appears to access queue.empty() without holding a mutex lock. Unless the queue object itself is thread-safe, (or at least the queue.empty() method is explicitly documented as being thread-safe), this will be undefined behavior.
So the first improvement would be to fix this likely bug.
Otherwise, this is a fairly stock, battle-tested, implementation of a worker pool. There's not much room for improvement here.
The only suggestion I can make is that if the number of worker threads is N, and after locking the mutex a thread finds that there are J jobs in the queue, the thread could remove J/N jobs (with the result of the division being at least 1) from the queue at once, and then do them in the sequence, on the assumptions that all other threads will do the same, and jobs take about the same amount of time to be done, on average. This will minimize lock contention.
|
[
"math.stackexchange",
"0000078773.txt"
] | Q:
Image of a function on a surface
Let $C$ be the cylinder $x^2+y^2=1$, let $f\colon C \rightarrow\mathbb R^3$ be the function $f(x,y,z) = (x\cos z, y\cos z,\sin z)$.
Prove that the image of $f$ is precisely the unit sphere $S^2$.
A:
FIRST PART: showing that the image of $C$ under $f$ is a subset of $S^2$:
$(x\cos(z))^2+(y\cos(z))^2+(\sin(z))^2=x^2 \cos^2(z)+ y^2\cos^2(z) + \sin^2(z)= $
$=\cos^2(z)(x^2+y^2)+\sin^2(z) = ... = 1 $ because $x^2 + y^2 = 1 $ since we're on the cylinder. That is, the image points lie on $S^2$.
SECOND PART: I leave this to you. You have to show that every point of $S^2$ is an image point.
|
[
"stackoverflow",
"0044577583.txt"
] | Q:
Py2exe - Can't run a .exe created on Windows 10 with a Windows 7 computer
I created a .exe file using Py2exe on Windows 10 but when I try to run it on a Windows 7 computer it says that the os version is wrong.
Can anyone tell me how to fix this? (like using another Python or Py2exe version or setting a specific configuration inside setup.py)
A:
I solved the problem myself and I'm going to share the answer if someone ever has the same mistake. I just had to download a 32-bit version of Canopy (with Python 2.7) and py2exe in order for them to work on Windows 7.
|
[
"mathoverflow",
"0000159071.txt"
] | Q:
Forms of algebraic varieties
Let $X$ be an algebraic variety (say, projective, irreducible and smooth), defined over a field $K$, and let $L$ be a Galois extension. I am interested in algebraic varieties $Y$, defined over $K$, such that there exists an isomorphism $\psi\colon X_L\to Y_L$ defined over $L$ (but not over $K$ in general).
The map $\psi$ induces a 1-co cycle from $Gal(L/K)$ to the group $Aut(X_L) $ of $L$-automorphisms, and it is easy to check that the image in $H^1 (Gal, Aut(X_L))$ only depends on the class of $Y$, up to $K$-isomorphisms. My question is the following: is every element of $H^1$ obtained? In other words, we have a map from the set of $L$-forms of $X$ to $H^1 (..)$, the map is injective but is it surjective?
If no, could it be true in some natural cases, if yes I would be happy to see a reference.
A:
CW answer, copied from the comments of Timo Keller and abx:
See J.P. Serre's “Galois Cohomology”, Chapter III, 1.3, Proposition 5.
A:
In case you are interested in seeing a situation where the map is not surjective, consider the set of rational maps of degree $f:\mathbb{P}^1\to\mathbb{P}^1$, modulo the conjugation action of $\phi\in\text{PGL}_2$, i.e., $f^\phi=\phi\circ f\circ\phi^{-1}$. This is the natural action if one is interested in dynamics (iteration of the map $f$). The automorphism group of $f$ is $\text{Aut}(f)=\{\phi\in\text{PGL}_2:f^\phi=f\}$. Two maps $f_1$ and $f_2$ defined over $K$ are isomorphic over $\bar K$ if $f_1=f_2^\phi$ for some $\phi\in\text{PGL}_2(\bar K)$, and the set of twists of $f$ is the set of maps that are $\bar K$-isomorphic to $f$, modulo $K$-isomorphism. Just as in the case you're looking at, the set of twists injects into the cohomology group $H^1(G_{\bar K/K},\text{Aut}(f))$. But the image is not surjective. The image turns out to be exactly the elements of $H^1(G_{\bar K/K},\text{Aut}(f))$ that become trivial in $H^1(G_{\bar K/K},\text{PGL}_2(\bar K))$. You can read about this in the following places:
The Arithmetic of Dynamical Systems, Springer, Section 4.9, specifically Theorem 4.79.
The Field of Definition for Dynamical Systems, Compositio Math. 98 (1995), 269-304.
|
[
"stackoverflow",
"0035123818.txt"
] | Q:
Softlayer API : How to get list of active usage prices of object storage?
How can I get all active usage prices in control UI?
Using the api below, I only get the prices of object storage.
To get the prices of object storage bandwidth and cdn bandwidth, what should I do more?
Service service = Package.service(client, 206);
service.withMask().categories();
service.withMask().categories().groups().prices().item().activeUsagePrices();
service.getObject();
Softlayer UI
A:
Try this method:
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getObjectStorageDatacenters
here a rest example:
URL: https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/206/getObjectStorageDatacenters
Method: Get
Regards
|
[
"askubuntu",
"0000792167.txt"
] | Q:
Usage of Ubuntu in Iran
Does anyone know about the legal usage of Ubuntu in US-embargoed countries like Iran? I have tried looking in the Ubuntu site but was not able to find such information.
Thanks.
A:
According to the Free Software Foundation's definition
Freedom to distribute means you are free to redistribute copies,
either with or without modifications, either gratis or charging a fee
for distribution, to anyone anywhere. Being free to do these
things means (among other things) that you do not have to ask or pay
for permission to do so.
but
Sometimes government export control regulations and trade sanctions
can constrain your freedom to distribute copies of programs
internationally.
Canonical is a UK company so subject to UK export law. Fortunately, UK export restrictions exclude 'information that is freely and legally available on public website[s]'
Here's an extract from the UK government page on Export of Technology
What does ‘in the public domain’ mean?
In the public domain means the information is made available without
any restrictions, other than copyright, being placed on further
dissemination. For instance, information you place on your website
that anyone can download or that you publish in a sales brochure would
be ‘in the public domain’.
This means the exporter doesn't need a license, but more widely, software defined as 'in the public domain' isn't subject to any export restrictions. (I found the same definition and exclusion in documents on restrictions relating to military technology)
Since anyone can download and use Ubuntu, it is 'in the public domain' as defined by the export restrictions
Canonical have a LoCo team in Iran, a Persian translation team (thanks Gunnar for pointing out) and an official Ubuntu.ir site (and one of the main sections is Download Ubuntu)
Here's my favourite quote from the Export of Technology legal page:
Do I require an export licence for information which is in my head?
No.
Long live free software ;)
|
[
"stackoverflow",
"0029735722.txt"
] | Q:
Idiom in magrittr for x <- x %>%
With magrittr (or dplyr), I find myself using the following pattern quite often:
x <- x %>%
fun %>%
fun
Is there a commonly used shortcut or idiom for that? by which I mean, an operand, e.g. %^>%, with which one could write:
x %^>% fun ...
A:
I think you want %<>%. You have to explicitly load magrittr though, at least I do. Check out the reference manual on cran (page 7).
|
[
"english.stackexchange",
"0000242754.txt"
] | Q:
Is the statement ending with "for" considered proper?
What would be a better and more formal way out of the two below:
The capability was not catered for.
or
We did not cater for this capability.
Or perhaps these are fully interchangeable?
A:
Contrary to popular thought, ending a sentence with a preposition is not verboten. Here is a wonderful (and short) video discussing the issue: https://www.youtube.com/watch?v=9OLxLK_R6jQ.
However, I would never suggest the use of the preposition "for" with the verb "cater". My suggested fix:
We did not provide for this capability.
"This capability was not provided for." While correct, this is unnecessarily passive in construction anyway.
|
[
"stackoverflow",
"0010088975.txt"
] | Q:
Display dynamic editors in JSF with ui:include
I want to display a group of editors in a tabview. Each editor has a property called component, that stores the rendered editor. Simple editors use HTML tags to render the editor, whereas complex ones use editors defined in another pages. I have found out that I cannot use editor.component with ui:include because the value is not available when the tree is build. How can I solve this issue? Are there any alternatives to ui:include that don't have this limitation?.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:panelGroup>
<p:tabView value="#{groupsBean.groups}" var="group">
<p:tab title="#{group.name}">
<h:panelGroup>
<p:dataTable value="#{group.editors}" var="editor">
<p:column headerText="Key">
<h:outputText value="#{editor.name}" />
</p:column>
<p:column headerText="Value">
<h:panelGroup rendered="#{not editor.href}">
<h:outputText value="#{editor.component}" escape="false" />
</h:panelGroup>
<h:panelGroup rendered="#{editor.href}">
<ui:include src="#{editor.component}" />
</h:panelGroup>
</p:column>
</p:dataTable>
</h:panelGroup>
</p:tab>
</p:tabView>
</h:panelGroup>
EDIT 1
web.xml contains these entries:
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/springsecurity.taglib.xml; /WEB-INF/custom.taglib.xml</param-value>
</context-param>
custom.taglib.xml is inside WEB-INF folder.
<facelet-taglib>
<namespace>http://www.custom.ro/</namespace>
<tag>
<tag-name>dynamic</tag-name>
<component>
<component-type>ro.custom.DynamicInclude</component-type>
</component>
</tag>
</facelet-taglib>
DynamicInclude is annotated with @FacesComponent("ro.custom.DynamicInclude")
In groups.xhtml I have added the namespace for dynamic include - xmlns:custom="http://www.custom.ro/".
EDIT2
Finally I have managed to make it work. The missing thing was the entry for handler-class(com.corejsf.tag.DynamicIncludeHandler). I have also removed the lines that tested the src for null in getSrc method of DynamicInclude.
A:
As far as I know there is no such component alternative to ui:include. We have implemented such thing ourselves using FaceletContext.includeFacelet api.
A fairly simple alternative would be to render table using c:forEach loop - no need to code an extra component yourself. The drawback is you will get a component for each row which might be resource heavy in some cases.
|
[
"stackoverflow",
"0030482151.txt"
] | Q:
convert a SOAP C# client to PHP
Good day all.
I'm converting a C# Soap client in PHP, with many troubles.
I don't know C# but the syntax is quite legible, so I don't have many problems, until now.
these are the lines I can't understand:
My_Arx_Search.Field_String campo = ((My_Arx_Search.Field_String)aggSearch);
campo.Operatore = My_Arx_Search.Dm_Base_Search_Operatore_String.Uguale;
campo.Valore = "DFLMHLD15GGFD...";
What I actually know is:
My_Arx_Search is (I suppose) an instance of the xml of the wsdl (there is a file called the same, which is exactly that).
how I can manage these 2 lines in php? anyone can help me in that?
thanks in advance.
A:
My_Arx_Search.Field_String campo = ((My_Arx_Search.Field_String)aggSearch);
This creates a variable "campo" of type "My_Arx_Search.Field_String", and as value, converts the variable "aggSearch" to this type.
campo.Operatore = My_Arx_Search.Dm_Base_Search_Operatore_String.Uguale;
This assigns the value on the right to the "Operatore" field of the "campo" variable. I assume it's either a static field, or an enum.
campo.Valore = "DFLMHLD15GGFD...";
This assignes the value "DFL..." to the "Valore" field of the "campo" variable.
Without the definition of the "My_Arx_Search.Field_String" class I can't help you more.
|
[
"stackoverflow",
"0002426920.txt"
] | Q:
Dealing with expired authentication for a partially filled form?
I have a large webform, and would like to prompt the user to login if their session expires, or have them login when they submit the form. It seems that having them login when they submit the form creates alot of challenges because they get redirected to the login page and then the postback data for the original form submission is lost.
So I'm thinking about how to prompt them to login asynchrounsly when the session expires. So that they stay on the original form page, have a panel appear telling them the session has expired and they need to login, it submits the login asynchronously, the login panel disapears, and the user is still on the original partially filled form and can submit it. Is this easily doable using the existing ASP.NET Membership controls? When they submit the form will I need to worry about the session key? I mean, I am wondering if the session key the form submits will be the original one from before the session expired which won't match the new one generated after logging in again asynchrounously(I still do not understand the details of how ASP.NET tracks authentication/session IDs).
Edit: Yes I am actually concerned about authentication expiration. The user must be authenticated for the submitted data to be considered valid.
A:
Very nice response @Mark Brackett reading the OP's comment below I believe this is his end goal.
On the button / submit element you want to write a javascript method that via ajax will poll the server to see if they are still authenticated.
If they are auth'd still you want to return true and let the form do it's regular submission, if it returns false you want to not allow the form to submit. At this point you will want to use javascript to display either a "window" inside the browser (think floating div) or to pop up a true new window for them to log in (I'd recommend the first method) that this new window will allow them to login via ajax and then hide/close itself.
Then with that window gone when they click the submit button again they will be able to successfully post the form.
|
[
"stackoverflow",
"0028466546.txt"
] | Q:
How to optimize (fewer cyclings) a specific while loop in r
I'm trying to check if any value in the 1st column of a2 matches any value in the 1st column of m_. If there is, extract that row with that value from a2. Finally merge all the qualified rows together.
i=1
while(i<149473)
{j=1
while(j<10249){
if(as.integer(a2[i,1])==as.integer(m_[j,1])){
ob<-rbind(ob,a2[i,])
}
j=j+1}
i=i+1
}
return(ob)
It's so time consuming to get the result because the large amount of rows in the data frames..
Can anybody help me optimize the loop?
A:
Something as simple as
ob <- a2[a2[[1]] %in% unique(m[[1]]),]
|
[
"stackoverflow",
"0033519857.txt"
] | Q:
issue with $_POST and mysql query
I have a MySQL DB from where i next to extract data based on user search.
I have no problem displaying the post variable like this :
<?php
if (isset($_POST)) {
$name = htmlspecialchars($_POST['name']);
echo "Results - " . $name ."\n";
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$conn->close();
?>
The error -
Parse error: syntax error, unexpected end of file.
As soon as I add a MySQL connection, without even any query to be done, I get a parse error. Why is that ?
I have tried adding a specific query as I need the results displayed.
I have also tried using a different from of submitting, still no luck, getting same parse error.
A:
I think you have a syntax error.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} <--- u have missed this
$conn->close();
Final code
<?php
if (isset($_POST)) {
$name = htmlspecialchars($_POST['name']);
echo "Results - " . $name ."\n";
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} <------- this is missing in your code.
$conn->close();
?>
|
[
"unix.stackexchange",
"0000119612.txt"
] | Q:
Executing bash shell scripts
I am reading an article on executing bash shell scripts.
Method 1: Create a directory for your shell scripts and add the directory to the contents of the PATH variable, so that you can execute the script as shown below. When this executes, the variables, functions and aliases created in this subshell are only known to the particular bash session of that subshell. When that shell exits and the parent regains control, everything is cleaned up and all changes to the state of the shell made by the script, are forgotten.
$ hello_world.sh
Method 2: A script can also explicitly be executed by a given shell. The specified shell will start as a subshell of your current shell and execute the script.
$ sh script_name.sh
Method 3: If you don't want to start a new shell but execute the script in the current shell, you source it:
source script_name.sh
I really don't understand the benefits and disadvantages of each of these methods. Can anyone clarify?
A:
sh
This executes the program called hello_world.sh in the program search path (PATH). If that program happens to start with a shebang line, that line indicates that the program must be passed to an interpreter in order to be executed; otherwise the program must be loaded as native code. The shebang line is read by the kernel. For example, if the first line of hello_world.sh is #!/bin/sh, then the kernel launches /bin/sh and passes it hello_world.sh as an argument.
If hello_world.sh neither begins with a shebang nor is valid native code, then the kernel will return an error when you try to execute it. If you're doing that from a shell, the shell will notice the error and try to execute hello_world.sh as a shell script (like the second form below).
sh script_name.sh
This runs the program called sh found in the PATH, with script_name.sh passed as an argument. The program sh, assuming that it's the usual shell, will open the file called script_name.sh in the current directory and interpret it. If the script starts with a shebang line, it's ignored. The script doesn't need to be executable.
. script_name.sh
source script_name.sh
When you execute this in a shell, either of these instructions tells the running shell to interpret the commands in the specified file. The script isn't executed as a separate program, but as part of the existing shell process. Thus the script can affect the current directory, the environment, … of the running shell. The builtin commands . and source are synonymous, except that . only searches script_name.sh in the PATH whereas in some shells source also looks in the current directory.
|
[
"stackoverflow",
"0009895498.txt"
] | Q:
duplicate declaration of method dismissviewdidfinish
Have two actionsheet buttons and one modalviewcontroller on mainviewcontroller in application. Now for two actionsheet buttons and for modalviewcontroller, can i have multiple dismissviewdidfinish method for each
-(void)dismissViewDidFinish:(ModalViewController *)controller
{
[self dismissModalViewControllerAnimated:YES];
}
-(void)dismissViewDidFinish:(Devanagari *)controller1;
{
[self dismissViewControllerAnimated:completion];
}
-(void)dismissViewDidFinish:(English *)controller2;
{
[self dismissViewControllerAnimated:YES];
}
Cause if i add these three methods on mainviewcontroller i get red warning message duplicate declaration of method dismissviewdidfinish.
Any ideas how to solve this kind of situation.
A:
You cannot have the same name for more than 1 method. Use a single dismissViewDidFinish:(UIViewController *)viewController method and then check to see which viewController finished:
- (void)dismissViewDidFinish:(UIViewController *)viewController {
//check to see what kind of class viewController is
//or use tags by setting the viewcontroller.view.tag when creating it
}
|
[
"math.stackexchange",
"0000154042.txt"
] | Q:
A proposition on a Dedekind domain
I need a proof of the following proposition(?).
Actually I think I came up with a proof.
But it's nice to confirm it and/or to know other proofs.
Thanks.
Proposition
Let $A$ be a Dedekind domain.
Let $I$ and $J$ be non-zero ideals of $A$.
Then there exist non-zero $\alpha \in I$ and an ideal $M$ such that $(\alpha) = IM, M + J = A$.
EDIT
Here's my proof.
Let $I = (P_1)^{e_1}...(P_n)^{e_n}$ be the prime decomposition of I.
Let $Q_1, ..., Q_m$ be all the prime ideals which divide $J$, but not divide $I$.
By the proposition and with its notation, there exists $\alpha \in A$ such that
$v_{P_i}(\alpha) = e_i, i = 1, ..., n$.
$v_{Q_j}(\alpha) = 0, j = 1, ..., m$.
Since $\alpha \in I$, there exists an ideal $M$ such that $(\alpha) = IM$.
Clearly $M + J = A$
A:
I think you are right. The essential point is the weak approximation theorem which you cite as the proposition. The weak approximation theorem is in turn essentially Chinese remainder theorem.
|
[
"stackoverflow",
"0044632486.txt"
] | Q:
Marklogic - What is the best way to loop throught 10 thousand documents if you know id
I have a list more than ten thousand ids need to retrieve XML data if they are matched. What is a best solution to approach this. I think my code is not the right way to loop through a $listKeyID. Please help. Thanks in advance.
let $listKeyID := ("accid01","accid02",......"accid100000") (: a huge list :)
let $uris := cts:uris((),
(),
cts:and-query((
cts:collection-query("/collection/TRIS"),
cts:or-query((
cts:field-word-query("key",($listKeyID))
))
))
)
)
return fn:count($uris)
A:
Actually, there is not that much wrong with this approach. cts:field-word-query accepts a sequence as second argument, and will return positive for any match within that sequence. We also refer to that as a shotgun-OR query, and it is pretty efficient.
You don't really need the extra cts:or-query around it though, and you might want to use a cts:field-value-query instead, which matches the entire key value, instead of mid-sentence tokens, depending on your use case.
let $listKeyIDs := (accid01,accid02,......accid100000) (: a huge list :)
let $uris := cts:uris(
(),
(),
cts:and-query((
cts:collection-query("/collection/TRIS"),
cts:field-value-query("key", $listKeyIDs)
))
)
return fn:count($uris)
HTH!
|
[
"gaming.meta.stackexchange",
"0000002437.txt"
] | Q:
Tag synonym request: [mtg-dotp-2012] and [magic-2012]
So Wizards of the Coast, not satisfied with having a really long company name, has taken to making video games with excessively long names, too. Last year, they released Magic: The Gathering: Duels of the Planeswalkers and mtg-duels-of-planeswalker was created as a way to fit most of the title into the 25-character tag limit.
Not to be outdone, they released a follow-up this year, Magic: The Gathering: Duels of the Planeswalkers 2012, a functionally different game that really does need a separate tag. Unfortunately, duels-of-planeswalker is 25 characters, so the "2012" can't be tacked on.
I asked a question about it a few days ago, and the tag mtg-dotp-2012 was created as a way to distinguish it from the earlier game, with the justification that "DotP" is sometimes used to refer to the series.
But the plot thickens: in trophy lists and in reviews, Magic 2012 is used to shorten the name of the game, and quick Google searches seem to indicate it has some good SEO (especially since Wizards of the Coast is also releasing the Magic 2012 core set for the physical card game at the same time).
So I humbly request we use magic-2012 and make mtg-dotp-2012 a synonym of it.
P.S. There's also a case to be made that duels-2012 should be a synonym too: WotC has used that shortened form in its FAQ for the game for example. But "Duels" is such a generic name, and I doubt many people would search for the game using it.
A:
Let's just hope that with the i18n efforts caused by German and Japanese, the tagging system will relax a little bit. :/
|
[
"tex.stackexchange",
"0000203057.txt"
] | Q:
Getting non-sense edges in my tree, or, how to get labels on edges
I have the following code. If I remove the edge commands, everything is fine. I suppose the problem is that my nodes have the same contents, but I can't avoid this obviously.
Bad code:
\documentclass[tikz,margin=10pt]{standalone}
\usetikzlibrary{positioning,shapes,arrows}
\begin{document}
\tikzset{
treenode/.style = {align=center, inner sep=0pt, text centered,
font=\sffamily},
}
\begin{tikzpicture}[->,>=stealth',level/.style={sibling distance = 5cm/#1, level distance = 1.5cm}]
\node (n) { 0 }
child { node (n0) { 0 }
edge from parent node[left] { 0 }
child { node (n00) { 0 }
edge from parent node[left] { 0 }
}
child { node (n01) { 1 }
edge from parent node[left] { 1 }
}
}
child { node (n1) { 1 }
edge from parent node[left] { 1 }
child { node (n10) { 0 }
edge from parent node[left] { 0 }
}
child { node (n11) { 1 }
edge from parent node[left] { 1 }
}
}
;
\end{tikzpicture}
\end{document}
\end{document}
Good code (but without labels):
\documentclass[tikz,margin=10pt]{standalone}
\usetikzlibrary{positioning,shapes,arrows}
\begin{document}
\tikzset{
treenode/.style = {align=center, inner sep=0pt, text centered,
font=\sffamily},
}
\begin{tikzpicture}[->,>=stealth',level/.style={sibling distance = 5cm/#1, level distance = 1.5cm}]
\node (n) { 0 }
child { node (n0) { 0 }
child { node (n00) { 0 }
}
child { node (n01) { 1 }
}
}
child { node (n1) { 1 }
child { node (n10) { 0 }
}
child { node (n11) { 1 }
}
}
;
\end{tikzpicture}
\end{document}
\end{document}
A:
Have a look at the following code. You have to position your edges at the right position and it will work. You have to paste the edge after all child nodes. If you insert it before it creates (i assume so) a new node which is taken as root node for all following childs.
If you try to add additional child in your code to your lowest nodes you'll see the issue.
\documentclass[tikz,margin=5mm]{standalone}
\begin{document}
\begin{tikzpicture}[->, %
>=stealth, %
level distance=1.5cm, %
level 1/.style={sibling distance=2.5cm}, %
level 2/.style={sibling distance=1.5cm}]
\node (n) {0}
child { node (n0) {0} {
child { node (n00) {0} edge from parent node [left] {0} }
child { node (n01) {1} edge from parent node [left] {1} }
} edge from parent node [left] {0}
}
child { node (n1) {1} {
child { node (n10) {0} edge from parent node [left] {0} }
child { node (n11) {1} edge from parent node [left] {1} }
} edge from parent node [left] {1}
}
;
\end{tikzpicture}
\end{document}
Rendered image:
|
[
"stackoverflow",
"0035372616.txt"
] | Q:
Can I use wildcard character * in JSF navigation rule?
Is there any way in JSF page navigation to create a joker rule? I have a logout link in my template header (almost for all pages). And I want to give just one rule which navigate all the pages inside the secure folder to the index page in the root.
<navigation-rule>
<from-view-id>/secure/*.xhtml</from-view-id>
<navigation-case>
<from-outcome>index</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
I tried this, but the parser said it had not found a rule from /secure/pagex.xhtml to /index.xhtml. Is this true? I have to give a rule for all of my pages one by one?
A:
The wildcard is only allowed as suffix (as the last character).
<navigation-rule>
<from-view-id>/secure/*</from-view-id>
<navigation-case>
<from-outcome>index</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
The <from-view-id> is however optional. You could also just remove it.
<navigation-rule>
<navigation-case>
<from-outcome>index</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
Or, better, use implicit navigation, then you can remove the <navigation-rule> altogether.
E.g. GET
<h:button ... outcome="/index" />
<h:link ... outcome="/index" />
Or POST
public String logout() {
// ...
return "/index?faces-redirect=true";
}
JSF will automatically worry about extension and mapping.
See also:
JSF implicit vs. explicit navigation
|
[
"stackoverflow",
"0058396275.txt"
] | Q:
conditionally assign docvar()
I am using quanteda and want to conditionally assign docvars().
Consider the following MWE:
library(dplyr)
library(quanteda)
library(quanteda.corpora)
testcorp <- corpus(data_corpus_movies))
I now want to assign a dummy docvar neg_sent_lg_id2, which should be 1 for all documents where the Sentiment is neg and where the id2 is > 10000.
Importantly, I don't want to subset the corpus but I want to assign the docvar to a subset of the corpus and then retain the entire corpus.
I have used docvars(testcorp, field = "neg_sent_lg_id2") <- 0 to assign 0 to the docvars and would now like to do something like this - the following lines are pseudo r code and do not work but convey the idea.
corpus_subset(testcorp, Sentiment == "neg") %>% # filter on "Sentiment"
corpus_subset(testcorp, id2 > 10000) %>% # filter on "id2"
docvars(testcorp, field = "neg_sent_lg_id2") <- 1 # selectively assign docvar
A:
You can use ifelse for this:
library(dplyr)
library(quanteda)
library(quanteda.corpora)
testcorp <- corpus(data_corpus_movies)
docvars(testcorp, field = "neg_sent_lg_id2") <-
ifelse(docvars(testcorp, field = "Sentiment") == "neg" & docvars(testcorp, field = "id2") > 10000,
1, 0)
It's not a pretty syntax but it works:
head(docvars(testcorp))
#> Sentiment id1 id2 neg_sent_lg_id2
#> neg_cv000_29416 neg cv000 29416 1
#> neg_cv001_19502 neg cv001 19502 1
#> neg_cv002_17424 neg cv002 17424 1
#> neg_cv003_12683 neg cv003 12683 1
#> neg_cv004_12641 neg cv004 12641 1
#> neg_cv005_29357 neg cv005 29357 1
table(docvars(testcorp, field = "neg_sent_lg_id2"))
#>
#> 0 1
#> 1005 995
Created on 2019-10-15 by the reprex package (v0.3.0)
|
[
"stackoverflow",
"0044108805.txt"
] | Q:
Bean validation size of a List?
How can I set a bean validation constraint that a List should at minimum contain 1 and at maximum contain 10 elements?
None of the following works:
@Min(1)
@Max(10)
@Size(min=1, max=10)
private List<String> list;
A:
I created simple class:
public class Mock {
@Size(min=1, max=3)
private List<String> strings;
public List<String> getStrings() {
return strings;
}
public void set(List<String> strings) {
this.strings = strings;
}
}
And test:
Mock mock = new Mock();
mock.setStrings(Collections.emptyList());
final Set<ConstraintViolation<Mock>> violations1 = Validation.buildDefaultValidatorFactory().getValidator().validate(mock);
assertFalse(violations1.isEmpty());
mock.setStrings(Arrays.asList("A", "B", "C", "D"));
final Set<ConstraintViolation<Mock>> violations2 = Validation.buildDefaultValidatorFactory().getValidator().validate(mock);
assertFalse(violations2.isEmpty());
It seems that @Size annotation is working well. It comes from javax.validation.constraints.Size
A:
You can use @NotEmpty to check for empty list. This make sure there is at least one item in list.
|
[
"stackoverflow",
"0001025816.txt"
] | Q:
how to reload saved "Embed Source" clipboard data?
some other windows application I'm trying to interface with, saves a dump of the clipboard to file. To be more precise, it looks for the "Embed Source" format in the clipboard, and if found saves it to file. "Embed Source" is some OLE based format, which is created, for example, when you copy an image from paintbrush.
Is there a way to reload the content of those files back to the clipboard, so I could paste them back in say, paintbrush or any office program?
In c# I've tried
System.Windows.Forms.Clipboard.SetData("Embed Source", data);
where data is an array containing the file's bytes, but it seems to wrap it further, before placing the data on the clipboard.
Does someone know of a good way to do so (not necessarily in C#)?
Thanks,
r
A:
Solved, you need to pass Clipboard.SetData a stream object, and by doing so, it does not wrap the data within another format.
i.e.
System.IO.FileStream s = System.IO.File.Open("c:\\temp\\dxf.ole",System.IO.FileMode.Open);
Clipboard.SetData("Embed Source", s);
s.Close();
Yet, some metadata is lost, since paintbrush doesn't let you paste such reloaded data, but that's another question.
|
[
"stackoverflow",
"0024960345.txt"
] | Q:
How to generate a random number only once, and reuse its output?
I'm learning programming starting with Javascript, and my instructor had us doing a random dice roll, a simple Math.ceil(6*Math.random())
I was trying to slightly gameify it and judge the result. So, if you roll a 7, you win, any other roll you lose. The ultimate result would be,
"You rolled a: 7
You win!"
However, I attempt to accomplish by saying approximately:
console.log("You rolled a: " + diceSum);
if (dicesum() == 7) {
console.log("You win!");
} else {
console.log("Aw... you lose. Better luck next time");
}
diceSum() function evaluates each time, so I may get "You rolled a: 7" and "Aw... you lose" because the first roll was a 7, but by the time the if statement came in, the diceSum was something different.
How do I generate a random number like a dice roll and then reuse its value over and over?
Here's my current code (there is far more than necessary because I'm trying to display the values so I know if it is returning the correct answer):
//Functions
//Generate a random single roll of a dice
var getDieRoll = function() {
return Math.ceil(6*Math.random());
};
//Sum up two dice rolls
var diceSum = function() {
var firstDie = getDieRoll();
var secondDie = getDieRoll();
return firstDie+secondDie;
};
//
//Variables
//Check to see if total sum of the roll is 7
var winMsg = "Winner!"
var loseMsg = "Aw... you lose. Better luck next time."
//
//Outputs
//show total sum to compare with message below
console.log(diceSum())
//Return a message stating the result
console.log("You rolled a " + diceSum())
//View true false status to compare with message returned below
console.log(diceSum()==7)
//If diceSum is a 7, give winning message, otherwise give losing message
if (diceSum()==7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
A:
You put the result in a variable, and use the variable:
var sum = diceSum();
//Outputs
//show total sum to compare with message below
console.log(sum);
//Return a message stating the result
console.log("You rolled a " + sum)
//View true false status to compare with message returned below
console.log(sum == 7);
//If diceSum is a 7, give winning message, otherwise give losing message
if (sum == 7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
By the way, the way to calculate the random number is wrong. The random method is defined to return a value that is 0 <= n < 1, i.e. it can be zero, but it can never be one.
If you use Math.ceil, the effect is that the result will occasionally be zero, and the chance to get a six is slightly smaller than the other numbers.
Use Math.floor instead:
function getDieRoll() {
return Math.floor(6 * Math.random()) + 1;
};
|
[
"android.stackexchange",
"0000224236.txt"
] | Q:
Remove Samsung Tab S3 SetupWizard Message 'Activation Incomplete' for Verizon service
I just purchased a used Samsung Tab S3 which comes with Verizon network capabilities. I don't want to use cell capabilities, just Wifi.
After setup, on the lock screen and in the notification center is a message from "Setup Wizard" that says "Activation Incomplete" and to call Verizon support to activate the device (which I don't want to do).
Is there a way to remove this message without calling Verizon?
A:
Here's an incomplete solution, since the notification itself says "These notifications can't be turned off":
Touch and hold on the notification in the notifications dropdown
Tap "Details"
When "System UI" opens under "App notifications" in Settings, it will briefly flash the "Ongoing" section
Tap the "Ongoing" section
Tap "Notification Style"
Tap "Silent and minimized"
Tap "App icon badges" to turn the switch off
This makes the notification much smaller in the notification dropdown, and doesn't show the icon in the notification bar
This works as of 2020-04-24 13:20 CDT on Android 9
|
[
"stackoverflow",
"0007047399.txt"
] | Q:
Best practice security measures for an enterprise Rails app?
What security measures should a Rails enterprise app have?
Examples of few security measures:
Admin area authenticated and IP restricted
No User added CSS, because of some old browsers can run JavaScript in CSS
Should User information in database be encrypted?
A:
I would suggest looking over the Rails Security Guide which should go over the common pitfalls that you would usually encounter. Also check out the additional resources that they list on the guide:
The security landscape shifts and it is important to keep up to date,
because missing a new vulnerability can be catastrophic. You can find
additional resources about (Rails) security here:
The Ruby on Rails security project posts security news regularly:
http://www.rorsecurity.info
Subscribe to the Rails security mailing list
Keep up to date on the other application layers (they have a weekly
newsletter, too)
A good security blog including the Cross-Site scripting Cheat Sheet
|
[
"math.stackexchange",
"0002604717.txt"
] | Q:
Estimation of connected components
Let $Z(f):=f^{-1}(0)$, i.e., the preimage of zero and $f:A\subset\mathbb{R}^m\to \mathbb{R}$.
Claim: if the function $f$ is $C^1$-smooth and 0 is not a critical value, then we can bound
the number of connected components $\gamma$ of $Z(f)$ contained in $B_R$ (ball of radius R centered at 0) by the number of connected components $G$ of $U \backslash Z(f)$ compactly contained in $B_R$.
Indeed, all we need for that is to note that each $\gamma ⊂ B_R$ is the outer boundary of some $G$ compactly supported in $B_R$ and no two different connected components $\gamma ⊂ B_R$ of $Z(f)$ can serve as the outer boundary of the same connected component $G$ of $U\backslash Z(f)$. simultaneously.
Source: https://arxiv.org/abs/1507.02017 by Nazarov and Sodin
I understand the idea, but I don't see why and where the assumption of critical values is needed.
A:
The idea is the following:
If 0 is a critical value of f, then Z(f) might have singleton components.
|
[
"webmasters.stackexchange",
"0000105025.txt"
] | Q:
Sitemap update lastmod and ping. what is the advantage?
My website has 6milions pages of companies.
ex: www.mywebsite.com/company-a
I will generate one sitemap index file and put the url in robots.txt
When the company A update one information in your page(example: address), I will change the lastmod in sitemap file that contais the url www.mywebsite.com/company-a and I will change the lastmod for this sitemap in sitemap index file. After, I will send a ping for google to my sitemap index file url.
My question is: Is it really worth doing this? What would be the gain in relation to not doing this update and send ping?
A:
Google's John Mueller says:
Sure, feel free to ping us when you have new or updated content!
Many CMS (including WordPress) also have a Sitemap generator either built-in or available as a plugin / extension. Those Sitemap generators will often also ping Google when you have changed or added content, making it easy for us to crawl and index that content as soon as possible once it's up. Google won't be upset if you ping too frequently (but doing so without changes on your site doesn't make sense either), so ping away!
Which makes it sound like generating a sitemap of new content and pinging Google could spur Googlebot into action. However, Google has said they don't usually use lastmod. Google ignores it because most webmasters don't keep it up to date. Google: We Mostly Ignore The LastMod Tag In XML Sitemaps.
I've seen pinging Google work nicely for fresh content. You can ping Googlebot to come fetch the page quickly after publishing it. That prevents scraper sites from copying quickly and getting Google to see it on their site first. I haven't seen much evidence that pinging Google gets Googlebot to come back and index updated content more quickly.
|
[
"stackoverflow",
"0006631480.txt"
] | Q:
UIView being initialized with wrong orientation
Well, I have a view controller that will control all subviews for my app (I hope). When initWithNibName: is called, the first view is displayed fine. When I press a button in that view it calls - (IBAction)pause:(id)sender. In this I have self.view = pauseView, pauseView being a UIView defined with IBOutlet. When that UIView is displayed, it is displayed with Portrait Orientation, even though the resizing function in the view controller is defined correctly and the iphone simulator is rotated the right way (and also the orientation is portrait in Interface Builder). In other words, everything is sideways from the user's perspective. How do I fix this?
A:
The pause view isn't receiving rotation events from the view controller. Only its view property will receive those events. Put your pauseView as a subview to the main view, but set it to hidden. You'll need to do this in the XIB file, drag and drop the pauseView into the view and find the hidden property and set that to on.
Change your button to:
- (IBAction)pause:(id)sender {
[pauseView setHidden:NO];
}
|
[
"stackoverflow",
"0010554124.txt"
] | Q:
bitbake fails on "bitbake nano"
I am trying to setup bitbake and openembedded in order to cross-compile code for angstrom 2009.x on devkit8000 (a beagleboard's clone). I have followed this page but when I try
$ bitbake nano
I get
Loading cache: 100% |##############################################################################################################################################################################################| Time: 00:00:00
Loaded 1 entries from dependency cache.
ERROR: Error parsing /home/hnsl/stuff/openembedded/recipes/images/initramfs-kexecboot-image.bb: Could not inherit file classes/rootfs_${IMAGE_PKGTYPE}.bbclass | ETA: --:--:--
ERROR: Command execution failed: Exited with 1
A:
Apparently it seems that I need to change version of Angstrom. Using
"DISTRO="angstrom-2010.x"
on stuff/build/conf/local.conf resolves this issue.
|
[
"stackoverflow",
"0043535058.txt"
] | Q:
Restsharp - Convert XDocument to Object
I am using RestSharp to request that is a simple SOAP services automation project. I load xml via XDocument but, I can't use it in request.AddBody.
Error: An exception of type 'System.InvalidOperationException' occurred in RestSharpXML.dll but was not handled in user code
public class SOAPSharp
{
XDocument currencyXML = XDocument.Load(@"../../Data/currencyXML.xml");
[Test]
public void xmlRequest() {
try
{
var client = new RestClient();
var request = new RestRequest("http://www.webservicex.net/periodictable.asmx?WSDL", Method.POST);
request.XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer();
request.RequestFormat = DataFormat.Xml;
request.AddHeader("Content-Type", "application/xml; charset=utf-8");
// request.AddBody(ParameterType.RequestBody);
request.AddBody(currencyXML);
var response = client.Execute(request);
}
catch (Exception)
{
throw;
}
}
}
A:
Your problem is that XDocument does not implement IXmlSerializable. Instead, use the root XElement which does implement IXmlSerializable:
request.AddBody(currencyXML.Root);
Or, just load it as an XElement to begin with:
var currencyXML = XElement.Load(@"../../Data/currencyXML.xml");
|
[
"math.stackexchange",
"0002442275.txt"
] | Q:
Convergence in p of bounded sequence of random variable implies convergence in rth mean
This is a homework question for a course in asymptotic statistics.
Definitions.
Let $X_1, X_2, \ldots$ be sequence of random variables with $|X_n| < B$ almost surely for all $n$.
Let $X_n \xrightarrow[]{p} X$ denote convergence in probability: $\lim_{n\to \infty} P(|X_n -X| > \epsilon ) = 0.$
Let $X_n \xrightarrow[]{r} X$ denote convergence in the rth mean: $\lim_{n\to \infty} E(|X_n -X|^r) = 0.$
Let $r > 0$.
Problem.
Show that $X_n \xrightarrow[]{p} X$ if and only if $X_n \xrightarrow[]{r}X$.
Work.
I have a proof for the if part, but not for the "only if" part:
$$X_n \xrightarrow[]{r} X \Leftarrow X_n \xrightarrow[]{p} X.$$
I tried to show that $E|X_n - X|^r \leq P(|X_n-X| \geq \epsilon)$.
First: I tried expanding $|X_n - X|$ using the binomial theorem. Could only find a bound in terms of a sum over $B$.
Second: Tried writing the expectation in terms of a probability density integral. Again I can only find a bound in terms of $B$.
Third: I tried splitting the $E|X_n - X|^r$ using indicator functions. I ended up getting that $E|X_n - X|^r \geq E|X_n - X|^r$. I don't see how to do this better. I feel like it should involve $B$ somehow.
Status.
I am very stuck.
A:
First off, notice that we have $|X| \leq B$ almost surely. Let $\epsilon > 0$. We find
\begin{align*} \mathbb{E}[|X_n - X|^r] &= \int_{|X_n -X| < \epsilon} |X_n -X|^r dP + \int_{|X_n -X| > \epsilon}|X_n -X|^r dP \\
&\leq \epsilon^r + \int_{|X_n -X| > \epsilon} (2B)^r dP = \epsilon^r + (2B)^r \cdot P(|X_n -X| > \epsilon)
\end{align*}
Taking the lim sup with respect to $n$ of both sides, we obtain $$\limsup_{n\to\infty} \mathbb{E}[|X_n -X|^r] \leq \epsilon^r$$ for any $\epsilon > 0$, which proves the claim.
|
[
"physics.stackexchange",
"0000075884.txt"
] | Q:
Why planes have propellers in front but watercraft have them behind?
Why do propeller airplanes mostly have their propellers in front (of the fuselage or wings) while ships and boats mostly have them at the back?
I realize that there are aircraft with pusher configurations but they are relatively rare.
A:
There are quite a lot of reasons for this, but it's a complicated design environment, and that's why it's not always the case.
Seals and cooling
The inside of a plane's wings is the same fluid as the air around it, but the inside of a boat's hull is a different phase than the water outside. Basically you can never have a rotating shaft over a pressure difference that doesn't permit some fluid through, around the shaft. There are ways to mask this, so that no one ever sees water leaking into the hull. For instance, you can have an intermediate stage between the hull and the water where air is pumped into a higher pressure cavity. Then it's possible that the seal can bubble with air passing out into the water.
Whichever design the ship maker uses you can't change the physical fact that you'll have some fluid flow through the prop seals, be that air or water. This presents a good reason to have the prop on the back of boats and the front of planes. Pressure is higher at the front because of the kinetic pressure of the fluid, and lower at the back for the reverse reason. By putting the prop of a boat in the back you reduce the pressure difference that the seals have to deal with. The plane has no such concern, and might prefer more air pressure and flow around its engines for cooling. In fact, Wikipedia seems to agree with the cooling point for plane engines.
In pusher configuration, the propeller does not contribute airflow over the engine or radiator. Some aviation engines have experienced cooling problems when used as pushers.[33] To counter this, auxiliary fans may be installed, adding additional weight.
Stability
A moving boat or plane has an aerodynamic center of pressure. If this point is behind the point of thrust, then it's a more stable setup and if it's in front then it's a less stable setup. It's likely not a problem either way because there are other dynamical factors that make it stable, or you have a pilot that acts as an active control system.
Nonetheless, planes worry about stability a lot more than boats.
Operational considerations
As others have pointed out, boats logically don't want the prop in the front because you're more likely to hit something (like a sandbar) with the front of the boat, and you don't want to shred things. This quite possibly dwarfs the basic physical considerations.
In fact, as I was thinking about cavitation concerns, it seems clear that the back of the boat isn't the ideal place. Directly under the hull would be superior. But this a) doesn't give a direct shaft line to the engine and b) it could make the prop hit the ground or a whale. For this case, it's clear that the operational safety concerns are much more pressing than a little bit more performance.
A:
Well the issue is relatively simple.
With the boat, all that is required is to propel the boat forward, and that is best achieved by accelerating a mass of water in a direction opposite to the direction of boat travel. That is best achieved by expelling the accelerated water into as unrestricted a space as possible; which clearly is behind the boat. With the propeller in front, the accelerated water has to move around the bow of the boat, so part of the energy is wasted moving the water sideways, away from the hull, and generating no net thrust since the two sides cancel out, so only the component of the velocity along the path of travel is useful in driving the boat.
With an aero-plane, there is an additional interest, namely increasing the lift of the wing, specially at low forward speeds such as at take off and landing. So having the propeller in front, (specially with twins) even at zero speed, the air flow over the wings, provides significant lift, reducing the necessary take off speed, and the possible landing speed. The plane propeller, even with a single engine, has a larger diameter, than the profile of the fuselage, and the propeller is designed so that most of the air movement is generated near the tips, rather than at the hub, so the energy lost to the fuselage drag is minimal.
Pusher propeller planes, or push-pull duals, are quite popular when used on primitive air strips, that may have loose stones on them, so the prop wash is not kicking up stones into the fuselage.
A:
A boat is most efficient when it is riding on a plane. This happens when the boat reaches a certain speed and is essentially lifted out of the water. This can not happen if the propeller were located on the front of the boat. Look up a boat with a hydrofoil and you can see how it works.
|
[
"stackoverflow",
"0000912217.txt"
] | Q:
Can I do use a direct URL like twitter or myspace in PHP
Can I do that thing that twitter and many other sites do where a url shows a users page.
www.mysite.com/the_user_name
In php... or how does one do it?
A:
Look into how to use the mod_rewrite module in .htaccess.
Here's some ALA goodness:
How to Succeed With URLs
URLS! URLS! URLS!
A:
The easiest method would be to use mod_rewrite in Apache (as opposed to doing it in PHP). Here's a good beginner's guide.
|
[
"stackoverflow",
"0042673009.txt"
] | Q:
QR Code Reader for Sony SmartEyeglass
$ Hello, I am using an app I found on Github https://github.com/simsor/SmartEyeglassQRCode/blob/master/AndroidApp/app/src/main/java/com/example/sony/smarteyeglass/extension/helloworld/HelloWorldControl.java, which is a qr code reader for Sony's SmartEyeglass. But for some reason it is not working. When I scan a QRcode, it either says "QR code not found" or "please wait" for a very long time, without ever showing the result. I tried a few things, but nothing changed. Does any of you maybe know what's going on ?
public void processPicture(CameraEvent event) {
updateLayout("Please wait...");
if (event.getIndex() == 0) {
if (event.getData() != null && event.getData().length > 0) {
byte[] data = event.getData();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
int[] intArray = new int[bitmap.getWidth() * bitmap.getHeight()];
//copy pixel data from the Bitmap into the 'intArray' array
bitmap.getPixels(intArray, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), intArray);
BinaryBitmap bbmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new QRCodeReader();
int DelayTime = 5000;
boolean error = false;
try {
Result result = reader.decode(bbmap);
Log.d(Constants.LOG_TAG, result.getText());
doWebsiteCommunication(result.getText());
} catch (NotFoundException e) {
updateLayout("QR Code Not Found");
error = true;
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
updateLayout(new String[] {
"QR Code looks corrupted",
"Maybe try again?"
});
error = true;
} catch (FormatException e) {
e.printStackTrace();
updateLayout("That's not a QR Code");
error = true;
}
if (error) {
try {
Thread.sleep(DelayTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentlyTakingPicture = false;
updateLayout(DEFAULT_TEXT);
}
}
}
}
A:
The problem is the
doWebsiteCommunication(result.getText());
Just replace it with
updateLayout(result.getText());
This should work fine
PS: the doWebsiteCommunication was meant to update an external Website with the scandata, but since you just wanna read the qr code you dont need it
|
[
"stackoverflow",
"0030544973.txt"
] | Q:
Two JSON douments linked by a key
I have a python server listening to POST from an external server.I expect two JSON documents for every incident happening on the external server. One of the fields in the JSON documents is a unique_key which can be used to identify that these two documents belong together. Upon recieving the JSON documents, my python server sticks into elasticsearch. The two documents related to the incident will be indexed in the elastic search as follows.
/my_index/doc_type/doc_1
/my_index/doc_type/doc_2
i.e the documents belong to the same index and has the same document type. But I don't have an easy way to know that these two documents are related. I want to do some processing before inserting into ElasticSearch when I can use the unique_key on the two documents to link these two. What are your thoughts on doing some normalization across the two documents and merging them into a single JSON document. It has to be remembered that I will be recieving a large number of such documents per second. I need some temporary storage to store and process the JSON documents. Can some one give some suggestions for approaching this problem.
As updated I am adding the basic structure of the JSON files here.
json_1
{
"msg": "0",
"tdxy": "1",
"data": {
"Metric": "true",
"Severity": "warn",
"Message": {
"Session": "None",
"TransId": "myserver.com-14d9e013794",
"TransName": "dashboard.action",
"Time": 0,
"Code": 0,
"CPUs": 8,
"Lang": "en-GB",
"Event": "false",
},
"EventTimestamp": "1433192761097"
},
"Timestamp": "1433732801097",
"Host": "myserver.myspace.com",
"Group": "UndefinedGroup"
}
json_2
{
"Message": "Hello World",
"Session": "4B5ABE9B135B7EHD49343865C83AD9E079",
"TransId": "myserver.com-14d9e013794",
"TransName": "dashboard.action"
"points": [
{
"Name": "service.myserver.com:9065",
"Host": "myserver.com",
"Port": "9065",
}
],
"Points Operations": 1,
"Points Exceeded": 0,
"HEADER.connection": "Keep-Alive",
"PARAMETER._": "1432875392706",
}
I have updated the code as per the suggestion.
if rx_buffer:
txid = json.loads(rx_buffer)['TransId']
if `condition_1`:
res = es.index(index='its', doc_type='vents', id=txid, body=rx_buffer)
print(res['created'])
elif `condition_2`:
res = es.update(index='its', doc_type='vents', id=txid, body={"f_vent":{"b_vent":rx_buffer}})
I get the following error.
File "/usr/lib/python2.7/site-packages/elasticsearch/transport.py", line 307, in perform_request
status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
File "/usr/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 89, in perform_request
self._raise_error(response.status, raw_data)
File "/usr/lib/python2.7/site-packages/elasticsearch/connection/base.py", line 105, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
RequestError: TransportError(400, u'ActionRequestValidationException[Validation Failed: 1: script or doc is missing;]')
A:
The code below makes the assumption you're using the official elasticsearch-py library, but it's easy to transpose the code to another library.
We'd also probably need to create a specific mapping for your assembled document of type doc_type, but it heavily depends on how you want to query it later on.
Anyway, based on our discussion above, I would then index json1 first
from elasticsearch import Elasticsearch
es_client = Elasticsearch(hosts=[{"host": "localhost", "port": 9200}])
json1 = { ...JSON of the first document you've received... }
// extract the unique ID
// note: you might want to only take 14d9e013794 and ditch "myserver.com-" if that prefix is always constant
doc_id = json1['data']['Message']['TransID']
// index the first document
es_client.index(index="my_index", doc_type="doc_type", id=doc_id, body=json1)
At this point json1 is stored in Elasticsearch. Then, when you later get your second document json2 you can proceed like this:
json2 = { ...JSON of the first document you've received... }
// extract the unique ID
// note: same remark about keeping only the second part of the id
doc_id = json2['TransID']
// make a partial update of your first document
es_client.update(index="my_index", doc_type="doc_type", id=doc_id, body={"doc": {"SecondDoc": json2}})
Note that SecondDoc can be any name of your choosing here, it's simply a nested field that will contain your second document.
At this point you should have a single document having the id 14d9e013794 and the following content:
{
"msg": "0",
"tdxy": "1",
"data": {
"Metric": "true",
"Severity": "warn",
"Message": {
"Session": "None",
"TransId": "myserver.com-14d9e013794",
"TransName": "dashboard.action",
"Time": 0,
"Code": 0,
"CPUs": 8,
"Lang": "en-GB",
"Event": "false"
},
"EventTimestamp": "1433192761097"
},
"Timestamp": "1433732801097",
"Host": "myserver.myspace.com",
"Group": "UndefinedGroup",
"SecondDoc": {
"Message": "Hello World",
"Session": "4B5ABE9B135B7EHD49343865C83AD9E079",
"TransId": "myserver.com-14d9e013794",
"TransName": "dashboard.action",
"points": [
{
"Name": "service.myserver.com:9065",
"Host": "myserver.com",
"Port": "9065"
}
],
"Points Operations": 1,
"Points Exceeded": 0,
"HEADER.connection": "Keep-Alive",
"PARAMETER._": "1432875392706"
}
}
Of course, you can make any processing on json1 and json2 before indexing/updating them.
|
[
"stackoverflow",
"0017857733.txt"
] | Q:
How do I reattach to a detached mosh session?
How do I reattach to a detached mosh session or otherwise get rid of
Mosh: You have a detached Mosh session on this server (mosh [XXXX]).
i.e. what's the mosh equivalent of
screen -D -R
or possibly
screen -wipe
Furthermore, where can this answer be found in documentation?
A:
For security reasons, you can not reattach, see https://github.com/keithw/mosh/issues/394
To kill the detached session, use the PID number displayed in that message (that's the 'XXXX' part.) For example, if you see --
Mosh: You have a detached Mosh session on this server (mosh [12345]).
And can run this command:
kill 12345
Also, to close all mosh connections you can:
kill `pidof mosh-server`
Note that if you are currently connected via mosh, this last command will also disconnect you.
A:
To my amazement, I used CRIU (https://criu.org) to checkpoint and restart a mosh client and it worked.
Shocking.
Find your mosh-client's PID:
$ ps -ef | grep mosh
Then, install CRIU according to their instructions.
Then, checkpoint it like this:
$ mkdir checkpoint
$ sudo ./criu dump -D checkpoint -t PID --shell-job
Then, restore it:
$ sudo ./criu restore -D checkpoint --shell-job
And, there it is. Your mosh client is back.
One thing to note, however, is that if your laptop reboots (which is the whole point of what we're trying to protect against), mosh uses a monotonic clock to track time on the client side, which doesn't work across reboots. This will NOT work, however, if your laptop just flat out crashes it won't work because mosh sequence numbers will be out of sync with the version that was checkpointed (the binary will resume, but communication will stop).
In order to fix this, you need to tell mosh to stop doing that and download the mosh source code. Then, edit this file:
cd mosh
vim configure.ac
Then, search for GETTIME and comment out that line.
Then do:
autoreconf # or ./autogen.sh if you've just cloned it for the first time
./configure
make
make install
After that, your CRIU-checkpointed mosh client sessions will survive reboots.
(Obviously you'd need to write something to perform the checkpoints regularly enough to be useful. But, that's an exercise for the reader).
A:
I realize this is an old post, but there is a very simple solution to this, as suggested by Keith Winstein, mosh author, here: https://github.com/mobile-shell/mosh/issues/394
"Well, first off, if you want the ability to attach to a session from multiple clients (or after the client dies), you should use screen or tmux. Mosh is a substitute (in some cases) for SSH, not for screen. Many Mosh users use it together with screen and like it that way."
Scenario: I'm logged into a remote server via mosh. I've then run screen and have a process running in the screen session, htop, for example. I lose connection (laptop battery dies, lose network connection, etc.). I connect again via mosh and get that message on the server,
Mosh: You have a detached Mosh session on this server (mosh [XXXX]).
All I have to do is kill the prior mosh session
kill XXXX
and reattach to the screen session, which still exists.
screen -r
Now, htop (or whatever process was running) is back just as it was without interruption.This is especially useful for running upgrades or other processes that would leave the server in a messy, unknown state if suddenly interrupted. I assume you can do the same with tmux, though I have not tried it. I believe this is what Annihilannic and eskhool were suggesting.
|
[
"graphicdesign.stackexchange",
"0000029784.txt"
] | Q:
Illustrator: Disappearing paths on export
I'm having issues exporting graphics with some of my lines disappearing. I'm a complete novice to illustrator, so sorry if this is something really basic.
The image should look like this:
Unfortunately, it is exporting like this:
Thanks if you are able to help!
Ps. I noticed it does the same thing if I open the flattener preview.
A:
When I am exporting a graphic from Illustrator, I tend to be quite cautious and make sure that everything is converted to paths in case anything is lost. It looks like only the 'second' line markers (around the circumference) that are really missing; how did you make these?
If they are all individual rectangles copied rotationally from the center, using the Rotate tool, then you shouldn't be losing any of them. If they are all individual 1px strokes, or if it is a 1px circular path with dots/dashes (constructed under the Stroke menu), then you might have trouble with exporting these.
If not, please let me know how you made the second markers so I can offer better assistance. :)
|
[
"math.stackexchange",
"0002766445.txt"
] | Q:
Proof explanation: tensor product of operators
Let $E$ be an infinite-dimensional complex Hilbert space, $E\otimes E$ be the Hilbert space tensor product and
We recall the following theorem:
Stochel's Theorem: Let $A_1, A_2,B_1, B_2\in \mathcal{L}(E)$ be non-zero operators. The following conditions are equivalent:
$A_1\otimes B_1=A_2\otimes B_2$.
There exists $z\in \mathbb{C}^*$ such that $A_1 =zA_2$ and $B_1= z^{-1}B_2$.
This is the proof from the paper
I don't understand why the operators $A_1, A_2,B_1, B_2$ must be non-zero?
I think it is sufficient to assume that $A_1$ and $B_1$ are non-zero.
A:
If $A_1$ and $B_1$ are nonzero, then necessarily $A_2$ and $B_2$ are nonzero, so it is the same. Many authors are not looking to optimize the hypotheses of theorems to the bare logical minimum that makes them work. Here, it is not possible to have $A_1,B_1$ nonzero and $A_2=0$ or $B_2=0$.
|
[
"stackoverflow",
"0002819059.txt"
] | Q:
Preallocating memory with C++ in realtime environment
I'm having a function which gets an input buffer of n bytes, and needs an auxillary buffer of n bytes in order to process the given input buffer.
(I know vector is allocating memory at runtime, let's say that I'm using a vector which uses static preallocated memory. Imagine this is NOT an STL vector.)
The usual approach is
void processData(vector<T> &vec) {
vector<T> &aux = new vector<T>(vec.size()); //dynamically allocate memory
// process data
}
//usage:
processData(v)
Since I'm working in a real time environment, I wish to preallocate all the memory I'll ever need in advance.
The buffer is allocated only once at startup. I want that whenever I'm allocating a vector, I'll automatically allocate auxillary buffer for my processData function.
I can do something similar with a template function
static void _processData(vector<T> &vec,vector<T> &aux) {
// process data
}
template<size_t sz>
void processData(vector<T> &vec) {
static aux_buffer[sz];
vector aux(vec.size(),aux_buffer); // use aux_buffer for the vector
_processData(vec,aux);
}
// usage:
processData<V_MAX_SIZE>(v);
However working alot with templates is not much fun (now let's recompile everything since I changed a comment!), and it forces me to do some bookkeeping whenever I use this function.
Are there any nicer designs around this problem?
A:
I don't see how you can get precisely what you describe. Something like this could be a good compromise for you.
void processData(vector<T>& vec)
{
static vector<T> aux(vec.size());
if (vec.size() > aux.size()) {
aux.resize(vec.size());
}
...
}
|
[
"stackoverflow",
"0030945206.txt"
] | Q:
Angularjs: View not updating list after POST
I am currently working on a small angularjs app which is basically a user profile management app.
The problem i am having is with adding users dynamically. When i enter the user data, it successfully POST's to my local server i have setup, BUT i have to refresh the page to see the new user in the users list
I obviously dont want to have to refresh.
-Yes i've tried $scope.apply() after running the POST function
Something i am noticing with Angular Batarang (Debugging tool), is that the scope is updating fine, but there is a blank spot or 'null' value where the new user should be.
Here are the Controllers:
UsersApp.controller('UserListController', [ '$scope', 'userService', function($scope, userService) {
$scope.usersList = userService.usersList;
$scope.users = userService.users;
$scope.user = userService.user;
}]);
UsersApp.controller('AddUserController', function($scope, $window, dataResources, userService) {
$scope.addNew = function addNew(newUser) {
$scope.usersList = userService.usersList;
var firstName = newUser.firstName;
var lastName = newUser.lastName;
var phone = newUser.phone;
var email = newUser.email;
$scope.newUserData = {
firstName , lastName, phone , email
}
new dataResources.create($scope.newUserData);
$scope.usersList.push(dataResources);
$scope.$apply();
};
And Here are my views:
Add User:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/minimize.js"></script>
<div ng-controller="AddUserController">
<div class="userInfo" id="usernameDiv">
<h2 id="username">User<img id="showhide" src="images/plus.png" style="position:absolute; padding-left:15px; width:31px; color:white;"></h2>
</div>
<div class="userInfo">
<div id="listInfo">
<form ng-controller="AddUserController">
<input type="text" placeholder= "First Name" ng-model="newUser.firstName"></input>
<input type="text" placeholder= "Last Name" ng-model="newUser.lastName"></input>
<input type="text" placeholder= "Phone Number" ng-model="newUser.phone"></input>
<input type="text" placeholder= "Email" ng-model="newUser.email"></input>
<button type="submit" ng-click="addNew(newUser)">Add User</button>
</form>
</div>
</div>
Users List:
<!DOCTYPE html>
<html>
<head></head>
<body id="">
<div ng-controller="UserListController">
<div class="userInfo">
<h2>List of Users</h2>
<div id="listInfo">
<ul style="list-style-type: none;">
<li ng-repeat="user in usersList">
<!--<p class="userData">ID: {{ user }}</p> -->
<p class="userData"><a style="cursor:pointer;" ui-sref="UserProfile">{{ user.firstName }}</a></p>
</li>
</ul>
</div>
</div>
Factory and Service:
UsersApp.factory('dataResources', [ '$resource', function($resource) {
return $resource('http://localhost:24149/users/:id', {}, {
query: {method:'GET', params:{idnum: '@id'}, isArray:true},
create: {method:'POST', headers: { 'Content-Type': 'application/json' }},
update: {method:'PUT', params:{idnum: '@id'}},
remove: {method:'DELETE', params:{idnum:'@id'}, isArray:true}
});
}]);
UsersApp.service('userService', function(dataResources) {
return {
usersList: dataResources.query()
}
});
A:
I'm not sure if I follow exactly, but I believe you need to deal with a promise from your POST and then push the result. e.g.,
dataResources.create($scope.newUserData).$promise.then(function(data) {
$scope.usersList.push(data);
});
Your service will return a promise and then when the POST is complete your service should return the new user and you just add it to your current list.
|
[
"stackoverflow",
"0043435785.txt"
] | Q:
How to encrypt/decrypt a file in iOS?
I am storing a (.sqlite) in my documents folder. I need to encrypt this file, so that no one can directly access the file. Can this be achieved in iOS?
A:
In iOS app no one actually can access your .sqlite file, except you. This documentation folder will be available only for your app
|
[
"math.stackexchange",
"0003118110.txt"
] | Q:
Show that an operator with certain properties is an isomorphism
Suppose $H$ is an infinite dimensional separable Hilbert space, with $\langle \cdot,\cdot\rangle$ denoting the duality pairing between the dual $H'$ and $H$ and $(\cdot,\cdot)$ the inner product on $H$. Let $A\,:\,H \to H'$ be a bounded linear functional such that
(a) there exists $\gamma \in H$ such that for all $v \in H$ we have $\langle A\gamma, v\rangle = \mu (\gamma,v)$, where $\mu < 0$;
(b) there exists $c > 0$ such that $\langle Aw,w\rangle \geq c \|w\|^2$ for all $w \in W$, where $W := \{ v \in H\,|\, (v,\gamma) = 0\}$.
It seems untuitively clear that $A$ is invertible, because we have a sole negative eigenvalue $\mu$ and the rest of the spectrum is bounded below by $c$. Is it an isomorphism? For that we would have to be able to find $c_2 > 0$ such that for all $v \in H$ we would have $\|Av\| \geq c_2 \|v\|$.
My futile attempt at establishing such an inequality centered around the decomposition $v = \alpha \gamma + w$, where $w \in W$ and $\alpha$ is some scalar. For instance we then have
$$
\langle Av,v \rangle = \alpha^2\mu\|\gamma\|^2 + \langle Aw,w \rangle \geq \alpha^2 \mu \|\gamma\|^2 + c\|w\|^2,
$$
but the fact that $\mu < 0$ seems to destroy the usual argument. I have a strong imppresion I am missing something obvious here. I'll gladly accept any comments you might have.
Edit: I probably should have also mentioned that $A$ is assumed self-adjoint in the sense that $\langle Av,w \rangle = \langle Aw,v \rangle$ for any $v,w \in H$.
A:
Let $v = \alpha \gamma + w$.
Instead of $v$ we use $ -\alpha \gamma + w$ as test function:
$$
\langle Av, -\alpha \gamma + w \rangle = \alpha\mu (\gamma,-\alpha \gamma + w) + \langle A(-\alpha \gamma + w),w\rangle
=- \alpha^2 \mu \|\gamma\|^2 + \langle Aw,w\rangle \\
\ge
\alpha^2 |\mu| \cdot\|\gamma\|^2 + c \|w\|^2.
$$
Now $\|{\pm}\alpha\gamma + w\|^2 = \alpha^2 \|\gamma\|^2 + \|w\|^2$, which implies
$$
\langle Av, -\alpha \gamma + w \rangle \ge \min(|\mu|,c) \|v\|\cdot \|-\alpha \gamma + w\|$$
and
$$
\|Av\|_{H'} \ge \min(|\mu|,c) \|v\|.
$$
|
[
"softwareengineering.stackexchange",
"0000373376.txt"
] | Q:
Why isn't encoding the names of arguments in function names more common?
In Clean Code the author gives an example of
assertExpectedEqualsActual(expected, actual)
vs
assertEquals(expected, actual)
with the former claimed to be more clear because it removes the need to remember where the arguments go and the potential misuse that comes from that. Yet, I've never seen an example of the former naming scheme in any code and see the latter all the time. Why don't coders adopt the former if it is, as the author asserts, clearer than the latter?
A:
Because it is more to type and more to read
The simplest reason is that people like to type less, and encoding that information means more typing. When reading it, every time I have to read the whole thing even if I am familiar with what the order of the arguments should be. Even if not familiar with the order of arguments...
Many developers use IDEs
IDEs often provide a mechanism for seeing the documentation for a given method by hovering or via a keyboard shortcut. Because of this, the names of the parameters are always at hand.
Encoding the arguments introduces duplication and coupling
The names of the parameters should already document what they are. By writing the names out in the method name, we are duplicating that information in the method signature as well. We also create a coupling between the method name and the parameters. Say expected and actual are confusing to our users. Going from assertEquals(expected, actual) to assertEquals(planned, real) doesn't require changing the client code using the function. Going from assertExpectedEqualsActual(expected, actual) to assertPlannedEqualsReal(planned, real) means a breaking change to the API. Or we don't change the method name, which quickly becomes confusing.
Use types instead of ambiguous arguments
The real issue is that we have ambiguous arguments that are easily switched because they are the same type. We can instead use our type system and our compiler to enforce the correct order:
class Expected<T> {
private T value;
Expected(T value) { this.value = value; }
static Expected<T> is(T value) { return new Expected<T>(value); }
}
class Actual<T> {
private T value;
Actual(T value) { this.value = value; }
static Actual<T> is(T value) { return new Actual<T>(value); }
}
static assertEquals(Expected<T> expected, Actual<T> actual) { /* ... */ }
// How it is used
assertEquals(Expected.is(10), Actual.is(x));
This can then be enforced at the compiler level and guarantees that you cannot get them backwards. Approaching from a different angle, this is essentially what the Hamcrest library does for tests.
A:
You ask about a long standing debate in programming. How much verbosity is good? As a general answer, developers have found that the extra verbosity naming the arguments is not worth it.
Verbosity does not always mean more clarity. Consider
copyFromSourceStreamToDestinationStreamWithoutBlocking(fileStreamFromChoosePreferredOutputDialog, heuristicallyDecidedSourceFileHandle)
versus
copy(output, source)
Both contain the same bug, but did we actually make it any easier to find that bug? As a general rule, the easiest thing to debug is when everything is maximally terse, except the few things which have the bug, and those are verbose enough to tell you what went wrong.
There's a long history of adding verbosity. For example, there's the generally-unpopular "Hungarian notation" which gave us wonderful names like lpszName. That has generally fallen by the wayside in the general programmer populace. However, adding characters to member variable names (like mName or m_Name or name_) continues to have popularity in some circles. Others dropped that entirely. I happen to work on a physics simulation codebase whose coding style documents require that any function which returns a vector must specify the vector's frame in the function call (getPositionECEF).
You might be interested in some of the languages made popular by Apple. Objective-C includes the argument names as part of the function signature (The function [atm withdrawFundsFrom: account usingPin: userProvidedPin] is written in the documentation as withdrawFundsFrom:usingPin:. That's the name of the function). Swift made a similar set of decisions, requiring you to put the argument names in the function calls (greet(person: "Bob", day: "Tuesday")).
A:
The author of "Clean Code" points out a legitimate problem, but his suggested solution is rather inelegant. There are usually better ways to improve unclear method names.
He is right that assertEquals (from xUnit style unit test libraries) does not make it clear which argument is the expected and which is the actual. This have also bit me! Many unit test libraries have noted the issue and have introduced alternative syntaxes, like:
actual.Should().Be(expected);
Or similar. Which is certainly a lot clearer than assertEquals but also much better than assertExpectedEqualsActual. And it is also a lot more composable.
|
[
"stackoverflow",
"0007927692.txt"
] | Q:
rewrite rule php correct page
i have in a file rewrite.php following rules
$rewrites = array(
'#^/searchresults.html$#' => '/info/searchresults'
);
$reverseRewrites = array (
'#^/info/searchresults$#' => '/searchresults.html'
);
this work and give me correct page searchresults.html
but with google custom search
i have error page non found because
format of searchresults page is:
http://site.com/searchresults.html?cx=partner-pub-***********&cof=FORID%3A10&ie=UTF-8&q=***&sa=Search&siteurl=site.com%2F
so can you help me to insert correct rewrite rule for this specific url ?
A:
I'm not sure exactly what API you are using for these rewrites, but the problem looks to be that the regex ends after .html and so it is not matching your query string. Something like this might help:
$rewrites = array(
'#^/searchresults.html(|\?.*)$#' => '/info/searchresults$1'
);
$reverseRewrites = array (
'#^/info/searchresults(|\?.*)$#' => '/searchresults.html$1'
);
|
[
"stackoverflow",
"0046057693.txt"
] | Q:
SQL : query large table
I want to query a large data set in SQL - which is the right approach?
declare @datetime Datetime
select *
from sales
where salesdate <= @datetme
or:
select *
from sales
where salesdate < (select GetDate())
or:
select *
from sales
where salesdate < GetDate()
or by using NOW()
A:
All three will have same execution plan other than 0% ASSIGN stage for variable in query no. 1. But it will turn out to be a good practice in the long run to always initialize variable as DATETIME and then use for comparison. When you have long comparisons to make this way, user will get the habit of formatting datetime in a variable and comparing column against those variables. Otherwise, it becomes a habit of formatting SQL column and then comapring it with date. That formats datetime field in every data row for comparison with value and makes datetime comparisons slow.
For this particular query, for readability and ease of use, you can select query no. 3 [Select * from sales where salesdate < GetDate()].
|
[
"stackoverflow",
"0058005167.txt"
] | Q:
Unity VR UNET make PC and VR the same player
Sorry that there is NO CODE to show, but this is a very architectural question.
First of all, I have to say that i have to use UNET and yes, I know it is deprecated, but i'm not doing an actual network game that will let users join the game. I will explain:
I have a project that is connected to hardware. The PC is running the Unity brain that controls the hardware and receive info from it and so on. This part is working great.
The thing is that I need to connect Simple VR glasses to look around (JUST FOR LOOKING AROUND AND "PRESSING" the start button) and nothing else, everything will still be controlled by the PC (That will run a UNET server if needed) and the main client that moves and get inputs and do things, And the VR need to be a "Slave" of sort just for looking around. I want UNET because the unity used for the project is 18.3.14f1 and yes, I know that it is old but it is a legacy that i can't change as for now and I don't need a could server as all the hardware is in the same LAN.
From what i can understand, In Client / Server every client (PC AND VR) SPAWNS a new client so when client in the VR will not have the same client that is on the PC. That is making things very complicated.
Can I have some kind of a MASTER / SLAVE thing that will control both?
If NOT should I do everything on the server and send everything to both the clients? Or should I still have the regular approach and send every thing from on client to the other (change all the code in the app)?
Couldn't find an answer for that, I don't think it is a very used case scenario.
10x.
A:
First of all, I have to say that i have to use UNET and yes, I know it
is deprecated, but i'm not doing an actual network game that will let
users join the game. I will explain: I have a project that is
connected to hardware. The PC is running the Unity brain that controls
the hardware and receive info from it and so on. This part is working
great.
You can use Mirror so you won't run into trouble when Unity removes UNET from the engine.
The thing is that I need to connect Simple VR glasses to look around
(JUST FOR LOOKING AROUND AND "PRESSING" the start button) and nothing
else, everything will still be controlled by the PC (That will run a
UNET server if needed) and the main client that moves and get inputs
and do things, And the VR need to be a "Slave" of sort just for
looking around.
That's not how UNET works. The basic idea is that the game runs simultaneously on every device. Your VR Glasses will have to run the game to be able to render it. With UNET you just sync the game state and make sure every connected instance has the same state.
From what i can understand, In Client / Server every client (PC AND
VR) SPAWNS a new client so when client in the VR will not have the
same client that is on the PC. That is making things very complicated.
Can I have some kind of a MASTER / SLAVE thing that will control both?
If NOT should I do everything on the server and send everything to
both the clients? Or should I still have the regular approach and send
every thing from on client to the other (change all the code in the
app)?
Every connected device can spawn a new Player on every connected instance of the game. I think this will help you to differentiate between the VR Glasses and sync states between the clients.
Couldn't find an answer for that, I don't think it is a very used case
scenario.
You are not locked-in to UNET. Sometimes it is feasible to setup your own TCP- or UDP-communication.
The description of your UseCase is not clear. Should ever VR Glass run independent and you want the PC to have all workload? Or are the VR Glasses are connected to create a shared experience? What is the role of the PC? What should be shown there?
|
[
"stackoverflow",
"0061442341.txt"
] | Q:
openshift commands to catch POD name programmatically/scripting
I have pods in my open shift and want to work on multiple open shift applications. Lets say like below
sh-4.2$ oc get pods
NAME READY STATUS RESTARTS AGE
jenkins-7fb689fc66-fs2xb 1/1 Running 0 4d
jenkins-disk-check-1587834000 0/1 Completed 0 21h
NAME READY STATUS RESTARTS AGE
jenkins-7fb689fc66-gsz9j 0/1 Running 735 9d
jenkins-disk-check-1587834000
NAME READY STATUS RESTARTS AGE
jenkins-9euygc66-gsz9j 0/1 Running 735 9d
I have tried with below command
oc get pods
export POD=$(oc get pods | awk '{print $1}' | grep jenkins*)
I want to find the pods starting with numbers "jenkins-7fb689fc66-fs2xb",jenkins-9euygc66-gsz9j, etc... using scripting and need to ignore disk check pods. If i catch the above pods and need to execute the terminal and run some shell commands via programmatically. Can someone help me on this?
A:
kubectl get (and by extension oc get) is a very versatile tool. Unfortunately, after looking around online for awhile, you will definitely not be able to do Regex without relying on an external tool like awk or grep. (I know this wasn't exactly what you were asking, but I figured I'd at least try to see if it's possible.
With that said, there are a couple of tricks you can rely on to filter your oc get output before you even have to pull in external tools (bonus points because this filtering occurs on the server before it even hits your local tools).
I first recommend running oc get pods --show-labels, because if the pods you need are appropriately labeled, you can use a label selector to get just the pods you want, e.g.:
oc get pods --selector name=jenkins
oc get pods --selector <label_key>=<label_value>
Second, if you only care about the Running pods (since the disk-check pods look like they're already Completed), you can use a field selector, e.g.:
oc get pods --field-selector status.phase=Running
oc get pods --field-selector <json_path>=<json_value>
Finally, if there's a specific value that you're after, you can pull that value into the CLI by specifying custom columns, and then greping on the value you care about, e.g.:
oc get pods -o custom-columns=NAME:.metadata.name,TYPES:.status.conditions[*].type | grep "Ready"
The best thing is, if you rely on the label selector and/or field selector, the filtering occurs server side to cut down on the data that ends up making it to your final custom columns, making everything that much more efficient.
For your specific use case, it appears that simply using the --field-selector would be enough, since the disk-check pods are already Completed. So, without further information on exactly how the Jenkins pod's JSON is constructed, this should be good enough for you:
oc get pods --field-selector status.phase=Running
|
[
"stackoverflow",
"0053303151.txt"
] | Q:
Global sequential number generator without using a relational database
I have an application. Suppose it's an invoice service. Each time a user creates an invoice I need to assign the next sequential number (I.e: ISequentialNumberGeneratorRepository.Next(); So essentially the invoice number must be unique despite having several instances of my application running (horizontal scalability is likely in the future).
In other words, I need a global sequential number generator.
Traditionally this problem is resolved by using a relational database such as SQL server, PostgreSQL, MySQL, etc. because these systems have the capability to generate sequential unique IDs on inserting a record and returning the generated id as part of the same atomic operation, so they're a perfect fit for a centralised sequential number generator.
But I don't have a relational database and I don't need one, so it's a bit brutal having to use one just for this tiny functionality.
I have, however, an EventStore available (EventStore.org) but I couldn't find out whether it has sequential number generation capability.
So my question is: Is there any available product out there which I could use to generate unique sequential numbers so that I can implement my Next(); repository's method with, and which would work well independently of how many instances of my client invoice application I have?
Note: Alternatively, if someone can think of a way to use EventStore for this purpose or how did they achieve this in a DDD/CQRS/ES environment it'd also be great.
A:
You have not stated the reasons(or presented any code) as to why you want this capability. I will assume the term sequential should be taken as monotonically increasing(sorting not looping).
I tend to agree with A.Chiesa, I would add timestamps to the list, although not applicable here.
Since your post does not indicate how the data is to be consumed, I purpose two solutions, the second preferred over the first, if possible; and for all later visitors, use a database solution instead.
The only way to guarantee numerical order across a horizontally scaled application without aggregation, is to utilize a central server to assign the numbers(using REST or RPCs or custom network code; not to mention an SQL server, as a side note). Due to concurrency, the application must wait it's turn for the next number and including network usage and delay, this delay limits the scalability of the application, and provides a single point of failure. These risks can be minimized by creating multiple instances of the central server and multiple application pools(You will lose the global sorting ability).
As an alternative, I would recommend the HI/LO Assigning method, combined with batch aggregation. Each instance has a four? digit identifier prefixed to an incrementing number per instance. Schedule an aggregation task on a central(or more than one, for redundancy) server(s) to pickup the data and assign a sequential unique id during aggregation. This process localizes the data(until pickup, which could be scheduled for (100, 500, 1000)? millisecond intervals if needed for coherence; minutes or more ,if not), and provides almost perfect horizontal scaling, with the drawback of increased vertical scaling requirements at the aggregation server(s).
Distributed computing is a balancing act, between processing, memory, and communication overhead. Where your computing/memory/network capacity boundaries lie cannot be determined from your post.
There is no single correct answer. I have provided you with two possibilities, but without specific requirements of the task at hand, I can go no further.
|
[
"stackoverflow",
"0004556071.txt"
] | Q:
The root element must match the name of the section referencing the file
I am using the "File" attribute of AppSettings but I am getting this error
The root element must match the name
of the section referencing the file,
'appSettings'
Well I am adding a ClassLibrary1.dll and ClassLibrary1.dll.config in my windows project.
Ny windows application is having its own app.config
<configuration>
<appSettings file="ClassLibrary1.dll.config">
<add key="main" value="main"/>
</appSettings>
</configuration>
thankx in advance
A:
Your external file must look like:
<?xml version="1.0"?>
<appSettings>
<add key="main" value="main"/>
</appSettings>
Unlike when you use configSource, you can't have a configuration node when using the file attribute. I'm not even 100% sure you can use a configuration node with the configSource attribute, I always match the root node that is being externalized. See the MSDN documentation for more information: http://msdn.microsoft.com/en-us/library/ms228154.aspx
Also, I've never tried to reference an assembly configuration file as you are here. I wonder if that may be causing problems? Try extracting just the appSettings node to another config file and see if that solves the issue.
edit: This external file (we'll call it appSettings_external.config) can be used in two ways:
app.config: (settings are merged)
<?xml version="1.0"?>
<configuration>
<appSettings file="appSettings_external.config">
<add key="main" value="main"/>
</appSettings>
</configuration>
app.config: (settings are pulled only from external config)
<?xml version="1.0"?>
<configuration>
<appSettings configSource="appSettings_external.config" />
</configuration>
A:
Make sure that the root XML element in your file "ClassLibrary1.dll.config" is "appSettings".
http://weblogs.asp.net/pwilson/archive/2003/04/09/5261.aspx
A:
Here is my follow-up answer based on the OP's recent comment: What if I have more than one external config file?
My suggestion is to revise the design of the configuration settings. I assume that you have multiple class libraries, and each class library has its own set of settings that are currently being stored in the appSettings section. In that case, your config file probably looks something like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- App Settings for Class Library 1 -->
<add key="ClassLibrary1Value1" value="123"/>
<add key="ClassLibrary1Value2" value="234"/>
<add key="ClassLibrary1Value3" value="345"/>
<!-- App Settings for Class Library 2 -->
<add key="ClassLibrary2Value1" value="ABC"/>
<add key="ClassLibrary2Value2" value="BCD"/>
<add key="ClassLibrary2Value3" value="CDE"/>
</appSettings>
</configuration>
and your code for accessing those settings might look something like this:
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
Console.WriteLine(appSettings["ClassLibrary1Value1"]);
Console.WriteLine(appSettings["ClassLibrary1Value2"]);
Console.WriteLine(appSettings["ClassLibrary1Value3"]);
Console.WriteLine(appSettings["ClassLibrary2Value1"]);
Console.WriteLine(appSettings["ClassLibrary2Value2"]);
Console.WriteLine(appSettings["ClassLibrary2Value3"]);
Instead, I suggest you try separating each class library's settings into its own config section. You could accomplish this by modifying your executable's config file to look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="classLibrary1" type="System.Configuration.AppSettingsSection"/>
<section name="classLibrary2" type="System.Configuration.AppSettingsSection"/>
</configSections>
<classLibrary1 configSource="ClassLibrary1.dll.config" />
<classLibrary2 configSource="ClassLibrary2.dll.config" />
</configuration>
Your ClassLibrary1.dll.config file would look like this:
<?xml version="1.0" encoding="utf-8" ?>
<classLibrary1>
<add key="Value1" value="123"/>
<add key="Value2" value="234"/>
<add key="Value3" value="345"/>
</classLibrary1>
Your ClassLibrary2.dll.config file would look like this:
<?xml version="1.0" encoding="utf-8" ?>
<classLibrary2>
<add key="Value1" value="ABC"/>
<add key="Value2" value="BCD"/>
<add key="Value3" value="CDE"/>
</classLibrary2>
and your code to access these settings would look something like this:
var classLibrary1AppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("classLibrary1");
Console.WriteLine(classLibrary1AppSettings["Value1"]);
Console.WriteLine(classLibrary1AppSettings["Value2"]);
Console.WriteLine(classLibrary1AppSettings["Value3"]);
var classLibrary2AppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("classLibrary2");
Console.WriteLine(classLibrary2AppSettings["Value1"]);
Console.WriteLine(classLibrary2AppSettings["Value2"]);
Console.WriteLine(classLibrary2AppSettings["Value3"]);
|
[
"stackoverflow",
"0004043008.txt"
] | Q:
How to test if SQL Server database is in Single User Mode
How can I test if the SQL Server database is in Single User Mode in a SQL script?
A:
You can check the sys.databases view ...
if (SELECT user_access_desc FROM sys.databases WHERE name = 'YourDb')
= 'SINGLE_USER'
begin
print 'It is in single user mode!'
end
|
[
"stackoverflow",
"0047707554.txt"
] | Q:
Storing an SQLite database file in TFS and the -journal file
I have a pre-populated, read only SQLite database file I am shipping as an Asset with my Android App. Changes to the read only data constitute a version release/update in the app store. Thus, the DB file (and currently the journal file) are being stored in version control (TFS).
The question:
Is there any advantage to storing the -journal file in version control? After everything I read about SQLite, my understanding is it is basically just a simple transaction log for a file and there's no database engine in play (like with MSSQL Server). In effect, TFS is keeping my read only data Versioned, so I see no reason to check-in the journal file or have it be part of my project / assets at all. Am I missing anything?
A:
As long as there is not a transaction that has not yet been committed or rolled back, the journal file is empty.
So it should never be required to have it in version control.
(The default journal mode is DELETE, so unless you have changed this setting, you should investigate how this file ended up in TFS in the first place.)
|
[
"stackoverflow",
"0002468165.txt"
] | Q:
Cannot understand how new or malloc does work with BYTE*
I trying to allocate memory for 10 bytes
BYTE* tmp;
tmp = new BYTE[10];
//or tmp = (BYTE*)malloc(10*sizeof(BYTE));
But after new or malloc operation length of *tmp more than 10 (i.e. '\0' char not in 10 position in tmp array)
Why?
A:
Neither new[] nor malloc() will place the \0 for you. When you call malloc() or new[] for char the block is unitilialized - you need to initialize it manually - either put \0 into the last element, or use memset() for the entire block.
A:
There is no reason for '\0' to be at the end of the array.
malloc (or new, for that matter), gives you back a block of 10 bytes, which is memory it allocated for you. It's your job to do whatever you want with this memory.
You're probably getting mixed up with a string (like char[10], for example).
The whole idea of a string is to be an array of bytes, but which ends with '\0' to denote its size.
An array of bytes, or any other array you allocate which isn't a string, won't neceassrily end with '\0'; it's your job to keep track of its size.
|
[
"stackoverflow",
"0047640512.txt"
] | Q:
PDO_ODBC accessing IBM DB2 tables with special characters in the table names
I'm working on a DB2 table on as/400. I'm trying to run a basic query against it but the table name contains a . in it. For example: my.table is the table name.
The problem is that PDO believes that I'm specifying a database name my with my table name table. Hence the prepared statement is failing and saying no such table table exists in database my. Changing the table name is not an option.
What is the best way to handle a period in the table name? I've tried escaping the period but haven't had any success.
Here's some example code of my problem:
$sql= "select * from '[THE.TABLE]'";
try {
$statement = $this->db->query($sql);
$results = $statement->execute();
foreach ($results as $result) {
print_r($result);
}
exit;
}
catch (\Exception $e)
{
//log issue and other stuff
}
The application is running in Zend Framework 2.
A:
I stand corrected. As aynber mentioned in a comment, the solution was to use double quotes escaped correctly. The answer could be found in the question directed towards MySQL.
|
[
"gaming.stackexchange",
"0000211302.txt"
] | Q:
I hired a fire godlike, how do I get these pillars to work?
In the first cave area, there is a room full of pillars. Interacting with these pillars does not seem to work if you are not a fire godlike. I went and hired a fire godlike at the next inn and doubled back, but the dialog is still unavailable as "the requirement is not met".
How do I deal with these pillars?
A:
You'll need to carry a Torch in your inventory. (No requirement to equip it.)
The Fire Godlike option only works if the player character is a Fire Godlike; it won't work with a companion NPC.
All that said, there's no point in going back to light them. All it does is disable a pathway through the trap file grid in the adjoining room - and if you're doubling back, you've clearly either gotten through it with the Mechanics skill or just gone around it entirely.
|
[
"gis.stackexchange",
"0000266508.txt"
] | Q:
How Many UTM Cylinders are there?
I've been reviewing the theory behind the UTM projection and I think I've gotten a handle on the approach, including the difference between transverse secant cylinders and tangent cylinders, standard lines and central meridians.
For any given single UTM projection, the zone only seems to apply to one side of the secant cylinder. Does each UTM zone have its own secant cylinder, or does one cylinder include opposite sides of the reference sphere?
I've been through many of the available sources on the net, and looked through a couple GIS text books, without a clear answer. I found the Penn State GIS textbook helpful https://www.e-education.psu.edu/natureofgeoinfo/c2_p23.html as well as the USGS Map Projections Working Handbook https://pubs.usgs.gov/pp/1395/report.pdf but I've not yet found a source that claims a solid answer.
I'd be happy with a "Let me Google that for you" answer... I've had no luck.
A:
In general, the transverse Mercator algorithms on an ellipsoid only support one hemisphere. The TM algorithms on a sphere could show both "sides" of the cylinder but usually don't as people don't like to see upside down countries except in polar/azimuthal projections.
|
[
"stackoverflow",
"0029768812.txt"
] | Q:
Windows Phone 8.1 custom controls
I'm developing Windows Phone 8.1 application and I want to use data visualization. I found WinRT XAML Toolkit as a solution, but I don't know how to use this. Can anyone tell the full instructions?
I've tried this way:
1)Package Manager Console: Install-Package WinRTXamlToolkit.Controls.DataVisualization.WindowsPhone
2)In Visual Studio 2013 toolbox right click->add tab->right click inside tab->choose items->open dll file from my project packages folder.
When I do this I can see new controls in toolbox, but I can't use, because when I drag control to my activity there appears empty box. And also icons of controls are the same.
A:
You could use Nuget to install this package, after adding the package, you could see it in your reference list.
Refer to the WinRT XAML Toolkit in nuget page: https://www.nuget.org/packages/winrtxamltoolkit/.
|
[
"stackoverflow",
"0003112594.txt"
] | Q:
How can I generate a list of pay-period-ending dates in PHP4?
I see that all of the good date/time functions are PHP5 only, which sort of makes this hard. I need to generate a list of all pay-period-ending dates starting with 52 weeks back and going to one pay period in the future, with bi-weekly periods.
So, suppose the next pay period ending is June 26, 2010 and today is June 23, 2010, I'd want a list starting with (approximately) June 26, 2009 and ending with June 26, 2010.
If the date is the same day as the pay period ending, I want to include the next one: If the next pay period ending is June 26, 2010 and today is June 26, 2010, I'd want a list starting with (approximately) June 26, 2009 and ending with July 10, 2010.
So, here'd be the call:
>>> get_pay_period_ending_dates($timeInSecondsFromEpoch);
[
$date52weeksBeforeTheNextPayPeriodEnding,
$date50weeksBeforeTheNextPayPeriodEnding,
...
$nextPayPeriodEnding
]
Obviously, that's an approximation of the dates I want. Preferably, in seconds since epoch.
What's the best way to do this, using only tools available in PHP 4.3?
A:
You can get an awful lot done with strtotime(). It feels a little dirty, but it keeps things simple.
$startDate = strtotime('June 26, 2010');
for($i = 0; $i <= 52; $i+=2) {
echo date('m-d-y', strtotime("-$i weeks", $startDate)), "\n";
}
I believe that's a decent starting point/proof of concept.
Update with calculation of start date:
function startDate($date) {
$knownDate = strtotime('June 26, 2010');
$diff = $date - $knownDate;
$weeks = 2 * ceil($diff / (60*60*24*7*2));
return strtotime("$weeks weeks", $knownDate);
}
$startDate = startDate(strtotime('June 26, 2011'));
for($i = 0; $i <= 52; $i+=2) {
echo date('m-d-y', strtotime("-$i weeks", $startDate)), "\n";
}
Might not be completely accurate, but you should get the idea.
|
[
"stackoverflow",
"0022102613.txt"
] | Q:
Does Git generally choke on mounted drives? Or just Git GUI's?
I know I should be diehard and use git in the terminal, but I use a Git client on Mac called Sourcetree to make the whole thing just a bit more sexy.
The problem is a new Synology NAS drive I've added to my setup. With one of the NAS shared folders mounted on my Mac, Sourcetree chokes when trying to stage/commit/push.
My master branch is on GitHub, so I cloned a repo to the mounted drive using Sourcetree. As a quick test I edited an unimportant file, saved, and watched for unstaged changes in the client. Success so far; the edited file appears in the unstaged window of Sourcetree. I go to stage it. Fatal error:
git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree add -f -- README.md
fatal: Unable to write new index file
Completed with errors, see above
I had a look at the file permissions of the index file within the hidden .git folder (using the NAS directory explorer as the Mac doesn't show the hidden file. The file permissions were reading, writing, but not executing. After allowing execution of the file, the stage/commit/push attempts with Sourcetree worked.
Obviously, I don't want to have to go and manually adjust file permissions every time I clone a git repository, so does anybody have any insight as to why Sourcetree/Git is not creating the repo clone with more helpful file permissions?
For the record, I tried the same operation with the GitHub OSX client, which seemed successful (no need to edit permissions). But I find the GitHub client a little primitive, and would prefer to use Sourcetree.
A:
It is git in general. This answer suggests, it is because of the filelocking. For more info, just search SO for "git samba"
From my experience, operating on a non-bare repo on a network drive is a bad idea.
For best-practises:
http://git-scm.com/book/ch4-1.html
So either:
Setup an SSH server on you NAS and push/pull to that
Map your network share (as you have now) but put a bare repo on that. Then, push/pull to that one.
In any case it is recommended that the git repo with the working copy resides on a local disk.
|
[
"stackoverflow",
"0017839686.txt"
] | Q:
Oracle - Difference between AND (Case1 OR Case2 OR Case3)
Hello everyone I have a fairly simple question.
I was wondering what the difference between
SELECT *
FROM TABLE
WHERE A = 'xxx'
AND (B = 'xxx' OR C='xxx' OR D='xxx')
And this Query
SELECT *
FROM TABLE
WHERE A = 'xxx'
AND B = 'xxx'
OR C='xxx'
OR D='xxx'
In the bottom query it will return 2 results and the top query it returns zero results.
A:
A = 'xxx' AND B = 'xxx' OR C='xxx' OR D='xxx'
is equivalent to
(A = 'xxx' AND B = 'xxx') OR (C='xxx') OR (D='xxx')
thanks to operators precedence order
A:
This
SELECT * FROM TABLE
WHERE A = 'xxx' AND (B = 'xxx' OR C='xxx' OR D='xxx')
is equivalent to this
SELECT * FROM TABLE
WHERE A = 'xxx' AND B = 'xxx' OR
A = 'xxx' AND C = 'xxx' OR
A = 'xxx' AND D = 'xxx'
The logic you put in a WHERE clause follows rules for Boolean expressions. Just like with an algebraic expression, there is an order operations. Generally, the order is
NOT
AND
OR
|
[
"stackoverflow",
"0018610978.txt"
] | Q:
Change Text of server Control in static Web Method
I am using a web method for ajax call, I want to change the text of my asp.net label control after ajax call.
I am changing its text on success of the ajax call,but after post back I am not getting updated value, as its changing on client side.
I want to change text so that it will reflect on post back as well.
How can I change the text of label in WebMethod?
Below is my code
[System.Web.Services.WebMethod()]
public static string RemoveVal()
{
//Do some work
//Return updated Value
//I want to change text here
}
jQuery.ajax({
type: "POST",
url: 'MyPage.aspx/RemoveVal',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var emaillbl = GetClientID("lblEmail").attr("id");
$("#" + emaillbl).html(data);
}
});
<asp:Label ID="lblEmail" runat="server" CssClass="labelclass"></asp:Label>
function GetClientID(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
A:
AJAX call will update control text in client side only. If you want to change label's text after post back , bind the changed value again to the control while page posts back. Like you can call function which binds changed value to label in postback event OR in page load wherever seems fit.
|
[
"physics.stackexchange",
"0000384245.txt"
] | Q:
How can we understand acceleration direction (positive or negative)?
I am studying motion in one dimension. I am having hard time to determine acceleration either positive or negative. How can I understand this?
For example in this question I thought accelaration was positive but it is negative so my answer was wrong.
A tennis ball is tossed upward with a speed of 3.0 m/s
We can ignore air resistance.
What is the velocity of the ball 0.40 s after the toss?
t = 0.40 s
V0 = 3.0 m/s
v= ?
a= 9.81 m/s^2 but it should be -9.81 but why?
A:
Once you fix the direction of the vertical axis, you fix the sign of the acceleration. In your example, you chose “up” to be positive since your velocity is $+3m/s$ for the ball going up. As gravity acts “down”, it means $g$ must be negative, i.e. $-9.8$.
The confusion occurs because in some problems it’s more convenient to define the vertical axis to point “down”.
|
[
"stackoverflow",
"0025502651.txt"
] | Q:
HTTP status code for an effectless request
I'm designing a small RESTfull API for a media player and encoder. There you can start, pause and stop a stream or recording.
Lets assume the service is idle - theres no encoding activity. Now the client sends a request to the service like
POST media.box/api/stream
action=stop
This obviously has no effect at the server side but the client should be noticed that theres something wrong with the request.
What HTTP status code is the most suitable for this case?
A:
If you feel that that is an error condition, you should consider returning 422 (Unprocessable Entity). It indicates that the request was received, but a semantic error in the request prevented it from being executed.
The other school of thought is that no-op requests like "stop everything!" when nothing is running should just say "Ok! Nothing is running anymore." and return gracefully. You'll have to decide which is right for your API.
|
[
"tex.stackexchange",
"0000538210.txt"
] | Q:
Adjust angle length in MetaPost
I'm making some triangles in ConTeXt using Metafun's anglebetween macro. However, some angles look awful, specially if they're larger.
\starttext
\startuseMPgraphic{name}
u := 4cm;
pair A, B, C, D, P;
path AB, BC, AC, BD, BP;
A = (0,0); C = (cosd 50 + cosd 80, 0)*u; B = (cosd 80, sind 80)*u;
P = (cosd 80, 0)*(u); D = P*2;
AB = A -- B; AC = A -- C; BC = B -- C;
BD = B -- D; BP = B -- P;
draw AB; draw BC; draw AC;
draw BD; draw BP;
draw anglebetween(A--B, A--C, "$8x$");
draw anglebetween(C--B, C--A, "$5x$");
draw anglebetween(B--D, B--A, "$2x$");
label.llft("{\tfx\ss A}", A);
label.urt("{\tfx\ss B}", B);
label.lrt("{\tfx\ss C}", C);
label.bot("{\tfx\ss P}", P);
label.bot("{\tfx\ss D}", D);
\stopuseMPgraphic
\useMPgraphic{name}
\stoptext
As readily seen, angles labelled 8x and 5x look too large. scaled gives weird results. How do I adjust angles so they have a smaller radius?
A:
Here's how you could do it using just the plain MP facilities. By "doing it yourself" you get the flexibility to adjust the arc sizes appropriately.
\starttext
\startuseMPgraphic{name}
pair A, B, C, D, P;
A = origin;
B = 6cm * dir 80;
ypart C = 0;
B - C = whatever * dir 130;
P = (xpart B, ypart A);
D = A reflectedabout(P, B);
path arc[];
arc1 = fullcircle rotated angle (C-A) scaled 21 shifted A cutafter (A--B);
arc2 = fullcircle rotated angle (B-C) scaled 32 shifted C cutafter (C--A);
arc3 = fullcircle rotated angle (A-B) scaled 42 shifted B cutafter (B--D);
drawoptions(withcolor 2/3 red);
draw arc1; label.urt("$8x$", point 1 of arc1);
draw arc2; label.ulft("$5x$", point 0.7 of arc2);
draw arc3; label.lft("$2x$", point 0 of arc3);
drawoptions();
draw A -- B -- C -- cycle;
draw P -- B -- D;
label.llft("{\tfx\ss A}", A);
label.top("{\tfx\ss B}", B);
label.lrt("{\tfx\ss C}", C);
label.bot("{\tfx\ss P}", P);
label.bot("{\tfx\ss D}", D);
\stopuseMPgraphic
\useMPgraphic{name}
\stoptext
|
[
"stackoverflow",
"0013066427.txt"
] | Q:
RequireJS and JS Module Pattern
I currently working on a Javascript application that's using multiple javascript file with a "module pattern".
Like so:
var app = app || {};
app.moduleName = app.moduleName || {};
app.moduleName = function () {
// private property
var someProp = null;
return {
// public method
init: function () {
return "foo";
}
};
}();
The reason why im using this is to structurize my code. I can call a method or property by just calling app.moduleName.init() for example.
One downside of this is that I must include lots of <script src="app.moduleName.js">.. etc in my HTML.
To solve this problem, I came across RequireJS, I read the documentation. But I'm not quite sure how to merge this in my existing structure, without adding bunch of code to the existing javascript files.
Does somebody have any suggestion how to accomplish this?
A:
You can build up your module tree like this with require.js.
// in main.js
require.config({/*...*/});
require(
['app'],
function (app) {
// build up a globally accessible module tree
window.app = app;
var foo = window.app.moduleName.init(); // returns "foo"
}
);
// in app.js
define(
['moduleName'],
function(moduleName){
return {
moduleName: moduleName;
}
}
);
// in moduleName.js
define(function(){
// private property
var someProp = "foo";
return {
// public method
init: function () {
return someProp;
}
}
});
However, with require.js you can build up your app without a global module tree like this... even if you easily can. You can access all parts of your module individually just be requiring them. Whatever you return in the define/require callback will be stored as a reference by require.js. That's something important to know. So it's possible to include a script twice in your application and have the same object or instance. For example if you include a module like this
// in SomeClass.js
define(function () {
function SomeClass() {
this.myValue = true;
}
return new SomeClass();
});
// app.js
define(
['SomeClass', 'someComponent'],
function (SomeClass, someComponent) {
return {
init: function () {
SomeClass.myValue = false;
someComponent.returnClassValue(); // logs false
}
};
}
);
// someComponent.js
define(
['SomeClass'],
function (SomeClass) {
return {
returnClassValue: function () {
console.log(SomeClass.myValue); // false
}
};
}
);
The value of SomeClass.myValue will be the same in all including modules...
|
[
"stackoverflow",
"0061507210.txt"
] | Q:
Error on running pod install --repo-update after installing Firebase
I try to install Firebase in a react native app but i keep getting errors when I run pod install --repo-update.
This is the error:
[!] CocoaPods could not find compatible versions for pod "Firebase/Core":
In snapshot (Podfile.lock):
Firebase/Core (= 6.22.0)
In Podfile:
RNFBApp (from `../node_modules/@react-native-firebase/app`) was resolved to 6.7.1, which depends on
Firebase/Core (~> 6.13.0)
You have either:
* changed the constraints of dependency `Firebase/Core` inside your development pod `RNFBApp`.
You should run `pod update Firebase/Core` to apply changes you've made.
I searched similar problem resolutions and I already tried replacing Firebase/Core with - FirebaseCore (~> 6.6) but that didn't help.
This is my podfile:
PODS:
- boost-for-react-native (1.63.0)
- CocoaAsyncSocket (7.6.4)
- CocoaLibEvent (1.0.0)
- DoubleConversion (1.1.6)
- FBLazyVector (0.62.2)
- FBReactNativeSpec (0.62.2):
- Folly (= 2018.10.22.00)
- RCTRequired (= 0.62.2)
- RCTTypeSafety (= 0.62.2)
- React-Core (= 0.62.2)
- React-jsi (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- Firebase/Analytics (6.22.0):
- Firebase/Core
- Firebase/Core (6.22.0):
- Firebase/CoreOnly
- FirebaseAnalytics (= 6.4.1)
- Firebase/CoreOnly (6.22.0):
- FirebaseCore (= 6.6.6)
- FirebaseAnalytics (6.4.1):
- FirebaseCore (~> 6.6)
- FirebaseInstallations (~> 1.1)
- GoogleAppMeasurement (= 6.4.1)
- GoogleUtilities/AppDelegateSwizzler (~> 6.0)
- GoogleUtilities/MethodSwizzler (~> 6.0)
- GoogleUtilities/Network (~> 6.0)
- "GoogleUtilities/NSData+zlib (~> 6.0)"
- nanopb (= 0.3.9011)
- FirebaseCore (6.6.6):
- FirebaseCoreDiagnostics (~> 1.2)
- FirebaseCoreDiagnosticsInterop (~> 1.2)
- GoogleUtilities/Environment (~> 6.5)
- GoogleUtilities/Logger (~> 6.5)
- FirebaseCoreDiagnostics (1.2.3):
- FirebaseCoreDiagnosticsInterop (~> 1.2)
- GoogleDataTransportCCTSupport (~> 2.0)
- GoogleUtilities/Environment (~> 6.5)
- GoogleUtilities/Logger (~> 6.5)
- nanopb (~> 0.3.901)
- FirebaseCoreDiagnosticsInterop (1.2.0)
- FirebaseInstallations (1.1.1):
- FirebaseCore (~> 6.6)
- GoogleUtilities/UserDefaults (~> 6.5)
- PromisesObjC (~> 1.2)
- Flipper (0.33.1):
- Flipper-Folly (~> 2.1)
- Flipper-RSocket (~> 1.0)
- Flipper-DoubleConversion (1.1.7)
- Flipper-Folly (2.2.0):
- boost-for-react-native
- CocoaLibEvent (~> 1.0)
- Flipper-DoubleConversion
- Flipper-Glog
- OpenSSL-Universal (= 1.0.2.19)
- Flipper-Glog (0.3.6)
- Flipper-PeerTalk (0.0.4)
- Flipper-RSocket (1.1.0):
- Flipper-Folly (~> 2.2)
- FlipperKit (0.33.1):
- FlipperKit/Core (= 0.33.1)
- FlipperKit/Core (0.33.1):
- Flipper (~> 0.33.1)
- FlipperKit/CppBridge
- FlipperKit/FBCxxFollyDynamicConvert
- FlipperKit/FBDefines
- FlipperKit/FKPortForwarding
- FlipperKit/CppBridge (0.33.1):
- Flipper (~> 0.33.1)
- FlipperKit/FBCxxFollyDynamicConvert (0.33.1):
- Flipper-Folly (~> 2.1)
- FlipperKit/FBDefines (0.33.1)
- FlipperKit/FKPortForwarding (0.33.1):
- CocoaAsyncSocket (~> 7.6)
- Flipper-PeerTalk (~> 0.0.4)
- FlipperKit/FlipperKitHighlightOverlay (0.33.1)
- FlipperKit/FlipperKitLayoutPlugin (0.33.1):
- FlipperKit/Core
- FlipperKit/FlipperKitHighlightOverlay
- FlipperKit/FlipperKitLayoutTextSearchable
- YogaKit (~> 1.18)
- FlipperKit/FlipperKitLayoutTextSearchable (0.33.1)
- FlipperKit/FlipperKitNetworkPlugin (0.33.1):
- FlipperKit/Core
- FlipperKit/FlipperKitReactPlugin (0.33.1):
- FlipperKit/Core
- FlipperKit/FlipperKitUserDefaultsPlugin (0.33.1):
- FlipperKit/Core
- FlipperKit/SKIOSNetworkPlugin (0.33.1):
- FlipperKit/Core
- FlipperKit/FlipperKitNetworkPlugin
- Folly (2018.10.22.00):
- boost-for-react-native
- DoubleConversion
- Folly/Default (= 2018.10.22.00)
- glog
- Folly/Default (2018.10.22.00):
- boost-for-react-native
- DoubleConversion
- glog
- glog (0.3.5)
- GoogleAppMeasurement (6.4.1):
- GoogleUtilities/AppDelegateSwizzler (~> 6.0)
- GoogleUtilities/MethodSwizzler (~> 6.0)
- GoogleUtilities/Network (~> 6.0)
- "GoogleUtilities/NSData+zlib (~> 6.0)"
- nanopb (= 0.3.9011)
- GoogleDataTransport (5.1.1)
- GoogleDataTransportCCTSupport (2.0.3):
- GoogleDataTransport (~> 5.1)
- nanopb (~> 0.3.901)
- GoogleUtilities/AppDelegateSwizzler (6.5.2):
- GoogleUtilities/Environment
- GoogleUtilities/Logger
- GoogleUtilities/Network
- GoogleUtilities/Environment (6.5.2)
- GoogleUtilities/Logger (6.5.2):
- GoogleUtilities/Environment
- GoogleUtilities/MethodSwizzler (6.5.2):
- GoogleUtilities/Logger
- GoogleUtilities/Network (6.5.2):
- GoogleUtilities/Logger
- "GoogleUtilities/NSData+zlib"
- GoogleUtilities/Reachability
- "GoogleUtilities/NSData+zlib (6.5.2)"
- GoogleUtilities/Reachability (6.5.2):
- GoogleUtilities/Logger
- GoogleUtilities/UserDefaults (6.5.2):
- GoogleUtilities/Logger
- nanopb (0.3.9011):
- nanopb/decode (= 0.3.9011)
- nanopb/encode (= 0.3.9011)
- nanopb/decode (0.3.9011)
- nanopb/encode (0.3.9011)
- OpenSSL-Universal (1.0.2.19):
- OpenSSL-Universal/Static (= 1.0.2.19)
- OpenSSL-Universal/Static (1.0.2.19)
- PromisesObjC (1.2.8)
- RCTRequired (0.62.2)
- RCTTypeSafety (0.62.2):
- FBLazyVector (= 0.62.2)
- Folly (= 2018.10.22.00)
- RCTRequired (= 0.62.2)
- React-Core (= 0.62.2)
- React (0.62.2):
- React-Core (= 0.62.2)
- React-Core/DevSupport (= 0.62.2)
- React-Core/RCTWebSocket (= 0.62.2)
- React-RCTActionSheet (= 0.62.2)
- React-RCTAnimation (= 0.62.2)
- React-RCTBlob (= 0.62.2)
- React-RCTImage (= 0.62.2)
- React-RCTLinking (= 0.62.2)
- React-RCTNetwork (= 0.62.2)
- React-RCTSettings (= 0.62.2)
- React-RCTText (= 0.62.2)
- React-RCTVibration (= 0.62.2)
- React-Core (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default (= 0.62.2)
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/CoreModulesHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/Default (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/DevSupport (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default (= 0.62.2)
- React-Core/RCTWebSocket (= 0.62.2)
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- React-jsinspector (= 0.62.2)
- Yoga
- React-Core/RCTActionSheetHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTAnimationHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTBlobHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTImageHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTLinkingHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTNetworkHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTSettingsHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTTextHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTVibrationHeaders (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-Core/RCTWebSocket (0.62.2):
- Folly (= 2018.10.22.00)
- glog
- React-Core/Default (= 0.62.2)
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsiexecutor (= 0.62.2)
- Yoga
- React-CoreModules (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- RCTTypeSafety (= 0.62.2)
- React-Core/CoreModulesHeaders (= 0.62.2)
- React-RCTImage (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-cxxreact (0.62.2):
- boost-for-react-native (= 1.63.0)
- DoubleConversion
- Folly (= 2018.10.22.00)
- glog
- React-jsinspector (= 0.62.2)
- React-jsi (0.62.2):
- boost-for-react-native (= 1.63.0)
- DoubleConversion
- Folly (= 2018.10.22.00)
- glog
- React-jsi/Default (= 0.62.2)
- React-jsi/Default (0.62.2):
- boost-for-react-native (= 1.63.0)
- DoubleConversion
- Folly (= 2018.10.22.00)
- glog
- React-jsiexecutor (0.62.2):
- DoubleConversion
- Folly (= 2018.10.22.00)
- glog
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- React-jsinspector (0.62.2)
- react-native-safe-area-context (0.7.3):
- React
- React-RCTActionSheet (0.62.2):
- React-Core/RCTActionSheetHeaders (= 0.62.2)
- React-RCTAnimation (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- RCTTypeSafety (= 0.62.2)
- React-Core/RCTAnimationHeaders (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-RCTBlob (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- React-Core/RCTBlobHeaders (= 0.62.2)
- React-Core/RCTWebSocket (= 0.62.2)
- React-jsi (= 0.62.2)
- React-RCTNetwork (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-RCTImage (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- RCTTypeSafety (= 0.62.2)
- React-Core/RCTImageHeaders (= 0.62.2)
- React-RCTNetwork (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-RCTLinking (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- React-Core/RCTLinkingHeaders (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-RCTNetwork (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- RCTTypeSafety (= 0.62.2)
- React-Core/RCTNetworkHeaders (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-RCTSettings (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- RCTTypeSafety (= 0.62.2)
- React-Core/RCTSettingsHeaders (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- React-RCTText (0.62.2):
- React-Core/RCTTextHeaders (= 0.62.2)
- React-RCTVibration (0.62.2):
- FBReactNativeSpec (= 0.62.2)
- Folly (= 2018.10.22.00)
- React-Core/RCTVibrationHeaders (= 0.62.2)
- ReactCommon/turbomodule/core (= 0.62.2)
- ReactCommon/callinvoker (0.62.2):
- DoubleConversion
- Folly (= 2018.10.22.00)
- glog
- React-cxxreact (= 0.62.2)
- ReactCommon/turbomodule/core (0.62.2):
- DoubleConversion
- Folly (= 2018.10.22.00)
- glog
- React-Core (= 0.62.2)
- React-cxxreact (= 0.62.2)
- React-jsi (= 0.62.2)
- ReactCommon/callinvoker (= 0.62.2)
- RNCMaskedView (0.1.9):
- React
- RNGestureHandler (1.6.1):
- React
- RNReanimated (1.8.0):
- React
- RNScreens (2.5.0):
- React
- Yoga (1.14.0)
- YogaKit (1.18.1):
- Yoga (~> 1.14)
DEPENDENCIES:
- DoubleConversion (from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`)
- FBLazyVector (from `../node_modules/react-native/Libraries/FBLazyVector`)
- FBReactNativeSpec (from `../node_modules/react-native/Libraries/FBReactNativeSpec`)
- Firebase/Analytics
- Flipper (~> 0.33.1)
- Flipper-DoubleConversion (= 1.1.7)
- Flipper-Folly (~> 2.1)
- Flipper-Glog (= 0.3.6)
- Flipper-PeerTalk (~> 0.0.4)
- Flipper-RSocket (~> 1.0)
- FlipperKit (~> 0.33.1)
- FlipperKit/Core (~> 0.33.1)
- FlipperKit/CppBridge (~> 0.33.1)
- FlipperKit/FBCxxFollyDynamicConvert (~> 0.33.1)
- FlipperKit/FBDefines (~> 0.33.1)
- FlipperKit/FKPortForwarding (~> 0.33.1)
- FlipperKit/FlipperKitHighlightOverlay (~> 0.33.1)
- FlipperKit/FlipperKitLayoutPlugin (~> 0.33.1)
- FlipperKit/FlipperKitLayoutTextSearchable (~> 0.33.1)
- FlipperKit/FlipperKitNetworkPlugin (~> 0.33.1)
- FlipperKit/FlipperKitReactPlugin (~> 0.33.1)
- FlipperKit/FlipperKitUserDefaultsPlugin (~> 0.33.1)
- FlipperKit/SKIOSNetworkPlugin (~> 0.33.1)
- Folly (from `../node_modules/react-native/third-party-podspecs/Folly.podspec`)
- glog (from `../node_modules/react-native/third-party-podspecs/glog.podspec`)
- RCTRequired (from `../node_modules/react-native/Libraries/RCTRequired`)
- RCTTypeSafety (from `../node_modules/react-native/Libraries/TypeSafety`)
- React (from `../node_modules/react-native/`)
- React-Core (from `../node_modules/react-native/`)
- React-Core/DevSupport (from `../node_modules/react-native/`)
- React-Core/RCTWebSocket (from `../node_modules/react-native/`)
- React-CoreModules (from `../node_modules/react-native/React/CoreModules`)
- React-cxxreact (from `../node_modules/react-native/ReactCommon/cxxreact`)
- React-jsi (from `../node_modules/react-native/ReactCommon/jsi`)
- React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`)
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)
- React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`)
- React-RCTAnimation (from `../node_modules/react-native/Libraries/NativeAnimation`)
- React-RCTBlob (from `../node_modules/react-native/Libraries/Blob`)
- React-RCTImage (from `../node_modules/react-native/Libraries/Image`)
- React-RCTLinking (from `../node_modules/react-native/Libraries/LinkingIOS`)
- React-RCTNetwork (from `../node_modules/react-native/Libraries/Network`)
- React-RCTSettings (from `../node_modules/react-native/Libraries/Settings`)
- React-RCTText (from `../node_modules/react-native/Libraries/Text`)
- React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`)
- ReactCommon/callinvoker (from `../node_modules/react-native/ReactCommon`)
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
- "RNCMaskedView (from `../node_modules/@react-native-community/masked-view`)"
- RNGestureHandler (from `../node_modules/react-native-gesture-handler`)
- RNReanimated (from `../node_modules/react-native-reanimated`)
- RNScreens (from `../node_modules/react-native-screens`)
- Yoga (from `../node_modules/react-native/ReactCommon/yoga`)
SPEC REPOS:
trunk:
- boost-for-react-native
- CocoaAsyncSocket
- CocoaLibEvent
- Firebase
- FirebaseAnalytics
- FirebaseCore
- FirebaseCoreDiagnostics
- FirebaseCoreDiagnosticsInterop
- FirebaseInstallations
- Flipper
- Flipper-DoubleConversion
- Flipper-Folly
- Flipper-Glog
- Flipper-PeerTalk
- Flipper-RSocket
- FlipperKit
- GoogleAppMeasurement
- GoogleDataTransport
- GoogleDataTransportCCTSupport
- GoogleUtilities
- nanopb
- OpenSSL-Universal
- PromisesObjC
- YogaKit
EXTERNAL SOURCES:
DoubleConversion:
:podspec: "../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec"
FBLazyVector:
:path: "../node_modules/react-native/Libraries/FBLazyVector"
FBReactNativeSpec:
:path: "../node_modules/react-native/Libraries/FBReactNativeSpec"
Folly:
:podspec: "../node_modules/react-native/third-party-podspecs/Folly.podspec"
glog:
:podspec: "../node_modules/react-native/third-party-podspecs/glog.podspec"
RCTRequired:
:path: "../node_modules/react-native/Libraries/RCTRequired"
RCTTypeSafety:
:path: "../node_modules/react-native/Libraries/TypeSafety"
React:
:path: "../node_modules/react-native/"
React-Core:
:path: "../node_modules/react-native/"
React-CoreModules:
:path: "../node_modules/react-native/React/CoreModules"
React-cxxreact:
:path: "../node_modules/react-native/ReactCommon/cxxreact"
React-jsi:
:path: "../node_modules/react-native/ReactCommon/jsi"
React-jsiexecutor:
:path: "../node_modules/react-native/ReactCommon/jsiexecutor"
React-jsinspector:
:path: "../node_modules/react-native/ReactCommon/jsinspector"
react-native-safe-area-context:
:path: "../node_modules/react-native-safe-area-context"
React-RCTActionSheet:
:path: "../node_modules/react-native/Libraries/ActionSheetIOS"
React-RCTAnimation:
:path: "../node_modules/react-native/Libraries/NativeAnimation"
React-RCTBlob:
:path: "../node_modules/react-native/Libraries/Blob"
React-RCTImage:
:path: "../node_modules/react-native/Libraries/Image"
React-RCTLinking:
:path: "../node_modules/react-native/Libraries/LinkingIOS"
React-RCTNetwork:
:path: "../node_modules/react-native/Libraries/Network"
React-RCTSettings:
:path: "../node_modules/react-native/Libraries/Settings"
React-RCTText:
:path: "../node_modules/react-native/Libraries/Text"
React-RCTVibration:
:path: "../node_modules/react-native/Libraries/Vibration"
ReactCommon:
:path: "../node_modules/react-native/ReactCommon"
RNCMaskedView:
:path: "../node_modules/@react-native-community/masked-view"
RNGestureHandler:
:path: "../node_modules/react-native-gesture-handler"
RNReanimated:
:path: "../node_modules/react-native-reanimated"
RNScreens:
:path: "../node_modules/react-native-screens"
Yoga:
:path: "../node_modules/react-native/ReactCommon/yoga"
SPEC CHECKSUMS:
boost-for-react-native: 39c7adb57c4e60d6c5479dd8623128eb5b3f0f2c
CocoaAsyncSocket: 694058e7c0ed05a9e217d1b3c7ded962f4180845
CocoaLibEvent: 2fab71b8bd46dd33ddb959f7928ec5909f838e3f
DoubleConversion: 5805e889d232975c086db112ece9ed034df7a0b2
FBLazyVector: 4aab18c93cd9546e4bfed752b4084585eca8b245
FBReactNativeSpec: 5465d51ccfeecb7faa12f9ae0024f2044ce4044e
Firebase: 32f9520684e87c7af3f0704f7f88042626d6b536
FirebaseAnalytics: 83f822fd0d33a46f49f89b8c3ab16ab4d89df08a
FirebaseCore: 9aca0f1fffb405176ba15311a5621fcde4106fcf
FirebaseCoreDiagnostics: 13a6564cd6d5375066bbc8940cc1753af24497f3
FirebaseCoreDiagnosticsInterop: 296e2c5f5314500a850ad0b83e9e7c10b011a850
FirebaseInstallations: acb3216eb9784d3b1d2d2d635ff74fa892cc0c44
Flipper: 6c1f484f9a88d30ab3e272800d53688439e50f69
Flipper-DoubleConversion: 38631e41ef4f9b12861c67d17cb5518d06badc41
Flipper-Folly: c12092ea368353b58e992843a990a3225d4533c3
Flipper-Glog: 1dfd6abf1e922806c52ceb8701a3599a79a200a6
Flipper-PeerTalk: 116d8f857dc6ef55c7a5a75ea3ceaafe878aadc9
Flipper-RSocket: 64e7431a55835eb953b0bf984ef3b90ae9fdddd7
FlipperKit: 6dc9b8f4ef60d9e5ded7f0264db299c91f18832e
Folly: 30e7936e1c45c08d884aa59369ed951a8e68cf51
glog: 1f3da668190260b06b429bb211bfbee5cd790c28
GoogleAppMeasurement: e49be3954045b17d046f271b9cc1ec052bad9702
GoogleDataTransport: 6ffa4dd0b6d547f8d27b91bd92fa9e197a3f5f1f
GoogleDataTransportCCTSupport: 2d7e609f8c5af1a33d7d59053e6f8cba59365df5
GoogleUtilities: ad0f3b691c67909d03a3327cc205222ab8f42e0e
nanopb: 18003b5e52dab79db540fe93fe9579f399bd1ccd
OpenSSL-Universal: 8b48cc0d10c1b2923617dfe5c178aa9ed2689355
PromisesObjC: c119f3cd559f50b7ae681fa59dc1acd19173b7e6
RCTRequired: cec6a34b3ac8a9915c37e7e4ad3aa74726ce4035
RCTTypeSafety: 93006131180074cffa227a1075802c89a49dd4ce
React: 29a8b1a02bd764fb7644ef04019270849b9a7ac3
React-Core: b12bffb3f567fdf99510acb716ef1abd426e0e05
React-CoreModules: 4a9b87bbe669d6c3173c0132c3328e3b000783d0
React-cxxreact: e65f9c2ba0ac5be946f53548c1aaaee5873a8103
React-jsi: b6dc94a6a12ff98e8877287a0b7620d365201161
React-jsiexecutor: 1540d1c01bb493ae3124ed83351b1b6a155db7da
React-jsinspector: 512e560d0e985d0e8c479a54a4e5c147a9c83493
react-native-safe-area-context: 8260e5157617df4b72865f44006797f895b2ada7
React-RCTActionSheet: f41ea8a811aac770e0cc6e0ad6b270c644ea8b7c
React-RCTAnimation: 49ab98b1c1ff4445148b72a3d61554138565bad0
React-RCTBlob: a332773f0ebc413a0ce85942a55b064471587a71
React-RCTImage: e70be9b9c74fe4e42d0005f42cace7981c994ac3
React-RCTLinking: c1b9739a88d56ecbec23b7f63650e44672ab2ad2
React-RCTNetwork: 73138b6f45e5a2768ad93f3d57873c2a18d14b44
React-RCTSettings: 6e3738a87e21b39a8cb08d627e68c44acf1e325a
React-RCTText: fae545b10cfdb3d247c36c56f61a94cfd6dba41d
React-RCTVibration: 4356114dbcba4ce66991096e51a66e61eda51256
ReactCommon: ed4e11d27609d571e7eee8b65548efc191116eb3
RNCMaskedView: 5dba3cb07493765fb66156c83c3dd281ca709a48
RNGestureHandler: 8f09cd560f8d533eb36da5a6c5a843af9f056b38
RNReanimated: 955cf4068714003d2f1a6e2bae3fb1118f359aff
RNScreens: ac02d0e4529f08ced69f5580d416f968a6ec3a1d
Yoga: 3ebccbdd559724312790e7742142d062476b698e
YogaKit: f782866e155069a2cca2517aafea43200b01fd5a
PODFILE CHECKSUM: ddc7d6c9cac170925f68656e3217289426c07041
COCOAPODS: 1.9.1
Thanks for your help!
Tim
A:
Run pod update Firebase/Core, and repeat for every problematic dependency.
The problem here is that the previously installed version of Firebase’s iOS library is different from the version that is required by the Native Module. The pod install command never updates Pods from versions listed in the lockfile.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.