text:
Q: Unimodality of q-binomial coefficients The q-Pochhammer symbol $[n]_q!$ is defined as
$$[n]_q! = \frac{(1-q^n)(1-q^{n-1})\cdots(1-q)}{(1-q)^n} = (1+q) (1+q+q^2) \cdots (1+q+\cdots+q^{n-1})$$
It can be easily shown that $[n]_q!$ (function of indeterminate $q$) is symmetric and unimodal, since it is the product of symmetric and unimodal sequences.
The q-binomial coefficient is defined similarly as,
$${n \choose k}_q = \frac{[n]_q!}{[k]_q![{n-k}]_q!}$$
It can be easily seen that ${n \choose k}_q$ is a polynomial in $q$ (and not a rational polynomial in $q$) from the recurrence relation
$${n \choose k}_q  = q^k {{n-1} \choose k}_q  + {{n-1} \choose {k-1}}_q $$
Can somebody show me an easy way to prove that ${n \choose k}_q$ is also symmetric and unimodal?
Edit: A polynomial in indeterminate $x$, F(x) = $\sum_{i=0}^n a_i x^i$ is defined to be symmetric when the sequence $\{a_i\}_{i=0}^n$ is unimodal and symmetric. The sequence $\{a_i\}_{i=0}^n$ is defined to be unimodal and symmetric if -
$$a_0 \leq a_1 \leq .... \leq a_{\lfloor{n/2}\rfloor}$$
and
$$a_k = a_{n-k}$$
Now for ${n \choose k}_q = F(q)$, we have $F(q) = q^{{(nk-k^2)}} F(1/q)$ therefore, $F(q)$ must be symmetric (in the above sense). How do I show it to be unimodal?

A: The symmetry ${n \choose k}_q = {n \choose n-k}_q$ follows immediately from
the formula ${n \choose k} = [n]_q! \bigl/ \bigl([k]_q! [n-k]_q!\bigr)\bigr.$.
Unimodality for all $q>0$ follows from the fact that
$\bigl\{{n \choose k}_q\bigr\}_{k=0}^n$ is log-concave:
$$
{n \choose k}_q^2 > {n \choose k-1}_q \,{n \choose k+1}_q
$$
(all $k=1,2,\ldots,n-1$), which in turn follows from the fact that
the sequence $\{[n]_q!\}_{n=0}^\infty$ is log-convex
(i.e. $[n]_q^2 < [n-1]_q [n+1]_q$ for all $n>0$).
Both of these generalize proofs for classical binomial coefficients
${n \choose k} = n! / (k! (n-k)!)$.

A: This is a famously difficult problem in combinatorics. The following is the outline of an algebraic proof by Richard Stanley, using the theory from his textbook Algebraic Combinatorics.
The proof requires the theory of graded posets. A poset is a set equipped with a partial order. If $x,y$ are poset elements, we say $x$ covers $y$ if $x> y$, and there is no poset element $z$ with $x>z>y$. Then, a poset is called graded if there exists a rank function defined on the poset, such whenever $x$ covers $y$, the rank of $x$ is one more than the rank of $y$. We also usually normalize things so all minimal elements of the poset have rank zero. Finally, a poset is called rank-unimodal if the sequence of sizes of the ranks is unimodal, increasing up to a widest point in the poset's middle and decreasing thereafter.
A common example of a poset is $B_n$, the Boolean poset of the set of subsets of an $n$ element set. Stanley's big theorem concerns a certain quotient poset of $B_n$. Given a subgroup $G$ of $S_n$, the symmetric group on the same $n$-element set, we get an induced action on $B_n$ in a natural way. We then turn the set of orbits of this action into a poset, by saying for all $S,T\in B_n$ that $\text{orbit}(S)\le \text{orbit}(T)$ whenever there exists permutations $g_1,g_2\in G$ such that $g_1(S)\subseteq g_2(T)$. This poset on orbits is denoted $B_n/G$.

Theorem: (Stanley) Let $G$ be a subgroup of $S_n$. Then the quotient poset $B_n/G$ is rank unimodal.

I omit the proof, but you can read it in Stanley's book hosted by Stanley for free online, Theorem 5.8.
Therefore, in order to prove that the coefficient sequence of $\binom{n}{k}_q$ is rank unimodal, it suffices to find a poset where the size of the $i^{th}$ rank is the coefficnet of $q^i$ in $\binom{n}k_q$, for each $0\le i\le k(n-k)$, and prove that this poset can be realized as the quotient of a Boolean poset by a group action.
For positive integers $m,n$, let $L(m,n)$ be the poset of integer partitions with at most $n$ parts, where every part is at most $m$, where $(\lambda_1,\dots,\lambda_n)\le (\mu_1,\dots,\mu_n)$ if $\lambda_i\le \mu_i$ for all $i\in \{1,\dots,n\}$. Equivalently, these are lattice paths in an $m\times n$ rectangle, ordered by subset inclusion of the regions beneath the path. It is well known that the rank of path is the area of the region beneath, and that the numbers of paths with each rank exactly match the coefficients of $\binom{m+n}{m}_q$.
To realize this as a quotient of a Boolean poset, we will use $B_{m\times n}$, where we think of this as subsets of the $m\times n$ boxes forming the lattice rectangle spanned by $(0,0)$ and $(m,n)$. The permutation group  $G$ acting on this array of boxes is as follows: $G$ is the set of permutations given by arbitrarily permuting within each row, and then permuting the rows themselves. It can be shown for any subset $S$ of the grid, the orbit of $S$ under this action will contain exactly one subset where every row is left-justified, and every columns is bottom-justified, which exactly corresponds to the region below some lattice paths. In this way, we can see that $L(m,n)$ is just the quotient of $B_{m\times n}$ by this action. Applying Stanley's theorem, we conclude the coefficents of $\binom{m+n}{m}_q$ are unimodal.
Over the years, other proofs have been given.

*

*Igor Pak and Greta Panova gave a proof using Schur functions: https://arxiv.org/abs/1306.5085

*Kathy O'hara gave a combinatorial proof. Here is an exposition of her proof by Doron Zeilberger: https://www.jstor.org/stable/2325177


text:
Q: PHP::MongoCollection->aggregate alternative or fix I'm using xhgui and getting this error:

127.0.0.1:27017: no such cmd: aggregate

Stack trace:

/var/www/profiler/src/Xhgui/Profiles.php(172): MongoCollection->aggregate(Array)

Code:
$mongo = new MongoClient($config['db.host'], $config['db.options']);
$db = $mongo->$config['db.db'];
$results = $db->results->aggregate(array(
    array('$match' => $match),
    array(
        '$project' => array(
            'date' => $col,
            'profile.main()' => 1
        )
    )
));

Is it possible to fix this error? Maybe need to update mongo extension OR is there any other alternative way?

A: This appears to actually be a problem with your MongoDB instance itself. Aggregation was introduced in version 2.2 of MongoDB, so if your server is running an older version, it won't understand the aggregate() command.
https://docs.mongodb.org/manual/core/aggregation-introduction/

redpajama_set_name: RedPajamaStackExchange


text:
Q: ARM - Infinite Loop While Searching String Can anybody point out why? I can't see the problem.
String to search: "aassaas"
String to search with: "as"
SEARCHSTRING:
  STMFD SP!, {R4-R7, LR}

  MOV R6, #0               @Matches found
  MOV R3, #0               @Placeholder

LOOP: LDRB R4, [R0]        @R4 = String to search
  LDRB R5, [R1]            @R5 = String to search with

  CMP R4, R5               @Do they match?
  ADDEQ R3, R3, #1         @If yes, increase placeholder
  LDREQB R4, [R0, #1]!     @Get next char
  LDREQB R5, [R1, #1]!     @Get next char
  BLNE RESET               @If not, reset placeholder and strings.
                           @R0 is nevertheless initial pos+1
  CMP R5, #0               @Is string to search with at the end?
  ADDEQ R6, R6, #1         @If so, add +1 to matches
  BLEQ RESET               @Reset placeholder and strings.

  CMP R4, #0               @Is the string to search finished?
  BNE LOOP                 @If not, start over.

  MOV R0, R6               @If so, move answer into R0.
  LDMFD SP!, {R4-R7, PC}   @Jump back.

RESET:
  STMFD SP!, {LR}

  CMP R3, #0               @Is the placeholder at 0? (initial position)
  SUBNE R0, R0, R3         @If not, subtract from String to search pos
  SUBNE R1, R1, R3         @And string to be searched pos
  ADDNE R0, R0, #1         @Increment string to search+1 so we don't start at the same spot
  MOVNE R3, #0             @Empty the placeholder

  LDMFD SP!, {PC}          @Jump back

A: I don't understand why a) you're writing this in assembler instead of C, and b) why you're not using some routine based on strstr.  The most likely scenario is that this is a homework problem, or some other form of learning exercise, so I don't want to give too much away.  In any event, there are a couple of problems that I noticed.  The first bit I notice is in the RESET routine:
RESET:
  STMFD SP!, {LR}

  CMP R3, #0               @Is the placeholder at 0? (initial position)
  SUBNE R0, R0, R3         @If not, subtract from String to search pos
  SUBNE R1, R1, R3         @And string to be searched pos
  ADDNE R0, R0, #1         @Increment string to search+1 so we don't start at the same spot
  MOVNE R3, #0             @Empty the placeholder

  LDMFD SP!, {PC}          @Jump back

The CMP is unnecessary - consider what the effect of the SUBNE calls will be if R3 is 0, and you'll see that you can perform the subtractions unconditionally.  You want to run ADD R0, R0, #1 unconditionally - in fact, this is a big part of the reason you have an infinite loop.  If you get to the RESET subroutine, and R3 is 0, then it doesn't change any state.  I also notice that the STMFD / LDMFD pair is really not necessary - LR won't be modified in this subroutine, so it doesn't need to go on the stack.
Next, I notice that you're not careful enough about when to terminate your loop.  Consider what happens if you give two empty strings as arguments to SEARCHSTRING.  Call it with two empty strings as arguments, and single-step through your assembly code to see the problem.  The general form of a for loop, when compiled to assembly, will be something like:
for(initial; comparison; increment) {
  body;
}

INITIAL:
    MOV R0, #0         @initialize variables
    B CONDITION        @jump to condition check
BODY:
    LDR R1, [R0]
INCREMENT:             @really, part of the for-loop body.
    ADD R0, R0, #1
CONDITION:
    CMP BLAH, BLAH     @test-condition
    BLT BODY           @restart loop if condition indicates we should do so.

hopefully this will help you to reorganize the code in a more straightforward way.


text:
Q: Passing quoted argument in json payload to shell script I am working on a python script that passes arguments to a shell script that lives in a Docker container. I'm achieving this using this Go webhook tool (https://github.com/adnanh/webhook). So far I've had success passing simple arguments to my shell script via the requests module. However, I've hit a roadblock.
The purpose of my tool is to trigger a dna assembly program that has a number of optional parameters that can be tuned by users. Currently, I have been triggering the webhook like so:
def trigger_assembler(out, assem_opts):
    id = "assemble"
    payload = {"FWD": f"-f data/{out}/R1.fq", "REV": f"-r data/{out}/R2.fq", "OUT": f"-o {out}",
                "OPT": f'-p \" {assem_opts} \"'}

    try:
        r = requests.post(f"http://0.0.0.0:9000/hooks/{id}", json=payload)
        r.raise_for_status()
    except requests.exceptions.RequestException as e:  # This is the correct syntax
        raise SystemExit(e)

In the shell script I am parsing the arguments and then trying to execute the following command:
   nohup Trinity --left "${FWD}" --right "${REV}" "${ASSEM_ARGS}" \
    --output data/"${OUT}"/trinity &

I have tried escaping the double quotes as you see in the example code. I have tried various numbers of backslashes after reading other stack overflow answers. I have tried simply using single quotes for the f-string and using double quotes within the string. None of these approaches has worked. No matter what I do there is a backslash present in the arguments delivered to my shell script, which obviously is problematic.
Also, I have tested the shell script in isolation with arguments of the form that I am hoping to pass and it works fine, so the problem seems to not be on that end.
Thanks for your help.

A: If anyone comes here looking for an answer, I never found one! I decided to store information in a yaml file that was accessible to all containers in my system. I would still very much like to know how to work around this problem in the future.

A: try this, pass-arguments-to-command pass argument as array start from 1
source:  https://github.com/adnanh/webhook/issues/357
another reference  https://gitlab.com/-/snippets/1972594
//payload json
{
    "data": {
        "id": "1651565",
        "username": "change me"
    }
}

---

//hook.json
[
  {
    "id": "payload",
    "execute-command": "/path/to/command.sh",
    "response-message": "Executing simple webhook...",
    "pass-arguments-to-command":
    [
      {
        "source": "payload",
        "name": "data.id"
      },
      {
        "source": "payload",
        "name": "data.username"
      }
   ]
  }
]

---

//command.sh
#!/bin/sh
ID=$1
USERNAME=$2

echo $ID //1651565
echo $USERNAME //change me


text:
Q: Output additional attributes WEKA 3.8 I am using GUI version of WEKA and I am classifying using the Random Forest. I'm trying to find out which instances are misclassified.
I know that earlier versions of WEKA had and option of "Output additional attributes" where I can add instance Id and get around this problem, but now with WEKA 3.8 I can't see this option.

A: Answering my own question, on the preprocess tab you need to use the filter addID or you can add your own attribute as string. Then you would have to use the classifier "FilteredClassifier" click on it and use the filter "Remove" specifying the index of the attribute that holds the id, and then start the classification.
To see the misclassified, right click on the the result int he Result List, choose Visualize classifier errors, then choose save as arff. This will result in seeing all the instances with their prediction.


text:
Q: What is the most influential work of Grothendieck in mathematics? Recently Alexander Grothendieck has passed away but his mathematical wave is still alive and passes its growth ages. It is hard to describe the influence of such a great man in mathematics just in few words and even more hard to determine a particular idea of him as the most influential but maybe some descriptive papers of some historians and expert researchers who work on his theories can help us to reach a better insight about it.

Question: What are examples of nice descriptive papers or books which are concentrated on impacts and connections of Grothendick's theorems and theories in mathematics, specially those which describe the influence of his works on those parts of mathematics which were developed before him and are under development now? In particular, as a logician I am interested in papers related to possible impacts of Grothendick's mathematical ideas on some fields of mathematicial logic like set theory and model theory.

A: The correspondence between Grothendieck and Serre during the period 1955-1987 illustrates how Grothendieck's mathematical work shifted from functional analysis to algebraic geometry. The correspondence edited by the American Mathematical Society has the special flavour of being bilingual.
http://www.amazon.com/Grothendieck-Serre-Correspondence-Pierre-Colmez-Grothendieck/dp/B0088OUXXY/ref=sr_1_1?s=books&ie=UTF8&qid=1416203841&sr=1-1

A: A very informative, brief paper is P. Deligne, Quelques idées maîtresses de l'œuvre de A. Grothendieck (Matériaux pour l'histoire des mathématiques au XXe siècle. Actes du colloque à la mémoire de Jean Dieudonné, Séminaires et Congrès 3), which focuses on Grothendieck's contribution to the theory of schemes, topos theory, homological algebra, and motives. (Thus it does of course not cover everything, in particular it says nothing about logic/set theory, but I guess it is agreed that this was not Grothendieck's speciality.) It can be found for instance here.


text:
Q: Why the normal distribution? This is a super soft question in a way, but I was wondering why the central limit theorem says that the distribution of means of converges to the normal distribution. I understand why we might want a symmetric distribution, and I understand why we might want the majority of mass centered at 0 (these are both elements of unbiased means). What I don't get is why the specific pdf we converge to is the normal distribution, and not some other "almost-gaussian" (symmetric, centered at zero) distribution?

This is mainly motivated by the fact that Lagrange's proof of the standard Gaussian integral seems kind of miraculous, but the general strategy seems to be creating a radially symmetric product measure from  a symmetric measure in one dimension by taking the measure product with itself. The problem is that, on a calculus level it seems like the normal distribution is kinda the only one Lagrange's proof will apply to, but on the measure theory level I don't really see why this is true. It seems that, a priori, there might be any number of symmetric distributions who's product measure with itself would be radially symmetric. My point is just that... the normal distribution doesn't seem that special, except for the CLT, which makes me think there is something special about it. I just don't get why it has to be the normal and not an almost-normal distribution, except, of course, for the fact that it is the case.

I guess my question is pretty simple, why not just an almost normal?

A: The derivations of the normal from the central limit theorem don't start or assume the form of the final distribution, instead they derive it. See Proof of CLT.


text:
Q: FLEX mx:DataGridColumn decode HTML entities automatically I would like to show HTML entities that encoded in grid cell like this:
|HTML ENTITY|

But the result is
|HTML ENTITY|

I used mx:DataGridColumn

A: I tried this, for me its coming with encoded value only in grid please send your data provider format
[Bindable]
private var myGAC:ArrayCollection = new
ArrayCollection([{label:"<div>"},{label:"<div>"},
{label:"<div>"},{label:"<div>"},{label:"<div>"}]);

<mx:DataGrid id="myGrid" dataProvider="{myGAC}" width="500" rowCount="2">
<mx:columns>
<mx:DataGridColumn dataField="label" />
</mx:columns>
</mx:DataGrid>


text:
Q: Get all Html5 Tags using Jsoup? Is there a way to get all html5tags with one command instead of doing this? :
int h = (doc.getElementsByTag("canvas").size()
                    + doc.getElementsByTag("audio").size()
                    + doc.getElementsByTag("embed").size()
                    + doc.getElementsByTag("source").size()

                        etc.

A: You can achieve the same result in one command using the select() method. This method allows you to specify multiple selectors, and Jsoup will return unique elements from the document that match any of the specified selectors.
For example:
int h = doc.select("canvas, audio, embed, source").size();

You can add as many comma-separated arguments as you need (e.g. all of the new elements introduced in HTML5).

A: Here you are :
all_html5_tags = [ '!DOCTYPE' ,'a' ,'abbr' ,'acronym' ,'address' ,'applet' ,'area' ,'article' ,'aside' ,'audio' ,'b' ,'base' ,'basefont' ,'bdi' ,'bdo' ,'big' ,'blockquote' ,'body' ,'br' ,'button' ,'canvas' ,'caption' ,'center' ,'cite' ,'code' ,'col' ,'colgroup' ,'command' ,'datalist' ,'dd' ,'del' ,'details' ,'dfn' ,'dir' ,'div' ,'dl' ,'dt' ,'em' ,'embed' ,'fieldset' ,'figcaption' ,'figure' ,'font' ,'footer' ,'form' ,'frame' ,'frameset' ,'h1' ,'h2' ,'h3' ,'h4' ,'h5' ,'h6' ,'head' ,'header' ,'hgroup' ,'hr' ,'html' ,'i' ,'iframe' ,'img' ,'input' ,'ins' ,'kbd' ,'keygen' ,'label' ,'legend' ,'li' ,'link' ,'map' ,'mark' ,'menu' ,'meta' ,'meter' ,'nav' ,'noframes' ,'noscript' ,'object' ,'ol' ,'optgroup' ,'option' ,'output' ,'p' ,'param' ,'pre' ,'progress' ,'q' ,'rp' ,'rt' ,'ruby' ,'s' ,'samp' ,'script' ,'section' ,'select' ,'small' ,'source' ,'span' ,'strike' ,'strong' ,'style' ,'sub' ,'summary' ,'sup' ,'table' ,'tbody' ,'td' ,'textarea' ,'tfoot' ,'th' ,'thead' ,'time' ,'title' ,'tr' ,'track' ,'tt' ,'u' ,'ul' ,'var' ,'video' ,'wbr' ]


text:
Q: Move files two directories up & delete directories afterwards, using wildcards I have a folder structure like the below.

1/data/f4aa9d39291bc37a7cacedfab656a941/x1.jpg

The first slot and the random string in the third slot vary depending on the folder. (Let's say for this example, I have 30 folders at that top level, in an incrementing fashion.)
I need to move the JPGs up two levels, so it's using this folder structure and deletes that data folder in each directory as it goes along:

1/x1.jpg

I searched for any examples that could help, but I think because of the wildcard aspect I'm running into an issue. I had tried the below (note in the code I went one level up), but it didn't work.
find 1/*/data/*/. -name '*.jpg' -exec cp {} 1/* \;

Any help would be greatly appreciated. Combining both elements would be ideal, but I'm alright with help just for the non-deletion portion as I probably can write up a separate deletion script if I needed to.
(I'm using macOS's Terminal, if that affects anything code-wise.)

A: If your directory structure is
1/data/f4aa9d39291bc37a7cacedfab656a941/x1.jpg

and only data is a fixed string, then wildcards in the find command would be
find */data/* -name '*.jpg'

Run that command and see if the output is what you expect.
Running a batch script or command to delete files or directories is always dangerous.
This command will only move the files to the parent directory two levels above.
find */data/* -name '*.txt' -exec bash -c 'file={};path=${file%/*};name=${file##*/};echo "mv -v $path/$name ${path%%/*}"' \;

Run that and see if the output appears ok to you. It will only print the command line without actually execute it.
To really run the command, erase the echo command and the double quotes
find */data/* -name '*.txt' -exec bash -c 'file={};path=${file%/*};name=${file##*/};mv -v $path/$name ${path%%/*}' \;

To delete empty directories, the command would be like this, a little more safe since rmdir only deletes empy directories.
find */data/* -name '*.txt' -exec bash -c 'file={};path=${file%/*};name=${file##*/};echo "mv -v $path/$name ${path%%/*} && rmdir -v $path && rmdir -v ${path%/*}"' \;


text:
Q: WordPress custom post type category order I'm looking for a way to manually reorder the category list for custom post types,
are there any plug-ins that already do this?
I can probably code my own, but I'm not sure where to start, can you add custom fields to the categories that can be used to order them?
Anything to point me in the right direction would be great!

EDIT [resolved]
After a bit more digging I uncovered this:
http://wordpress.org/support/topic/plugin-my-category-order-custom-taxonomy-order-and-code-improvements
Which linked to this:
http://snipplr.com/view/48599/mycategoryorder-custom-taxonomy-mod/
and once you change line 51 to you custom taxonomy type it works like a charm, eg:
$tax = ($_GET['mytax'])? $_GET['mytax'] : 'category';

becomes
$tax = ($_GET['mytax'])? $_GET['mytax'] : 'my_custom_taxonomy';

works perfectly with 'Types' plugin linked by @Ajay Patel, cheers.

A: Not able to get you question perfectly.
But use this plugin Types - Custom Fields and Custom Post Types Management
Types makes it easy to customize the WordPress admin. Define your own content using custom post types and custom taxonomy. Redesign editing screens using custom fields.


text:
Q: Logo looks different after uploading
Hi, in the first picture you can see what logo I want to upload.
But, after uploading it changes it's color specification a little bit, shown in the second picture (right down corner). It adds the black color.
Could you please help me out?
The code I'm using:
axes(handles.axes13)
imshow('logo4.png')

A: The problem is in the original png. Here, the top of the logo is set as transparent while the bottom is white. So, when you plot the images using imshow, you have this effect. Either you change the logo png or you can pretend as this problem never existed by setting the background color as white when you load the image.
logo4 = imread('logo4.png,'BackgroundColor',[1 1 1]);
imshow(logo4)

The problem is still there, it´s just someone else´s problem now.
profit.


text: Q: Endpoint to access sbt releases We have a policy against caching the releases directly from GitHub for security reasons. We were relying on https://sbt-downloads.cdnedge.bluemix.net/releases to access various sbt releases and cache them internally. Unfortunately, this endpoint is no longer reachable. Is there an alternate endpoint or archive to https://github.com/sbt/sbt/releases/ ? Thanks.


text:
Q: Can't find compiler executable in your configured search path for gnu gcc compiler in Ubuntu I have installed Code::Blocks in Ubuntu for the first time and tried to run a simple C program. But I got the error:
Can't find compiler executable in your search path (GNU GCC Compiler). I tried many ways to solve this. But alas!

A: Open Code::Blocks, go to Settings and then go to Compiler. Global compiler settings will open, there go to Toolchain executables and set the path as C:\Program Files (x86)\CodeBlocks\MinGW and then click okay.
This worked for me. Although I don't use it in Ubuntu, it may work for you. You can try it.

A: I fixed this on my computer by hitting "Reset Defaults", the far right button on the compilers dialog box, which you can load by hitting the menu item Settings->Compilers.
I believe it was caused by installing CodeBlocks first without mingw, then later installing the version with it.

A: I had the same problem on Linux Mint 21, I installed Code::Blocks with mint software manager, that Code::Blocks has problems and with the deb package is imposible the installation. But I solved the problem with full Code::Blocks uninstall and purge and after I install Code::Blocks with this guide:
How to Install Code::Blocks in Ubuntu
sudo apt install g++
sudo add-apt-repository universe
sudo apt update
sudo apt install codeblocks -y

And reboot


text:
Q: Send email on Tuesday or Thursdays using SP 2013 Workflow I have created an approval request from using InfoPath that is connected to a Sharepoint 2013 list. My goal is to create a workflow that sends an email containing certain elements of the information collected on the form to managers but the challenge is that management only wants to receive these type of request on either a Tuesday or a Thursday of each week.
Would greatly appreciate your help on how I could build that functionality in a workflow.
Thanks!

A: There are two methods, you can check if it's feasible for your requirement:
1.You can create a simple workflow associated with the list to send email to relevant users.
Then write the PowerShell to run the workflow on all items of a list as below:
# URL of the Site
$web = Get-SPWeb -Identity "http://sharepointsite"
$manager = $web.Site.WorkFlowManager
# Name of the list
$list = $web.Lists["Shared Documents"]
# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName("WFName","en-US")
$data = $assoc.AssociationData
$items = $list.Items
foreach($item in $items)
{
$wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
}
$manager.Dispose()
$web.Dispose()

Reference: SharePoint Start Workflow on All Items of a List via PowerShell
Then use Windows Task Scheduler to run the workflow every Tuesday or Thursday.
Reference: How to: Run PowerShell Scripts from Task Scheduler
2.Add a stage at the end to put in a "Pause for Duration" action. And we can set this for 7 day (or 168 hours). For the Transition to stage, make it to back up to the first stage.
Then run the workflow first time in Tuesday or Thursday.


text:
Q: Verifying changes in array after memset to default value I have the following code in which I: (1) initialize an array with default values; (2) do something with the array; (3) check the array is still default. I'm unsure about (3).
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>

#define ARRAY_MAX 10
#define DEFAULT_VALUE 0

int main(int argc, char *argv[])
{
    uint32_t array[ARRAYMAX];

    memset(array, DEFAULT_VALUE, sizeof(array));
    do_something_with(array);
    check_array_is_default(array);
    return 0;
}

The way I would check if the array is only default values is the following (i.e. this is how I would write the check_array_is_default() function):
int check_array_is_default(uint32_t *array)
{
    int i;
    uint32_t defval = DEFAULT_VALUE;

    for (i = 0; i < ARRAY_MAX; i++)
    {
    if (memcmp((array + i * sizeof(uint32_t)), &defval, sizeof(uint32_t)))
    {
        return 0;
    }
    }
    return 1;
}

A: memset fills bytes, not words so you need to look at the bytes individually:
int check_array_is_default(uint32_t *array)
{
    char *p = (char *)array;
    int n = ARRAY_MAX * sizeof(array[0]);
    for (int i = 0; i < n; i++) {
        if(p[i] != DEFAULT_VALUE) {
           return 0;
        }
    }
    return 1;
}


text:
Q: Scrapy POST formdata with a single url I face a situation that I have to post some data to get information I want.
Besides,POST information, anything else is the the same. For example,
{'data':'cat'}

the website will show information about cat.
{'data' : 'dog'}

show dog's information.
the question is I got millions of data need to be sent.
I knew how to run this spider by single thread. I just want to know is there any way I can run the spider In parallel?
Thanks


text:
Q: Client Side Filtering vs Server Side Filtering Хотел узнать о задачи каждого из типов фильтрации..

*

*Что именно фильтруется на клиентской стороне ?

*Что именно фильтруется на стороне сервера ?

*Какова может быть цель фильтрации клинентской стороны ?

*Какова может быть цель фильтрации серверной стороны ?

Если кто сможет предоставить ссылки на примеры кода для понимания 1-4, буду благодарен.

A: Виды и назначения фильтрации зависят от разновидности клиентов/серверов, но раз речь про JEE то буду исходить из того, что клиент это браузер а сервер bean обслуживающий страницу facelet.

"Что именно фильтруется на клиентской стороне ?"

Все что можно отфильтровать. Фильтрация может полностью совпадать с серверной. Данная проверка это так называемая "защита от дурака", целью которой является помочь пользователю правильно "оформить" запрос.

"Что именно фильтруется на стороне сервера ?"

Нужно фильтровать все т.к. серверная фильтрация это проверка на то что в алгоритм попадут данные в правильном формате и в первую очередь что данные от пользователя не могут нанести вред серверу или привести к несанкционированному доступу и любым другим проблемам безопасности.

"Какова может быть цель фильтрации клиентской стороны ?"

В первую очередь уменьшение нагрузки на сервер (http трафик, обработка запроса и т.п.). Из второстепенных причин можно назвать ускорение валидации - к примеру ненужно отправлять форму и ждать ответа.

"Какова может быть цель фильтрации серверной стороны ?"

Гарантия, что ошибка получения неверных данных будет выявлена максимально быстро (а не в середине процесса вычислений), и что данные не скомпрометируют безопасность сервера.
Ссылка на то что и как валидировать(материал на английском).

A: Тут очень обширный ответ можно дать.
Ну во-первых на стороне сервера фильтруется всё связанное с информационной безопасностью (валидный ввод, для защиты от sql запросов, например). Количество обращений к серверу, сомнительные действия и т.д. А так же просто валидируются различные параметры, чтобы система неожиданно не упала, например юзер решил загрузить файл размером в 1000 gb :)
Что фильтруется на клиенте? Ровно тоже самое, что и на сервере, но цель у этого другая. На клиенте мы во-первых, подсказываем юзеру, где он мог ошибиться, а во-вторых не отправляем лишние (бракованные) запросы на сервер, чтобы не загружать его лишний раз. Те, в теории, если бы злоумышленников не было и фильтрация на стороне клиента всегда бы работала - нам бы хватило и её.


text:
Q: Best options for 4 million files on ext4 I'm going to put 4 million files into an EXT4 partition. I have about 700 files in each dir, the average file size is 38kb, total size is 169 gigabyte.
What are the best options in terms of block size, inode size and inode ratio I can choose?
Is it better to create two or more partitions, thinking at the checking time fsck could take?

A: Handling 4M files in a single filesystem is no problem for ext4, so long as the filesystem is formatted with enough inodes.  It is no problem to even have 4M files in a single directory, if the filenames are not excessively large.
There are Lustre filesystems with 1.5-2B files, and 10-12M files in a single directory (which is about the directory limit until kernel 4.recent when the "large_dir" feature was added). That means you don't need to do anything special with the directory structure to handle the files, unless you might need to store many more files in the future, or if you have a regular turnover of files, where you might want to make "age" based directories and then delete them after some time.
Reasonable formatting options would be:
mke2fs -t ext4 -i 32768 -b 4096

-i 32768 = average file size is 32KB, to ensure enough inodes
-b 4096 = blocksize, to allow large directories

The default inode size is fine, unless you store a lot of xattrs on each file.  If yes (use getfattr -d -m- -ehex /path/to/existing/file to see what the average xattr size is), then use -I to increase it. The core inode size is about 180 bytes these days, and the rest is available for fast xattrs.
If you put the filesystem on an LVM/DM device, then you can also resize it online to add more space/inodes if you need more in the future.  What you can't easily change is the inode ratio or inode size.


text:
Q: Finding all the triangles possible out of coordinates (python) Hello everyone i am new here. So far i have had a lot of information from StackOverflow so thanks everyone.
I got 6 coördinates:
A: (4,2)
B: (6,1)
C: (9,4)
D: (8,9)
E: (5,2)
F: (2,2)
And i have a measured position, lets say P=(3,7)
I want to find out all the combinations of points that can make a triangle that will cover the position P. I already have a code to calculate if a position is within a triangle:
# A utility function to calculate area
# of triangle formed by (x1, y1),
# (x2, y2) and (x3, y3)

def area(x1, y1, x2, y2, x3, y3):

    return abs((x1 * (y2 - y3) + x2 * (y3 - y1)
                + x3 * (y1 - y2)) / 2.0)

# A function to check whether point P(x, y)
# lies inside the triangle formed by
# A(x1, y1), B(x2, y2) and C(x3, y3)
def isInside(x1, y1, x2, y2, x3, y3, x, y):

    # Calculate area of triangle ABC
    A = area (x1, y1, x2, y2, x3, y3)

    # Calculate area of triangle PBC
    A1 = area (x, y, x2, y2, x3, y3)

    # Calculate area of triangle PAC
    A2 = area (x1, y1, x, y, x3, y3)

    # Calculate area of triangle PAB
    A3 = area (x1, y1, x2, y2, x, y)

    # Check if sum of A1, A2 and A3
    # is same as A
    if(A == A1 + A2 + A3):
        return True
    else:
        return False

# Driver program to test above function
# Let us check whether the point P(10, 15)
# lies inside the triangle formed by
# A(0, 0), B(20, 0) and C(10, 30)
if (isInside(0, 0, 20, 0, 10, 30, 10, 15)):
    print('Inside')
else:
    print('Not Inside')

But in this way I have to make all the triangles one by one. I am looking for a way to calculate all the triangles that cover point P.
As extra information, the goal of the script is to do a triangle interpolation to determine the wind speed at point P.
Could anyone help me with this? I really cant find out how to use all the possible combinations.
Kind regards,
Simon
some notes:
*using Anaconda
*using Spyder
*I am capable of using modules

A: Nice to see that you have put some effort in your code already.
You can use combinations from itertools [1] to create triangles:
import itertools
data = ['p1', 'p2', 'p3', 'p4', 'p5']

triangles = itertools.combinations(data, 3)
print(*triangles, sep='\n')

Output:
('p1', 'p2', 'p3')
('p1', 'p2', 'p4')
('p1', 'p2', 'p5')
('p1', 'p3', 'p4')
('p1', 'p3', 'p5')
('p1', 'p4', 'p5')
('p2', 'p3', 'p4')
('p2', 'p3', 'p5')
('p2', 'p4', 'p5')
('p3', 'p4', 'p5')

Triangles is a generator. You can use your code to go over each triangle and check your existing code to check if point P is inside a triangle.
in this case I used strings as elements, but you can also use tuples:
import itertools
data = [(0,0), (1,1), (2,2), (2,3)]

triangles = itertools.combinations(data, 3)
print(*triangles, sep='\n')

((0, 0), (1, 1), (2, 2))
((0, 0), (1, 1), (2, 3))
((0, 0), (2, 2), (2, 3))
((1, 1), (2, 2), (2, 3))

You can for exmample use this part of code as a starting point:
import itertools

points = [(4,2), (6,1), (9,4), (8,9), (5,2), (2,2)]

P = (3,7)

for triangle in itertools.combinations(points, 3):
    p1, p2, p3 = triangle
    if isInside(*p1, *p2, *p3, *P):
        print(f"P {P} is in triangle: {triangle}")
    else:
        print(f"P {P} is NOT in triangle: {triangle}")

[1] https://docs.python.org/3/library/itertools.html#itertools.combinations


text:
Q: What does it mean to "ODR-use" something? This just came up in the context of another question.
Apparently member functions in class templates are only instantiated if they are ODR-used.
Could somebody explain what exactly that means. The wikipedia article on One Definition Rule (ODR) doesn't mention "ODR-use".
However the standard defines it as

A variable whose name appears as a potentially-evaluated expression
  is odr-used unless it is an object that satisfies the requirements for
  appearing in a constant expression (5.19) and the lvalue-to-rvalue
  conversion (4.1) is immediately applied.

in [basic.def.odr].
Edit: Apparently this is the wrong part and the entire paragraph contains multiple definitions for different things. This might be the relevant one for class template member function:

A non-overloaded function whose name appears as a
  potentially-evaluated expression or a member of a set of candidate
  functions, if selected by overload resolution when referred to from a
  potentially-evaluated expression, is odr-used, unless it is a pure
  virtual function and its name is not explicitly qualified.

I do however not understand, how this rule works across multiple compilation units? Are all member functions instantiated if I explicitly instantiate a class template?

A: It's just an arbitrary definition, used by the standard to
specify when you must provide a definition for an entity (as
opposed to just a declaration).  The standard doesn't say just
"used", because this can be interpreted diversely depending on
context.  And some ODR-use doesn't really correspond to what one
would normally associate with "use"; for example, a virtual
function is always ODR-used unless it is pure, even if it isn't
actually called anywhere in the program.
The full definition is in §3.2, second paragraph, although this
contains references to other sections to complete the
definition.
With regards to templates, ODR-used is only part of question;
the other part is instantiation.  In particular, §14.7 covers
when a template is instantiated.  But the two are related: while
the text in §14.7.1 (implicit instantiation) is fairly long, the
basic principle is that a template will only be instantiated if
it is used, and in this context, used means ODR-used.  Thus,
a member function of a class template will only be instantiated
if it is called, or if it is virtual and the class itself is
instantiated.  The standard itself counts on this in many
places: the std::list<>::sort uses < on the individual
elements, but you can instantiate a list over an element type
which doesn't support <, as long as you don't call sort on
it.

A: In plain word, odr-used means something(variable or function) is used in a context where the definition of it must be present.
e.g.,
struct F {
   static const int g_x = 2;
};

int g_x_plus_1 = F::g_x + 1; // in this context, only the value of g_x is needed.
                             // so it's OK without the definition of g_x

vector<int>  vi;
vi.push_back( F::g_x );      // Error, this is odr-used, push_back(const int & t) expect
                             // a const lvalue, so it's definition must be present

Note, the above push_back passed in MSVC 2013. This behavior is not standard compliant - both gcc 4.8.2 and clang 3.8.0 failed, with error message:
undefined reference to F::g_x


text:
Q: WebService (Soap) with Delphi XE2 complex responses I am trying to create a WebService with Delphi, the simple part is working for example a simple response.
But my issue is how to make it multi array/multi level response
For example :
i want to get something like this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
   <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:NS1="urn:RoommatikIntf-IRoommatik">
      <NS1:GetAllRoomTypeRatesResponse xmlns:NS2="urn:RoommatikIntf">
         <NS2:RoomTypeRate id="1" xsi:type="NS2:RoomTypeRate">
            <NS2:RoomType id="2" xsi:type="NS2:RoomType">
               <Id xsi:type="xsd:int">1</Id>
               <Name xsi:type="xsd:string">Test0</Name>
            </NS2:RoomType>
            <Price xsi:type="xsd:double">100.2</Price>
         </NS2:RoomTypeRate>
      </NS1:GetAllRoomTypeRatesResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

RoomType is inside the RoomTypeRate tag.
But at the moment all i get is literally this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
   <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:NS1="urn:RoommatikIntf-IRoommatik">
      <NS1:GetAllRoomTypeRatesResponse xmlns:NS2="urn:RoommatikIntf">
         <return xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="NS2:RoomTypeRate[1]">
            <item href="#1"/>
         </return>
         <NS2:RoomTypeRate id="1" xsi:type="NS2:RoomTypeRate">
            <RoomType href="#2"/>
            <Price xsi:type="xsd:double">100.2</Price>
         </NS2:RoomTypeRate>
         <NS2:RoomType id="2" xsi:type="NS2:RoomType">
            <Id xsi:type="xsd:int">1</Id>
            <Name xsi:type="xsd:string">Test0</Name>
         </NS2:RoomType>
      </NS1:GetAllRoomTypeRatesResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

the Intf file is:
unit RoommatikIntf;

interface

uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns;

const
  IS_OPTN = $0001;
  IS_UNBD = $0002;
  IS_NLBL = $0004;
  IS_REF  = $0080;

type

  RoomType = class(TRemotable)
  private
    FId: Integer;
    FName_: string;
  published
    property Id:          Integer  read FId write FId;
    property Name:        string   read FName_ write FName_;
  end;
  RoomTypeRate2 = class(TRemotable)
  private
    FRoomType : String;
  published
    property RoomType: String Read FRoomType write FRoomType;
  end;

  RoomTypeRate = class(TRemotable)
  private
    FRoomType: RoomType;
    FPrice: Double;
  published
    property RoomType:     RoomType      Index (IS_OPTN) read FRoomType write FRoomType;
    property Price:        Double        read FPrice write FPrice;
  end;

  ArrayOfRoomTypeRate = array of RoomTypeRate;

  { Invokable interfaces must derive from IInvokable }
  IRoommatik = interface(IInvokable)
  ['{DB8CC9DF-B105-4CCF-9CE5-C45EBCF4CF43}']

    { Methods of Invokable interface must not use the default }
    { calling convention; stdcall is recommended }
    function GetDateTime: TXSDateTime; stdcall;
    function GetAllRoomTypeRates: ArrayOfRoomTypeRate; stdcall;
  end;

implementation

initialization
  { Invokable interfaces must be registered }
  InvRegistry.RegisterInterface(TypeInfo(IRoommatik));

end.

and Impl file is :
unit RoommatikImpl;

interface

uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, RoommatikIntf, DateUtils, SysUtils;

type

  { TRoommatik }
  TRoommatik = class(TInvokableClass, IRoommatik)
  public
    function GetAllRoomTypeRates: ArrayOfRoomTypeRate; stdcall;
    function GetDateTime: TXSDateTime; stdcall;
  end;

implementation

function TRoommatik.GetDateTime: TXSDateTime; stdcall;
var
  DateTime : TXSDateTime;
begin
  DateTime := TXSDateTime.Create;
  DateTime.AsDateTime := now+1;
  Result := DateTime;
end;

function TRoommatik.GetAllRoomTypeRates: ArrayOfRoomTypeRate; stdcall;
Var
  RoomArray : ArrayOfRoomTypeRate;
begin
  RoomArray := ArrayOfRoomTypeRate.Create();
  SetLength(RoomArray, 1);
  RoomArray[0] := RoomTypeRate.Create;
  RoomArray[0].RoomType := RoomType.Create;
  RoomArray[0].RoomType.Id := 1;
  RoomArray[0].RoomType.Name := 'Test0';
  RoomArray[0].Price    := 100.20;

  Result := RoomArray;
end;

initialization
{ Invokable classes must be registered }
   InvRegistry.RegisterInvokableClass(TRoommatik);
end.

Please point me in the right direction as i find no info on how to make this correctly.
Thank you in regards.


text:
Q: ListField(ReferenceField(x)) query mongoengine i am trying to make a mongodb database , the code bellow has some of the database documents, i am trying to divide the models into two parts, a part on a common/models.py file where i put the abstract classes, the other part is on monitor/models.py where i add some class methods:
common.py:
class device(DynamicDocument):
    hostname = StringField(required=True)
    management = EmbeddedDocumentField(access)
    interfaces = ListField(ReferenceField(interface))
    loopback_addr = StringField()

    meta = {'abstract': True}

class topology(DynamicDocument):
    topology_name = StringField(required=True)
    topology_desc = StringField(required=False)
    devices = ListField(ReferenceField(device))
    links = ListField(ReferenceField(link))

    meta = {'abstract' : True}

monitor.py (the class methods are not important for this question):
from mongoengine import *
from common.models import *

class device(device):

  def connect(self):
    driver = get_network_driver("ios")
    device = None
    try:
        device =  driver(self.management.management_address,self.management.username,
                        self.management.password)
        device.open()
    except Exception as e:
        print(e)
    return device

class topology(topology):

    def do_things(self)

         pass

Now when i try fetching the list of devices for a topology after creating some instances  :
mongoengine.connect("testdb",host = "0.0.0.0", port = 27017)
topology_ins = topology.objects()[0]
for dev in topology_ins.devices:
    print(dev.hostname)

I receive this error:
Traceback (most recent call last):
 File "models.py", line 45, in <module>
 for dev in topology_ins.devices:
  File "/usr/lib/python3.7/site-packages/mongoengine/fields.py", line 852, in _get_
return super(ListField, self).__get__(instance, owner)
  File "/usr/lib/python3.7/site-packages/mongoengine/base/fields.py", line 282, in _get_
name=self.name
  File "/usr/lib/python3.7/site-packages/mongoengine/dereference.py", line 92, in _call_
self.object_map = self._fetch_objects(doc_type=doc_type)
  File "/usr/lib/python3.7/site-packages/mongoengine/dereference.py", line 174, in _fetch_objects
object_map[(collection, doc.id)] = doc
AttributeError: 'device' object has no attribute 'id

the error does not occur when the code is not divided

A: There are some internals of mongoengine that rely on the model class names to be unique, try using different name for the concrete class (avoid class device(device): and class topology(topology):)
EDIT:
I was able to reproduce your issue. On my end, I could make it work by specifying allow_inheritance in meta = {'abstract': True, 'allow_inheritance': True} in both of your abstract classes


text:
Q: Global.asax: session_end fire when page is loaded (Session variables lost) I am building a webapplication and have noticed some strange behaviour debugging this application. When the first page is loaded some session variables are being set. These session variables adopt the correct values (seen in debug mode) but if the page is done loading I noticed that the Global.asax session_end method is called. This ensures of course that the next page which expects these session variables fails.
I was wondering if visual studio or IIS (7.5 or higher) ends the session if visual studio has to rebuild/reload the page?
P.S.: The session_end method only gets called if a change in code has been made.

A: I have found the answer on another page: ASP.Net Inproc session restarted after markup change in VS2012
Hope this helps other people too.


text:
Q: How do I make smaller pdf file sizes with pdflatex? (Or, how do I make pdflatex use CFF fonts?)
Possible Duplicate:
how to create small final pdf files for the internet

When I compile
tex -> dvi -> ps -> pdf
I have a 9 MB file... something emailable
When I .tex -> pdf  with pdflatex, its 44 MB
I read that its likely largely due to how pdflatex embeds the Type 1 fonts..
Does anyone have any idea about how or what to adjust to get smaller filesizes with pdflatex?
Thanks

A: Use pdfsizeopt, as described in this answer.


text:
Q: A Silverlight application with .net Ria services and SilverlightFX I am starting to write an application in Silverlight with RIA services and SilverlightFx.
 Now this application is a pretty big one has has lot of interaction between controls.
As an estimate it will have around 60-70 user controls. Now my questions are..

*

*Is it good to choose .Net Ria and SilverlightFx? (My view is..It is not going to production very soon. And as it is a big one using frameworks will help unit testing and save development time once the frameworks are understood properly.)

*After reading through the blogs I am not really clear how SilverlightFx handles interaction between user controls. For example I have a user control (say "S") that have the search functionality...auto complete and all...Now I have another UserControl (Say "R") that displays the search results. The display result panel can be used from search user control or another user control (Say F) that gives all items of a particular category. I can not marge Search and Select Category into a single userontrol. So how to do it?
If I create different ViewModels how they will interect with each other?

*Is it better to create Domain service context in each ViewModel or to use a single one across the application?

A: Note to preface answer - I am the author of Silverlight.FX, and architect for RIA Services ... so factor in bias in the reply :-) ...
I did two blog posts on the combination of the two you might find helpful: here and here. These cover basic view model scenarios using a DomainContext and basic unit testing of view models using the Silverlight Unit Test Framework.
Silverlight.FX offers more than just graphical interaction. From the site (http://projects.nikhilk.net/SilverlightFX):

*

*Application Model - SilverlightFX
features a richer Application object
providing a service model, an IoC
container, support for theming, view
model (M-V-VM), navigation and MVC,
amongst various other features.

*User Interface Components - SilverlightFX
provides a small set of enhanced
controls, support for Forms and
Windows, master page like containers,
layout controls and data-bound
controls.

*Declarative Views -
SilverlightFX provides a framework
for writing behaviors, actions,
triggers, and commands, and also
provides a set of out-of-the-box
implementations.

*Effects and
Transitions - SilverlightFX provides
a procedural animation framework
capable of implementing tweens and
interpolations and easing behaviors.
Additionally it provides simple but
broadly applicable animations that
can be applied as effects and
transitions to standard controls in a
fully declarative manner.

The way to handle the notifications across view models would be to use some sort of event aggregator pattern that allows view models to publish and subscribe to events in a decoupled manner.
This feature isn't yet in Silverlight.FX, but is slated to go in hopefully soon. I demonstrated this sort of communication recently in my TechEd South Africa talk - check out the slides and code for an implementation of this: http://www.nikhilk.net/TechEd09-South-Africa-Samples.aspx.
Hope that helps.

A: Hey there, first off i dont know if SLFX provides any useful features besides graphical interaction, i suggest you take a look at prism for proper MVVM integration and proper use of Regions in your design, and then communication between regions (simply speaking, usercontrols but a little more dynamic in its loading)

*

*Unit testing from SL3 interface
means that you must have a means to
simulate user input, there are quite
a few ways todo this. One of the
easiest is the MVVM approach and
thereby simulating input into the
viewmodel. prism support for SL3
will co-incide with the release of
WPF 4.0. prism currently does
support SL3 just not the navigation
framework, as it clashes alot with
prism's region navigation, but they
perform different tasks and they
dont overlap functionality.

*If you have usercontrols "S", and "R" then, they both will share a
common datasource, being the
viewmodel, therefore properties
within the viewmodel can communicate
with each other, this mostly happens
when the OnPropertyChanged event is
fired. or a button is clicked, then
using prism's commanding, you can
hookup a button control click method
to a method in the viewmodel.

*It really depends on alot of things, such as concurrency, since
all calls from SL3 are async,
meaning you can shoot of 3 queries
at once over the same domain
context, and how many connections
you want created to your WCF
service. i havent used RIA enough to
understand the implications of the
choices you have, so i cant give you
an exact answer, but the general
rule is to keep db connections to a
minimum (Domain context recycling
does not automatically convert into
less connections since WCF is
stateless unless otherwise designed)


text:
Q: What is wrong with my sizeof operator? I tried sizeof operator (VS code, Mac)
#include <stdio.h>

int main()
{
    char i;
    int  j;
    double k;

    printf("%d\n", sizeof(i));
    printf("%d\n", sizeof(j));
    printf("%d\n", sizeof(k));

    return 0;
}

but the warning says:
warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat]
printf("%d\n", sizeof(k));
        %lu

What is wrong? I think there's nothing wrong with the syntax and it shows me output.

A: Nothing is wrong with the sizeof operator.
You are using the wrong specifier for printf.
sizeof returns a size_t.
The actual type of a size_t is implementation defined.
As such, %z is correct specifier for printing size_t
Use printf("%zu\n", sizeof(k));


text:
Q: How to Update status line according to UI I am developing a rcp application where i want to add a status line and show message according to control selected in the view .(Eg- Suppose Check box is selected than status bar should show a message than it should show message that check box is selected).
I am using
getViewSite().getActionBars().getstatuslineManager().setMessage but i could not update  the status line.
I mean that whatever text i set at beginning that things are not changing at runtime.

A: The vogella tutorial is a good piece of information on developing a rcp application. Check the following

*

*Acessing status line - on similar line you can also update it.

*Displaying message box


text:
Q: C - Pointer inside a function pointing to an array displaying invalid character I have an array product[6] and a pointer (*productPtr) pointing to this array. When I pass the pointer as an argument to a function called productCheck and try to print one of the characters, I get an invalid reading of the characters from the product array. Any help as to why this is happening is greatly appreciated.
For example if i = 3, instead of reading 'u', the output is '{'.
int i = 3;
char product[6] = "xddua";
char * productPtr;
productPtr = product;

bool productCheck(int i, char * productPtr);

productOk = productCheck(i, &product);

bool productCheck(int i, char * productPtr)
{
    printf("product is %c\n", *productPtr + i);

A: The function has the second parameter of the type char *.
bool productCheck(int i, char * productPtr);

You are calling the function passing expression the expression &product as the second argument
productOk = productCheck(i, &product);

As the array product is declared like
char product[6] = "xddua";

then the type of the expression ^product is char ( * )[6]. That is the type of the argument is not compatible with the type of the function parameter.
You need to call the function either like
productOk = productCheck(i, product);

or like
productOk = productCheck(i, productPtr);

Within the function dereferencing the passed value of the expression &product in this statement
printf("product is %c\n", *productPtr + i);

And then to the result expression you are adding the value i instead of at first to add the value i to the pointer and then to dereference the pointer expression..
Thus you need to call the function like
productOk = productCheck(i, product);

or like
productOk = productCheck(i, productPtr);

and within the function you need to write either
printf("product is %c\n", *( productPtr + i ) );

or
printf("product is %c\n", productPtr[i] );

A: The unary * operator has higher precedence than + operator.
*productPtr + i first reads what is pointed at by productPtr, then adds i to the value read.
To access another element, You should write *(producePtr + i) or productPtr[i].
Also the argument &product is not good. Most arrays in expressions are automatically converted to pointers to the first element (one of the exceptions is the operand of unary &), so it should be product to pass char* value.


text:
Q: How to package a kivy python windows I've been trying to package a kivy app for windows with PyInstaller but I have could not do it. My app is split into a few modules.
Here is my tree directory:

The main.py file calls the mainframe that contains my kivy app.
import os, sys
from kivy.resources import resource_add_path
from controllers.corecontroller import CoreController
from views.app import PassEwokApp

workspace=os.path.abspath(os.getcwd())

if __name__=="__main__":
    resource_add_path(os.path.join(workspace,"resources"))
    if hasattr(sys, '_MEIPASS'):
        resource_add_path(os.path.join(sys._MEIPASS))
    app=PassEwokApp()
    controller=CoreController(app)
    controller.start()

Then main.py file is the file which I run the PyInstaller.
The command would be: python -m PyInstaller main.py --onefile.
The result of that is a .exe file of 426mb (which is ridiculous) and this one doesn't make anything, no screen appears. I thought that problem was because I was loading kv files with  Builder.load_file("bla_bla.kv") so I changed that for loading kv files like strings.
For example in views\app.py which is the mainframe.

I load the kv file like this.
import os
kv_file=os.path.join(os.getcwd(),"views\\app.kv")
with open(kv_file,"r") as kv:
    css=kv.read()
Builder.load_string(css)

and so in the rest of the files where I need it.
Then I run the pyinstaller again and I had a .exe file of 426 mb and again it doesn't make anything but after a long time (almost 5 minutes) appears a window with errors about it doesn't find my modules controllers, models, utilities, and views and other kivy modules.
So, how I can do it correctly? Why the final .exe file is too large?
Edit 1
I change the .spec file and added the submodules which it doesn't had recognizing and finally my app appears, but it takes too long for show the windows, almost 5 minutes, so i checked the process runing in my pc
and i saw that the process of Antimalware runing strong with the process of my app, i don't know if it has something to do with that take too long in appear.

My .spec file
from PyInstaller.utils.hooks import collect_submodules
from kivy_deps import sdl2, glew

submodules = collect_submodules('controllers')
submodules += collect_submodules('models')
submodules += collect_submodules('views')
submodules += collect_submodules('utilities')
submodules += collect_submodules('pycryptodome')
submodules += collect_submodules('kivy')
from kivy.tools.packaging.pyinstaller_hooks import hookspath, runtime_hooks

a = Analysis(['D:\\Python\\kivy\\passwordmanager\\main.py'],
             pathex=['D:\\Python\\kivy\\passwordmanager'],
             binaries=[],
                         datas=[],
             hiddenimports=submodules,
             hookspath=hookspath(),
             hooksconfig={},
             runtime_hooks=runtime_hooks(),
             excludes=[],
                         win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,Tree('D:\\Python\\kivy\\passwordmanager'),
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
                    *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
          [],
          name='Passewok',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False,
          disable_windowed_traceback=False,
          target_arch=None,
          codesign_identity=None,
          entitlements_file=None , icon='resources\\app-200x200.ico')


text:
Q: How to style django in bootstrap? It is way easier to work with django forms, however they are not as good looking as a form created with bootstrap (I am using bootstrap for frontend), my question is:
Is there any way I can give style to my django form to have something like this:

Currently I am using a django form and including some widgets to customize, but I think I limited to control-form, here is my code:
class societyForm(forms.ModelForm):
    class Meta:
        model = sociedad
        fields = '__all__'
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'RUC': forms.TextInput(attrs={'class': 'form-control'}),
            'NIT': forms.TextInput(attrs={'class': 'form-control'}),
            'resident_agent': forms.TextInput(attrs={'class': 'form-control'}),
            'president': forms.TextInput(attrs={'class': 'form-control'}),
            'vicepresident': forms.TextInput(attrs={'class': 'form-control'}),
            'secretary': forms.TextInput(attrs={'class': 'form-control'}),
            'incorporation_date': forms.TextInput(attrs={'class': 'form-control'}),
            'expiration': forms.TextInput(attrs={'class': 'form-control'}),
            'contact': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.TextInput(attrs={'class': 'form-control'}),
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
            'status': forms.TextInput(attrs={'class': 'form-control'}),
            'comments': forms.TextInput(attrs={'class': 'form-control'}),
        }

Ideas, tips and suggestions will be very appreciated.

A: Django Forms and Bootstrap - CSS classes and <divs>
were you check this question before ?
and I'm usually using django-crispy-form to give style
maybe it's what you were looking for


text:
Q: A good approach for handling overriding multiple CSS backgrounds? I love that CSS3 has introduced multiple background images... but the method of just having comma-separated images is kind of, well, not very cascading, if you know what I mean.
Is there any approach out there to take this:
.a {
   background: url(a.png) no-repeat center center;
}

.b {
   background: url(b.png) repeat-x 0 bottom;
}

And apply it to an element such as this:

Such that the computed style is:
background-image: url(a.png), url(b.png);
background-repeat: no-repeat, repeat-x;
background-position-x: center, 0;
background-position-y: center, bottom;

(I get that if the above CSS did this, it would be wrong. But it'd be great if there were a solution like a property background-add or something.)
I'm looking for any hope of a future solution to this... a spec, a solution that only works in some browsers, the use of jQuery, whatever... because there are a couple of other similar issues with the CSS3 spec as well. For instance, you can't separate out the properties of text-shadow, etc. It's rather frustrating.
Thanks....

A: Not sure if this is what you're going for... but it works without having to add extra elements to the HTML, and should give you some ideas to play with: http://jsfiddle.net/howlx5/VrWDk/
.a {
    position: relative;
    width: 100%;
    height: 350px;
    background-image: url('http://placekitten.com/g/100/100');
    background-repeat: repeat-x;
    background-position: 0 0;
}

.a * {
    position: relative;
}

.a:before {
    position: absolute;
    top:0;
    content:"\0020";
    display:block;
    width: 100%;
    height: 100%;
    background-image: url('http://placekitten.com/100/100');
    background-repeat: repeat-y;
    background-position: 0 0;
};


text:
Q: Using Excel VBA Combo Box to Draw A Chart From Different Sheets Okay so what I am trying to do is have a userform with a combobox that displays each sheet as an option. I got that down. I want to be able to select a sheet and draw a chart from certain ranges on said sheet on my userform. I hope that makes sense.... Here is what I have got so far. It works with the first combobox selection, but once I change sheets and try to draw a chart from a different worksheet I get an error, "Method 'Values' of object 'series' failed. Any help would be greatly appreciated. Thanks in advance =)
    Private Sub ComboBox1_Change()

End Sub
Private Sub CommandButton1_Click()
If ComboBox1.Text = "Select A Client" Then
MsgBox "You Must Select a Name to Continue.", , "ERROR:Select A Name"
ComboBox1.SetFocus
    Exit Sub
End If

Dim MyChart As Chart
Dim ChartData As Range
Dim chartIndex As Integer
Dim ChartName As String

chartIndex = ComboBox1.ListIndex

Select Case chartIndex
    Case 1
        Set ChartData = ActiveSheet.Range("L4:L103")
        ChartName = ActiveSheet.Range("A1")

    End Select

Application.ScreenUpdating = False

Set MyChart = ActiveSheet.Shapes.AddChart(xlXYScatterLines).Chart

MyChart.SeriesCollection.NewSeries
MyChart.SeriesCollection(1).Name = ChartName
MyChart.SeriesCollection(1).Values = ChartData
MyChart.SeriesCollection(1).XValues = ActiveSheet.Range("J4:J103")

Dim imageName As String
imageName = Application.DefaultFilePath & Application.PathSeparator & "TempChart.gif"

MyChart.Export Filename:=imageName

ActiveSheet.ChartObjects(1).Delete
Application.ScreenUpdating = True
UserForm1.Image1.Picture = LoadPicture(imageName)

    End Sub

    Private Sub UserForm_Click()

    End Sub

    Private Sub UserForm_Initialize()
Dim sht As Worksheet, txt As String
For Each sht In ActiveWorkbook.Sheets
Me.ComboBox1.AddItem sht.Name
Next sht

    End Sub

A: The only time you are defining ChartData is if the ComboBox ListIndex is 1. Any other selection and the ChartData object will remain Nothing. Therefore when you try to set your chart values to ChartData you'll receive an error.
It's difficult to tell what you're trying to do with the Ranges. If you want to define the Range on whichever sheet is selected in the ComboBox then you're code would need to look like this:
Dim ws as Worksheet

Set ws = ThisWorkbook.Worksheets(ComboBox1.Text)

And delete your Select block.
All of your code is referencing the ActiveSheet which is probably not what you want, so you would need to replace all references to that with this new variable ws.


text:
Q: most efficent way to compare a form value and database value I have created a single table in my Magento database, this table has no connections to any of the magento tables. I have created a form that allows a user to put information into that table.
Within that table there is a column that must hold a unique value, I have set that column to only allow unique values in it.
What i'm currently doing is simply passing the data in without checking if the value is unique and getting a 'Integrity constraint violation' message shown on my screen.
What I want to do is before trying to pass data to that table is check that the value the user is trying to enter does not already exists within the table and if it does, pass them on to the relevant page, or is it possible to use that 'Integrity constraint violation' to then pass the user onto the relevant page?
I know how to compare values using raw php and mysql code, but after reading up on Magento I see that using sql queries are discouraged so I considered creating an array which will hold all rows from that column then comparing that array against the users inputted data, but this seems like a big waste of resources especially as the database grows.
How would be the best way to achieve this?
If this is a situation that a sql query would be acceptable to be run directly on the table, where do I look in the code to find that function I need to use?

A: In my view, following can be possible solutions:

*

*Either use a stored procedure in the database to check if the value exists in the table. If it does simply return a message to be trapped
  and corresponding action to be performed in the front end.

*use a hashmap construct (map collection) which will cut the processing time to minimum in the front end.

I hope that helps.


text:
Q: Android Wear Add Library from Existing app I have an existing app that I'm trying to build an Android Wear module out of. I need to access the codes/module of that existing app.
I understand that to add a library normally, I do compile project(':app') in build.gradle.
And I have to change this apply plugin: 'com.android.application' to  apply plugin: 'com.android.library' as well as take out the applicationId of the library/module being added.
When I change the aforementioned for the existing app to accommodate my Android Wear module, it wrecks the existing app.
How do I add the module/codes of an existing app to my Android library?
Thanks.

A: You're correct that one app can't reference the code of another app; the referenced code needs to be in a library module (which is not itself an app).
What you probably want to do is create a library module separate from your original app, and set both apps (Wear and original) up to reference it, as you already described. Then you start the process of moving code that you want available to both from your original app into the library module. This unfortunately tends to be fairly laborious, teasing the common bits out in a way that doesn't break your original app - and you'll undoubtedly find more dependencies than you'd really like.
Yes, it's kind of a pain, but AFAIK there's no better way.


text:
Q: how can type text in the ajax combo box i added ajax combo box to my page, but i have 2 problems.
1- i can not type in that.
2- when i type in that , it automatically find matched words.
for example when i type "j" , it finds "jack".
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs"  Inherits="_Default" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
    </head>
   <body>
<form id="form1" runat="server">
<div>

    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

    <asp:ComboBox ID="ComboBox1" runat="server" AutoCompleteMode="SuggestAppend"
            DropDownStyle="DropDownList"

              style="display: inline;">
        <asp:ListItem>masoud</asp:ListItem>
        <asp:ListItem>jack</asp:ListItem>
    </asp:ComboBox>

    </ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

A: Is your browser Firefox? If so, you may have to change the MaxLength property of the ComboBox control to a value other than the default 0.

A: This link will show you how to use all of the ajax controls, look at the combo box one. And you can see which one you need then.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ComboBox/ComboBox.aspx
That is a link to all of the ajax controls with samples.

A: as @CallumHolden said.. if you will set the dropdownstyle property to dropdown rather than dropdownlist it will work. this solved my problem as well.


text:
Q: Kusto query for email filtering with regex Raw string:
| Mail_To_s                                        |
| "AAA@xxx.com,BBB@yyy.com,CCC@zzz.com,DDD@kkk.com"|

Current query:
CUSTOM_LOG_TABLE
| extend mail_count = countof(Mail_To_s, @"@", "regex")
| extend internal_mail_count = countof(tolower(Mail_To_s), @"yyy.com|zzz.com", "regex")
| extend external_mail_conut=mail_count - internal_mail_count
| where external_mail_count > 0

Results:
| mail_cout | internal_mail_count | external_mail_count | Mail_To_s                                        |
|     4     |          2          |           2         | "AAA@xxx.com,BBB@yyy.com,CCC@zzz.com,DDD@kkk.com"|

Expect results:
How to extend column "external_email" for email filtering with regex
| mail_cout | internal_mail_count | external_mail_count | external_mail                 | Mail_To_s                                       |
|     4     |          2          |           2         | ["AAA@xxx.com","DDD@kkk.com"] |"AAA@xxx.com,BBB@yyy.com,CCC@zzz.com,DDD@kkk.com"|

A: Here is one approach:
datatable(Mail_To_s:string)["AAA@xxx.com,BBB@yyy.com,CCC@zzz.com,DDD@kkk.com"]
| extend mail_count = countof(Mail_To_s, @"@", "regex")
| extend internal_mail_count = countof(tolower(Mail_To_s), @"yyy.com|zzz.com", "regex")
| extend external_mail_count=mail_count - internal_mail_count
| where external_mail_count > 0
| extend external_mail   = split(Mail_To_s,",")
| mv-apply external_mail   on (
     parse external_mail   with * "@" Domain
     | where Domain !in("yyy.com", "zzz.com")
     | summarize external_mail= make_set(external_mail)
)
| project-reorder mail_count, internal_mail_count, external_mail_count,external_mail

mail_count
internal_mail_count
external_mail_count
external_mail
Mail_To_s

4
2
2
[  "AAA@xxx.com",  "DDD@kkk.com"]
AAA@xxx.com,BBB@yyy.com,CCC@zzz.com,DDD@kkk.com


text:
Q: Automated XML Data Collection to Spreadsheet I'm trying to set up an XML parser that automatically collects data and appends it to the bottom of a spreadsheet every hour. The data I'm collecting updates every hour and I want to keep current with it as much as possible.
The XML I'm drawing from is from here: https://api.eveonline.com/map/Jumps.xml.aspx
and is formatted as such:
<?xml version='1.0' encoding='UTF-8'?>
<eveapi version="1">
  <currentTime>2007-12-12 11:50:38</currentTime>
  <result>
    <rowset name="solarSystems" key="solarSystemID" columns="solarSystemID,shipJumps">
      <row solarSystemID="30001984" shipJumps="10" />
    </rowset>
    <dataTime>2007-12-12 11:50:38</dataTime>
  </result>
  <cachedUntil>2007-12-12 12:50:38</cachedUntil>
</eveapi>

Naturally there's a lot more rows in the actual (4,000-5,000 per collection).
Currently I have a google spreadsheet with a script set up to collect the data, which works fine up until I get to the 'automated' part of what I'm trying to do. Here's the script:
function EVEJumpsCollection() {
  var ss = SpreadsheetApp.openByUrl(
     "https://docs.google.com/spreadsheet/ccc?key=0AgjR0Xz9d5o_dFc1RDdsYmZtNFo5eEp3a1FYZ2piT3c&usp=sharing");
   var sheet = ss.getSheets()[0];

  var newrowstart = sheet.getLastRow()+1;

  sheet.appendRow(['=ImportXML("https://api.eveonline.com/map/Jumps.xml.aspx", "/eveapi/result/rowset/row/@solarsystemid")', '=ImportXML("https://api.eveonline.com/map/Jumps.xml.aspx", "/eveapi/result/rowset/row/@shipjumps")', '=ImportXML("https://api.eveonline.com/map/Jumps.xml.aspx", "//eveapi/cachedUntil")', '=ImportXML("https://api.eveonline.com/map/Jumps.xml.aspx", "//eveapi/currentTime")']);

  var newrowend = sheet.getLastRow();

  sheet.getRange(newrowstart,3,1,2)
  .copyTo(sheet.getRange(newrowstart+1, 3, newrowend-newrowstart,2),{contentsOnly:true});

  sheet.getRange(newrowstart,1,newrowend-newrowstart+1,4)
  .copyTo(sheet.getRange(newrowstart,5,newrowend-newrowstart+1,4),{contentsOnly:true});

}

This works great when I run it manually, but it's the automated part the breaks down. I've tried setting up an hourly time-driven trigger to run the script, but I get the same error over and over again with the automated script: "The coordinates or dimensions of the range are invalid. (line 13, file "Code")"
I also recognize that even if I get this to work I'll only be collecting ~10 hour chunks at a time (thank you 400,000 cell limit...)
As such I'm hoping for any advice on either:

*

*Are there other ways of doing what I'm hoping to accomplish?

*Are there ways of re-tooling my current setup to work for what I want to do?

A: Interesting approach but think you'll always hit problems using import formula in combination with triggered Google Apps Script functions because of a delay in the formula calculating and the script executing.
As Google Apps Script has it's own XmlService Service which works great on well-formed Xml using this instead is a better approach. For your particular Xml document you can use:
function EVEJumpsCollection() {
  var output = [];

  // modified from https://developers.google.com/apps-script/reference/xml-service/
  var url = 'https://api.eveonline.com/map/Jumps.xml.aspx'; // where
  var xml = UrlFetchApp.fetch(url).getContentText(); // fetch
  var document = XmlService.parse(xml); // parse

  // next nav to part of tree and get values
  var cachedUntil = document.getRootElement().getChild("cachedUntil").getValue();
  var currentTime = document.getRootElement().getChild("currentTime").getValue();

  // get rowset elements and iterate accross
  var rowset = document.getRootElement().getChild("result").getChild("rowset").getChildren();
  for (var i = 0; i < rowset.length; i++) {

    // extracting attribute values (note case sensitive)
    var solarSystemID = rowset[i].getAttribute("solarSystemID").getValue();
    var shipJumps = rowset[i].getAttribute("shipJumps").getValue();

    // more effiecient to build object[][] of values and do one write
    output.push([solarSystemID, shipJumps, cachedUntil, currentTime]);
  }

  // where we want it to go
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheet/ccc?key=0AgjR0Xz9d5o_dFc1RDdsYmZtNFo5eEp3a1FYZ2piT3c&usp=sharing");
  var sheet = ss.getSheets()[0];
  sheet.getRange(sheet.getLastRow()+1, 1, output.length, 4).setValues(output);
}

In terms of the Google Sheet filling up there are a couple of options. You could script the creation of a new Google Spreadsheet each time it runs or for this recent project it writes a .CSV file to Google Drive. Also worth noting that similar Apps Script/XML on Stackoverflow like this one use the old Xml Service which is deprecated.


text:
Q: Assured wakeup of AsyncTask after Thread.sleep I have a foreground service, which creates an asynctask in its onCreate().
The asynctask has a while(true)in its doInBackground. In this function, it performs certain network operation and goes to sleep for a random interval after each iteration. Here is the logic:
doInBackground(){
     while(true){
         //Do network operation
         //randomNumber is a random number calculated each iteration and is in range of 60-180
         Thread.sleep(randomoNumber*1000);
     }

}

Now my issue is that as soon as the device goes to sleep, it sleeps the asynctask too. The network operation is highly critical in sticking to the time interval(randomNumber) and it can not be afforded that it be sleeping more than the randomNumber seconds(although difference of a few seconds can be tolerated). So how do I assure that the asynctask does wakes up after Thread.sleep, even when the device is not in active state?
I think I can use a wakelock, but that may keep the task running forever as it has a while(true) loop and hence drain out the battery. If I use it before Thread.sleep and release it after the network operation, again the same issue of the task not waking after the thread.sleep may occur. So what can be done here?

A: You could force the CPU to be on even when the device sleeps see here http://developer.android.com/training/scheduling/wakelock.html#cpu as they say:

One legitimate case for using a wake lock might be a background
  service that needs to grab a wake lock to keep the CPU running to do
  work while the screen is off


text:
Q: Help with symplectic integrators I'm trying to develop a physics simulation and I want to implement a fourth-order symplectic integration method. The problem is that I must be getting the math wrong, since my simulation is not working at all when using the symplectic integrator (as compared to a fourth-order Runge-Kutta integrator that works reasonably well for the simulation). I've been googling this forever and all I can find are scientific articles on the subject. I tried to adapt the method used in the articles, but am having no luck. I want to know if anyone has source code for a simulation that makes use of symplectic integrators, preferably to simulate a gravitational field but any symplectic integrator would do. What language the source is in doesn't matter too much, but I would appreciate a language using C-style syntax. Thanks!

A: As you asked for source code: From HERE you can download MATLAB and FORTRAN code for symplectic methods for Hamiltonian systems and symmetric methods for reversible problems. And a lot of other methods for dealing with diff equations too.
And in THIS paper you can find the description of the algorithms.
Edit
If you use Mathematica this may help too.

A: Here is the source code for a fourth order composition method based on the Verlet scheme.
A linear regression of $\log_{10}(\Delta t)$ vs. $\log_{10}(Error)$ will show a slope of 4, as expected from theory (see the graph below).
More information can be found here, here or here.
#include <cmath>
#include <iostream>

using namespace std;

const double total_time = 5e3;

// Parameters for the potential.
const double sigma = 1.0;
const double sigma6 = pow(sigma, 6.0);
const double epsilon = 1.0;
const double four_epsilon = 4.0 * epsilon;

// Constants used in the composition method.
const double alpha = 1.0 / (2.0 - cbrt(2.0));
const double beta = 1.0 - 2.0 * alpha;

static double force(double q, double& potential);

static void verlet(double dt,
                   double& q, double& p,
                   double& force, double& potential);

static void composition_method(double dt,
                               double& q, double& p,
                               double& f, double& potential);

int main() {
  const double q0 = 1.5, p0 = 0.1;
  double potential;
  const double f0 = force(q0, potential);
  const double total_energy_exact = p0 * p0 / 2.0 + potential;

  for (double dt = 1e-2; dt <= 5e-2; dt *= 1.125) {
    const long steps = long(total_time / dt);

    double q = q0, p = p0, f = f0;
    double total_energy_average = total_energy_exact;

    for (long step = 1; step <= steps; ++step) {
      composition_method(dt, q, p, f, potential);
      const double total_energy = p * p / 2.0 + potential;
      total_energy_average += total_energy;
    }

    total_energy_average /= double(steps);

    const double err = fabs(total_energy_exact - total_energy_average);
    cout << log10(dt) << "\t"
         << log10(err) << endl;
  }

  return 0;
}

double force(double q, double& potential) {
  const double r2 = q * q;
  const double r6 = r2 * r2 * r2;
  const double factor6  = sigma6 / r6;
  const double factor12 = factor6 * factor6;

  potential = four_epsilon * (factor12 - factor6);
  return -four_epsilon * (6.0 * factor6 - 12.0 * factor12) / r2 * q;
}

void verlet(double dt,
            double& q, double& p,
            double& f, double& potential) {
  p += dt / 2.0 * f;
  q += dt * p;
  f = force(q, potential);
  p += dt / 2.0 * f;
}

void composition_method(double dt,
                        double& q, double& p,
                        double& f, double& potential) {
  verlet(alpha * dt, q, p, f, potential);
  verlet(beta * dt, q, p, f, potential);
  verlet(alpha * dt, q, p, f, potential);
}

A: I am in the field of accelerator physics (synchrotron light sources), and in modelling electrons moving through magnetic fields, we use symplectic integrators on a regular basis.  Our basic workhorse is a 4th order symplectic integrator.  As noted in the comments above, unfortunately these codes are not so well standardized or easilly available.
One open source Matlab based tracking code is called Accelerator Toolbox.  There is a Sourceforge project called atcollab.  See a messy wiki here
https://sourceforge.net/apps/mediawiki/atcollab/index.php?title=Main_Page
For the integrators, you can look here:
https://sourceforge.net/p/atcollab/code-0/235/tree/trunk/atintegrators/
The integrators are written in C with MEX link to Matlab.
Because the electrons are relativistic the kinetic and potential terms look a little different than in the non-relativistic case, but one can still write the Hamiltonian as H=H1+H2 where H1 is a drift and H2 is a kick (say from quadrupole magnets or other magnetic fields).


text:
Q: Can a single table inheritance entity extend a class table inheritance entity? This is my base/parent entity, setup so its children are using their own tables.

/**
 * @ORM\Entity
 * @ORM\Table(name="layer_object")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"service"="Service", "aircraft"="Aircraft", ...})
 */
class LayerObject {}

Aircraft entity. A simple child that is doing well

/**
 * @ORM\Entity
 * @ORM\Table(name="aircraft")
 */
class Aircraft extends LayerObject

Service entity. A complex child, that itself is using single table inheritance.

/**
 * @ORM\Entity
 * @ORM\Table(name="service")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"ground"="Ground", "onboard"="Onboard"})
 */
class Service extends LayerObject {}

A child of the Service entity

/**
 * @ORM\Entity
 */
class Ground extends Service {}

app/console doctrine:schema:validate finds no errors but app/console doctrine:schema:update --force just won't generate the 'service' table, the one that should use single table inheritance. Seems like the service entity definition is simply ignored.
Sure I could create the SQL for this table by hand, but the application will grow and at some point I will need to use migrations.
Could anyone point me in some direction? Thanks.
Found a duplicate, but there are no answers so far, see: Doctrine 2 multiple level inheritance
Edit:
When I use class table inheritance for the 2nd level too (@ORM\InheritanceType("JOINED") for the Service entity) it works pretty well. See: Doctrine2 Multiple level inheritance

A: What you're trying to achieve is not possible with pure mapping.
The documentation for Class Table Inheritance and Single Table Inheritance clearly state:

The @InheritanceType, @DiscriminatorColumn and @DiscriminatorMap must
  be specified on the topmost class that is part of the mapped entity
  hierarchy.

You might be able to make this work by implementing a subscriber to the loadClassMetaData event that changes the inheritance-type dynamically (i.e. based on annotations on of the child entities).
Some further inspiration can be found in this article.


text:
Q: Java9 module error only in Eclipse (not IntelliJ/Gradle) I am getting a The package javax.xml.namespace is accessible from more than one module: <unnamed>, java.xml when trying to upgrade an app from Java8 -> 11.
The error, as well as potential solutions are well documented.
So my question is: Why do I only get this error in Eclipse/Buildship, whereas my team mates don't see anything in IntelliJ, and the Gradle build isn't affected either.
How is it that these module errors seem to be unavoidable in Eclipse, yet IntelliJ/Gradle can skip them altogether. Isn't this a restriction of the Java9 module system that should apply to any build tool?


text:
Q: Node.js - Infinite Loop in Custom Code (Custom business logic) Hi I'm making a business application in which user can write his custom code and execute it.
How can i handle situations when the custom code generates infinite loops ?
A way is to handle each request in separate child process and kill that process on request completion but if there are  thousands of users this doesn't seem to be appropriate. What else can be done in such cases ?


text:
Q: Nan value in Impala_queries I have a Kudu table with a column of type double, which has some values Nan.  So when I perform a sum function on the table, the query outputs the value Nan.  In Oracle there is a function called Nanvl which gets rid of the Nan values and does the sum function.  I performed the following query:
select case
when Column_name ='NaN' then 0
else Column_name
end
from table_name;

The above query works fine in oracle but I am getting the following error in impala-shell:
AnalysisException: operands of type DOUBLE and STRING are not comparable: column_name= 'NaN'

A: select if(is_nan(Column_name), 0, Column_name) from table_name;


text:
Q: Custom Layout, losing custom defined attributes in attrs.xml I have the following in attrs.xml
  <declare-styleable name="ToolsView">
        <attr name="width_behaviour" format="reference" />
    </declare-styleable>

I have the following code in my layout file:
  <com.hidden.hidden2.view.ToolsView
        xmlns:app="http://schemas.android.com/com.hidden.hidden2"
        android:id="@+id/page_toolbar_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:background="@drawable/tools_background"
        android:gravity="center_horizontal"
        android:layerType="software"
        android:visibility="visible"
        app:width_behaviour="@integer/tools_view_width_behaviour" />

However, when I try to read app:width_behaviour in the constructor of my class
if (attributeSet != null) {
            TypedArray a = getContext().obtainStyledAttributes(attributeSet, R.styleable.ToolsView, 0, 0);
            final int N = a.getIndexCount();
            for (int i = 0; i < N; i++) {
                int attr = a.getIndex(i);
                switch (attr) {
                case R.styleable.ToolsView_width_behaviour:
                    widthBehaviour = a.getInteger(attr, -1);
                    break;
                }
            }

            a.recycle();

The attributes set is not null, but N is 0 - no custom attributes are obtained! So it never gets inside the for loop.
Any idea why is that? I used to this to a lot of layouts, for the first time I am having issues.

A: Change attribute's format to integer or dimension (depends on what you mean under width_behaviour) and it should work. References are for another purpose.

A: Ouch. This was a rather dumb mistake.
See the definition of xmlns:app -  xmlns:app="http://schemas.android.com/com.hidden.hidden2"
It should be xmlns:app="http://schemas.android.com/apk/res/com.hidden.hidden2"
The /apk/res/ part was somehow missing in my declaration.
Hope this helps someone someday.


text:
Q: How to specify location of angle-bracket headers in gcc/g++? Is there a way to tell gcc/g++/clang where to look for headers that are included via angle brackets ("<", ">")?
I don't use the angle bracket convention for non-system files, but the problem is that when I try using the headers from some packages I download, I get errors for all of the included files.
For example, say I want to include headers from a module called Foo that I download:
/foo-v1.0/include/DependencyA.hpp:
#ifndef DEP_A_HPP
#define DEP_A_HPP

class DependencyA
{
  ...
};

#endif

/foo-v1.0/include/Api.hpp:
#ifndef FOO_HPP
#define FOO_HPP
#include <Foo/DependencyA.hpp>

void doSomething(DependencyA* da);

#endif

Then, in my own code:
/mycode.cpp:
#include "/foo-v1.0/include/Api.hpp"

DependencyA* da = new DependencyA();
doSomething(da);

I get a compile error:
fatal error: 'Foo/DependencyA.hpp' file not found
I've tried building with:

*

*clang -c mycode.cpp -isystem./foo-v1.0/include -o mycode.o

*clang -c mycode.cpp -isystem./foo-v1.0/include/ -o mycode.o

*clang -c mycode.cpp -I./foo-v1.0/include -o mycode.o

*clang -c mycode.cpp -I./foo-v1.0/include/ -o mycode.o
and so on, to no avail.
How do I tell the compiler to resolve <Foo/**/*> to a particular root directory for every included file?

A: The answer is already in the comments.
To check include dirs one can use the method described here: What are the GCC default include directories? , preferably with - replaced with /dev/null:
clang -xc -E  -v /dev/null

On my machine for clang it gives
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/clang/11.0.0/include
 /usr/include
End of search list.

To discover how to manipulate this list, it suffices to read the gcc (or clang) manual (man clang or find it in the Internet, for example,  https://man7.org/linux/man-pages/man1/gcc.1.html ). For gcc this reads:
Options for Directory Search
       These options specify directories to search for header files, for
       libraries and for parts of the compiler:

       -I dir
       -iquote dir
       -isystem dir
       -idirafter dir
           Add the directory dir to the list of directories to be searched
           for header files during preprocessing.  If dir begins with = or
           $SYSROOT, then the = or $SYSROOT is replaced by the sysroot
           prefix; see --sysroot and -isysroot.

           Directories specified with -iquote apply only to the quote form
           of the directive, "#include "file"".  Directories specified with
           -I, -isystem, or -idirafter apply to lookup for both the
           "#include "file"" and "#include <file>" directives.

This description is followed by a detailed description of the order in which header files are searched and by some recommendations as to which option to use for which purpose. You'll find it in the manual. Search for "Options for Directory Search".
What I really  don't like in your code is this line:
#include "/foo-v1.0/include/Api.hpp"

It seems to contain the absolute path to the header and I've never seen anything like this. I would change it to
#include "Api.hpp"

with /foo-v1.0/include being added to the search list via the usual compiler -I command-line option.


text:
Q: How to check rails environment? How check rails environment on Ubuntu Server?
command: Rails.env => command not found
command:  rails.env => command not found

A: rails r -e production 'p Rails.env'
production

rails r -e production 'p Rails.env.production?'
true

rails r 'p Rails.env'
development

rails r -e development 'p Rails.env.development?'
true

rails r -e test 'p Rails.env.test?'
true

PS If rails command not found try to use path bin/:
bin/rails r 'p Rails.env'
development

PS2 If use rvm, check installed ruby versions:
rvm list

ruby-2.2.0 [ x86_64 ]
ruby-2.2.4 [ x86_64 ]
ruby-2.6.2 [ x86_64 ]
ruby-2.7.0 [ x86_64 ]
ruby-2.7.1 [ x86_64 ]
=> ruby-2.7.2 [ x86_64 ]
* ruby-2.7.3 [ x86_64 ]
ruby-3.0.0 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

Select to version:
rvm use ruby-3.0.0

Bundle install:
bundle

A: You can also check your environment from your Rails console in the shell. Start at the application directory path.
rails console<enter>

after you see the output from your console... (your output will most likely differ)
Running via Spring preloader in process XXXXX
Loading development environment (Rails X.x.x)
irb(main):001:0>

At the promt type
Rails.env<enter>

Unless you have custom environments, one of the following environment is loaded
=> "development"
=> "production"
=> "test"

A: It sounds like you tried to run Rails.env in a shell.  That won't work because Rails.env is Ruby code, not a Unix shell command.
How are you deploying and starting your rails app on the server?  The Rails environment is determined by whatever the value of the RAILS_ENV environment variable is when the server starts.  You might have some configuration file somewhere that specifies it, or maybe you just start your server with a command of the form RAILS_ENV=production my_rails_server?  I would need to know more details about exactly what commands you run to start the server in order to really answer this.  Are you using unicorn, mongrel, Webrick, or something else?

A: You can check complete details about your rails app. By typing this command "rake about". Will give you brief details about which version of ruby have you installed on your machine, rails version etc. For example -
About your application's environment
Rails version ------>           4.2.6
Ruby version  ------>           2.3.1-p112 (x86_64-linux)
RubyGems version ---->         2.5.1
Rack version ---->             1.6.4
JavaScript Runtime ------->        Node.js (V8)
Middleware  ------>              Rack::Sendfile, ActionDispatch::Static,
Application root   ---->       /data/www/testapp
Environment     ------>          development
Database adapter  ----->        mysql2
Database schema version  ----->  0

A: One liner if you are in app root

rails r "puts Rails.env"

A: On your Rails Application directory type :

rake about