text:
Q: Why can only analog signals pass through air (wireless channel)? I read the following in a book:

"When the transmitted signal is passed through the air using electromagnetic waves, it must take the form of a continuous (analog) waveform."

Why is this so? Why can't the signal take the form of a digital waveform?

A: Digital signals are an abstraction that humans use to describe and understand things by omitting information that we are not interested in.
For example, consider the following:
1001010101000101010
Is that a digital signal or an analog one? If you only care about the pattern of ones and zeroes, then it's a digital signal. But the actual physical thing you are looking at is entirely analog because each digit is in a slightly different physical position and has a slightly different level of brightness and so on.
There might be exceptions in quantum mechanics, but that's not relevant here.

A: Consider an electromagnetic channel such that you can send and receive, say, voltage within -5 V and +5 V (wire, radio with different modulations, etc.) If you give different relevance to all voltage levels within this range (e.g. to operate a speaker) then you are in an analog regime. If you choose two voltage intervals, say (-4, -2) and (2, 4), and you only care if the voltage falls within one or the other — into one could mean "0" and into the other could mean "1", otherwise it would mean nothing — then you are in a digital regime.

A: Adding to Tom's answer:
The wording is not very clear, but what this means is that digital signals do not actually exist in reality. All signals are analog.
When we decide that a voltage above a certain threshold is a "1", a voltage below a certain threshold is a "0", and the space in between is "undefined", then we interpret an analog signal as a digital value. However, it is only a very convenient approximation that greatly simplifies the job of the designer.
Digital is abstract information. It is a meaning we choose to assign to physical values. This is why you cannot send a digital signal over the air as radio waves. It must be converted first into something that exists outside of abstraction, like an analog signal which represents the information to be transmitted.
The real signal is made of physical analog values: voltage, light, current, fields, acoustic pressure, whatever.
For your radio application, you could encode your digital bits into the frequency of a carrier, or its phase, or any other encoding, of which they are many. Now, you have an analog signal which carries your information, and you can transmit it, then receive it and recover your bits.

A: The important take away point is that you need a continuous waveform if you are using electromagnetic waves. That is not to say you can't have a signal which represents digital data, just that the signal itself must be continuous.
Consider a square wave, or even a sequence of binary voltages (1 0 1 1 0 etc.). If you take the FFT of such a signal you will find that it has spectral content over an infinite bandwidth. In other words, to produce a perfect step change you need a channel with infinite bandwidth.
There is no such thing as a channel with infinite bandwidth. In the case of sending electromagnetic wave based signals wirelessly we have a massive limitation on bandwidth which prevents a non-continuous waveform (i.e. ones with step changes) being sent.
However just because you can't send a signal which is non-continuous, doesn't mean you can't send a signal which represents one. All of the digital modulation schemes do just that. OOK is the most basic example - a zero is represented by no signal, a one is represented by a simple tone.

A: Electromagnetic waves, or signals that pass through space or air, exist due to the energy exchange between the electric-wave and the magnetic-wave.
This energy exchange happens at a fixed frequency, or colour for light-waves.  The frequency is determined by the source radiating the energy.
Waves of different frequencies can be mixed, but they exist as separate colours that cannot be changed as they trave through space.  This is why white sunlight can be seperated into the colours in the rainbow.


text:
Q: Display WordPress on example.com/blog/ and m.example.com/blog/ I'm looking to display the same WordPress blog on a mobile subdomain and the main domain in a subfolder. This would look like the following:

*

*example.com/blog/ (with main theme and customisations)

*m.example.com/blog/ (with mobile theme and customisations)

However, is this possible or do I need to install a separate blog and duplicate content onto the mobile blog from the main blog?
PS - This is a test environment at this stage, and I will handle user-agent switching and SEO duplicate content considerations.

A: This is doable but you there's no simple unobtrusive solution.
There is ONE simple way to do this. Hack the core, find wp_set_wpdb_vars() in wp-includes/load.php and right after $prefix = $wpdb->set_prefix( $table_prefix ); add this:
if($_SERVER['SERVER_NAME'] == 'm.domain.tld'){
    $wpdb->options = "mobile_{$wpdb->options}";
    $wpdb->postmeta = "mobile_{$wpdb->postmeta}";
    $wpdb->commentmeta = "mobile_{$wpdb->commentmeta}";
}else{
    $wpdb->options = "mobiless_{$wpdb->options}";
    $wpdb->postmeta = "mobiless_{$wpdb->postmeta}";
    $wpdb->commentmeta = "mobiless_{$wpdb->commentmeta}";
}

This trick will sandbox options and metas into two different sets of tables. This way they will not overwrite but if you use different settings for plugins installed. You can just sandbox the options table if you have control over plugins and prevent settings collision.
In your wp-config.php you will need to do this:
if($_SERVER['SERVER_NAME'] == 'm.domain.tld'){
    require_once(dirname(__FILE__).'/wp-config-mobile.php');
}else{
    require_once(dirname(__FILE__).'/wp-config-mobiless.php');
}

Both must have same settings (dbname, prefix) except WP_SITEURL and WP_HOME. You can use one file if you don't hard define WP_HOME and WP_SITEURL in the wp-config.php.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closed Pipe error while doing sftp in vm using docker I have a dockerized container of camel router which does sftp from remote host to VM local folder.  If I just run my code in VM in conventional way (ie java -jar my-sftp-camel-router.jar), it downloads all 5000 files. However, when I run the same as docker image using docker run -P /tmp/:/tmp/ my-sftp-camel-router-image  it fails after downloading around 12 files.
Both cases works fine in my local machine, but not on VM.
org.apache.camel.component.file.GenericFileOperationFailedException: Cannot change directory to: /
at org.apache.camel.component.file.remote.SftpOperations.doChangeDirectory(SftpOperations.java:576)
at org.apache.camel.component.file.remote.SftpOperations.changeCurrentDirectory(SftpOperations.java:533)
at org.apache.camel.component.file.remote.SftpOperations.buildDirectory(SftpOperations.java:472)
at org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport.renameFile(GenericFileProcessStrategySupport.java:106)
at org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.begin(GenericFileRenameProcessStrategy.java:43)
at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:367)
at org.apache.camel.component.file.remote.RemoteFileConsumer.processExchange(RemoteFileConsumer.java:137)
at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:226)
at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:190)
at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:175)
at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:102)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: 4:
at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:359)
at org.apache.camel.component.file.remote.SftpOperations.doChangeDirectory(SftpOperations.java:574)
... 17 more
Caused by: java.io.IOException: Pipe closed
at java.io.PipedInputStream.read(PipedInputStream.java:307)
at java.io.PipedInputStream.read(PipedInputStream.java:377)
at com.jcraft.jsch.ChannelSftp.fill(ChannelSftp.java:2882)
at com.jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2908)
at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2328)
at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:342)
... 18 more


text:
Q: ordering foreach loop in results Hello I am looking to order my foreach loop.
The information I have found on the top use arrays and since I am using the get_term function, I am unsure how to add an order command.
this is my code, from what i have read online i should be able to use 'Orderby' => 'count' 'order' => 'DESC' but when I add that in nothing happens.

Popular Categories

          <?php
          $terms = get_terms('category'); /*Name Of category*/
           foreach (array_slice($terms, 0, 5)  as $term ):
           ?>

           <?php echo $term->name ;?>   (<?php echo $term->count ;?>)

           <?php
          endforeach;
          wp_reset_query();
           ?>

I read that I might have to create another array. Thank you for your time.

A: WordPress allows you to order the result directly in the WP_Query. Just pass an array to the get_terms() function and you should get what you want:
$args = array(
   'orderby'  => 'id',
   'order'    => 'DESC'
);
get_terms('category', $args);

Replace the orderby with the row you want it to order by.


text:
Q: Regex matches but sed fails replace I am having a tricky regex issue
I have the string like below
some_Name   _  _Bday Date Comm.txt

And here is my regex to match the spaces and underscore
\_?\s\_?

Now when i try to replace the string using sed and the above regex

echo "some_Name   _  _Bday Date Comm.txt" | sed 's/\_?\s\_?/\_/g'

The output i want is
some_Name_Bday_Date_Comm.txt

Any ideas on how do i go about this ?

A: You are using a POSIX BRE regex engine with the \_?\s\_? pattern that matches a _?, a whitespace (if your sed supports \s shorthand) an a _? substring, i.e. the ? are treated as literal question mark symbols.
You may use
sed -E 's/[[:space:]_]+/_/g'
sed 's/[[:space:]_]\{1,\}/_/g'

See online sed demo
The [[:space:]_]+ POSIX ERE pattern (enabled with -E option) will match one or more whitespace or underscore characters.
The POSIX ERE + quantifier can be written as \{1,\} in POSIX BRE. Also, if you use a GNU sed, you may use \+ in the second sed command.

A: This might work for you (GNU sed):
sed -E 's/\s(\s*_)*/_/g' file

This will replace a space followed by zero or more of the following: zero or more spaces followed by an underscore.


text:
Q: Algorithm for Least Edge Intersections (Before anyone asks, it's not homework.)
Say you have 2 Arrays y0 and y1 where
y0 = [1,2,3,4,5,6] and
y1 = [2,1,6,3,4,5]
Notice y0[0] = y1[1] = 1, it essentially means y0[0] is connected to y1[1]. Similarly, y0[2] = y1[3] = 3 so they are "connected" as well.
(Image courtesy : belisarius)
Each element in one array has a corresponding entry in the second array. Imagine each element in the array as a vertex, and these connections as Edges being drawn from one array to the other.
I need to find a set of edges (of maximum size) such that none of the "edges" (or lines) will intersect.
In the above example, notice,

*

*Edge 1 and Edge 2 will intersect.

*Edge 6  will intersect with  Edge 3, Edge 4, Edge 5.

Therefore, the solution can be be 1,3,4,5 or 2,3,4,5 (size = 4) since none of those lines will intersect each other. There can be multiple solutions, but I need just one.
My Question, Is there any known CS Problem that resembles this? What algorithm should i be using?
I've tried to explain my problem with an example, however, incase it's still not clear i'll clarify any queries.
Thanks in advance.

A: Assuming that no element is repeated in a single array, this is simply longest increasing subsequence.
Without loss of generality, assume that the first array, A1, is just [1, 2, 3, ..., n]. This transformation can be done in O(n) with a hash-set, or O(nlogn) with a BST.
Note that our set has a crossing if and only if it contains i and j with i < j but j appearing before i in the second array A2 (we know since i < j that i appears before j in A1).
Then if a set has no crossing it clearly corresponds to an increasing subsequence of A2 and vice versa.
Longest increasing subsequence has a simple O(n^2) solution and a slightly more complex O(nlogn) solution.

A: It is basically counting number of inversions problem.[Source - Section 5.3, Algorithm Design, Kleinberg and Tardos. http://books.google.co.in/books/about/Algorithm_Design.html?id=25p3mHu3ij8C]

A: What you are describing is known as the  matching problem for bipartite graphs.  I suspect there is something (as yet unstated) about the problem which makes it difficult to solve.  So far you really haven't placed any restriction on what edges can be used.  Supposing that there are certain edges (not all) available, those "possible" edges form a graph, and the ones you decide to use form a maximum matching.  Finding a maximum matching in a graph is a polynomial time algorithm, and it is particularly easy to code for the bipartite case.
The title makes it sound as though circumstances might impose some circumstance so that "disjoint" edges might not be feasible ("least edge intersections").  Perhaps you want edge covering (or 1-cover), i.e. that every vertex belongs to at least one edge.  Then, if the two "vertex" arrays are of different length, there will not be a "perfect matching", i.e. a matching that is also a cover.  A classic result  Hall's Marriage Theorem characterizes when there are perfect matchings in a bipartite graph.  If the graph is regular (all vertices have equal degree), then  König's Theorem tells us there is perfect matching (and more).
Added:
It may be worth stating what the picture seems to say about the restrictions on choosing edges.  Two sets of vertices have coordinates {(i,0) | i=1,..,N} and {(j,1) | j=1,..,N}.  There are N available edges, line segments that connect (i,0) and (j,1) whenever y0[i] = y1[j].  Although the subject line says "least edge intersections", a solution is a maximum subset of these edges that admits no intersections, a largest  planar straight-line graph contained in a given  permutation graph.
It is related to the 2-level crossing minimization problem considered here:
An Alternative Method to Crossing Minimization on Hierarchical Graphs -- P. Mutzel
"We suggest... removing the minimal number of edges such that the resulting graph is k-level planar...  In this paper we address the case k = 2... [W]e address the problem of extracting a 2-level planar subgraph of maximum weight in a given 2-level graph.  This problem is NP-hard."
The present problem imposes an equal number of points in the two vertex sets, the base graph is regular of degree 1, and no choice is allowed in the numbering or positioning of points.  So it is not possible to conclude it is as hard as the one described in the above paper.  However it does direct us to so-called "branch and bound" methods for the exact solution of such problems.
Let's consider the "edges" of the original problem as "nodes" of a new graph where two nodes are adjacent iff the original edges intersect.  [This is an example of an intersection graph.]  The problem as restated is now to find  a maximum independent set of the new graph.  The problems of that kind are in general NP-hard, but again we suspect the extent of the present problems may not be so general.
One reason to suspect a polynomial time algorithm could exist is the availability of polynomial time approximation algorithms for maximum independent subsets of intersection graphs for finite collections of planar convex sets:
Independent Set of Intersection Graphs of Convex Objects in 2D -- P. Agarwal and M Mustafa
"In this paper, we present approximation algorithms for the independent-set problem on intersection graphs of line segments and convex objects in the plane."
There is one further observation about the specialness of the present problem that seems to make it solvable in polynomial time.  A  circle graph is the intersection graph of line segments that can be drawn as chords of a circle.  By a pertubation argument the straight-line edges of a permutation graph can be so drawn, without loss or introduction of intersections.
Now the maximum independent set problem for circle graphs can be solved in polynomial time.  The Wikipedia article linked above gives this reference:
Nash, Nicholas; Gregg, David (2010), "An output sensitive algorithm for computing a maximum independent set of a circle graph", Information Processing Letters 116 (16): 630–634
I also found this reference in Google Books:
Valiente, Gabriel (2003), "A New Simple Algorithm for the Maximum-Weight Independent Set Problem on Circle Graphs", Algorithms and computation: 14th Symposium, ISAAC 2003 Kyoto


text:
Q: $S_n$ has only four (irred.) representations with degree $6$) I'm working on the following exercise:

For $n\ge 7$, $S_n$ has no irreducible representations of dimension $m$ with $2\le m\le n-2$.

There is a solution here but I'd like to follow the suggestion of Fulton and Harris (exercise 4.14) and prove this using the hook-length formula. Presumably the proof will proceed inductively, and I've shown the base case $n=7$, but it's the rest I'm struggling with.

A: Claim: The only irreducible representations of $\mathcal{S}_d$ (over $\mathbf{C}$) which have dimension less than $d$ are $V_{(d)}$, $V_{(1,\ldots, 1)}$, $V_{(d{-}1, 1)}$ and $V_{(2,1,\ldots,1)}$ as well as the representations $V_{(2,2)}$ of $\mathcal{S}_4$ and $V_{(3,3)}$ & $V_{(2,2,2)}$ of $\mathcal{S}_6$.
F&H want you to show that for all $\lambda$ except those in the claim,$$\dim V_\lambda = \frac{d!}{\prod(\text{Hook lengths})}\geq\ d$$ by induction (removing the first column of $\lambda$). This is going to be slightly ugly, because it seems we have to say explicitly what happens when removing a column yields one of the seven exceptional diagrams listed in the claim.

First let's do the induction without worrying about those seven.
Proof: Assume the claim is true for all $d < k$. Now assume we have a partition $\lambda\vdash k$ (with $\lambda_1\geq\ldots\geq\lambda_n\geq 1$) and that $\lambda$ with one column removed (denoted $\hat\lambda$) is not one of the seven bad diagrams in the claim.
By induction, we're assuming that the hooks of $\hat\lambda=(\lambda_1-1,\ldots,\lambda_n-1)\vdash k-n$ satisfy$$\frac{(k-n)!}{\prod(\text{Hooks of }\hat\lambda)} \geq k-n$$ or equivalently$$(k-n-1)!\geq\prod(\text{Hooks of }\hat\lambda).$$
Starting from the top, the hook lengths of the first column of $\lambda$ are $\lambda_1-1+n$, $\lambda_2-2+n$, all the way to $\lambda_n$. So the product of the hooks of $\lambda$ is then$$\prod_{i=1}^n(\lambda_i+n-i)\cdot\prod(\text{Hooks of }\hat\lambda)$$so this part of the induction is complete if we show that this is at most $(k-1)!$.
Fact: $\lambda_i+n\leq k$. Why? There are $n$ boxes in the first col. of $\lambda$ and $\lambda_i$ boxes in the $i$th row of $\lambda$. So we double counted by the one box in the first col. and the $i$th row, but there must be another nonempty row in $\hat\lambda$ (otherwise $\hat\lambda$ would be one of the diagrams from the claim that we're putting off until later).
From the fact, we get $\lambda_i +n-i\leq k-i$, so$$\prod_{i=1}^n(\lambda_i+n-i)\ \leq\ (k-1)\cdots(k-n).$$But this combined with what we know about $\hat\lambda$ is gives us exactly$$\prod(\text{Hooks of }\lambda) = \prod_{i=1}^n(\lambda_i+n-i)\cdot\prod(\text{Hooks of }\hat\lambda)\leq(k-1)!$$This is what we wanted since we can rearrange this to$$k\leq\frac{k!}{\prod(\text{Hooks of }\lambda)}.$$

Now we have to worry about what happens if $\hat\lambda$ is one of the diagrams listed in the claim (since we couldn't use the inductive step on those). These are more tedious than anything since you can just explicitly compute the product of the hooks. For example, suppose $\hat\lambda$ is the partition corresponding to the trivial representation. Then we can take the dual of $\lambda$ and do the induction above unless $\hat\lambda$ is $(1,1)$. In that case, the product of the hooks is $2(n+1)(n)(n-2)!$ ($n$ is still the no. of boxes in the first column) so we want to know if$$\frac{(n-2)!}{2(n+1)(n)(n-2)!}\geq n-2.$$ This is true since this reduces to $n-1\geq 2$. The other cases can be handled similarly, but I don't think there is anything to be learned from writing it all out.


text:
Q: Can't get my mail.app filter I created to work on messages that are coming in to the Gmail IMAP spam folder On Leopard, I use Mail.app. I have filters set up. They work. Except for this new one I made. It works when I choose Apply Filters manually. But does not seem to filter incoming messages.
It is my only filter that operates on something in the IMAP Gmail Spam folder. I think that mail just sees this as any other IMAP folder, so I don't know why it won't work. But do you think that Mail.App does realize that this IMAP/spam folder is actually a spam/junk folder and for some reason because of this it prevents my filter from being run?
As I said all my other filters work fine.

A: I think the spam detection of gmail is a filter applied before others...
How to deal with it:

*

*To filter mails flagged as spam: add label:spam  in the "Has the words" input box.

*To avoid the spam flagging, create a filter that describes the cases when Gmail should not flag the incoming messages as spam and then check "Never send it to spam".

source: googlesystem.blogspot.com


text:
Q: How to label a textbullet with tikz? I have this code:
\documentclass[table,dvipsnames,svgnames]{beamer}

\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
       \node[red] at (6.6, 2.7) {\textbullet};
    \end{tikzpicture}
\end{document}

which will produce a text-bullet. How to label that bullet?
I tried with:
\node[red] at (6.6, 2.7) {\textbullet}\q;

but got a compilation error. If I just do {q}, then I just get a red q.

A: Two solutions for you, the first one uses a line break, the second the positioning library of tikz.
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
    \begin{tikzpicture}
       \node[red,align=center] at (6.6, 2.7) {\textbullet \\ Your Text is here};
    \end{tikzpicture}
    \begin{tikzpicture}
       \node[red](dot) at (6.6, 2.7) {\textbullet};
       \node[below=0cm of dot]  {Your Text is here};
    \end{tikzpicture}
\end{document}


text:
Q: Jenkins not checking out all files from Starteam I'm experimenting with a Jenkins setup to improve our CI strategy which currently consists of an Automated Build Studio script getting kicked off by a Windows task scheduler. The source code that I want to integrate is a .NET solution which I'm attempting to build via MSBuild.
As our SCM we use StarTeam (v. 10.4) and I'm currently experiencing issues when Jenkins attempts to check-out files to the workspace and compile the solution.
There are certain files (it appears to always be the same) which don't get checked-out by the Jenkins StarTeam plugin. Obviously, Since these files are missing I'm unable to use Jenkins for CI. I'm not experiencing this issue with our Automated Build Studio script: Here all files are checked out correctly.
From my point of view there's nothing special about the C# files which don't get checked out: They're in different projects, contain different type of data (some winforms, some interfaces), they're all part of the same view, appears to have been added to StarTeam in the same manner etc.
The StarTeam polling log in Jenkins doesn't reveal anything. I don't know if there is some kind of debug mode that I might be able to use in order to trace down the nature of the problem?
Perhaps I should add that currently Jenkins runs locally on my desktop pc (Win7) whilst I'm experimenting with a setup. I'm using a default location of
c:\Program Files(x86)\Jenkins\Jobs\JOB_NAME\Workspace
to integrate my solution.
I hope some of you guys might have an idea about what the issue is, as I would really like to have a better CI setup than what we currently have in place.

A: I managed to identify the problem: Apparently, one of the developers in our team sometimes manages to change the default location property of folders when adding them to StarTeam. So instead of checking in files with a location relative to the project root, we end up with an absolute path in our repository.
I was able to verify this by deleting the file in the original location (i.e. NOT in the Jenkins jobs folder) and then watch as the files reappeared in their original location during the Jenkins checkout. What really lead me to investigate this further was to try an checkout the files from StarTeam using a cmd-line utility to check the files into a different location. When this still didn't get all the files checked out I assumed that Jenkins was no longer to blame but instead something else was wrong.
The reason I hadn't noticed this before is partly due to my little experience with StarTeam and due to all of the developers in our team using the same mappings and paths in our development environment. Hence, the absolute path placed the file in the right location on all machines because the paths used were identical.

A: Essentially the StarTeam SDK handles the checkout of the files when integrating with any external application.  The 10.4 build of client you are running seems quite out of date so I would recommend upgrading the SDK build if not the entire client.
StarTeam has relatively good forward/backward compatability when it comes to client/SDK so you could in theory run a 2009/2009R2 SDK against your existing 2008 R2 client installation.
As far as the debugging mode within Jenkins, you can activate this in the command line by running the following syntax:
java -Drally.debug="true" -jar jenkins.war --httpPort=9000


text:
Q: Angular $scope values set in reverse order I have been working on Angular for one month now. I have been struggling with scoping and keeping state between views.
I don't know how to debug in angular, so I use the console to track the values of the scope when a view is loaded.
This is one of my controllers:
.controller('LegDetailCtrl',function($scope,$stateParams, LegService,ControllerService){
    $scope.reservation = ControllerService.getReservation();
    LegService.getLeg($stateParams.legId).then(function(data){
        ControllerService.setLeg(data.data);
        $scope.leg = data.data;
        console.log('Check leg',angular.toJson($scope.leg));
    });

    $scope.seats = LegService.getSeats();
    $scope.pax = LegService.getPax();
    $scope.user = ControllerService.getUser();
    $scope.reservation.leg = $scope.leg;
    $scope.reservation.client = $scope.user;
    $scope.reservation.pax = $scope.pax;
    console.log('Check scope leg', angular.toJson($scope.leg));
})

As I understand, in JS the execution is made in order from top to bottom (not sure of this). I think this way, I am processing and then setting the $scope.leg value, then I use it to feed the $scope.reservation object.
To me, the correct console output would be:
log Check leg, {aJsonObject}
log Check scope leg, {anotherJsonObject}

But what I get is this:
log Check scope leg,
log Check leg, {aJsonObject}

So, it looks like it sets all the values to the scope and then, executes the LegService.getLeg() method.
How do I make this to run in the correct order?
Thanks in advance.

A: If you're using chrome there's a great debugging tool for AngularJS apps called Batarang
.
To solve your problem you can chain your promises like below.
function LegDetailCtrl($stateParams, LegService, ControllerService){
    var vm=this;
    vm.reservation=ControllerService.getReservation();

    LegService
        .getLeg($stateParams.legId)
        .then(function(data){
            ControllerService.setLeg(data.data);
            vm.leg=data.data;
            return data.data;
        })
        .then(function(data) {
            var user=ControllerService.getUser();
            var pax=LegService.getPax();
            var seats=LegService.getSeats();

            vm.seats=seats
            vm.pax=pax
            vm.user=user
            vm.reservation.leg=vm.leg;
            vm.reservation.client=user
            vm.reservation.pax=pax
        });
}
LegDetailCtrl.$inject=['$stateParams', 'LegService', 'ControllerService'];

angular
    .module('yourModule')
    .controller('LegDetailCtrl', LegDetailCtrl)

A: The .then( in the following line
LegService.getLeg($stateParams.legId).then(function(data){

is an asynchonous call to the function inside the then-block (which contains the "Check leg")
The execution is deferred till the event loop of javascript is empty (javascript is only single threaded).
That means that the code of the main function is executed first (result is "Check scope leg")
and after that the async call inside the then-block is executed ("Check leg")

A: If you ran this code outside of the browser, you'd find that the console.log call within the callback you passed to then is never called at all. That is because the callback is not called until the promise returned by getLeg is resolved, and that won't happen until the next angular $digest cycle.


text:
Q: ArgumentOutOfRangeException using IndexOf with CultureInfo 1031 string s = "Gewerbegebiet Waldstraße"; //other possible input "Waldstrasse"

int iFoundStart = s.IndexOf("strasse", StringComparison.CurrentCulture);
if (iFoundStart > -1)
    s = s.Remove(iFoundStart, 7);

I'm running CultureInfo 1031 (german).
IndexOf matches 'straße' or 'strasse' with defined 'strasse' and returns 18 as position.
Neither Remove nor Replace got any overload for setting a culture.
If I remove 6 chars using Remove 1 character will be left if input-string is 'strasse' and 'straße' will work.
If input-string is 'straße' and I remove 7 chars I get ArgumentOutOfRangeException.
Is there a way to safely remove the found string? Any method which provides the last index of IndexOf? I stepped closer into IndexOf and it's native code under the hood as expected - so no way to do something own...

A: The native Win32 API does expose the length of the string that was found. You can use P/Invoke to call FindNLSStringEx directly:
static class CompareInfoExtensions
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
    private static extern int FindNLSStringEx(string lpLocaleName, uint dwFindNLSStringFlags, string lpStringSource, int cchSource, string lpStringValue, int cchValue, out int pcchFound, IntPtr lpVersionInformation, IntPtr lpReserved, int sortHandle);

    const uint FIND_FROMSTART = 0x00400000;

    public static int IndexOfEx(this CompareInfo compareInfo, string source, string value, int startIndex, int count, CompareOptions options, out int length)
    {
        // Argument validation omitted for brevity
        return FindNLSStringEx(compareInfo.Name, FIND_FROMSTART, source, source.Length, value, value.Length, out length, IntPtr.Zero, IntPtr.Zero, 0);
    }
}

static class Program
{
    static void Main()
    {
        var s = "<<Gewerbegebiet Waldstraße>>";
        //var s = "<<Gewerbegebiet Waldstrasse>>";
        int length;
        int start = new CultureInfo("de-DE").CompareInfo.IndexOfEx(s, "strasse", 0, s.Length, CompareOptions.None, out length);
        Console.WriteLine(s.Substring(0, start) + s.Substring(start + length));
    }
}

I'm not seeing a way to do this using purely the BCL.


text:
Q: Keeping consitent android styling In my android application I have both programmatically generated buttons and buttons designed in a layout file.
My question is what is the best way to ensure that my programmatically generated buttons match the ones that are in my layout file?
Main Method:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);

    Button subButton = new Button(getApplicationContext());

    subButton.setText("-");
    TableRow.LayoutParams lp2 = new TableRow.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
    subButton.setLayoutParams(lp2);

    LinearLayout container = (LinearLayout) findViewById(R.id.container);

    container.addView(subButton);

}

Layout File:

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="-"
        android:id="@+id/addButton"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/container"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

In this example both buttons appear to be different.
Edit:
The difference between the two buttons are the height and width. I've tried to minimize the difference in parameters by making the button simple.
Edit 2:
Picture of the XML button compared to the Generated button.

A: If you are using AppCompatActivity, you'll want to use AppCompatButton instead of Button. As explained in the Support Library 22.1 blog post, the standard widgets are replaced with their AppCompat equivalents automatically for you when you define them in XML to ensure consistent styling across all API levels, but for programmatic usage you must manually ensure you use the AppCompat versions.

A: Use the activity context instead:
Button subButton = new Button(this); // not getApplicationContext()

A: Create a button_style.xml like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item>
<shape>
<gradient android:startColor="#449def" android:endColor="#2f6699" android:angle="270" />
<stroke android:width="1dp" android:color="#2f6699" /> <corners android:radius="4dp" />
<padding android:left="10dp" android:top="10dp" android:right="10dp"
android:bottom="10dp" />
</shape>
</item>

</selector>

Then apply this style programmatically to your buttons:
 Button mybutton = new Button(this);
    mybutton.setText("Test Example");
    mybuttonsetId(R.string.myButton);
    myButton.setBackgroundResource(R.layout.buttonstyle);

For buttons created in XML directly be sure to also reference the same style:
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@layout/buttonstyle"
        />

A: I suggest using a factory method for this problem.
Implementing a factory method is as simple as defining a method that constructs your object, and adds the required fields before returning it to you. This cuts down on a lot of boiler plate code.
Also, you're using layout elements for a RelativeLayout, so I'm going to show you a method that receives a RelativeLayout as its container. If you really are using a LinearLayout (or something else!), we'll have to deviate from your layout parameters to achieve the same looks.
A suitable example:
public Button getNewStyledButton(String text) {
    Button button = new Button(this);
    button.setText(text);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
    button.setLayoutParams(layoutParams);
    return button;
}

Then, whenever we need a styled button, it's as simple as calling:
yourRelativeLayout.addView(getNewStyledButton("-")); //replace "-" with your desired text. You can also pass a `Runnable` as an argument for the button callback.

Let me know if this helps you, and if you need help with your LinearLayout as well.


text:
Q: React Native and httpS with axios / heroku api How does HTTPS work with react native after deploying?
I would deploy my Node/Express API Server to Heroku.
From there I get the SSL Certificate automatically.
But do I have to do something on the client side (React Native App) that the connection uses the httpS protocol?
(encrypted data traffic?)
Here is my Old Post, but nobody answered..
React Native - Authentication - Prevent Token / Cookie being stolen / sniffed? #man in the middl #encrypt data? SSL / HTTPS?


text:
Q: Exception #0 (Magento\Framework\Exception\LocalizedException): Invalid method Vendor\Modulename\Model\Doccountmodel::create I have created a crud model for a custom table in a  module but when I have called that model to do operations. I am getting an error
public function __construct(Context $context , \Vendor\Modulename\Model\Doccountmodel $doccountfactory,  Session $customerSession)
    {

        $this->_customerSession = $customerSession;
        $this->doccountfactory = $doccountfactory;
        parent::__construct ( $context );
    }

public function execute(){
  $sampleModel = $this->doccountfactory->create();

    // Load the item with ID is 1
    $item = $sampleModel->load(1);
    var_dump($item->getData());

}

A: Replace in your your __construct signature this
\Vendor\Modulename\Model\Doccountmodel $doccountfactory

with this
\Vendor\Modulename\Model\DoccountmodelFactory $doccountfactory


text:
Q: solidity: how can i call a payable function from another contract and enter the amount i want to pay? the other contract is not on the editor // SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

interface IBank {
    function addTax(uint256 moneyToAdd) external payable;

}

contract Counter {
    uint public count;
    address bankAddress;

    function setbankAddress(address _bankAddress) public payable {
       bankAddress = _bankAddress;
    }

    function addMon(uint moneyToAdd) public payable {
        require(moneyToAdd <= msg.value, "Ether value sent is not
        correct");

    }
    function pay(uint _Amount) public payable {
        IBank(bankAddress).addTax{value:_Amount}(_Amount);

    }
}

when I deploy it I first add the contract address that I want to interact with, it's working with all functions that do not require value


text:
Q: MYSQL: Select items that do not contain a certain date Say I have a table
CustID   |   OrderDate
1        |   2017-05-30 05:15:18
2        |   2017-04-18 05:15:18
2        |   2017-04-15 05:15:18
3        |   2017-02-17 05:15:18
4        |   2017-05-29 05:15:18
4        |   2017-03-24 05:15:18

Any I only want to return back the CustIDs that do not contain an order date newer than 30 days (Today being 2017-05-30). So the above example would only return 2 and 3.
I have:
SELECT DISTINCT CustID
FROM TABLE
WHERE NOT EXISTS (SELECT CustID FROM TABLE WHERE OrderDate > DATE_ADD(NOW(),INTERVAL-30DAY));

But I only get syntax errors.
Thanks again, I am quite new with SQL.

A: You can try this:
select distinct CustIDs from YourTableName where OrderDate < now() - interval 30 day;

PS: In your query, you're using FROM TABLE - it isn't right, you must use FROM {YourTableName}, where {YourTableName} is real name of your table in database, like (customers, clients, etc.)

A: because you're missing a vital component in where clause: and t1.id = t2.id
select distinct CustID from table t1 where not exists (select 1 from table t2 where [whatever_your_conditions_are] and t1.id = t2.id);
A table similar to yours... It just has date instead of timestamp (and a relaxed date condition in where clause, just for the sake of simplicity):

selecting the users whose date > current_date (which is order_date in your case):

A: as far as i understand your question.
your query will be:
SELECT DISTINCT CustID FROM TABLE WHERE OrderDate < GETDATE()-30
Let me know if you  require changes like < or > OrderDate in Where Clause.


text:
Q: Do I need a partition scheme for each partitioned table Sorry if this is a stupid question, but I'm setting up table partitioning for the first time.  It will be on multiple existing tables all within the same database.
I know I need a partition function and a partition scheme, but do I need one of each for each table or a combination of 1 function and multiple partition schema or just one of each?
I'm using SQL Server 2014 Enterprise edition.
I tried Google but couldn't find the answer.
Hope someone can help.
Thanks
Alex

A: A separate partition function/scheme for each table/index provides the most flexibility and granularity but can increase complexity and redundant maintenance when boundaries are added or removed, such as when aligning or partitioning related tables.
I generally recommend a single function for all tables/indexes that are partitioned similarly and boundaries are always added/removed at the same time. You'll need separate partition schemes related to the function only if your file group mappings differ. You'll of course require separate partition functions if you need to maintain boundaries at different times.

A: A partition function gives the ranges to partition by, e.g. if you want to partition by years then your partitions could be 2012, 2013, 2014...
A partition scheme is a mapping of the "parts" of a given partition function to particular filegroups - if you are using the PRIMARY filegroup only, then they will all be mapped there, but some partitions could be on a different filegroup if you want.
A partitioned table has a partition scheme applied to a particular column. For example if your table is "Movies" then you might have a field "ReleaseYear" and all the movies released in 2012 would go into the 2012 partition, etc.
The partition scheme and function can be applied to more than one table, but every partitioned table must have one (by definition), they just don't need to be unique.
However, keep in mind that if you use the same partition scheme/function on more than one table, any changes you make to it will be applied to all the tables, e.g. splitting or merging a partition.
MSDN has some further information on partition schemes here.
Often you will find that you need to index those partitioned tables, and then you'd usually create a partitioned index as well. If it matches the partitioning scheme and field of the "base" table then it is known as apartition-aligned index, which allows special operations like "switching" data from one partition to another without having to physically move all the data.

A: There are no stupid questions. If you are using the same partition scheme and same partition function (e.g. put the same ranges to same file groups) then you can go by with the one partition scheme and one partition function. If not then you need multiple. Still you can use the same partition scheme with various partition functions if you put the ranges on the same file groups.
HTH


text:
Q: Newton-Raphson Search for Implied Volatility Returning Low Solutions I am working on a project for a Python class that required us to download and run a sample of code. I chose a section of code from StackExchange that calculates the implied volatility of an option using a Newton-Raphson search. I had to modify the initial code fragment slightly to get it to run. I noticed that when I compared the output to an Excel spreadsheet model that the calculated implied volatilities were consistently lower, averaging around 3% below the values produced by the Excel sheet.
For those who have experience with this type of problem, is there anything obviously incorrect in the following code that could be producing that type of error? Any suggestions would be welcome.
Please see problem description above for details. The problematic code is:
# s = stock price
# k = strike
# t = time to maturity
# rf = risk free interest
# cp = +/-1 call/put
# price = option price

import math as math
import numpy as np
from scipy.stats import norm

pi = 3.14159

def newtonRap(cp, price, s, k, t, rf):
    v = math.sqrt(2*pi/t)*price/s
    print ("initial volatility: ",v)
    for i in range(1, 100):
        d1 = (math.log(s/k)+(rf+0.5*pow(v,2))*t)/(v*math.sqrt(t))
        d2 = d1 - v*math.sqrt(t)
        vega = s*norm.pdf(d1)*math.sqrt(t)
        price0 = cp*s*norm.cdf(cp*d1) - cp*k*math.exp(-rf*t)*norm.cdf(cp*d2)
        v = v - (price0 - price)/vega
        print ("price, vega, volatility\n",(price0, vega, v))
        if abs(price0 - price) < 1e-25 :
            break
    return v

# TEST using known implied volatility from standard black scholes model

v = newtonRap(cp=1, price = 12.19, s=125, k=150, t=365/365, rf=0.06)
print (v)


text:
Q: Deleting a selected item from a listview in xamarin (using a SQLite DB) I want to delete a single selected row, I dont think my code is far off. Currently it deletes all rows in the listview thats saved on the SQLite DB which is great for a delete all button but I'm not wanting that. Below is my code:
 void SaveButton_Clicked(object sender, System.EventArgs e)
    {
        MainWindowViewModel APR = new MainWindowViewModel()
        {
            ProductName = proName.Text,
            TotalAPR = totAPR.Text,
            Total = tot.Text,
            Monthly = mon.Text
        };

            using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.CreateTable<MainWindowViewModel>();
            int rowsAdded = conn.Insert(APR);
        }

        DisplayAlert("Saved!", "Your APR has been saved!", "OK");

        BindingContext = new MainWindowViewModel();

        OnAppearing();
    }

    void RemoveButton_Clicked(object sender, System.EventArgs e)
    {
        MainWindowViewModel APR = new MainWindowViewModel()
        {
            ProductName = proName.Text,
            TotalAPR = totAPR.Text,
            Total = tot.Text,
            Monthly = mon.Text
        };

        using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.DeleteAll<MainWindowViewModel>();
            int rowsDeleted = conn.Delete(APR);
        }

        DisplayAlert("Deleted!", "This saved APR has been deleted!", "OK");

        BindingContext = new MainWindowViewModel();

        OnAppearing();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.CreateTable<MainWindowViewModel>();
            var APRS = conn.Table<MainWindowViewModel>().ToList();

            APRListView.ItemsSource = APRS;

        }
    }

I have also tried:
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.Delete<MainWindowViewModel>();
            int rowsDeleted = conn.Delete(APR);
        }

But I'm getting told to change it to conn.DeleteALL as per Intellisense.

A: // you do not need to create a new instance of your VM
var item = (MainWindowViewModel)APRListView.SelectedItem;

conn.Delete(item);


text:
Q: Backbone.js hidden fields on submit I am in the process of integrating my custom shopping cart with a payment gateway(Paypal).
I need to submit my items with the use of hidden fields, but when I submit the form the hidden fields seems to be missing. (According to the the payment gateway my cart is empty)
I know it might be a simple problem, but I've been going in circles for the last couple of hours.
The code that I generate the hidden fields with:
 <% for(i=0,l=products.length;i<l;++i) { p = products[i]; %>

          <input type="hidden" name= "item_name_"+<% i %>  value="beach ball">
          <input type="hidden" name="amount_1" value="15">
 <% } %>

Any help would be appreciated.
Thanks

A: Yeah, it's quite simple :)
<input type="hidden" name="item_name_<%= i %>" value="beach ball" />

FYI:
<%  i %> evaluate
<%= i %> interpolate
<%- i %> escape


text:
Q: Wrong path in System Environment Variables - CMDER I would like to ask how can I find wrong mistyped path in System Environmental Variables?
Below you can see that the CMDER application complains that this variable is not right:
C:\Program was unexpected at this time.
But I cannot find in my System Environmental variables. Where and how can I find it?

A: In last row remove semicolon(;). I think that is creating a problem for you.


text:
Q: "Ghost" ContentControl stealing focus I have a tabbed control using a Template Selector, the correct template is selected which contains a WebBrowser component, when using the KeyBoard (Up/Down Arrows) the KeyBoardFocus toggels between the rest of the application and the web page.
Using snoop I can get the WebBrowser control to behave by setting the Focusable property of the containing ContentControl to false, however I can't figure out where/how to set the ContentControl property programmatically!
A snippet from snoop:

    PART_SelectedContentHost is from the Theme (Focusable == False)
    ContentControl (Focusable == **True**) [Where does this come from? It's "Content" is a ViewModel]
    ContentPresenter (Focusable == False) [Where does this come from?]
    WebPageView (My created component, Focusable == False)
    ... (Focusable == False)
    wbContent (Focusable == True)

I've tried using a targeted style resource in the ContentPresenter of PART_SelectedContentHost but with no luck.
Anyone any ideas?
Thanks

A: Try deriving from the tab control. Override the OnApplyTemplate method and find the contentcontrol by name. Once found change its property.


text:
Q: node.js performance for amazon EC2 instances with ECU's I have a node.js server. I undertsand that 1 node process is bound to 1 CPU/CORE. So I have 2 CORE box, the I use cluster to launch 2 processes to utilize the 2 CORES of box.
However, I am not able to understand how would this work with EC2 instances ECU concept.
for eg. an m1.large instance has 2 vCPUs with 4 ECU's (Effective compute unit)
When I launch node.js with cluster, it launches 2 node processes. However, on my desktop which has 8 cores, it launches 8 node processes.
Now I am wondering whether node.js sever on m1.large with 2 cores and 4 ECUs would perform any better than a box with just 2 CORES and no ECU's
Please answer my query.

A: Amazon ECU are virtual core because they are basically virtual sever with 2 real core of a xeon processor.So a box with real 2 core will perform better than a virtual ECU.And also I dont think than amazon ECU are the same thing like the real cpu core Amazon elastic cloud.
As far i am working with nodejs and EC2 on my production server i simply set up two thing to utilize the max cpu power of a m1.large instance.

*

*Multiple node process behind the nginx as reverse proxy load-balencer
a. I set up different nodejs process on different port.
b. On front of them an nginx load balancer o distribute the load across each thread.

*I have also tries hands with forking child process with main thread using Cluster module .
I finally ends up with nginx and coz its have less management than cluster and also cluster is in experimental stage.
I have also tries exploring more about EC2 and nodejs here is my another answer Utilizing cpu core with nodejs.
And i also suggest you just try some of the solution and keep monitoring your system in each case like cpu uses memory io and finally you will get the better solution for your use case. Every application has its own requirement.So its better to try and find what your applications real need .


text:
Q: Dimesnion from React/native not working properly on Android device I am trying to create an Instagram like reel functionality in react-native app.
I want to display a video element on entire screen available space.
For the purpose of it I am using a FlatList.
This code doesn't work on every device.
const HomeScreen = ({navigation}) =\> {
const dataArray=\[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19\];

const renderItem=({item,index})=\>{
return(

    <View style={[{height:Dimesnions.get('window').height-bottomtabBarHeight,borderBottomColor:'black'},]}>
       <Text>{item}</Text>
      </View>

    )

}
return (

    <SafeAreaView style={styles.container}>
    <StatusBar />
    <FlatList
    data={dataArray}
    renderItem={renderItem}
    pagingEnabled
    decelerationRate={'fast'}
    />

</SafeAreaView\>

)
}

export default HomeScreen

const styles = StyleSheet.create({
container:{
flex:1,

}

})

A: work for me
import dimansion from react native
const {height,width} = dimansion.get('window')

const Myfun=()=>{
    return(
      <View style={{flex:1}}>
         <View style={{height:height}}></View>
     </View>
          )
                }

A: actually what you need to do is make a state variable and assign dimension's value in it and then in useEffect make a listener which would be triggered every time your device rotates or dimensions of device gets changed
example below:
const [dim, setDim] = useState(Dimensions.get('screen');
useEffect(() => {
const subscription = Dimensions.addEventListener(
  'change',
  ({ screen}) => {
    setDim({ screen});
  },
);
return () => subscription?.remove(); });

you can use dim.height for height and dim.width for width in your desired component
PS. I have made a complete and comprehensive tutorials regarding Dimensions API if you want to check it out then link is below(Tutorial is in Urdu/Hindi)
https://www.youtube.com/watch?v=mISuyh_8-Cs&t=605s&ab_channel=LearnByDill

A: I think it is because of typo which you used Dimesnions instead of Dimensions. You can get height or width of device as below:
const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;


text:
Q: How to correct an existing DocuSign envelope to add a document to it with their C# SDK? I have an existing envelope with a document in it. This document has a fixed number of places to sign built in. If we think we need more places to sign, we have an additional document dedicated to just that.
I can create the envelope with the additional signatures document if we know we're going to have that many signatures from the beginning. But I'm unsure how to add the document to an existing, not yet complete, envelope for situations where new signers come on-board after the first signature is received. I'd like to not have to require those that have already signed to sign again, so it sounds like I need to correct the envelope.
Their REST documentation seems to have exactly what I'm looking for with UpdateDocument. I'm using the C# SDK and it seems to have a similar function except with no place to actually put the document's Base64 bytes.
Is it possible to use the C# SDK to append a document to an existing, incomplete envelope?

A: It currently seems impossible to use the C# SDK for this as the UpdateDocument function has an open bug for this exact reason (no place to specify document bytes that would go in the request body): https://github.com/docusign/docusign-esign-csharp-client/issues/357


text:
Q: Angular Routing: Instance Creation vs Instance Activation The Angular Routing docs mention component instance creation, component instance activation, and route activation.
The docs do not explain the differences of these concepts, and when each creation/activation occurs.

Questions

*

*What is the difference between instance creation and instance activation?

*What is the difference between instance activation and route activation?

*Does instance activation always occur at the same time as instance creation?

In summary: It is not clear what is really meant by component instance activation and route activation, and how that relates to component instance creation (particularly timing wise).

Known Information
Instance Creation

*

*Component instances are created by Angular when navigating between components of different types

*When navigating between instances of the same component, the instances are re-used by default

Instance Activation

*

*When browser's location URL changes to match a path segment (e.g /crisis-center), Router activates an instance of corresponding component (e.g CrisisListComponent) and displays its view

*When app requests navigation to a path (e.g /crisis-center), Router activates instance of corresponding component (e.g CrisisListComponent), displays its view, and updates browser's address location and history with URL for that path

Route Activation

*

*Mentioned a few places throughout the docs. See below

Angular Doc References
Here are some mentions of the above three concepts, in the Angular docs:
Instance Creation

By default, the router re-uses a component instance when it
re-navigates to the same component type without visiting a different
component first.
...
This application won't re-use the HeroDetailComponent. The user always
returns to the hero list to select another hero to view. There's no
way to navigate from one hero detail to another hero detail without
visiting the list component in between. Therefore, the router creates
a new HeroDetailComponent instance every time.

Link
Instance Activation

When the browser's location URL changes to match the path segment
/crisis-center, then the router activates an instance of the
CrisisListComponent and displays its view.

Link

When the application requests navigation to the path /crisis-center,
the router activates an instance of CrisisListComponent, displays its
view, and updates the browser's address location and history with the
URL for that path.

Link
Route Activation

The data property in the third route is a place to store arbitrary
data associated with this specific route. The data property is
accessible within each activated route.

Link

You can also protect child routes with the CanActivateChild guard. The
CanActivateChild guard is similar to the CanActivate guard. The key
difference is that it runs before any child route is activated.

Link

In the Hero Detail and Crisis Detail, the app waited until the route
was activated to fetch the respective hero or crisis.

Link

The ActivatedRouteSnapshot contains the future route that will be
activated and the RouterStateSnapshot contains the future RouterState
of the application, should you pass through the guard check.

Link

A:
What is the difference between instance creation and instance
  activation?

Instantiating means creating an instance of a route (ActivateRoute) or component. Activating of a route means attaching it to the router-outlet directive. Activating of a component means attaching it to the DOM. Routes and components are activated using activateWith function of a router-outlet directive.
Let's see some examples. Suppose you have the following routes:
{
    path: 'a',
    component: AComponent,
    children: [
        { path: 'b', component: BComponent },
        { path: ':name', component: DComponent }
    ]
}

Now you navigate to a/b.
The router will:

*

*instantiate { path: 'a', component: AComponent, children: [] } route

*instantiate { path: 'b', component: BComponent } route

*activate these routes by attaching them to the respective router-outlet locations

*instantiate AComponent and BComponent using this approach

*activate AComponent and BComponent by adding them to DOM

Now you navigate to a/n1.
The router will:

*

*reuse route for a - { path: 'a', component: AComponent, children: [] } route (no instantiation or activation)

*instantiate { path: ':name', component: DComponent } route

*activate { path: ':name', component: DComponent } route

*reuse AComponent instance (no instantiation or activation)

*instantiate DComponent instance

*activate DComponent by attaching it to the router-outlet in AComponent view

Now you navigate to a/n2.
The router will:

*

*reuse route for a - { path: 'a', component: AComponent, children: [] } route (no instantiation or activation)

*reuse route for n2 - { path: ':name', component: DComponent } route (no instantiation or activation)

*update params for the n2 activated route

*reuse DComponent instance (no instantiation or activation)


text:
Q: Like button Ajax in Ruby on Rails I have a Ruby on Rails project with a model User and a model Content, among others. I wanted to make possible for a user to "like" a content, and I've done that with the acts_as_votable gem.
At the moment, the liking system is working but I'm refreshing the page every time the like button (link_to) is pressed.
I'd like to do this using Ajax, in order to update the button and the likes counter without the need to refresh the page.
In my Content -> Show view, this is what I have:
<% if user_signed_in? %>
  <% if current_user.liked? @content %>
      <%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put %>
  <% else %>
      <%= link_to "Like", like_content_path(@content), class: 'vote', method: :put %>
  <% end %>
   ·
<% end %>

<%= @content.get_likes.size %> users like this

The Content controller does this to like/dislike:
def like
    @content = Content.find(params[:id])
    @content.liked_by current_user
    redirect_to @content
end

def dislike
    @content = Content.find(params[:id])
    @content.disliked_by current_user
    redirect_to @content
end

And in my routes.rb file, this is what I have:
resources :contents do
    member do
        put "like", to: "contents#like"
        put "dislike", to: "contents#dislike"
    end
end

As I said, the liking system is working fine, but does not update the likes counter nor the like button after a user presses it. Instead, to trick that, I call redirect_to @content in the controller action.
How could I implement this with a simple Ajax call? Is there another way to do it?

A: You can do so in various ways, the simple way goes like this:
Preparations

*Include Rails UJS and jQuery in your application.js (if not already done so):
//= require jquery
//= require jquery_ujs

*Add remote: true to your link_to helpers:
<%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>

*Let the controller answer with a non-redirect on AJAX requests:
def like
  @content = Content.find(params[:id])
  @content.liked_by current_user

  if request.xhr?
    head :ok
  else
    redirect_to @content
  end
end

Advanced behaviour
You probably want to update the "n users liked this" display. To archieve that, follow these steps:

*

*Add a handle to your counter value, so you can find it later with JS:
<span class="votes-count" data-id="<%= @content.id %>">
  <%= @content.get_likes.size %>

users like this

Please also note the use of data-id, not id. If this snippet gets used often, I'd refactor it into a helper method.

*Let the controller answer with the count and not simply an "OK" (plus add some information to find the counter on the page; the keys are arbitrary):
#…
if request.xhr?
  render json: { count: @content.get_likes.size, id: params[:id] }
else
#…

*Build a JS (I'd prefer CoffeeScript) to react on the AJAX request:
# Rails creates this event, when the link_to(remote: true)
# successfully executes
$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
  # the `data` parameter is the decoded JSON object
  $(".votes-count[data-id=#{data.id}]").text data.count
  return

Again, we're using the data-id attribute, to update only the affected counters.
Toggle between states
To dynamically change the link from "like" to "dislike" and vice versa, you need these modifications:

*

*Modify your view:
<% if current_user.liked? @content %>
  <%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_content_path(@content), id: @content.id } %>
<% else %>
  <%= link_to "Like", like_content_path(@content), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_content_path(@content), id: @content.id } %>
<% end %>

Again: This should go into a helper method (e.g. vote_link current_user, @content).

*And your CoffeeScript:
$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
  # update counter
  $(".votes-count[data-id=#{data.id}]").text data.count

  # toggle links
  $("a.vote[data-id=#{data.id}]").each ->
    $a = $(this)
    href = $a.attr 'href'
    text = $a.text()
    $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
    $a.data('toggle-text', text).data 'toggle-href', href
    return

  return


text:
Q: trigger pendsv from svc || trigger systick manually cortex m4 i am currently working on an arm cortex m4. I implemented a simple context switch by triggering PendSV (which does the switch) from the SysTick interrupt. I tried to implement a void delay(int ms) function via SVC. It should work like this:

*

*Trigger SVC

*The Delay function writes delay into task_info

*The scheduler decrements delay in task_info next time it's the tasks turn and skips the task.

*When delay is equal to 0 the task gets scheduled normally again

The problem is, that i would like to trigger the context switch after the delay function has written the respective value to the task_info. Else the delay would only have effect after the next context switch. I tried to trigger PendSV from the SVC interrupt. Sadly this seems not to work.
With my former implementation of the delay function i got into memory usage faults when more than one task called the function at the same time.
Due to the current idea being more precise in timing i would like it to work. Help is greatly appreciated.
PS: Just for clarity, the delay value in int ms is multiplied with a factor derived from the clock speed and the SysTick frequency.


text:
Q: Alignment of equation number with the end of the line I' trying to reproduce this equation array from an IEEE paper

you can see that the equation numbers are aligned at the end of the line same as the above statement.
my code:
\begin{IEEEeqnarray}{rCl}
%
I(\lambda)\;\;\; &= &\;\;\;\int_{}^{}\int_{D}^{} g(x,y) e^{i \lambda h (x,y)}dx\,dy.\\
\prod_{j\geq0}^{}\bigg(\sum_{k\geq0}^{}a_{jk} z^k\bigg)\;\;\;\; &=&\;\;\;\;\sum_{n\geq0}^{}z^n \Bigg(\sum_{\substack{k_0,k_1,...\geq0\\k_0+k_+...=n}}^{}a_{0k_0}a_{1k_1} \, . \, . \, . \,\Bigg).\IEEEeqnarraynumspace\\
%
\end{IEEEeqnarray}

It produces:

you can see that the equation numbers shifted to the left and aren't aligned with the above statement.

If I add spaces more, the numbers shift and start to interleave with the statement of the second column in the paper.
So, I want to know how to force the equation numbers to be aligned at the end of the line.
Any help is appreciate. Thanks.

A: The problem is that the second equation is too wide for the column. However, you just need to fix the wrong things inside it:

*

*the \; commands around = should be removed

*use \iint instead of \int\int

*\Bigg should be \biggl and \biggr
\documentclass{IEEEtran}
\usepackage{amsmath}

\usepackage{lipsum,xcolor} % just for the example

\begin{document}

%% the line below is a trick to show the margin
\hspace*{\fill}\rlap{\color{red}\smash{\vrule depth 8cm width 0.2pt}}

\lipsum*[2]
\begin{IEEEeqnarray}{rCl}
I(\lambda) &=& \iint_{D} g(x,y) e^{i \lambda h (x,y)}dx\,dy.\\
\prod_{j\geq0}\biggl(\,\sum_{k\geq0}^{}a_{jk} z^k\biggr) &=&
  \sum_{n\geq0} z^n
    \biggl(
    \sum_{\substack{k_0,k_1,\dotsc\geq0\\k_0+k_1+\dotsb=n}}a_{0k_0}a_{1k_1} \dotsm
    \biggr).
  \IEEEeqnarraynumspace
\end{IEEEeqnarray}
\lipsum[3]

\end{document}


text:
Q: Angular6 Tree Component Filtering does not work https://angular2-tree.readme.io/docs
The tree was constructed through the angular tree-node.
Custom template in use. You can use filtering when it is not a custom template,
but it is not filtered when you use a filter.

The guide has filtering features, and my tree is not filtered.
<input class="form-control f-12" id="filter2" #filter2 (keyup)="tree.treeModel.filterNodes(filter2.value)" placeholder="filter nodes"/>

<tree-root #tree [nodes]="nodes" [focused]="true">
                <ng-template #treeNodeTemplate let-node="node" let-index="index">
                  <input class="pt-1" (change)="clickCheckbox(node, $event)" type="checkbox" [indeterminate]="node.data.indeterminate" [checked]="node.data.checked">
                  {{node.data.name}}
                </ng-template>
              </tree-root>

Nodes in the ng-template cannot be searched.
Add nodes as shown below.
public nodes: any = [];
public chart;

constructor(
private _http: HttpClient
) {
this.addNodeData();
}

addNodeData(){
this._http.get("url").subscribe(res => {
      this.chart = res;
      let node = this.addNdoeGroup(this.chart[0]);
      this.nodes.push(node);
    });
}

addNdoeGroup(Chart: any) {
let node = { id: Chart.TeamID, name: Chart.TeamName, children: [], member: []};

for (let child in Chart.Children) {
  let nChild = this.addNdoeGroup(Chart.Children[child]);
  node.children.push(nChild);
}

for (let member in Chart.Members) {
  let nMembers = this.addNodeMember(Chart, Chart.Members[member]);
  node.children.push(nMembers);
}
return node;
}

addNodeMember(Chart, member) {
let node = { id: Chart.TeamID, name: member.UserName, children: [], member: []};
return node;
}


text:
Q: Independent variables in conditional probability So I am reading this paper about reasoning(Hall, Ali, Chater, & Oaksford, 2016). Consider this conditionals.
If the fuse blows (p) then the lights go out (q)
If there is a power cut (r) then the lights go out (q)

Basically two independent causes that can make the lights go out. A few lines from (Hall, Ali, Chater, & Oaksford, 2016) really confuse.
So, the probability of the fuses blowing (p) is independent of power
cuts (r).
However, they are not independent if the effect is known to have occurred, i.e., Pr(p|r,q) != Pr(p|q).
Indeed, it is easily proven that Pr(p|r, q) < Pr(p|q)

From my basic understanding of conditional probability if p and r are independent their probabilities should be independent, regardless of the consequent.
Hall, S., Ali, N., Chater, N., & Oaksford, M. (2016). Discounting and augmentation in causal conditional reasoning: Causal models or shallow encoding? PLoS ONE, 11(12). https://doi.org/10.1371/journal.pone.0167741

A: The authors are pointing out that two events that are unconditionally independent can be dependent when conditioned on a third event. For example, toss a fair coin twice. Let $H_1$ be the event that the first toss lands heads, and let $H_2$ be the event that the second toss lands heads. Then $H_1$ and $H_2$ are independent, i.e.,
$$
P(H_1\mid H_2)=\frac12=P(H_1).
$$ Now consider the event $Q$ that at least one head is observed on two tosses. You can check that
$$P(H_1\mid H_2, Q) = \frac12\ne \frac23 = P(H_1\mid Q),
$$
which is saying that $H_1$ and $H_2$ are not independent given $Q$. (Note the event $Q$ is a consequent of both $H_1$ and $H_2$.)


text:
Q: Encrypt an existing (important point) directory I'd like to encrypt an existing directory. I know there exists a software like cryptkeeper which could do such thins, but it doesn't allow to encrypt existing folder. With that software, we have to create one encrypt directory and put the existing directory in the new one. Could anyone be able to explain a clever way to do that from the shell or with an adapted software?
In fact, I'd like this file to be encrypted to protect it as much as possible (e.g., NSA). If I send this file to another user in other country, I want this file to be protected from hacker.
P.S. This file is very important. I work on a project since many years, and I want anyone could access this file.
Thanks in advance!

A: Use gpg. First, have the recipient of the files do:
gpg --gen-key

and follow the prompts to generate a 4096-bit RSA key. Then have the recipient do:
gpg --armor --export (name)

where name is the name given for the key in the first step. Then send the output of the command to you. Then you do:
gpg --armor --import

and paste in the key. For increased security, do:
gpg --list-keys --fingerprint

and confirm the fingerprint with the recipient by phone (the public key does not need to be sent confidentially, but it does need to not have been tampered with). Then, to encrypt a file for sending, do:
gpg --encrypt --recipient (name) <file.clear >file.encrypted

To make a single file out of a directory tree, use tar:
tar -f file.clear -C /path/to/directory -c .

You don't need to compress the tar file, as gpg does its own compression. The recipient can use gpg --decrypt to decrypt and then tar -x to unpack the tar file.

A: There are several ways to transfer safely folders and files over the Internet. Of course, whenever you put some archive on someone else's disk you run the risk that the space is «jeopardized», i.e. that it has been somehow hacked. That's why the best (but absolutely useless by today standards) method would be to keep your files at home, on a good safe vault. So, you have to compromise. This means that you have to take extra cautions to avoid mistakes.
I'd suggest the following procedures. They have advantages and disadvantages. In any case it is a good practice to employ strong passwords.
First option
Owncloud or Nextcloud. At this stage they are pretty similar, as Nextcloud is a recent fork from mid-2016. If you choose to use either of them, you will have to set your own server (which is best), or you can hire a shared hosting service, or even a VPS. As an admin, be sure to enable both the encryption module as well as the server side encryption. If some has access to the file within the server they will only see the file name but the content will be useless. You can share files or directories. Ubuntu has an official owncloud client to sync.

Second option
Seafile offers the option to encrypt a folder, but in this case you can only share the whole folder. You will have to register with them to download and install your own server. It seems easier to pay their service.

Third option
If you don't plan to share frequently, you can always compress a folder, encrypt it and send it, provided that it is not that large.
First, install seahorse-nautilus. Then, quit and restart Nautilus. You can now compress and encrypt. Your receiver must know the password: use Telegram's Secure Chat or some other private communication service.


text:
Q: How to mock class instantiated inside function - Sinon? Let say I have a function like follow.
import NetworkService from './services';

async function sendAPIRequest(data: any){
  // validations
  const service = new NetworkService();
  await service.call(data)
}

my test looks like this which used mocha, chai, sinon.
describe('sendAPIRequest', function(){
   it('make api', async function(){

       // trying to mock Network service like below
       const serviceMock = sinon.createStubInstance(NetworkService);
       await sendAPIRequest({name: 'foobar'})
   });
});

but I am getting error like

Error: Expected to stub methods on object but found none

How to mock my NetworkService. when testing sendAPIRequest.

A: sinon.createStubInstance() API will not replace the original call method of the imported NetworkService with a stubbed one. It just creates a stub instance, so you need to pass this stub instance into your sendAPIRequest and use it. Which means you should use it as a dependency injection pattern.
There are two ways to test your code:

*

*stub the call method in the NetworkService.prototype
index.ts:
import NetworkService from "./services";

export async function sendAPIRequest(data: any) {
  const service = new NetworkService();
  await service.call(data);
}

services.ts:
export default class NetworkService {
  public async call(data) {
    return "real implementation";
  }
}

index.test.ts:
import sinon from "sinon";
import NetworkService from "./services";
import { sendAPIRequest } from "./";

describe("sendAPIRequest", function() {
  afterEach(() => {
    sinon.restore();
  });

  it("should make api", async () => {
    const callStub = sinon.stub(NetworkService.prototype, "call");
    await sendAPIRequest({ name: "foobar" });
    sinon.assert.calledWithExactly(callStub, { name: "foobar" });
  });
});

Unit test results with coverage report:
 sendAPIRequest
    ✓ should make api

  1 passing (12ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |       95 |      100 |    83.33 |    94.44 |                   |
 index.test.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
 services.ts   |       75 |      100 |       50 |       75 |                 3 |
---------------|----------|----------|----------|----------|-------------------|

*use proxyquire module

index.test.ts
import proxyquire from "proxyquire";
import sinon from "sinon";

describe("sendAPIRequest", function() {
  afterEach(() => {
    sinon.restore();
  });

  it("make api", async function() {
    const networkServiceInstanceStub = {
      call: sinon.stub(),
    };
    const NetworkServiceStub = sinon.stub().callsFake(() => networkServiceInstanceStub);
    const { sendAPIRequest } = proxyquire("./", {
      "./services": {
        default: NetworkServiceStub,
      },
    });
    await sendAPIRequest({ name: "foobar" });
    sinon.assert.calledOnce(NetworkServiceStub);
    sinon.assert.calledWithExactly(networkServiceInstanceStub.call, { name: "foobar" });
  });
});

Unit test results with coverage report:
  sendAPIRequest
    ✓ make api (279ms)

  1 passing (286ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |    95.24 |      100 |    85.71 |       95 |                   |
 index.test.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
 services.ts   |       75 |      100 |       50 |       75 |                 3 |
---------------|----------|----------|----------|----------|-------------------|

Related post:

*

*Why is the constructor invoked despite calling createStubInstance?

*Can ES6 constructors be stubbed more easily with Sinon?
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59897060


text:
Q: Detecting iPhone movement on a flat surface I'm a coremotion beginner.
I need to detect iPhone movement on a flat surface like table - so far, I made it to detect its sideways movement by accessing the yaw of the gyro, but I can't think of a way to detect the up/down changes. I tried using the accelerometer, but it detects more of a device tilt than movement. Also, there is a counterforce when the movement stops.
Do you have any idea to do it so that it would be possible to have the movement data with fair precision? I need it for something like air-hockey game.

A: In order to determine horizontal position from the deviceMotion is not really doable. The horizontal sensors to use would be the accelerometers, but they measure changes in speed. Therefore, to find position from that, you would need to integrate the sensor data twice. Once to get speed, then a second time to get position.
That means that even the smallest inaccuracy in the acceleration data will make an error in the resulting speed, meaning that your program thinks the phone is moving at constant speed, while in reality it is standing still.
If you don't need to be accurate (for example, when you do not need it to come back to the same position when you move it back and forth), then you might get acceptable results if you force the speed to zero if the accelerometer data is quiet and close to zero.
If you are really set on trying this, then a Kalman filter is probably your best bet to derive speed and position from the accelerometer data.
That means that your code will in the end look something like the following, where acceleration, speed, and position are three variables you keep, and acc is a data sample from the accelerometer.
// correction step:
double delta = (acc - acceleration);
acceleration += FACTOR1 * delta;
speed += FACTOR2 * delta;
position += FACTOR3 * delta;

// prediction step:
position = position + speed * DT + 0.5 * acceleration * DT * DT;
speed = speed + acceleration * DT;

where DT is the time between data samples, and suitable values for FACTOR1..3 you will need to find out.
By the way, Yaw does not give you horizontal motion, but rotation.

EDIT: Nowadays, you may get good results with ARKit's Motion Tracking, which combines accelerometer input with image analysis from the camera. It does all the hard work for you.

A: So I'm pretty new to CoreMotion as well. I'll give my best shot at explaining why what you ask can't be done, at least not accurately.
Based on the Apple Docs I read, there are 3 motion handlers for iOS:

*

*Accelerometer

*Gyroscope

*Magnetometer

(I believe the newest devices have an altimeter?)
Based on my understanding of physics, I gathered that accelerometer would be most useful for your scenario, as the gyroscope and magnetometer are more focused on rotation. I did some research and found this book. Chapter 9.5 in particular. From the book:

While an accelerometer provides measurement of forces in the x-, y-, and
  z-axes it cannot measure rotations. On the other hand, a gyroscope is
  a rate-of-change device; as the phone rotates around an axis, it
  allows you to measure the change in such rotations.

Following their code under figure 9-5 for implementing a simple app to watch the acceleration:
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface ViewController : UIViewController {

    CMMotionManager *motionManager;
    NSOperationQueue *queue;
}

@property (weak, nonatomic) IBOutlet UILabel *xLabel;
@property (weak, nonatomic) IBOutlet UILabel *yLabel;
@property (weak, nonatomic) IBOutlet UILabel *zLabel;

@property (weak, nonatomic) IBOutlet UIProgressView *xBar;
@property (weak, nonatomic) IBOutlet UIProgressView *yBar;
@property (weak, nonatomic) IBOutlet UIProgressView *zBar;

@end

Then in the .m viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];

    motionManager = [[CMMotionManager alloc] init];
    motionManager.accelerometerUpdateInterval  = 1.0/10.0; // Update at 10Hz
    if (motionManager.accelerometerAvailable) {
        NSLog(@"Accelerometer avaliable");
        queue = [NSOperationQueue currentQueue];
        [motionManager startAccelerometerUpdatesToQueue:queue
          withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
            CMAcceleration acceleration = accelerometerData.acceleration;
            xLabel.text = [NSString stringWithFormat:@"%f", acceleration.x];
            xBar.progress = ABS(acceleration.x);

            yLabel.text = [NSString stringWithFormat:@"%f", acceleration.y];
            yBar.progress = ABS(acceleration.y);

            zLabel.text = [NSString stringWithFormat:@"%f", acceleration.z];
            zBar.progress = ABS(acceleration.z);
        }];

    }
}

After linking everything up and running it on the phone, I see that the accelerometer is measuring the changes of my phone accelerating and decelerating as I move it on a flat table. Now we have the acceleration, but to get the change in position (which is what you asked) from that requires double integration (ie fun calculus). While doable, I looked up what the knowledgeable folks over at arduino have to say about that here and boy is it grim news. (They aren't discussing the iPhone accelerometer but I extrapolated that this info applies to this question as well).
The relevant parts I've posted here:

Getting position from acceleration is a double integration, so the
  error stackup is really evil. Getting good position data with a bolted
  down IMU (what you are trying to do) is a genuinely hard problem; the
  kind of accelerometers needed to do it are very expensive.

and

What you are talking about is double integration, which is just too
  inaccurate with a single accelerometer on this hardware. Even single
  integration will have a growing error per unit time simply because of
  the lack of accuracy in this setup.

All of this research leading up to my conclusion that it's not feasible on an iPhone to do what you ask. Though like I said, I'm a beginner at this as well! Sorry that this isn't the answer you wanted to hear.

A: The device cannot detect movement. A straight-line constant motion along the surface of the table is absolutely undetectable. That is because there no forces acting.
The device can detect only attitude (orientation in space, and change in that orientation) and force (increase or decrease in velocity).
So, you need to form your expectations around those abilities.

A: This link may be able to explain things a little more
http://blog.denivip.ru/index.php/2013/07/the-art-of-core-motion-in-ios/?lang=en
It seems like you need to pick up on the Y-Axis Acceleration though. The Apple Docs seem to cover this pretty well. https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/motion_event_basics.html
Use the motion-handling methods to detect when motion changes and then access the change in y position. I can attempt to provide some code if you'd like as well.


text:
Q: Send image data with AJAX request I have this working code in Python
reponse = requests.post(url, auth=auth, data=open('image.jpg','rb'))

I need to do the exact same thing with AJAX, just in this case image is base64 encoded
$.ajax({type: 'POST',
        username: username,
        password: password,
        data: atob(image),
        url: url,
        success: function(response) { ... }});

also tried
var fd = new FormData();
fd.append('fname', 'image.jpg');
fd.append('data', atob(image));
$.ajax({type: 'POST',
        username: username,
        password: password,
        data: fd,
        processData: false,
        contentType: false,
        url: url,
        success: function(response) { ... }});

I can't seem to get it working. The call itself is a success, but the API on the other side does not seem to be getting the image. What am I missing ?

A: Apparently contentType needed to be set manually to a value corresponding to the data. It's working now with the proper contentType.


text:
Q: Countif yes in Power Query How can I do Countifs of dates in Power query?
I have multiple columns with 2 dates columns.
I need to count the rows that meet the 2 dates criteria of status.
Criteria and objective: Identify obvious potential overlaps. If one order# is started before the last one is completed, we should flag that as Yes.
My data model has a date table. My challenge is getting the current row in Rep# as criteria. Please see the sample data for more reference. The formula that I use is listed below. Also, I have attached data image.
=IF((COUNTIFS($C$2:$C$40,"<="&D2,$D$2:$D$40,">="&C2,$A$2:$A$40,"="&A2))>1,"YES","NO")

My challenge is getting the current row in Rep# as criteria. Please see the sample data for more reference.
  A    B         C                    D               E
15   84165  6/6/17 6:22 PM      6/6/17 8:45 PM        NO
15   83671  6/6/17 8:46 PM      6/6/17 10:11 PM       NO
15   84410  6/13/17 11:27 AM    6/13/17 1:17 PM      YES
15   83410  6/13/17 11:27 AM    6/13/17 1:32 PM      YES
15   84471  6/13/17 1:18 PM     6/13/17 1:50 PM      YES
15   84773  6/17/17 3:03 PM     6/17/17 6:35 PM       NO
15   84471  6/27/17 11:06 PM    6/28/17 1:05 AM       NO
15   85092  6/28/17 1:07 AM     6/28/17 2:05 AM       NO
15   85577  7/11/17 6:10 PM     7/11/17 8:01 PM      YES
15   85546  7/11/17 6:10 PM     7/11/17 9:30 PM      YES

Thanks in Advance.

A: Assuming data is in range Table1 with column headers as shown in your example then this should work
In the opened Power Query Editor window and on the ribbon bar, choose: Home => Advanced Editor and paste it in
The magic is in the 3rd line which grabs all matching rows based on criteria for current values of Rep, Time In and Time Out
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Rep#", Int64.Type}, {"Order#", Int64.Type}, {"Date/Time In", type datetime}, {"Date/Time Out", type datetime}}),
Total = Table.AddColumn(#"Changed Type", "Count",(i) => Table.RowCount(Table.SelectRows(#"Changed Type", each ([#"Rep#"] = i[#"Rep#"] and [#"Date/Time In"] <= i[#"Date/Time Out"] and [#"Date/Time Out"] >= i[#"Date/Time In"] ))), type number ),
#"Added Custom" = Table.AddColumn(Total, "YES_NO", each if [Count]>1 then "YES" else "NO")
in #"Added Custom"


text:
Q: Add color of each pixel to ArrayList - java I want to add the red-Value of each pixel of an Image to an ArrayList.
This is my code:
BufferedImage image = null;
    try {
        image = ImageIO.read(imageFile);
    } catch(IOException e) {
        e.printStackTrace();
    }

    ArrayList<List<List<Integer>>> colors = new ArrayList<List<List<Integer>>>();

    for ( int i = 0; i < image.getHeight(); i++ ) {
        for ( int j = 0; j < image.getWidth(); j++ ) {
            colors.get(i).get(j).add(new Color(image.getRGB(i, j)).getRed());
        }
    }

But I get this error: Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0.
What do I do wrong?

A: I think that you only need a list of lists to represent the 2d nature of the pixels (you currency have a list of list of lists).  Each time you iterate over each pixel of height you should create a new as shown below.
   List<List<Integer>> colors = new ArrayList<List<Integer>>();

   for ( int i = 0; i < image.getHeight(); i++ ) {
        List<Integer> rowOfColours = new ArrayList<Integer>();
        colors.add(rowOfColors);

        for ( int j = 0; j < image.getWidth(); j++ ) {
            rowOfColours.add(new Color(image.getRGB(i, j)).getRed());
        }
    }

A: Use PillHead's answer. If later you want to get the whole pixel then slightly alter the code to:
for ( int i = 0; i < image.getHeight(); i++ ) {
    List<Integer> rowOfPixelData = new ArrayList<Integer>();
    colors.add(rowOfPixelData);

    for ( int j = 0; j < image.getWidth(); j++ ) {
        rowOfPixelData.add(image.getRGB(i, j));
    }
}

From there you can extract the values you want. This website has lots of good information on how to get the Red, Green, Blue, and Alpha values from the integer returned by image.getRGB(i, j).


text:
Q: Remove Duplicate rows in left join base on one column I want to remove the duplicates column with the same id. I want to keep only the first one that shows up.
    SELECT  t.ticketId ,t.userIdOwner , t.ticketCreateDatetime , t.ticketExpectedEndDatetime , t.ticketUpdateDatetime, t.ticketUpdateBy, t.ticketLabel,t.statusTypeIdTicketState,t.statusTypeIdTicketType,t.statusTypeIdTicketModule,
    c.clientLabel, c.clientLogoOnList ,s.taskLabel , s.statusTypeIdTaskCompletion
    FROM ticket AS t
    INNER JOIN client AS c
    ON c.clientId = t.clientId
     LEFT  JOIN task AS s
    ON s.ticketId = t.ticketId  AND  s.statusTypeIdTaskCompletion = (SELECT statusTypeId FROM statusType WHERE statusTypeCode = 'waitingTask' AND statusTypeTargetTable = 'statusTypeIdTaskCompletion'  )

    WHERE 1=1
    AND t.ticketDeleteDatetime IS NULL

Here's my screen of results

Edit Image query all results
enter image description here
Edit Image of task structure table  :
enter image description here

A: You probably have more tasks for each ticket with same statusType
so, if you don't care about different tasks, you can simply add a DISTINCT clause in your SELECT
SELECT DISTINCT
    t.ticketId ,t.userIdOwner , t.ticketCreateDatetime , t.ticketExpectedEndDatetime ,
    t.ticketUpdateDatetime, t.ticketUpdateBy, t.ticketLabel,t.statusTypeIdTicketState,
    t.statusTypeIdTicketType,t.statusTypeIdTicketModule,
    c.clientLabel, c.clientLogoOnList ,s.taskLabel , s.statusTypeIdTaskCompletion
FROM ticket AS t
INNER JOIN client AS c ON c.clientId = t.clientId
LEFT  JOIN task AS s ON s.ticketId = t.ticketId  AND  s.statusTypeIdTaskCompletion = (
    SELECT statusTypeId
    FROM statusType
    WHERE statusTypeCode = 'waitingTask'
    AND statusTypeTargetTable = 'statusTypeIdTaskCompletion'
)
WHERE 1=1
AND t.ticketDeleteDatetime IS NULL

ok, after your edit, now we can see, that the problem is that more than one task is eligible for the ticket.
Unfortunaterly "the first that show up" is not a valid SQL statement (because the same query could give different results depending on different circumnstances).
So you have to decide wich one to keep, you need to decide a rule, a logic to keep one of the rows.
If you don't need the task label you can simply strip off that column and use the DISTINCT.
If you want to show a task label but don't mind which one, you can use MAX(s.taskLabel) and group by on all other columns.
If you want to keep the last task for that ticket you should provide informations about cronological order (a datetime column or an autoincrement column)
Example with MAX(taskLabel):
SELECT
    t.ticketId,
    t.userIdOwner,
    t.ticketCreateDatetime,
    t.ticketExpectedEndDatetime,
    t.ticketUpdateDatetime,
    t.ticketUpdateBy,
    t.ticketLabel,
    t.statusTypeIdTicketState,
    t.statusTypeIdTicketType,
    t.statusTypeIdTicketModule,
    c.clientLabel,
    c.clientLogoOnList,
    s.taskLabel,
    s.statusTypeIdTaskCompletion

FROM ticket AS t
INNER JOIN client AS c ON c.clientId = t.clientId
LEFT JOIN (
    SELECT s.ticketId, MAX(s.taskLabel) AS taskLabel
    FROM task AS s
    WHERE s.statusTypeIdTaskCompletion = (
        SELECT statusTypeId
        FROM statusType
        WHERE statusTypeCode = 'waitingTask'
        AND statusTypeTargetTable = 'statusTypeIdTaskCompletion'
    )
    GROUP BY s.ticketId
) S ON s.ticketId = t.ticketId
WHERE 1=1
AND t.ticketDeleteDatetime IS NULL


text:
Q: How to design SSRS Report and SQL Server Table if data has a hierarchy? I have to design table and the SSRS report that contains data in below format.
Please click on below URL to download excel sheet here
Once you downloaded the file, see the tab that contains RAW Data. It lists all the figures on row with rollover summation (i.e states "A-F", "G-N" and "O-Z") and months are separated by columns
The issue here is that the month should be generated dynamically based on current month. Hence right now the report shows data for September Month, but I am not sure how to store values for future month in database and how to show all months data in report.
Should I create table with all future months or should I mentions "Months" column dynamically?
Please note that USA states and rollover formula remains constant and I am able to write a query to generate states value.
The database structure I have thought of (& the reporting structure) is visible in Tab "Sample Report"

A: I am just trying what you have tried to do. i think you need to create column grouping for month. just try with below dataset for your ref.
CREATE TABLE #TEMP_RAW_DATA
(
    N_id NUMERIC(18,0) IDENTITY(1,1),
    VC_Country VARCHAR(30),
    VC_States VARCHAR(50),
    D_Date DATE,
    I_Values INT
)

INSERT INTO #TEMP_RAW_DATA
(
    VC_Country,VC_States,D_Date,I_Values
)
SELECT 'USA','Alabama','09-01-2019',57 UNION ALL
SELECT 'USA','Alabama','10-01-2019',47 UNION ALL
SELECT 'USA','Alabama','11-01-2019',69 UNION ALL
SELECT 'USA','Alabama','12-01-2019',1 UNION ALL
SELECT 'USA','Alabama','01-01-2020',42 UNION ALL
SELECT 'USA','Hawaii','09-01-2019',80 UNION ALL
SELECT 'USA','Hawaii','10-01-2019',55 UNION ALL
SELECT 'USA','Hawaii','11-01-2019',19 UNION ALL
SELECT 'USA','Hawaii','12-01-2019',73 UNION ALL
SELECT 'USA','Hawaii','01-01-2020',76 UNION ALL
SELECT 'USA','Massachusetts','09-01-2019',20 UNION ALL
SELECT 'USA','Massachusetts','10-01-2019',74 UNION ALL
SELECT 'USA','Massachusetts','11-01-2019',30 UNION ALL
SELECT 'USA','Massachusetts','12-01-2019',36 UNION ALL
SELECT 'USA','Massachusetts','01-01-2020',53 UNION ALL
SELECT 'USA','Pennsylvania','09-01-2019',53 UNION ALL
SELECT 'USA','Pennsylvania','10-01-2019',17 UNION ALL
SELECT 'USA','Pennsylvania','11-01-2019',1 UNION ALL
SELECT 'USA','Pennsylvania','12-01-2019',13 UNION ALL
SELECT 'USA','Pennsylvania','01-01-2020',42 UNION ALL
SELECT 'USA','Virginia','09-01-2019',26 UNION ALL
SELECT 'USA','Virginia','10-01-2019',24 UNION ALL
SELECT 'USA','Virginia','11-01-2019',29 UNION ALL
SELECT 'USA','Virginia','12-01-2019',79 UNION ALL
SELECT 'USA','Virginia','01-01-2020',73

SELECT VC_Country,VC_States,DATENAME(MONTH,D_Date) VC_Month,
CASE
    WHEN PATINDEX('[a-f]%',VC_States)>0 THEN 'A-F'
    WHEN PATINDEX('[g-n]%',VC_States)>0 THEN 'G-N'
    WHEN PATINDEX('[o-z]%',VC_States)>0 THEN 'O-Z'
END VC_Group,
SUM(I_Values) I_Values
FROM #TEMP_RAW_DATA
GROUP BY VC_Country,VC_States,
CASE
    WHEN PATINDEX('[a-f]%',VC_States)>0 THEN 'A-F'
    WHEN PATINDEX('[g-n]%',VC_States)>0 THEN 'G-N'
    WHEN PATINDEX('[o-z]%',VC_States)>0 THEN 'O-Z'
END,DATENAME(MONTH,D_Date)


text:
Q: How to implement MultipartFormDataContent in net framework 3.5 I have a web forms application in net framework 3.5, I must send a request to a web api built in net 6, which receives an object through the [FromForm] decorator. I already have something similar done between two applications in net 6 using MultipartFormDataContent but as far as I read this it only exists up to version 4.5 :(
What is the best way to do it or what alternative can I take?
First of all, Thanks.
Greetings