text:
Q: Is this a proper usage for a semicolon?
I enjoy kayaking, hiking, tennis, volleyball, skiing; and I really want to learn how to snowboard this winter.

A: There are a couple problems with that sentence.  First, a list usually ends with "and (last item)"; you're missing the "and".  (There is an argument about whether "and" should be preceeded by a comma; I'm not addressing that here.)
Second, if you want to use the semicolon to separate two clauses, then the clauses must each stand alone.  Technically "and I really..." does, but it would be stronger without the "and".  With the "and", you could just as easily use a comma instead of the semicolon.
So, to sum up, the following would be correct and better than what you have:

*

*I enjoy kayaking, hiking, tennis, volleyball, and skiing; I really want to learn how to snowboard this winter.

*I enjoy kayaking, hiking, tennis, volleyball, and skiing, and I really want to learn how to snowboard this winter.

A: Larry Trask advises

Use a semi-colon to connect two complete sentences not joined by
  and, or, but, yet or while.

That makes the semi-colon in your example unnecessary.

A: It looks like what you really want is an em dash (—) to go with the asyndeton in your first clause:

I enjoy kayaking, hiking, tennis, volleyball, skiing — and I really want to learn how to snowboard this winter.

The dash turns the balance of the sentence into an anacoluthon (i.e., a change in direction or a break in structure), which is another rhetorical device used to express urgency or excitement. That's what you seem to be going for by piling up words one on the other, and finishing with the climactic announcement about learning to snowboard. The change in direction is from things you currently enjoy to something you intend to do.
Now, strictly speaking, you could view your sentence as a simple enumeration, and that is how others seem to have understood and answered the question. I find nothing wrong with their answers. Still, you may not be asking the right question for what it appears to me that you actually want to express.


text:
Q: Subsonic activerecord gets an object reference error when updating I can Insert and can read no probs using Subsonic 3.0.0.4.
However when I try to update, I get a runtime error from my generated ActiveRecord.cs on the line of code below
   public void Update(IDataProvider provider){

        if(this._dirtyColumns.Count>0){
            _repo.Update(this,provider); //<--EXCEPTION BLOWS UP HERE
            _dirtyColumns.Clear();
        }
        OnSaved();
   }

Heres the error information and the relevant part of the Stack Trace:
System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=SubSonic.Core
  StackTrace:
       at SubSonic.Extensions.Database.ToUpdateQuery[T](T item, IDataProvider provider)
       at SubSonic.Repository.SubSonicRepository`1.Update(T item, IDataProvider provider)
My Method that calls Update() is a wrapper method that looks like this:
    public static void UpdatePerson(Person person)
    {
        person.Update();
    }

Anyone got any ideas? I'm using the .net 4.0 framework just in case that throws a spanner into the works....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Symfony2: Problems with function parameter In my template I call a function like this:
  loadResults('asc');

  function loadResults(order) {
            return $.get('{{ url('_example_results', { 'order' : ''}) }}'+order, function (html) {
                $('#results').html(html);
            });
        }

The function in my controller looks like this:
 public function resultsAction($order, Request $request)
 {
      // content is not crucial for solving my problem
 }

My results don't get loaded, I get the following error:
Controller "...resultsAction()" requires that you provide a value for the "$order" argument (because there is no default value or because there is a non optional argument after this one).

What adjustments do I need to make?

A: Because TWIG render the page BEFORE you can act with js, you can't compose the right route with TWIG.
You can archive your problem with two approach:
1) Make the param optional and pass it on query string as follow:
js
loadResults('asc');

  function loadResults(order) {
            return $.get('{{ url('_example_results') }}'+"?order="order, function (html) {
                $('#results').html(html);
            });
        }

controller
public function resultsAction(Request $request)
 {
      //...
      $order= $request->get('order','asc'); // second parameter is the default if is null
 }

2) Using FOSJsRoutingBundle
Hope this help


text:
Q: Searching for multiple solutions with NDpend Is there a way with NDepend to have it search for sln files to load?  I need to look at metrics across a large codebase that has hundreds of sln files in it.  I want to create some summary info, like total lines of code.  In the interface I can browse to sln files but that will take me a long long time.
The perfect solution would be to just select a top directory and then have it recurse looking for the sln files automatically...

A: You can achieve this by writing a program based on NDepend.API. See the getting started with NDepend.API page.
Basically your program will recursively search for all *.sln files under the top directory.
For each solution file it'll call GetAssembliesFromVisualStudioSolutionOrProject().
Once you gathered all assemblies file paths from all .sln files, you aggregate them in a newly created NDepend project.
The getting started page shows how to create such project and eventually run a first analysis if you have a build machine license (else the analysis will be ran from VisualNDepend.exe).


text:
Q: Spring Security authenticated() doesn't work with AngularJS Currently I'm having some problems with Spring Security and connected Angular. I configured Spring Security in a class which looks like:
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/static/node_modules/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/auth").permitAll()
            .antMatchers("/", "/login").permitAll()
            .antMatchers("/resources/templates/index.html").permitAll()
            .antMatchers("/api/client, /api/reservation", "/api/reservationreminder", "/api/review", "/api/user", "/api/vehicle", "/api/wash", "/api/washlocation", "/api/washtype", "/api/worker").hasAuthority(AuthoritiesConstants.CLIENT)
            .antMatchers("/static/app/styles", "/static/app/js").permitAll()
            .anyRequest().authenticated()
            .and()
        .logout()
            .logoutSuccessUrl("/static/views/pages/login.html")
            .permitAll()
            .and()
        .formLogin()
            .loginProcessingUrl("/static/views/pages/login.html")
            .permitAll()
}

And for every time I try to run my app I have fails in browser like that:

But when I throw out the .anyRequest().authenticated() everything seems to work - in that way that I can see my app in a browser. The thing which doesn't work in that example is that the Spring Security doesn't work - I mean despite I have roles per each site I can go on those sites from role/users which theoretically I couldn't..

A: Your URLs for static resources in your HTML files are wrong, see Spring Boot Reference:

By default, resources are mapped on /** but you can tune that via spring.mvc.static-path-pattern.

Remove /static from your URLs in your HTML files and in your Spring Security configuration.

A: I use Spring Boot with Angular (in resource/static folder), configuration:
.antMatchers("/css/**", "/js/**", "/img/**", "/fonts/**").permitAll()
.antMatchers("/index.html", "/")

I suspect you do not need static prefix.


text:
Q: Downvote answer because the author's clarifications in comments are unhelpful Sometimes answers lead to discussions, and suddenly the answerer's comments become as much a part of the answer as the original post.  I occasionally see the asker being led down a path that he/she does not want to go (according to me, at least) in the discussion between the asker and the answerer.
Is it acceptable to downvote an answer because I think that the answerer's advice and expansions given in the comments lead to an unhelpful solution?

A: If the answer needs comments to clarify the answer, then probably the answer is incomplete. Imagine how you would vote without the comments. Is it helpful then?
If the answer isn't complete or accurate, the answer should be edited. A downvote could be an indication to do so. It might be better to ask the one posting the answer to update the answer with the relevant information.
If the answer is still clear and valid without the comments, but OP missed to tell some crucial facts, it is maybe not the fault from the one answering. Although the answer might not be useful to OP, downvoting seems to strong to me then.
In all other cases, vote as you deem best. It's yours and yours only.


text:
Q: In Vue JS, how can I make my APIService.js class globally available to components without requiring individual components to import it? Almost all of my components require some kind of interaction with my apiservice.js class, which imports Axios and makes appropriate http requests depending on the method called. I know this isn't normally recommended, but, in every one of my components, I have the following:
import {APIService} from '../store/APIService.js';
const apiService = new APIService();

My APIService.js looks roughly like this (trimmed down for simplicity):
import axios from 'axios';
const API_URL = 'http://myserver:82/services/locationmanagement';

export class APIService{

constructor(){
}

getLocations() {
    const url = `${API_URL}/api/locations/`;
    return axios.get(url).then(response => response.data);
}

saveLocation(location) {
    let url = `${API_URL}/api/locations/`;
    let id = location.id;
    let httpMethod = 'post';

    if(id > 0 ) {
        httpMethod = 'put';
        url = `${API_URL}/api/locations/${id}`;
    }

    let options = {
        method: httpMethod,
        url: url,
        headers: { 'Content-Type': 'application/json' },
        data: location
    }

    return axios(options);
   }

}

I would prefer if this were somehow made available to the global Vue instance and my components could access it somehow.
I believe this needs to be implemented in some form within my main.js file, possibly via Vue.use, but I'm still unsure of how to implement this even after reviewing the docs.
Any input would be greatly appreciated. Thanks!

A: Create a Vuejs Plugin import it into main.js, and call it there with Vue.use(myservice)
EDIT:
Per comment, one way is to add the plugin to the Vue prototype. For example, an axios wrapper could be defined as
import axios from 'axios'

export default {

  install:function(Vue,options) {

    Vue.prototype.$dataservice = axios.create({...})
    ...

then it can be called from a component like other global vue functions, e.g., $refs, $set, $emit:
 ...
 this.$dataservice.get(...)
 // or
 this.$dataservice.post(...)
 ...

With a data service api, if using Vuex, it may be useful to use this primarily in "actions".


text:
Q: Bijection between noncrossing sets of arcs and row-strict Young tableaux There is a well-known bijection between (i) noncrossing partitions of the set {1,...,2n} where all blocks have size 2, and (ii) standard Young tableaux with n rows and 2 columns. There exist a Catalan number $C_n$ of them.
Define a noncrossing set of arcs between 2n points with $w_i$ arcs starting or ending at the point $i$. Loops are not allowed to occur. It seems to me that such patterns are in bijection with row-strict Young tableaux with $\frac12 \sum_{i=1}^{2n} w_i$ rows and 2 columns with weights $(w_1,...,w_{2n})$. One side of the bijection consists of listing all starting points on the left column and all ending points on the right column. Here is an example with weights (2,2,1,1,1,1):

I could not find any reference about it, perhaps I have the wrong keywords. I would be glad to have any reference talking about this kind of bijection.


text:
Q: Serialization of arbitrary objects on Android I would like to automatically dump a Var object resulting from the Clojure's initialization - i.e. a complex object that does not implement Serializable and nests several other objects like that.
I experimented with a few frameworks, but they did not work (XStream produced XML with some null values), were not supported by Android (Kryo requires java.misc.Unsafe which has a limited implementation on Android; JBoss Serialization also requires something not available on Android...), or were not automatic (GSon requires to define type tokens for generics...).
Efficiency is not important (it's only an experiment / for debugging).
Any idea how to go about this?

A: You can use pr-str to convert to string:
user=> (pr-str [:map {:a [1 2 3]} "string"])
"[:map {:a [1 2 3]} \"string\"]"

and read back using edn:
user=> (require '[clojure.edn :as edn])
user=> (edn/read-string "[:map {:a [1 2 3]} \"string\"]")
[:map {:a [1 2 3]} "string"]

or just read-string:
user=> (read-string "[:map {:a [1 2 3]} \"string\"]")
[:map {:a [1 2 3]} "string"]

NOTE that read-string is unsafe for reading from "untrusted sources" - http://clojuredocs.org/clojure_core/1.3.0/clojure.core/read


text:
Q: Permission Hierarchy possible in OpenSolaris + ZFS + ACLs? I've been doing some research into OpenSolaris and ZFS for use in a NAS.
Thus far I have created the following:

/tank/projects
/tank/storage
/tank/developer
/tank/sandbox

The total space allocated for tank is 3.4Tb (RAIDZ2). Developers mount is our Subversion repository, it should be locked so only the sysadmins have access to that content plus those in the suDevelopers group.
SandBox is a play area, it's all open doors, read/write/delete whatever.
I'm wondering how I'd achieve the following, whether I'd have to go to using ACLs or just standard Unix permissions.
There are three main groups of users of this NAS, this is in the hierarchy of users. There are no ADs or anything else apart from CIFS to share this NAS.

*

*suDevelopers
They have access to all the content in tank.

*suStaff
These users are the staff at the premises, they should have access to everything except for the developer zfs in the tank.

*suContractors
These users can only see the Storage folder and not be able to access the others.
The problem is that some files on the storage area contain sensitive information (serial numbers, license keys) we don't want the contractors to see. Can we set those permissions up in Windows by the user who put the file there and they will automatically set to the right place?
I'm not sure how to do the above properly and whether it's ACLs or just CHMOD I should use.

A: Well, whether you use traditional POSIX permissions or ACLs, you'll be using chmod on Solaris. I would suggest you use ACLs in this case. You'll have to apply the ACL separately to each file system in the tank storage pool. I suggest setting the aclmode and aclinherit properties of each filesystem to passthrough as well.
I think it's preferable to set the ACLs on the Solaris side of things instead of doing it through windows.
Basically it would look something like:
chmod -R A=\
group:suDevelopers:full_set,\
group:sysadmins:full_set,\
/tank/projects

chmod -R A=\
group:suDevelopers:full_set:allow,\
group:suStaff:full_set:allow,\
group:suContractors:full_set:allow
/tank/storage

chmod -R A=everyone@:full_set:allow /tank/sandbox

and etc as necessary. You can also use read_set for read-only permissions.
There's a lot of other ways you can cut things with ACLs, they're an extremely powerful system on Solaris. You can read man chmod and man zfs for details.
There's also this article which gives some further examples.
Also make sure you are using /usr/bin/chmod instead of /usr/gnu/bin/chmod which I believe is the default.


text:
Q: Why seaborn histogram plot with kernel density estimator fails to change the color? I was trying to plot a histogram with kernel density estimator using seaborn. First I used seaborn.distplot, but I got a warning that 'distplot is a deprecated function and will be removed in a future version.'
So I used seaborn.histplot, but when I used the same argument kde_kws=dict(linewidth = 2 , color = 'black'), I got an error 'unexpected keyword argument 'linewidth' and 'color'.
But I checked the documents showing that the argument in the two functions is seems used in the same way that the argument is passed to seaborn.kdeplot(). And this function seaborn.kdeplot() indeed has the argument 'color'. So my question is why it works on distplot, but fails to work on histplot?
sb.distplot(sn2, bins = 10, kde = True, color = 'teal', kde_kws=dict(linewidth = 2 , color = 'black'))

sb.histplot(sn2, bins = 10, kde = True, color = 'teal', kde_kws = dict(linewidth = 2, color = 'red'))

Meanwhile, when I used argument line_kws = dist(linewidth = 2, color = 'red'), I got no error. And it succeeded in changing the linewidth but failed to change the color.
sb.histplot(sn2, bins = 10, kde = True, color = 'teal', line_kws = dict(linewidth = 2, color = 'red'))

Can anyone explain to me why this happened? Thank you in advance.


text:
Q: How to get Canvas DataURL on img.onload event when I click on submit button? I want to save the canvas as image on the server, I have a button to submit. When I click on save button I called a function that get the canvas dataURL on img.onload event. The problem is img.onload is fired after submitting the form, so I can't get dataURL value until it gets back from server.
Here's my code :
 <input onclick="savepoint('same');" id="btnsave" type="submit" value="Save Eyes Coordinate" />

function savepoint(btn) {

    SavePreviewImg();
}

function SavePreviewImg() {
    //Other code here to get the image src and other stuff..

    // here the excution of the function doesn't go into onload event it skip it
    // and after the click event finished it comes to onload event
    img.onload = function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // here i draw the first image
        ctx.drawImage(img, 480, 320);//210,10

        // here i draw the second image and put it on the first
        //image
        ctx.save();
        ctx.translate(mx, my);
        ctx.rotate(angle * TO_RADIANS);
        ctx.drawImage(imge2, -(width / 2), -(height / 2), width, height);

        ctx.restore();

        //get img data url
        dataURL = canvas.toDataURL("image/png");//.replace(/^data:image\/(png|jpg);base64,/, "");
    }
}


text:
Q: Prove that $Z(G)$ is a subgroup of $C(a)$
Let $(G, o)$ be a group and $a\in G$. Prove that $Z(G)$ is a subgroup of $C(a)$. If there exist an element $g\in G$ such that $C(g)=Z(G)$, prove that $G$ is a commutative group. Deduce that in a non-commutative group $G$, $Z(G)$ is a proper subgroup of $C(g)$ for every $g\in G$.
$Z(G)$ is the center of $G$ and $C(a)$ is the Centralizer of $a$ in $G$

We have $$Z(G)=\{g\in G : gx=xg ~~ \forall x\in G\}  $$ and $$C(a)=\{g\in G : ag=ga \} ~~~~~~(a~~ \text{is fixed in } G)  $$
EDIT

*

*To show $Z(G)\subset C(a)$
Let $p\in Z(G)$, then by definition, $px=xp$ for all $x\in G$ i.e $p$ commutes with every element of $G$ then in particular, $p$ commutes with $a$ as $a\in C(a)$, i.e $pa=ap$ and that implies $p\in C(a)$
Therefore, $Z(G)\subset C(a)$ for all $a\in G$

*To show $Z(G)$ is non-empty
As $ex=xe$,    $e$ being the identity element in $G$. Then $e\in Z(G)$. So $Z(G)$ is non-empty.

*To show closer property
Let $g_1,g_2\in Z(G)$ then $g_1x=xg_1, g_2x=xg_2$ for all $x\in G$ Then $(g_1g_2)x=g_1(g_2x)=g_1(xg_2)=(g_1x)g_2=x(g_1g_2)$ in implies $g_1g_2\in Z(G)$ How to go further.

A: Note that $g\in C(g)$.
Since $C(g)=Z(G)$, $g\in Z(G)$.
By definition of $Z(G)$, $xg=gx$ for all $x\in G$, which means $x\in C(g)$ for all $x\in G$.
Thus $G=C(g)=Z(G)$.
Since $G=Z(G)$, we can conclude that $G$ is Abelian (or commutative)
After you have completed this part, you just take the contrapositive of this result (($p \implies q)\iff(\neg q\implies\neg p)$
For your updated answer, it just suffices to show that $Z(G)\subseteq C(a)$ since the center of a group $G$ is always subgroup of $G$. So if $Z(G)\subseteq C(a)$, automatically $Z(G)\leq C(a)$.


text:
Q: Google Chrome is not caching web page My web app's pages don't seem to be cached (bfcache) in google chrome. It works well with firefox and even with qupzilla.
I wanted the pages to be left as is when the user opens a link and back but this doesn't seem to work with chrome. When I press the back button it reloads the page, $(document).ready() is called.
Google Chrome: Version 46.0.2490.71 (64-bit)
Response Headers
view source
Content-Type:text/html; charset=utf-8
Date:Fri, 23 Oct 2015 03:48:59 GMT
Server:WSGIServer/0.1 Python/2.7.6
X-Frame-Options:SAMEORIGIN
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8000
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36

A: It seems that all these decisions about refreshing the cache are not standard across browsers and even prone to change on the whims of the maker of the browser.  My latest testing is showing some consistency finally:

*

*USE CACHE (chrome/ff): follow a link from another page

*USE CACHE (chrome/ff): use history or forward/back buttons

*USE CACHE (chrome/ff): press enter on url in address bar

*USE CACHE (ff): go into dev tools, remove Cache-Control from request header, resubmit

*BYPASS CACHE (chrome/ff): refresh button in toolbar

*BYPASS CACHE (chrome/ff): F5 (but still uses ETag)

*BYPASS CACHE (chrome/ff): [ctrl|cmd]-F5 (ignores ETag)

*BYPASS CACHE (chrome/ff): enable dev tools "bypass cache" checkbox


text:
Q: Passing a value stored in a function within a child component to a parent in React Below is my code.
CHILD COMPONENT
  const onSave = () => {
    var val = value
    props.onSave();
  }

<div onClick={() => { onSave() }}>
            <CheckButton variant="contained" text-align='center' />
          </div>

PARENT COMPONENT
export const Card = (props) => {
    const onSave = (val) => { [I WANT TO ACCESS val within here] }
}

<TextInputContainer onSave={() => onSave()} />

Is there any way I can access that variable val inside the parent component? The code is truncated big-time. The actual code uses Redux.

A: The createRef of react helps u to access the value of a react component:
Reference (https://pt-br.reactjs.org/docs/hooks-reference.html)
constructor () {this.CheckButtonRef = createRef()}
onSave = () => {props.onSave(this.CheckButtonRef.current.value)}
<CheckButton ref = {this.CheckButtonRef}/>


text:
Q: Can I know what is in my .Rdata file without opening it Our group has invested a great amount of time into saving all of our work into .Rdata files. Unfortuneatly we have not invested time into creating a database.
So, each of our data experiments are saved into lists of data frames and other objects within the R class list. Our files are ~500MB to 2GB, so loading these experiments are not trivial, and I have hundreds to go through.
Is there away to get list names, dataframe names, or any other information without opening the entire .Rdata file.


text:
Q: Is there a saying in English corresponding to "Another loach under the willow tree"? In Japanese there's a saying "another loach" in the short form, "look for another loach under the same willow tree" in the long form.
This saying is for ridiculing a person who blindly repeats what s/he once successfully did, or who imitates what somebody else successfully did, in the hope that s/he can succeed again not knowing s/he would surely fail the second time.
It comes from a famous folklore about a man who once captured a loach (like a catfish) in a stream under a willow tree, who tried unsuccessfully to catch another loach exactly at the same spot.
I am wondering if there is a saying in English similar to this?

A: Cargo-cult is probably the nearest.
eg. in software a cargo-cult programmer keeps writing the same code they wrote before - because it worked in that situation.

A: There is at least one saying that is the other side of this coin - for a person who fails, but nevertheless continues the same action: "A fool trips over the same stone twice." Not what you want, but useful in its own right.
Ironically, a good fishing hole really is a good fishing hole, and what made it a favored habitat for the first loach would likely attract others to it as well - venerated sayings notwithstanding.

A: It sounds a little like "searching under the street light."

A: Wow, that's a useful saying.  English seems to have the opposite sayings -- that success or failure of a particular sort make repetitions less likely:

The cat, having sat upon a hot stove
  lid, will not sit upon a hot stove lid
  again. But he won't sit upon a cold
  stove lid, either. -- Mark Twain

or

Lightning never strikes twice in the same place

A: Lost in translation Is that loaches are represented as slippery/hard to catch in China and Japan so it like "betting on the winning number twice" or something along that line

A: Well, there is a saying in the Dutch language  that comes pretty darn close, it goes, A donkey never bumps into the same rock twice.... And I was looking for a similar thing that I could quote in the English language, but so far , I can't find much about a saying that has even a little bit of similarity. This post was just the only one with SOME effort put into a meaningful intellectual answer. And about the similarity of the loach and the Donkey.. Close but no cigar ? Or did I hit the nail on the head ?

A: I think this English saying is close to your meaning, with the caveat that it's a little more optimistic. ;-) Maybe there's a few "loaches", but if you fish out the stream, you're a fool.

The pitcher which goes too often to the well gets broken


text:
Q: Which Pokemon have a different ability in a horde? Is there a way to tell which Pokemon in a horde has a different ability than the others?
Here is my dilemma: I've come across a horde of 4 Tauros and 1 Miltank. I get 2 notifications on my screen about Tauros' ability Intimidate. So that leaves me 2 out of the 4 Tauros that might have their hidden ability. But how do I know which one to capture?
I have noticed in different horde battles that the Pokemon may be facing in different directions, does that give any indication of their abilities? Does anything show up by their name/hp bar when an ability is triggered? Or is it all a guessing game?

A: Use a Skill swapping/changing move on each Pokemon of the horde in turn until you find one with the ability you want.
For example,

*

*Skill Swap - Swaps yours and the opposing Pokemon's Abilities

*Worry Seed - Sets the opposing Pokemon's Ability to Insomnia

*Entrainment - Sets the opposing Pokemon's Ability to your ability (unlike Skill Swap, it doesn't change yours).

Their Ability will briefly flash up on the screen (before changing to the new Ability), allowing you to tell which ability it carries normally. Don't worry, their ability will revert to the original at the end of the battle.
As for some Pokemon that have access to these moves:

*

*Sylveon learns Skill Swap on level 25, Carbink/Solosis on level 40

*Budew learns Worry Seed on level 16, Pumpkaboo on level 11.

*Pancham/Pangoro learn Entrainment on level 42/45 respectively,


text:
Q: Rust build script to copy a file to target directory For my project, I would like to copy the file config.ron that is in the root of my project to the target directory when the project is built. I know that you can use include_str! to add the content of the file to the program at compile time, but I would like the file to stay in the root of the target folder so that it can be edited without the need to recompile the program.
I've currently been trying out a build script to accomplish this but I am have no luck.
use std::process::Command;
use std::env;

fn main() {
    let profile = std::env::var("PROFILE").unwrap();
    match profile.as_str() {
        "debug" => {
            Command::new("cmd")
                .args(&["copy", "/y"])
                .arg(&format!(r#"{}\config.ron"#, env::var("CARGO_MANIFEST_DIR").unwrap()))
                .arg(&format!(r#"{}\target\debug"#, env::var("CARGO_MANIFEST_DIR").unwrap()))
                .status()
                .expect("Copy failed to execute.");
            ()
        },
        "release" => {
            Command::new("cmd")
                .args(&["copy", "/y"])
                .arg(&format!(r#"{}\config.ron"#, env::var("CARGO_MANIFEST_DIR").unwrap()))
                .arg(&format!(r#"{}\target\release"#, env::var("CARGO_MANIFEST_DIR").unwrap()))
                .status()
                .expect("Copy failed to execute.");
            ()
        },
        _ => (),
    }
}

What would be the correct way to get this file copied to the target directory using a build script?

A: If you really want to do it in a build script, I would go with these ingredients:

*

*OUT_DIR and CARGO_TARGET_DIR

*std::fs::copy


text:
Q: MenuItem - CustomControl with Event Handler for IsSubMenuOpen In my WPF MVVM application, when the (sub-)menu of a MenuItem opens, I want to populate the (sub-)menu.
E.g. there is a MenuItem "Logs". Only when the submenu opens, I want to search for corresponding log files on disk and display their filenames in the SubMenu afterwards.
Populating submenu dynamically
MainWindow.xaml
<Grid>
    <Menu ItemsSource="{Binding MenuItems}">
        <Menu.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:MyMenuItemViewModel}"
                                      ItemsSource="{Binding Children}">
                <local:CustomMenuItemControl/>
            </HierarchicalDataTemplate>
        </Menu.Resources>
    </Menu>
</Grid>

MyMenuItemViewModel.cs
public class MyMenuItemViewModel : ObservableObject
{
    public string Text { get; set; }
    public ObservableCollection<MyMenuItemViewModel> Children { get; set; }

    public MyMenuItemViewModel(string item)
    {
        Text = item;
        Children = new ObservableCollection<MyMenuItemViewModel>();
    }
}

My application is significantly larger, for illustrative purposes I have removed most of it.
I work with a ViewModel that contains a Text and an ObservableCollection "Children" for SubMenus.
It is displayed with a CustomControl that only displays the text.
However, I am already failing to get a trigger when the SubMenu is opened.
I've already tried adding event handler to HierarchicalDataTemplate and CustomMenuItemControl and
a DependencyProperty to the control and tried binding events in XAML, but apparently not in the right place.
Where exactly do I need to define the trigger or handler that executes code when the SubMenu is opened?

A: I'll answer my own question. Whether it's the best way to solve my problem, I don't know, but that's how I went about it:
In the ViewModel I created a property "IsSubMenuOpen". In the setter, I query whether the text matches "Logs". If yes, I fill the list with the log files.
private bool _isSubMenuOpen;
public bool IsSubMenuOpen
{
    get => _isSubMenuOpen;
    set
    {
        if(Text == "Logs")
        {
            Children.Clear();
            foreach (var file in Directory.GetFiles(@"C:\MyDir", "*.log"))
            {
                Children.Add(new MyMenuItemViewModel(Path.GetFileName(file)));
            }
        }
        SetProperty(ref _isSubMenuOpen, value);
    }
}

In the MainWindow I have created a setter for the property "IsSubMenuopen", and bound my VM property in the value.
<Grid>
    <Menu ItemsSource="{Binding MenuItems}">
        <Menu.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="IsSubmenuOpen" Value="{Binding IsSubMenuOpen}"></Setter>
            </Style>
        </Menu.ItemContainerStyle>
        <Menu.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:MyMenuItemViewModel}"
                                  ItemsSource="{Binding Children}">
                <local:CustomMenuItemControl/>
            </HierarchicalDataTemplate>
        </Menu.Resources>
    </Menu>
</Grid>


text:
Q: Smart search indexing not working I want to start using joomlas smart search plugin.
The "content - smart search plugin" is enabled. All the other plugins that have to do with search are also enabled.
When I go on components -> smart search, I see that no content has been indexed. When I click on the index button a small pop-up appears, however, it stays blank, no text, no nothing in it, just the close 'x'.
Any ideas?
I am using Joomla! 3.2.1

A: This is not really a question about programming, but anywho.
If you seeing a blank screen, this probably means that you've encountered either:

*

*a permissions error of some kind that results in a browser timeout or

*a Javascript error.

*a server side error permissions or PHP

First, check your browser Javascript console for errors.
Second, turn on Error reporting and Debug mode in Joomla and repeat steps looking for error messages.
Third, check server and PHP error logs for clues.
The modal overlay for the "Smart Search Indexer" is an iframe that loads and then runs several AJAX requests.
Model open the iframe at:
index.php?option=com_finder&view=indexer&tmpl=component

If the iframe's initial URL works you should at least see something like this:

If you're not seeing any of that UI look for timeouts in your browsers web inspector, you may see that the resource i.e. the URL above didn't load. In that case check your servers logs and any php error logs.
After that loads, AJAX requests are sent to:
    index.php?option=com_finder&tmpl=component&format=json&ALONGNUMBER=1
with various tasks:

*

*&task=indexer.start

*&task=indexer.batch

*&task=indexer.optimize
Based on what you've said though, you're not gettig to the AJAX calls yet.
Update
Based on the the error message:
Uncaught TypeError: Object [object global] has no method 'addEvent' and a warning
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.

You have a Javascript conflict going on — I would look at disabling any 3rd part extensions that use Javascript as one of them may be loading conflicting JQuery/Mootools/Bootstrap code.
If you have new content regularly being added, now that the initial index has been run, you can setup a CRON job to run the Smart Search CLI periodically.


text:
Q: Unable to sum across dates (Dplyr) I have a dataset similar to this:
> dput(df)
structure(list(Date.Bought = structure(c(18262, 18262, 18262,
18265, 18266, 18266, 18268, 18269, 18270, 18270, 18272, 18273
), class = "Date"), Wasted = c(4L, 1L, 0L, 2L, 2L, 1L, 1L, 0L,
1L, 1L, 0L, 1L), Ordered = c(12L, 2L, 0L, 4L, 5L, 7L, 3L, 2L,
1L, 4L, 5L, 1L)), row.names = c(NA, -12L), class = "data.frame")

I want to divide the total wastage by the total ordered by date.
So, for example, on 2020-01-01, we see a total of 5 wastages (4+1) and a total of 14 orders (12+2). I want to create a column that divides 5/14 to show the proportion of waste in relation to order by that date. The output for 2020-01-01 should be 36%.
I tried this, but it gives me row-wise calculations (whereas I want to group it by date):
df <- df %>% group_by(Date) %>%
  mutate(all = Wasted/Ordered)

A: The first column of your df is Date.Bought, not Date. You also want to use summarize instead of mutate in this case. This should work:
df |>
  group_by(Date.Bought) |>
  summarise(all = sum(Wasted)/sum(Ordered))


text:
Q: Capacitor not charging? I am yet another software developer trying to step into the world of electronics... (so sorry for the basic questions...)
I am trying to understand how a capacitor works, but obviously I am missing a crucial part from all the helpful websites like sparkfun and adafruit.
I failed to solve an issue I currently have in a pretty basic project that reads a temperature from a thermocouple and displays the value on an LCD. An electrical engineer at work pointed me in the direction of adding a capacitor to filter the noise I introduce when I touch the thermocouple. Long story short; the capacitor doesn't seem to charge, no matter how I add the capacitor to the circuit, almost no voltage comes out; ever.
So I thought to be smart, and make a new circuit of:

*

*a battery supply (9.6V)

*an LED

*a capacitor "104"

The circuit is simple, all components are in series, so I expected that my LED would light up, and when I disconnect the battery, the LED would fade out. But again... nothing happens. The LED never lights up, and my multi meter measures 0.8V after the capacitor. But also, when I hold the multimeter probes to the leg of the capacitor, the measured voltage drops from 0.8V to close to zero in no time.
Please forgive me if this drawing is wrong (and please do tell me what is wrong so that I can learn from it):

*

*Why doesn't the capacitor charge up to the voltage of 9V (but seem to stop charging at 0.8V?)?

*Why does it discharge when I measure the voltage with a multi meter?

PS: there is no resistor between in the circuit limiting the current, and the batteries are 8x 1.2V rechargeables = 9.6V

A: Your circuit should look like this:

simulate this circuit – Schematic created using CircuitLab
Also, if the value of your capacitor is small, when you disconnect the power source, the led might go out very quickly. Are you sure your capacitor is 104F?
edit: as G36 points out, you probably meant it was marked 104, which means 100nF (except for with aluminium capacitors). To see any afterglow, you'll probably need at least 1000uF

A: First of all you have to know the working voltage of your LED, if the LED requires a 5V input, applying 9.6V will damage your LED and you will get a no response result. So you have to add a resistor in series to drop the extra 4.6 Volts from the circuit.
Since your battery rated at 9.6V and assuming you have a LED that works on 5V as input and consumes 20mA of current, the required series resistance value can be calculated using kirchhoff's voltage law, which states that "for a closed loop series path the algebraic sum of all the voltages around any closed loop in a circuit is equal to zero"

this means Vs ( Battery ) = V ( LED ) + V ( Resistor )
where V ( Resistor ) = I ( current ) x R ( resistor value )
By Substitution 4.6v = 20mA x R , so R = 230 Ohms. So you need a resistor of at least 230 Ohms. So the next higher popular standard resistor is 330 ohms.
Its not necessary to connect a capacitor to this circuit, the main purpose of a capacitor is to smooth the voltage generated from the power source and to eliminate voltage ripples. But if you intend to add a capacitor it should be connected in parallel with the LED. Because all the loads are designed to function optimally when connected to rated supply voltage. When capacitor is connected in parallel, full supply voltage is available to the load. However when it is connected in series, it drops the supply voltage, resulting in altered performance of the load.


text:
Q: Disable two week view in the Mountain Lion Calendar App In Lion I enabled the "Top sekret" debug menu and checked the box to show 14 days in the weekview. In Lion it worked quite nice.
Now I upgraded to Mountain Lion it doesn't work as nice as it was and I want to change it back to the normal 7 days in a week-view. One problem, I can't enable the debug menu anymore! So I don't know how to change it back.
I already searched the internet, looked in the App bundle etc, but I can't find where Calendar stores this setting. Do you know how to "reset" Mountain Lions calendar to the default setting for the weekview?

Just replaced my Calendar.app with the Calendar.app from another Mac, but no luck. So it seems that this preference is saved somewhere else. Hope somebody can point me in the correct direction.

A: Another (and more definite way) to get this fixed:

*

*Close the Calendar app.

*Edit ~/Library/Preferences/com.apple.iCal.plist and REMOVE the following keys:

*

*CalUIDebugUseIPadStyleEventLayout

*last calendar view description

*IncludeDebugMenu

*CalUIDebugDefaultDaysInWeekView

*Save and restart Calendar.
You may need XCode or the PList Editor to edit the file (or use plutil to convert to text, edit with TextEdit and convert it back to binary).

A: Like you, I had set iCal's week view to 14 days using the Debug menu in iCal under Lion before upgrading to Mountain Lion.  However, at least for me, changing the value via Calendar>Preferences... did not permanently change the setting.  When I restarted Calendar, it always reverted to the previous value (in my case, 14 days) if the value was not one of those available from the menu (i.e., 5 or 7).
There is another way to set the number of days shown in week view, and that's to use the following shell command:
defaults write com.apple.iCal CalUIDebugDefaultDaysInWeekView 7

This works where Calendar>Preferences... does not, for reasons I don't understand.
The "7" in the command above can be another number, including ones not previously available from Lion iCal's Debug menu, e.g., 10.  However, I find that Mountain Lion's Calendar has a peculiar bug when the value is not 5 or 7: in week view, if you have moved the viewed range of dates such that today is not visible, then using View>Go To Today (or Command+T) does not move the days in the grid to show today.  The title changes to the correct dates, but the days in the grid don't change to the correct range of dates.
(Hat tip to this posting for pointing out that the numerical value could be anything, not just a value shown in iCal's Debug menu.)

A: Finally I figured it out! :) Was pretty simple actually. Just go to Calendar > Preferences... and change the value of days in a week to another value. This will make Calendar reset the number of days in a week!
Full story over here.


text:
Q: What is the best way to rearrange files in a big project in Intellij? I am new to IntelliJ IDE so i might ask silly question.
I am using IntelliJ IDE and working on a big project. I want to change the name of 1 directory(A to B) and want to move few files of this directory in to another directory(C), what is the best way of doing it so that I don't need to change the package name inside .java file(i.e IDE handle all those things)?

A: Right click the directory in the project explorer ->refactor->rename A to B.
Then drag and drop the files you want to move into the C package using the project explorer.
Intellij will automatically change the package definitions at the top of the .java files for you.

A:
Or use shift+F6 for renaming directory.
For moving files between directories
Just select file (If you want to move multiple file , select files by pressing ctrl + select) and move to destination directory


text:
Q: One processor is working wierdly My Overall CPU condition is fine, but one of my processors (the first one) seems to be heavily working (and I can feel that from my fan noise and the heat).

I checked task manager and resource monitor to see which process is taking that much power. Found nothing. I guessed that maybe not all the processes are actually shown in resource monitor so I installed Process Lasso and Process Explorer (both are more or less similar to Windows' resource monitor). Still found nothing. I also set all affinities to 1-7, meaning that all my processes can be start on all my CPUs except the first one. Yet, there is a huge load on my first CPU.

By some research, I found that it may be the case that my first CPU's clock is somehow set to be really high, which I guess, means more power consumption, more fan speed and more heat (I don't have a concrete knowledge about the clock, so not sure if my guess is really correct). Noting that my Maximum Frequency in resource monitor, is actually suggesting that my CPU (don't indicates which one) is working with nearly 130% of maximum frequency (= boost speed/base speed *100 = 3.6/2.6 *100 = 138 %) or my maximum boost speed frequency to be more precise. So I tried to change my maximum processor state to something considerably less than 100% (say 50) to see If there is any difference in heat and noise. Nothing again even after reboot.

My system is dual-boot and I don't have that problem in my other OS (Ubuntu 16.04). No noise or heat.
So here are my questions:

*

*Is my first CPU really working that much? If so, then how it's possible to have such normal average CPU usage (the average is incredibly close tho the mean of all other CPUs)?

*Why affinity change doesn't made any difference on the CPU usage?

*The CPU usage of all my processes is less than what is actually is being used. Look at resource monitor picture: I have selected all the processes and now the orange line shows the amount of CPU that is taken by them. I checked the same in safe mode. Orange line, exactly coincides the total usage in safe mode. So I'm suspecting that something is happening in my normal boot. What may be the reason and how I can solve it?
My system is:

*

*Intel core i7 - 4720 HQ  2.6 GHz upto 3.6

*Windows 10 (64 bit)

*NVidia GTX 950 M

PS:
This screenshot, shows the Process Lasso's interface. Those 8 green bars on upper right show my CPU usage. Also the column called Rules, indicates the affinities on the processes.


text:
Q: How to separate some overlapping time periods in python? I have a list of different time periods, start and end, let's say :
[(0, 50), (40, 70), (60,100), (65, 105), (90, 120), (110, 150) ]

I need somehow to find overlapping timerange and assign these time periods into different layers, where there is no overlapping in each layer, for example for the list above result should be :
[(0, 50, 'layer 1'), (60,100, 'layer 1'), (110,150, 'layer 1'),
 (40,70, 'layer 2'), (90,120, 'layer 2'),
 (65,105, 'layer 3')]

Right now I have added a "+"/"-" sign to the start_time/end_time, then sort them. I am stuck to the next step.

A: Another solution, using defaultdict:
from collections import defaultdict

def find_layer(start, end, layers):
    l = 0
    while layers[l] > start:
        l += 1
    layers[l] = end
    return l

lst = [(0, 50), (40, 70), (60,100), (65, 105), (90, 120), (110, 150)]

# assuming lst is already sorted
# lst = sorted(lst)
layers = defaultdict(int)

for start, end in lst:
    print(start, end, 'layer_{}'.format(find_layer(start, end, layers) + 1))

Prints:
0 50 layer_1
40 70 layer_2
60 100 layer_1
65 105 layer_3
90 120 layer_2
110 150 layer_1

A: One approach is to create a list to contain the different layers, and populate it with your tuples, dynamically creating a new layer when needed.
# sort the data if it is not already in the order we need
data = sorted(data, key=lambda x: x[1])
data = sorted(data, key=lambda x: x[0])

# build layers as a list of lists
# the outer list will contain the layer levels
# the inner list will contain the periods/tuples in each layer
layers = [[data[0] + ('layer 1',)]] # initialize layer 1
for period in data[1:]: # get one period at a time and find which layer is a good fit
    for lay, temp in enumerate(layers):
        if period[0] > temp[-1][1]:
            # period starts after current layer's last period's end
            # add third element to tuple and append to layer
            temp.append(period + (f'layer {lay + 1}',))
            break
    else:
        # did not find a layer that can hold current period, create a new layer
        layers.append([period + (f'layer {len(layers) + 1}',)])

# flatten layers
layers = [e for L in layers for e in L]

Output
[(0, 50, 'layer 1'), (60, 100, 'layer 1'), (110, 150, 'layer 1'), (40, 70, 'layer 2'), (90, 120, 'layer 2'), (65, 105, 'layer 3')]


text:
Q: aframe: how does look-controls set its initial values When an AFrame <scene> gets loaded and a camera component has been set with look-controls enabled, how does the current orientation of the device (mobile) set the values of rotation and position of the camera?
Since a scene will have a certain point of origin. I have found that when open the scene from different positions the initial view is different, while I would like it to be the "look ahead" view.
The code is simple:
<a-entity camera="userHeight:1.6" look-controls></a-entity>

A: look-controls takes the orientation from the sensors of the phone that is absolute and not relative to where you position the camera initially in the scene. The initial values are overridden by those coming from the sensors. Phones in 2017 do not have positional tracking but have a head neck model and calculate the position of your eyes with respect of the base of your neck which is the rotation pivot.
I don't know the context of your application but in VR you cannot rely on the same degree of control of the camera that you would have on a traditional 3D application. If you require the user to look in a certain direction you can place hints or indications to influence the user's behavior.


text:
Q: Method overloading using varargs in Java The following code in Java uses varargs to overload methods.
final public class Main
{
    private void show(int []a)
    {
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+"\t");
        }
    }

    private void show(Object...a)
    {
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+"\t");
        }

        System.out.println("\nvarargs called");
    }

    public static void main(String... args)
    {
        int[]temp=new int[]{1,2,3,4};

        Main main=new Main();
        main.show(temp);
        main.show();         //<-- How is this possible?
    }
}

The output of the above code is as follows.
1        2        3        4

varargs called

The last line main.show(); within the main() method invokes the show(Object...a){} method which has a varargs formal parameter. How can this statement main.show(); invoke that method which has no actual arguments?

A: main.show() invokes the show(Object... a) method and passes a zero-length array.
Varargs allows you to have zero or more arguments, which is why it is legal to call it with main.show().
Incidentally, I'd recommend that you don't embed \n in your System.out.println statements - the ln bit in println prints a newline for you that will be appropriate for the system you're running on. \n isn't portable.

A: The varargs syntax basically lets you specify that there are possible parameters, right? They can be there, or cannot be there. That's the purpose of the three dots. When you call the method, you can call it with or without those parameters. This was done to avoid having to pass arrays to the methods. For example, you can write:
main.show(1, 2, 3, 4);

That will also work, because the numbers will become objects in wrapper classes.
If you're still confused, take a look at this:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
or this:
When do you use varargs in Java?

A: The main.show() call takes NO arguments, which is perfectly valid for matching the show(Object...a) method.


text:
Q: WPF - can't display page content I'm trying to display a wpf page inside a wpf window (to reproduce some bug in an isolated environment) and I'm unable to see the page inside the window.
My code is quite simple:
MainWindow.xaml:
 <ContentPresenter
        Content="{Binding ElementName=Root, Path=MyPage}"
        ContentTemplate="{Binding ElementName=Root, Path=MyPage.TT}"
        />

MainWindow.xaml.cs:
 public MainWindow()
    {
        InitializeComponent();
        this.MyPage = new Page1();
    }

Page1.xaml:
<DataTemplate x:Name="TT">
<Grid>
    <TextBlock Text="doodle dood doodle da"></TextBlock>
</Grid>
</DataTemplate>

Any Idea why MainWindow appears empty?
Thanks,
Li

A: Path=MyPage.TT looks for a property called TT, TT in all likelihood is not a property.


text:
Q: Pair of employees that worked together for the longest period of time - Python/Pandas I recently had to do a code, which returns the pair of employees that have worked the most together on a common project. This is the code I came up with:
Note 1: Null is read by the program as "Today"
Note 2: The data comes from a .txt file in this form:
EmpID,ProjectID,DateFrom,DateTo
1,101,2014-11-01,2015-05-01
1,103,2013-11-01,2016-05-01
2,101,2013-12-06,2014-10-06
2,103,2014-06-05,2015-05-14
3,100,2016-03-01,2018-07-03
3,102,2015-06-04,2017-09-04
3,103,2015-06-04,2017-09-04
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
4,104,2014-10-01,2015-12-01
5,100,2013-03-07,2015-11-07
5,101,2015-07-09,2019-01-19
5,102,2014-03-15,NULL
6,101,2014-03-15,2014-03-16

The problem that I currently have is that I have to adapt/change the code to return the pair of employees that have worked together with each other the longest (not on a single project, but all projects combined). I am having troubles of adapting my current code, which runs perfectly fine for what it is, and I am wondering if I should just scratch all of this and start from the beginning (but it would cost me a lot of time, which I don't have currently). I am having difficulties with obtaining the combinations of employees that have worked together on projects.
I would very much appreciate it if anyone can give me any tips! Thanks!
Edit 1: A person in the comments reminded me to mention that overlapping days should be counted as for example:
Person A and B work on two projects for the entirety of June. This means that it should be counted as 30 days total common work (for the two projects), not adding both project times together, which would result in 60 days.

A: Here's one of the more straight-forward ways I can think of doing this.

*

*Expand the timespans to a single row per date.

*Merge all Days on the same project (to get all combinations of people who worked together)

*Remove duplicated rows of people who work together on the same day, but different projects.

*Just find how many rows are within each worker pairing.

Code:
import pandas as pd
import numpy as np

def expand_period_daily(df, start, stop):
    # Allows it to work for one day spans.
    df.loc[df[stop].notnull(), stop] = (df.loc[df[stop].notnull(), stop]
                                        + pd.Timedelta(hours=1))

    real_span = df[[start, stop]].notnull().all(1)

    # Resample timespans to daily fields.
    df['temp_id'] = range(len(df))
    dailydf = (df.loc[real_span, ['temp_id', start, stop]].set_index('temp_id').stack()
                 .reset_index(level=-1, drop=True).rename('period').to_frame())
    dailydf = (dailydf.groupby('temp_id').apply(lambda x: x.set_index('period')
                      .resample('d').asfreq()).reset_index())

    # Merge back other information
    dailydf = (dailydf.merge(df, on=['temp_id'])
                      .drop(columns=['temp_id', start, stop]))

    return dailydf

# Make dates, fill missings.
df[['DateFrom', 'DateTo']] = df[['DateFrom', 'DateTo']].apply(pd.to_datetime, errors='coerce')
df[['DateFrom', 'DateTo']] = df[['DateFrom', 'DateTo']].fillna(pd.to_datetime('today').normalize())

dailydf = expand_period_daily(df.copy(), start='DateFrom', stop='DateTo')

# Merge, remove rows of employee with him/herself.
m = (dailydf.merge(dailydf, on=['period', 'ProjectID'])
            .loc[lambda x: x.EmpID_x != x.EmpID_y])

# Ensure A-B and B-A are grouped the same
m[['EmpID_x', 'EmpID_y']] = np.sort(m[['EmpID_x', 'EmpID_y']].to_numpy(), axis=1)

# Remove duplicated projects on same date between employee pairs
m = m.drop_duplicates(['period', 'EmpID_x', 'EmpID_y'])

m.groupby(['EmpID_x', 'EmpID_y']).size().to_frame('Days_Together')

Output:
                 Days_Together
EmpID_x EmpID_y
1       2                  344
        3                  333
        4                   78
2       6                    2
3       4                  396
        5                  824

Test Case
To give a bit more clarity on how it handles overlaps, and combines different projects, Here's the following test case:
   EmpID  ProjectID   DateFrom     DateTo
0      1        101 2014-11-01 2014-11-15
1      1        103 2014-11-01 2014-11-15
2      1        105 2015-11-02 2015-11-03
3      2        101 2014-11-01 2014-11-15
4      2        103 2014-11-01 2014-11-15
5      2        105 2015-10-02 2015-11-05
6      3        101 2014-11-01 2014-11-15

Employees 1 and 2 perfectly overlap for 15 days on 2 projects in Nov 2014. They then work together for 2 additional days on another project in 2015. 1, 2 and 3 all work together for 15 days on a single Project.
Running with this test case we obtain:
                 Days_Together
EmpID_x EmpID_y
1       2                   17
        3                   15
2       3                   15


text:
Q: Get root and all successors from parent child table on SQL Server I'm using ms sql server.
I have a simple table with a parent child relationship, like
Parent, Child
Now I need a query which delivers every Element with itself, all its successors and successors of them an so on.
Example
Parent Child
------ -----
A      A1
A1     A11
A      A2
A2     A21
A21    A211

Now the result should look like:
Root   Successor
------ ---------
A      A
A      A1
A      A11
A      A2
A      A21
A      A211
A1     A1
A1     A11
A11    A11
A2     A2
A2     A21
A2     A211
A21    A21
A21    A211
A211   A211

Any idea to do it recursivly on MS SQL Server with a sql query?
I searched for the internet and found some solutions, but not for my problem. I never got a list with the root and all its successor, only parent child for one level.

A: WITH CTE_AllRoots AS
(
    SELECT Parent as Root FROM Table1
    UNION
    SELECT Child FROM Table1
)
, RCTE AS
(
    SELECT Root, Root AS Successor FROM CTE_AllRoots
    UNION ALL
    SELECT r.Root, t.Child
    FROM RCTE r
    INNER JOIN Table1 t ON t.Parent = r.Successor
)
SELECT *
FROM RCTE
ORDER BY Root, Successor

db<>fiddle

A: We could also use CROSS JOIN:
SELECT
y1.parent AS Root, y2.child AS Successor
FROM
yourtable AS y1
CROSS JOIN
yourtable AS y2
WHERE y2.child LIKE y1.parent + '%'
UNION
SELECT parent, parent FROM yourtable
UNION
SELECT child, child FROM yourtable
ORDER BY Root, Successor;

Note: This could get slow in case your table has a very high amount of rows due to the LIKE condition in the WHERE clause.
I think using the CTE approach should be prefered here, I just wanted to show you another option.
db<>fiddle


text:
Q: How can this confetti code be improved to include shadows and gravity? Here's some confetti:
Graphics@Table[{
    RGBColor @@ RandomReal[{0, 1}, 3],
    Translate[#, RandomVariate[NormalDistribution[], 2]] &@
    Rotate[#, RandomReal[{0, 2 \[Pi]}]] &@
    Scale[#, .1] &@
    GeometricTransformation[
        #,
        ShearingTransform[
            RandomReal[{-45, 45}] Degree,
            {1, 0}, {0, 1}
        ]
    ] &@
    Translate[Rectangle[], {-.5, -.5}]
}, {1000}]

How can this code be improved, for example, by including shadows, raytracing or the effects of gravity to make it more realistic?

A: No fluid dynamics I'm afraid, but here's what I came up with
Preliminaries
n = {200, 200, 200};
dim = 2;
edges = {.015, .018, .024};
speed = {{0, -1}, {0, -1.5}, {0., -2}};
basePoly = {{0, -1}, {1/2, 0}, {0, 1}, {-1/2, 0}};
period = 3;

Initial position colour and orientation
angularVelocity = N[RandomChoice[Range[-8, 8], #] period Pi] & /@ n;
initPos = RandomReal[dim, {#, 2}] & /@ n;
initAngle = RandomReal[2 Pi, #] & /@ n;
colors = Transpose[ConstantArray[Hue /@ RandomReal[1, 200], 4]];

Visualisation
polygons[t_] :=
  Graphics[Table[
    Polygon[Function[{pos, ang, vel},
       Mod[pos + speed[[i]] t,
           2] + # & /@ ((edges[[i]] basePoly).RotationMatrix[
           ang + vel t])] @@@
      Transpose[{initPos[[i]], initAngle[[i]], angularVelocity[[i]]}],
      VertexColors -> colors], {i, 3}],
   PlotRange -> {{0, dim}, {0, dim}}];

Manipulate[polygons[t], {t, 0, period - .03, .03}]

Or to get an animated gif (note that exporting takes quite some time)
tab = Table[polygons[t], {t, 0, period - .03, .03}];
Export["confetti2.gif", tab]

A: Here is my modest attempt at confetti:
With[{g = 9, n = 120},
  confe[t_] = Table[
    With[{f = RandomReal[{9, 20}],
          th = RandomReal[{Pi/4 + Pi/12, Pi/2 - Pi/12}],
          ph = RandomReal[{-Pi, Pi}]},
     Translate[
      With[{l = RandomReal[{2/5, 3/4}], h = RandomReal[{2/5, 3/4}],
            c = RandomReal[{0, 1}]}, {Directive[EdgeForm[], Hue[c]],
           Polygon[AffineTransform[
             Orthogonalize[RandomReal[1, {3, 3}]]] /@
                     {{l, 0, 0}, {0, h, 0}, {-l, 0, 0}, {0, -h, 0}}]}],
      {f t Cos[th] Cos[ph], f t Cos[th] Sin[ph], f t Sin[th] - (g t^2)/2}]],
         {n}]];

(* poor man's antialiaser, by Szabolcs *)
antialias[g_, n_: 3] :=
  ImageResize[Rasterize[g, "Image", ImageResolution -> n 72], Scaled[1/n]]

With[{tf = 2, frames = 81},
 Export["confetti.gif",
  Table[
   antialias@Graphics3D[confe[t], Axes -> None, Boxed -> False,
    ImagePadding -> None, Lighting -> "Neutral",
    PlotRange -> {{-20, 20}, {-20, 20}, {-2, 21}},
    SphericalRegion -> True],
   {t, 0, tf, tf/(frames - 1)}],
  AnimationRepetitions -> Infinity, "DisplayDurations" -> 1./20,
  ImageSize -> Medium]]

Change Export[]+Table[] to Animate[] if desired.

(added 02/18/2012)
A little bird told me that the admonition "the more, the merrier" is quite applicable to the subject of confetti; I thus decided to see if I can do an animation with three confetti launchers instead of just one. I also wanted to experiment with Yves's enhancement of using confetti pieces with varying colors, so I added that enhancement in the following code as well:
i = 0;
Scan[
 With[{g = 9, n = 150, pt = #},
   confe[t_, ++i] = Table[With[{
       (* projectile motion parameters *)
       f = RandomReal[{9, 20}],
       th = RandomReal[{Pi/4 + Pi/12, Pi/2 - Pi/12}],
       ph = RandomReal[{-Pi, Pi}],
       (* polygon parameters *)
       l = RandomReal[{2/5, 3/4}], h = RandomReal[{2/5, 3/4}]},
      {EdgeForm[],
       Polygon[Composition[
          TranslationTransform[pt + {f t Cos[th] Cos[ph], f t Cos[th] Sin[ph],
             f t Sin[th] - (g t^2)/2}],
          AffineTransform[Orthogonalize[RandomReal[1, {3, 3}]]]] /@
                   {{l, 0, 0}, {0, h, 0}, {-l, 0, 0}, {0, -h, 0}},
            VertexColors -> Map[Hue, RandomReal[1, 4]]]}], {n}]] &,
         40 RandomReal[{4/5, 1}, 3] PadRight[
         Map[Composition[Through, {Cos, Sin}], 2 Pi Range[3]/3], {3, 3}]/Sqrt[3]]

With[{tf = 2 + 1/4, frames = 81},
 Export["confetti-tri.gif",
  Table[antialias@
    Graphics3D[{confe[t, 1], confe[t, 2], confe[t, 3]}, Axes -> None,
     Boxed -> False, ImagePadding -> None, Lighting -> "Neutral",
     PlotRange -> {{-20 - 20/Sqrt[3], 40/Sqrt[3] + 20},
                   {-40, 40}, {-2, 21}}, SphericalRegion -> True],
        {t, 0, tf, tf/(frames - 1)}], AnimationRepetitions -> Infinity,
          "DisplayDurations" -> 1./20, ImageSize -> Medium]]

Generalizing the code to more than three confetti launchers should be straightforward.
As David had previously noted; the use of Szabolcs's antialias[] routine might make the Export[]-ing slow on some machines; it can be removed if need be.

A: Elaborating on Mr. Wizard´s answer, a quicker way to generate and render the polygons is to define your own roughshod transformation functions and use the multi-primitive syntax for Polygon together with random VertexColors. The resulting graphics is rendered way faster and is much more responsive to mouse interaction:
diamond = {{#, -#} #2, -{#, #}, {-#, #} #2, {#, #}} &;
diamond3D = Polygon[{##, 0} & @@@ diamond[1, 1/2]];

n = 5000;

rt[pts_, rot_, tran_] := (rot.#) + tran & /@ pts

rm[axis_, \[Theta]_] := With[{ax = Normalize[axis]},
  With[{x = ax[[1]], y = ax[[2]], z = ax[[3]], cos = Cos[\[Theta]],
    sin = Sin[\[Theta]]},
   {{cos + x^2 - cos x^2, x (y - cos y) - sin z,
     sin y - (-1 + cos) x z}, {x (y - cos y) + sin z,
     cos + y^2 -
      cos y^2, -sin x - (-1 + cos) y z}, {-sin y - (-1 + cos) x z,
     sin x - (-1 + cos) y z, cos + z^2 - cos z^2}}
   ]
  ]

pts = Table[
   rt[diamond3D[[1]],
    rm[RandomReal[{0, 1}, 3], RandomReal[{0, 2 Pi}]],
    RandomReal[NormalDistribution[25, 6], 3]
    ], {n}];

Graphics3D[
 Polygon[pts,
  VertexColors -> Table[ConstantArray[Hue[RandomReal[]], 4], {i, n}]]]

or if you are feeling particularly whimsical (it is carneval time):
Graphics3D[
 Polygon[pts,
  VertexColors -> Table[Hue[RandomReal[]], {i, n}, {t, 4}]]]

A:
It's very windy here today, so the confetti is going everywhere.
g = Graphics3D[
Table[{EdgeForm[], RandomChoice[{White, Pink, Yellow}],
 Translate[
  Polygon[RandomReal[.01, {4, 3}] ], {RandomReal[], RandomReal[],
   RandomReal[]}]} , {x, 1500}], Boxed -> False];
Export["animation.gif",
 Table[Show[g, ViewAngle -> 1, ViewPoint -> {0, 0, 0},
    ViewCenter -> {Sin[2 x], Cos[-2 x], Cos[2 x]} ,
    Lighting -> "Neutral"] , {x, -2, 2, 0.05}]]

A: Since Heike is AWOL here is some 3D confetti to tide us over.
diamond = {{#, -#} #2, -{#, #}, {-#, #} #2, {#, #}} &;
diamond3D = Polygon[ {##, 0} & @@@ diamond[1, 1/2] ];

rots = Rest@Tuples[{0, 1}, 3];

Graphics3D[{EdgeForm[None],
  Table[
   {Hue @ Random[],
     Translate[
       Rotate[diamond3D, Random[] Pi, RandomChoice@rots],
       RandomReal[NormalDistribution[25, 6], 3]
     ]},
   {500}
  ]
}, RotationAction -> "Clip"]

A:
How can this code be improved, for example, by including shadows, raytracing or the effects of gravity to make it more realistic?

I felt that this question deserved an answer.  The one I describe here is to create a set of confetti "agents" that respond in quasi-physical ways to external forces and "know" how they should be displayed.
It is handy, and a whole lot of fun, to do this in an extensible and easily modified way, because you're going to think of loads of improvements to make once the framework is in place.  It helps to have well-documented code--there is less cognitive burden on you, the programmer, when modifying it--so I hope you won't mind that it's somewhat more verbose than usual.
By taking a top-down approach, this code practically writes itself.  Start with the agents themselves, the confetti:
update[confetto[symbols_, location_, frame_, momentum_, angularMomentum_],
      force_, {t_, dt_}] :=
  With[{δMomentum = force[location, frame, momentum, t]},
   confetto[symbols, location + dt momentum,
   rotate[frame, dt angularMomentum],
   momentum + dt δMomentum, angularMomentum]
  ];

I have endowed a single "confetto" with information about how to draw it (symbols), its present location and momentum (location and momentum)--that is, its physical state--, and some internal state information (frame for the orientation and angular momentum for its rate of change: you will see the little pieces of paper rotate as they move).  That should be enough for rich simulations.  A simulation will proceed by applying update over time periods of short duration to update the state of each object.  This will rely on two other methods: force to compute forces and display to draw an object in its current state.
Update calls rotate to change the orientation, so let's take care of that detail now:
crossProduct[{x_, y_, z_}, {x0_, y0_, z0_}] :=
   {y z0 - y0 z, z x0 - z0 x, x y0 - x0 y};
rotate[frame_, α_] := # / (Norm[#] + 0.000001) & /@
      (Map[# + crossProduct[#, α] &, frame, {1}]);

(You can probably do this faster with quaternions, but this is good enough for a start.)
There are many ways to display a confetto, depending on what kind of object you would like it to be.  For instance--this will be relatively fast and is useful for testing--just draw a point as a visual placeholder:
display[confetto[symbols_, location_,  ___]] := {symbols, Point[location]}

You can get more information by drawing a "tail" showing how the objects have been moving:
display[confetto[symbols_, location_, frame_, momentum_, ___]] :=
    {symbols, Thick, Line[{location, location - 0.2 momentum}]}

To emulate the other examples offered in this thread, and to show how the angular momentum works, let's view each object as a square.  The frame attribute of a confetto determines its size and orientation.  At the same time we draw these objects, we also draw their "shadows," provided they are in front of the coordinate planes. Here, then, is a fancier version of display:
shadow[x_, k_] /; 1 <= k <= Length[x] := ReplacePart[x, k -> 0];
display[confetto[symbols_, location_, frame_, ___]] :=
  Block[{x = frame[[1]], y = frame[[2]], vertices, objects,
    shadowPlanes},
   vertices = {location + x, location + y, location - x, location - y};
   objects = {symbols, Polygon [vertices]};
   shadowPlanes = Pick[Range[Length[location]], Positive[location]];
   If [Length[shadowPlanes] > 0,
    f = Function[{k}, Polygon[shadow[#, k] & /@ vertices]];
    objects = Join[objects,
      {Opacity[0.5], GrayLevel[0.3], EdgeForm[{GrayLevel[0.3], Opacity[0.1]}]},
      f /@ shadowPlanes];
    ];
   objects
   ]

Write your own display function to simulate other objects.
Notice that none of this graphical work needs to get done except when we want to look at an object.  Thus, we could create a long simulation (using update) but call display only at key times, or when interesting things happen.  Separating the physics from the graphics is a good strategy.
Later on, to help the eye make sense of these shadows, we will want to have some fixed "walls" on which the shadows appear.
walls[indexes_List, size_, ϵ_] :=
  With[{square = {{1, 1}, {-1, 1}, {-1, -1}, {1, -1}}},
   {RGBColor[.97, .97, .97], Opacity[.1],
    Polygon /@
     Outer[Insert[ #2, ϵ, #1] &, indexes, size square, 1]
    }
   ]

Update invokes a "force" function to change an object's momentum.  Newtonian gravitation on a flat earth is especially simple:
gravity[location_, frame_, momentum_, time_] := {0, 0, -1}

In general, the forces applied to an object depend on its location, the time (for time-varying forces), the object's location, and the situations of all other objects.  Handling the latter is complicated so I have not built it into this framework: only external forces are applied.  Here is a more complex example of what we can still do despite this limitation:
smokeRing[location_, frame_, momentum_, time_] :=
  Module[{normal = crossProduct @@ frame, origin = {15, 15, 15}, x,
    wind0 , ρ, z, wind1, wind, windSpeed = 5},
   x = location - origin;
   wind0 = {x[[2]], -x[[1]], 0};
   ρ = Sqrt[x[[1]]^2 + x[[2]]^2] ;
   If[ρ == 0, ρ = 1];
   z = x[[3]] ;
   wind1 = {-z x[[1]] / ρ, -z x[[2]]/ ρ, ρ - 3};
   wind = (wind0  + wind1) windSpeed / Norm[x] - momentum;
    Abs[normal . wind] wind / Norm[wind]
   ]

You can see it in action in the example below, where it has been added to the gravitational force.  If you would like to see this force field, (partial) visualizations can be drawn; e.g.,
VectorPlot3D[
    smokeRing[{x, y, z}, {{1, 0, 0}, {0, 0, 1}}, {0, 1, 0}, 0],
        {x, 0, 30}, {y, 0, 30}, {z, 0, 30}]

Note, though, that the force on a confetto depends on its orientation and its momentum: this attempts a realistic simulation of what wind does to a small slip of paper.
You might like to write code for other kinds of forces.  Can you blow one smoke ring through another and then turn it green? :-)
We're all set to go!  Let's make some confetti.  I will place them all at the same location with the same orientation at the outset, but endow them with randomly varying momenta and angular momenta so that they all do different things:
r[n_] := RandomReal[NormalDistribution[0, 1], n];
confetti =
  Table[confetto[
    Hue[RandomReal[]], {20, 20, 25}, {{1,0,0}, {0,1,0}}, r[3], r[3]/2], {320}]

To make them fly, we just need to keep updating their state as a clock ticks:
 Module[{c = confetti, speed = 0.06, nFrames = 240,
    w = walls[Range[3], 30, e = -0.02], time = 0, slices,
    force = Through[(gravity + smokeRing)[##]] &},
   slices = Table[time = time + speed;
   c = ParallelMap[update[#, force, {time, speed}] &, c, {1}], {i, 1, nFrames}];
   frames = ParallelMap[Graphics3D[{w, Map[display, #, {1}]},
         PlotRange -> {{e, 29}, {e, 29}, {e, 29}},
         ViewVector -> {{70, 50, 40}, {-1, -1, -1}},
         Boxed -> False, ImageSize -> 400] &, Prepend[slices, confetti], {1}]
  ];

(You could anti-alias the graphics here if you like.  I find that the computation takes too long, so I have left it out.)  Through is a handy way to create combinations of forces: this gives you a manageable way to handle extremely complex combinations of additive forces.
That was a 30 second calculation, by the way: not fast, but not too shabby.
To keep the file size down, I have exported only some of these frames:
Export["F:/temp/confetti4a.gif", frames[[141 ;; 210]]]

Enjoy!


text:
Q: PFUser current User Parse Edit
The code in question and 'this here ... because only by changing the parameters PfUser Current User in PfUser User, the app does not create problems ... I forgot to indicate the type of Crash ...
-(void) {RichiamaDatiInattesa

PFQuery *EsamiInAttesa = [PFQuery queryWithClassName: @ "EsamiInAttesa"];

[EsamiInAttesa whereKey: @ "user" equalTo: [PFUser currentUser]];** //This is the problem Crash "Equal To: [PFUser currentUser]

[EsamiInAttesa countObjectsInBackgroundWithTarget: self selector: @ selector (countcallback: error :)];}

This' crash that returns the Log
U 03/08/2013 00:04:10.650 [20120:907]  Terminating app two to uncaught exception 'NSInvalidArgumentException', reason: 'Can not do a comparison for query type: (null)'
 First throw call stack:
(0x31a703e7 0x3976b963 0x31a70307 0xcdb6b 0xbba53 0xa939d 0xa9117 0x3389e579 0x338ded59 0x338daaf5 0x3391c1e1 0x338df803 0x338d7833 0x3387fd1f 0x3387f7ad 0x3387f1ef 0x355975f7 0x35597227 0x31a453e7 0x31a4538b 0x31a4420f 0x319b723d 0x319b70c9 0x338d646d 0x338d32b9 0xa89bd 0x39b98b20)
libc + + abi.dylib: terminate called throwing an exception
/////////////////////////////////////////////////////////////////////////////////////////
I'm working PARSE (spectacular) but I can not figure out where I'm wrong because I continually from this CRASH .... : (
Terminating apt two to uncaught exception 'NSInvalidArgumentException', reason: 'Can not do a comparison for query type: (null)'
If I modify this query "equal to [PFUser current user] in [PFUser user] does not return the application problems and it works perfectly, except that when I open the application, the first page I need you to give me the values of the current user and this is not 'possible if instead of current user only insert user ...
The problem occurs when I run the LOGOUT the time the user and try to log in again ... at this time the application CRASH ... Not even the screen displays PF Login
The code 'this, can you tell me where I'm wrong? thanks to all
- (void) {RichiamaDatiInattesa

PFQuery EsamiInAttesa * = [PFQuery queryWithClassName: @ "EsamiInAttesa"];
     [EsamiInAttesa whereKey: @ "user" equalTo: [PFUser currentUser]];
     [EsamiInAttesa countObjectsInBackgroundWithTarget: self selector: @ selector (countcallback: error :)];
}

- (void) countcallback: (NSNumber *) count error: (NSError *) error {
     if (error) {
         self.DisplayNumero.text = [NSString stringWithFormat: @ "% d tests are currently pending," [count intValue]];

     Else {}

         self.DisplayNumero.text = [NSString stringWithFormat: @ "Connection Absent"];
        / * [[[UIAlertView alloc] initWithTitle: @ "Missing Information"
                                     message: @ "Make sure you fill out all of the information!"
                                    delegate: nil
                           cancelButtonTitle: @ "ok"
                           otherButtonTitles: nil] show]; * /
        }

}

A: You need to check if there is a currently logged in user before trying to perform any operations that require one. If [PFUser currentUser] == nil then you should not create and try to run your PFQuery because there is no current user to generate it with.

You could try:
- (void)RichiamaDatiInattesa {
    if ([PFUser currentUser] != nil) {
        PFQuery EsamiInAttesa * = [PFQuery queryWithClassName: @ "EsamiInAttesa"];
        [EsamiInAttesa whereKey: @ "user" equalTo: [PFUser currentUser]];
        [EsamiInAttesa countObjectsInBackgroundWithTarget: self selector: @ selector (countcallback: error :)];
    } else {
        [self countcallback:0 error:nil];
    }
}

When the user is logging in, be sure that RichiamaDatiInattesa method is called once the login is complete (if its done in the background).


text:
Q: What is the Google BigQuery equivalent AWS service? I heard Athena is data analytics service from AWS which provides the same features like big query. Can we use Athena as alternative product for bigquery?

A: Athena is often used as a SQL layer for structured data in S3 such as formatted logs rather than a production DB like BigQuery which brings built-in multi-region support, etc. The AWS equivalent would still be a dedicated DB, either Postgres for SQL or Dynamo for NoSQL.


text:
Q: Como visualizar se existem dois itens iguais no ArrayList e removê-los? Estou fazendo a "Tokenização" de um arquivo TXT.
Preciso que o código guarde todos os tokens em uma ArrayList, mas não pode ficar nenhum token duplicado.
Gostaria de saber como faço para remover os tokens duplicados, ou verificar se o token já existe e neste caso não adicioná-lo.
Meu código atual:
for (org.cogroo.text.Token token : sentence.getTokens()) { // lista de tokens

    token.getStart(); token.getEnd(); // caracteres onde o token comeca e termina
    token.getLexeme(); // o texto do token (palavra que ele separa e pega exp: "clinico"
    token.getLemmas(); // um array com os possiveis lemas para o par lexeme+postag
    token.getPOSTag(); // classe morfologica de acordo com o contexto("coloca "prp, adj,n(noun))
    token.getFeatures(); // genero, numero, tempo etc
    contadorTokens++;
    System.out.println(expandirAcronimos(token.getLexeme()) + "_" + token.getPOSTag() + "_" + token.getFeatures());// imprime a palavra com o tag
    gravarArq.println(token.getLexeme() + "_" + token.getPOSTag() + "_" + token.getFeatures());// grava no arquivo txt cada palavra tokenizada
    gravarArquivo.println(token.getPOSTag() + "_" + token.getFeatures());// grava no arquivo "Tokens.txt" cada token

    listaTokens.add(token.getPOSTag()); //ADICIONA as tags para dentro de uma lista

    for(int s=0;s<listaTokens.size();s++){  //PERCORRE A LISTA
        if (!listaTokens.equals(token.getPOSTag())) {

        }
    }
}

A: Para guardar elementos sem repetição, o ideal é usar um tipo de dados "conjunto" em vez de "lista". Eu sugiro o HashSet, ou talvez o LinkedHashSet se a ordem dos tokens deve ser preservada:
Set conjuntoTokens = new HashSet(); // Pode ser genérico, i.e. Set<Tipo>

for (org.cogroo.text.Token token : sentence.getTokens()) { // lista de tokens
    ...

    //listaTokens.add(token.getPOSTag()); //ADICIONA as tags para dentro de uma lista
    boolean mudou = conjuntoTokens.add(token.getPOSTag()); // adiciona as tags no conjunto
                                                           // em vez da lista
    if ( !mudou ) {
        ... // O elemento já existia no conjunto
    }
}

listaTokens.addAll(conjuntoTokens); // adiciona todos os elementos do conjunto na lsta


text:
Q: JScript runtime error when using UpdatePanel I am trying to create a dynamic UI using UpdatePanel of AJAX toolkit.
Let me explain the context of my application a bit. There are many profiles. Each profile has a number of product classes. Each product class has a number of products.
I am implementing a comparison of products.
Profiles are represented by RadioButtonList (dynamically created). For each product class of selected profile a DropDownList need to
be dynamically created that allows user to select a product of that class.
Everything is working fine on the first selection. However when I try to select another product and click submit the second time, the following error is thrown:

Microsoft JScript runtime error:
  Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback
  or callback argument.  Event validation is enabled using  in configuration or <%@ Page
  EnableEventValidation="true" %> in a page.

Any hints on why this error is thrown would be very helpful.
protected void Page_Load(object sender, EventArgs e)
{
    pnlDynamic.Visible = false;
    if (!this.IsPostBack)
    {
        LoadProfiles();  //Data binding is done for radio button list
    }
    else
    {
        btnSubmit.Enabled = true;
        GenerateProductUI(ProfileID); //DropDownLists are dynamically created and populated from database
        //ProfileID is the selected profile id
    }
}

 <asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger controlid="rblProfiles" eventname="SelectedIndexChanged" />
    </Triggers>
     <ContentTemplate>
        <asp:Panel ID="Panel1" runat="server">
            <asp:RadioButtonList ID="rblProfiles" runat="server" AutoPostBack="True"
                onselectedindexchanged="rblProfiles_SelectedIndexChanged">
            </asp:RadioButtonList>
        </asp:Panel>

        <asp:Panel ID="pnlDynamic" runat="server" Visible="false">
            <asp:Panel ID="Panel2" runat="server">
                <asp:Table ID="table" runat="server"/>
            </asp:Panel>
        </asp:Panel>

    </ContentTemplate>
</asp:UpdatePanel>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" CssClass="btnSubmit" AutoPostBack="True" />

<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger controlid="btnSubmit" eventname="Click" />
    </Triggers>
     <ContentTemplate>

    <asp:Panel ID="pnlResult" runat="server" Visible="false">

    </asp:Panel>

    </ContentTemplate>
</asp:UpdatePanel>

A: IMPORTANT! EVERYONE WHO EVER DISABLES EVENT VALIDATION SHOULD UNDERSTAND WHAT HE IS DISABLING!
Imagine that you have a blogging application (or a banking application) and there is a list of comments (or bank accounts) all users can see the comments (or the accounts) but only moderators (or managers) can delete them. So you write a check to switch the delete button visible property depending on the access of the user. Users who are not moderators (managers) cannot delete the comment (account). Problem solved.
HOWEVER if you disable event validation a malicious user can send a post request claiming to have pressed the delete button despite the fact that it was never enabled for him. Normally the event validation would kick in and produce an exception but if it is disabled ASP.NET would not check if the button was visible and will just run the button click handler code and the comment (account) would be deleted. This can be prevented if you check if the user can delete in the button click event but you should also consider that another developer may come later and add another button (edit?) without noticing that event validation was disabled. Also now all other buttons on the page require the appropriate checks. Be very careful if you disable event validation!
The error occurs because you are triggering a postback from a control which does not exist when the original page was rendered. One way to fix it would be to disable event validation for this page but you should make sure to check the credentials of the user requesting the change in the event itself otherwise it is a security issue because a user will be able to "press" a button that was not rendered at all (for example on products he does not have access to).
You can disable event validation through the page directive:
<%@ Page EnableEventValidation="false" ... %>

I believe it is also possible to set the update mode of the update panel to always instead of conditional which maybe will fix the issue (can you try it and tell us?) but this will increase the data sent over the network. If it is a good trade off depends on your use case, on the number and size of the update panels you have on the page (the more you have the worse). If it is an internal app or this UI is accessed relatively rarely I would go for this approach (assuming it works because I have not validated that).
BTW this is not actually a script error. You are getting a client side script error simply because the error surfaces through an AJAX request. This is purely a server error that is raised because of a potential security issue with your code.

A: Add <%@ Page EnableEventValidation="false" %> at the top of the page.

A: Once dynamic dropdown lists are created you have to recreate them or any dynamically created control on every page init or page load. In such case you don't need to use EnableEventValidation="false".
protected void Page_Load(object sender, EventArgs e)
{
    pnlDynamic.Visible = false;
    if (!this.IsPostBack)
    {
        LoadProfiles();  //Data binding is done for radio button list
    }
    else
    {
        btnSubmit.Enabled = true;
    }

        GenerateProductUI(ProfileID); //DropDownLists are dynamically created and populated from database
        //ProfileID is the selected profile id
}

Or just move GenerateProductUI(ProfileID) from Page_Load to Page_Init


text:
Q: Can output current of buck current more then input current? I want to power a bulb from solar panel(17V/.9A) but due to low resistace (2 Ohm)of load i have to reduce the input voltage to 5.5V @ 2.75A for max power.
I am using generic buck converter (not any mppt module)to lower voltage but as i studied buck converter has not more output current than input current. So is there any way to increase output current?
Some days ago i found that increasing input capacitance at buck converter can let you increase o/p current. Is it true?

A: Yes it can have a higher output current then input current.
But let's have a look at your numbers:
 - Input: 17V 0.9A that is 17*0.9 = 15.3W
 - Output: you want 5.5V and 2.75A that is 5.5*2.75 = 15.125 W.
That is lower then at the input so at least we are not violating the law conversion of energy.
Your buck converter then needs an efficiency of 15.125/15.3 = 98.8%.
That however is a challenge, and as far as I know++ not possible for converters of about 15W.
++I have not got much experience with buck converters so I am happy to be corrected.

A: "17V /0.9A" might imply the PV has a source impedance of 17/0.9 = 18.9 Ω
...
 so guess what happens with a 2Ω load transformed to a higher impedance.
Due to the law of energy conservation , so Zin (Ω ) is just like transformers so  \$P=\dfrac{V_{in}²}{Z_{in}}=\dfrac{V_{out}²}{Z_{load}}\$ (neglecting losses)
so \$Z_{in}=(\dfrac{V_{in}}{V_{out}})² * Z_{load}\$
In your case load is 2Ω and the other variables are unknown with this load. So the design objective is to regulate the voltage rate for maximum power transfer (MPPT) to match the PV source impedance \$Z_{min}\text~ \dfrac{V_{oc}}{I_{sc}}\$ at mppt voltage which starts around 82%~85% \$V_{oc}\$ and drops >10% with useable solar power input,  under varying solar input which means Z rises with useable lower power input.
If you understand maximum power transfer occurs at match impedances then you will understand one method used to regulate the above Buck impedance ratio. Your Buck uses a series switched inductor so its effective impedance rises with lower duty cycle, d, such that \$Z_L \text{~} 2\pi f*L/d~\$ is an approximation.
I have over-simplified this analysis for you to understand the fundamentals, so that you can examine more detailed design calculations not included in this answer.


text:
Q: ajax formdata append does not work for key value style why this code does not work ? how am I supposed to append additional data in formdata?
fd = new FormData();
fd.append("file_for_upload", file_blob_chunk);
fd.append("test", "testing");
fd.append("test2", original_file_name);

xhr = new XMLHttpRequest();
xhr.open("POST", "files/index/" + file_name + '/' + file_part, true);
xhr.send(fd);

when I debug it, I can see the array for 'file_for_upload', but not for 'test' or 'test2'.
basicly usually you will use $_FILES and then it should show array of file_for_upload. It works that way. but now I need to add another one such as original_file_name. but it does not show the other array.
Is it possible because I only have one form for file upload in the html page, and don't have the other two textbox form?

A: You will find those two in $_POST. Only files go into $_FILES.


text:
Q: How to optimize a query when grouping on a date / unix timestamp? I'm not very used to MySQL, but I think it can be much faster than it is.
Here's my table:
CREATE TABLE `crashes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
 `added_date` int(11) NOT NULL,
 `status` int(11) NOT NULL,
 `issue_id` varchar(32) NOT NULL,
 `report_id` text NOT NULL,
 `app_version_code` text NOT NULL,
 `app_version_name` text NOT NULL,
 `package_name` varchar(80) NOT NULL,
 `package_name_id` tinyint(4) NOT NULL,
 `file_path` text NOT NULL,
 `phone_model` text NOT NULL,
 `android_version` text NOT NULL,
 `build` text NOT NULL,
 `brand` text NOT NULL,
 `product` text NOT NULL,
 `total_mem_size` int(11) NOT NULL,
 `available_mem_size` int(11) NOT NULL,
 `custom_data` text NOT NULL,
 `stack_trace` text NOT NULL,
 `initial_configuration` text NOT NULL,
 `crash_configuration` text NOT NULL,
 `display` text NOT NULL,
 `user_comment` text NOT NULL,
 `user_app_start_date` text NOT NULL,
 `user_crash_date` text NOT NULL,
 `dumpsys_meminfo` text NOT NULL,
 `dropbox` text NOT NULL,
 `logcat` text NOT NULL,
 `eventslog` text NOT NULL,
 `radiolog` text NOT NULL,
 `is_silent` text NOT NULL,
 `device_id` text NOT NULL,
 `installation_id` text NOT NULL,
 `user_email` text NOT NULL,
 `device_features` text NOT NULL,
 `environment` text NOT NULL,
 `settings_system` text NOT NULL,
 `settings_secure` text NOT NULL,
 `shared_preferences` text NOT NULL,
 `application_log` text NOT NULL,
 `media_codec_list` text NOT NULL,
 `thread_details` text NOT NULL,
 `user_ip` text NOT NULL,
 PRIMARY KEY (`id`),
 KEY `package_name_id` (`package_name_id`)
) ENGINE=MyISAM AUTO_INCREMENT=202364 DEFAULT CHARSET=utf8

As you can see it's filled with 200k rows. I'd like to retrieve the row added_date (unix timestamp, int(11)), and number of rows on that day.
So I select the date, day (as Y-M-D), and count:
SELECT date_format(from_unixtime(added_date), '%Y-%c-%d') as date, added_date, count(*) as nb_crashes FROM crashes WHERE package_name = 'net.bicou.redmine' GROUP BY date ORDER BY date ASC

It's very slow! Almost 1.5sec on a dedicated mysql server on my host.
So I figured I could optimize the thing a little bit: I added a package_name_id that is a tinyint, which is unique per package_name (I have 5 different package_name values on that 200k rows). I made that an INDEX so that MySQL can browse it faster.
Result: 0.9sec. That's much better, but still off the performance I'm expecting!
How could I optimize the thing? I guess creating the date on each row, then grouping is very expensive. However I don't know how I could make this faster...
Edit:
Here's what I did to update the table:
ALTER TABLE  `crashes` ADD  `temp` DATETIME NOT NULL
UPDATE crashes SET temp = FROM_UNIXTIME( added_date )
ALTER TABLE  `crashes` ADD INDEX (  `temp` )

Here's the updated query:
SELECT added_date, count(*) as nb_crashes FROM crashes WHERE package_name_id=3 GROUP BY year(temp),month (temp),dayofmonth(temp) ORDER BY temp ASC

I've still got execution times of around one second... Did I do something wrong?

A: You should not be using unix timestamp values if you ever need to query against that field in a date-like way. You should use date, datetime, or timestamp field types.
Why?
Because if you want to do something like query results for a specific date or group records by date, you will always have to use FROM_UNIXTIME() in order to do so.  This function call will prevent you from using any sort of index on the date value if you are trying to use it for sorts, joins, where filters, groups, etc.  There is nothing you can do to improve your query outside of using the proper data type and then indexing the fields you are going to be using for sorts, filters, joins, groups, etc.
Really the use of unix timestamps in DB's seems to be proliferated by inexperienced PHP developers who think that it is easier to work with dates in this format in PHP (either they are too lazy to convert date/datetime DB output to unix timestamps in PHP, or they have not figured out how to use dateTime and dateInterval PHP classes to make working with dates in PHP easier).
My suggestion is to break this habit now and start learning how to work with date/datetime fields in MySQL.
Antoher thing I would suggest looking at your table DDL is that you probably should revisit the use of text fields there.  Most of those cases look like they might better be varchar fields.

A: If you need performance, you need an index, and if you need an index, then you need to create a column with the right kind of data in it before you do your query.
This requires creating an additional column and populating it with the result of your transformation, plus inserting all new rows with that column populated correctly.
Why are you storing your date as a timestamp instead of as a proper DATE column, anyway?

A: You could make an index on both the package_name and the added_date columns. Also, change your ORDER BY to order by added_date instead of by date, since ordering by date would probably need a filesort step.
In any case EXPLAIN helps diagnose the query better.