text:
Q: Integrating over the rate of change to find x I am stuck trying to turn a graph of dx/dt vs time into a graph of x in each bin vs time.
I have a large dataset of galaxies. For each galaxy there is an array which is the rate of change in mass over time, ie dM/dt. So for each galaxy there is a 1d array declaring the dM/dt at certain intervals of time. I also have a time array. I can make a plot of dM/dt versus time and see the rate of change over the course of the universe.
However now I want to make a different plot with the mass of the galaxy at each time. Ie how much mass has formed in each time interval. I'm trying to integrate over each array but that just gives me the total mass at the end. I want the masses at each interval so I can make a plot.
This is the array of dM/dt for the galaxy 1.
`[ 1.34162134e+10  1.00928939e+11  6.60376576e+10  3.42446745e+11
    2.73107925e+11  1.91493528e+11  6.73213607e+11  8.64649622e+11
    2.05433614e+11  8.47043150e+11  3.87556687e+11  1.67345819e+11
    5.12216609e+11  1.87612654e+12  7.74310416e+11 -5.22415543e+09
   -1.25683250e+11 -5.54250651e+10 -3.76655769e+10 -1.59683145e+10
    2.82219633e+11  6.00554078e+11  3.44238577e+11  2.79598376e+11
    1.05315182e+11 -3.21916236e+11 -1.50353059e+10  4.55187056e+10
   -3.65908025e+10  7.60636622e+10  6.41365631e+10  7.13690729e+10
    1.05199767e+11]`

And here's the time array. Units in Gyr but not important.
`[ 0.418  0.547  0.687  0.844  1.036  1.282  1.54   1.944  2.384  2.839
 3.285  3.744  4.206  4.657  5.115  5.577  6.073  6.522  6.998  7.453
 7.932  8.432  8.902  9.389  9.837 10.299 10.834 11.323 11.824 12.337
12.795 13.328 13.803]`

Then of course I can plot a graph of these two:
graph of galaxy
Now I want to plot a graph of the mass formed in each interval and plot that against time (I hope this makes sense). So I would need to integrate the first array over each time interval. I'm having trouble though. This is what I have so far
` for i in range(galaxyarray.shape[0]): # for i in number of galaxies

      for j in range(galaxyarray.shape[1]): # for j in each element

         result = integrate.trapz((Mhdotarr[i,j]), time)`

but that's not working. I can get the total mass formed over time by integrating over the whole array, but I want to get the mass at each interval. I hope this makes sense?
To look something like this: example
Any help is appreciated!

A: I think you are looking for cumulative integration. To do this swap trapz for cumtrapz
for i in range(galaxyarray.shape[0]): # for i in number of galaxies
      for j in range(galaxyarray.shape[1]): # for j in each element

         result = integrate.cumtrapz((Mhdotarr[i,j]), time)

This returns an array of mass over time where the final element is the final mass.


text:
Q: Will my emails be kept if I upgrade from 10.6.8 to 10.11? I have a (Mid 2009) Macbook Pro. I want to upgrade my MacOS X version from 10.6.8 to 10.11 but I have some issues.
I have so many important emails stored in Mail v4.5 on Snow Leopard that I don't want to lose. I wanted to know if I upgrade, will all my mail be kept in the new version of Mail?

A: The upgrade does keep all emails, but the new mail program will reprocess and reindex and move the actual files.
IF there is corruption in the filed or database on your computer now, an upgrade is when things get worse, so be sure to back up your Mac before the upgrade. That way, no matter what happens with the script, you could wipe and go back to the way things were or investigate your follow on question of how to export or make the mails portable in general as opposed to trusting the upgrade does what is intended.

redpajama_set_name: RedPajamaStackExchange


text:
Q: pandas reshaping dataframe with different length rows I have a the following pandas data frame with the index on the left:
      0   1   2   3   4   5   6   7   8   9   10   11   12   13   14
A17   a   b   1  AUG) NaN NaN NaN NaN NaN NaN NaN  NaN  NaN  NaN  NaN
nn6   c   d   2  POS) e   f   2   Hi)
AZV   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN  NaN  NaN  NaN
JFK   a   b   4   UUI) c   v   8   Yo)  t   f   9   po)

I'm looking to re-shape it to:
     0    1    2    3
A17  a    b    1   AUG)
nn6  c    d    2   POS)
nn6  e    f    2   Hi)
AZV  NaN  NaN  NaN NaN
JFK  a    b    4   UUI)
JFK  c    v    8   Yo)
JFK  t    f    9   po

I have tried reshape() and used itertools to iterate over the columns but still can't seem to get it.
Basically, each time a ) is encountered then break to a new line.
The real table has over 150 columns.
thanks

A: Another option that doesn't require iterating over rows (which can be very slow if there are many) is to do the following
[ins] In [1]: df
Out[1]:
     0    1    2     3    4    5    6    7
A17  a    b    1  AUG)  NaN  NaN  NaN  NaN
nn6  c    d    2  POS)    e    f    2  HI)
AVZ     NaN  NaN   NaN  NaN  NaN  NaN  NaN

[ins] In [2]: joined = df.apply(lambda x: ' '.join([str(xi) for xi in x]), axis=1)
[ins] In [4]: split = joined.str.split(')', expand=True).reset_index(drop=False).melt(id_vars='index')

[ins] In [6]: split.drop('variable', axis=1, inplace=True)

[ins] In [7]: split
Out[7]:
  index                        value
0   A17                    a b 1 AUG
1   nn6                    c d 2 POS
2   AVZ  nan nan nan nan nan nan nan
3   A17              nan nan nan nan
4   nn6                     e f 2 HI
5   AVZ                         None
6   A17                         None
7   nn6
8   AVZ                         None

[ins] In [8]: sel = split['value'].str.strip().str.len() > 0

[ins] In [9]: split = split.loc[sel, :]

[ins] In [9]: split
Out[9]:
  index                        value
0   A17                    a b 1 AUG
1   nn6                    c d 2 POS
2   AVZ  nan nan nan nan nan nan nan
3   A17              nan nan nan nan
4   nn6                     e f 2 HI

[ins] In [10]: out = split['value'].str.strip().str.split(' ', expand=True)

[ins] In [11]: out.index = split['index']

[ins] In [12]: out
Out[12]:
         0    1    2    3     4     5     6
index
A17      a    b    1  AUG  None  None  None
nn6      c    d    2  POS  None  None  None
AVZ    nan  nan  nan  nan   nan   nan   nan
A17    nan  nan  nan  nan  None  None  None
nn6      e    f    2   HI  None  None  None

and then it's a matter of dropping the 4th to 6th column which is simple.
I added some of the output so that you can see what's happening in each step.

A: I think an efficent way to concat the values would be to chunk the dataframe into 4 equal parts and re-concat it along the index.
The issue here is the column names which we can dynamically rename inside the concat statement.
import numpy as np
lst = np.array_split([i for i in range(len(df.columns))],4)

[array([0, 1, 2, 3]),
 array([4, 5, 6, 7]),
 array([ 8,  9, 10, 11]),
 array([12, 13, 14])]

dfs = pd.concat( [
        df.iloc[:,i].rename(columns=
                            dict(zip(df.iloc[:,i].columns,range(4)))
                            )

        for i in lst
    ]).dropna(how='all')

 print(dfs)

 0  1    2     3
A17  a  b  1.0  AUG)
nn6  c  d  2.0  POS)
JFK  a  b  4.0  UUI)
nn6  e  f  2.0   Hi)
JFK  c  v  8.0   Yo)
JFK  t  f  9.0   po)

the only diff here is that your missing a row from your desired output due to it being na.
we can do a union with combine_first to get the delta between the two dataframes.
dfs = dfs.combine_first(df.iloc[:,:0])

print(dfs)

       0    1    2     3
A17    a    b  1.0  AUG)
AZV  NaN  NaN  NaN   NaN
JFK    a    b  4.0  UUI)
JFK    c    v  8.0   Yo)
JFK    t    f  9.0   po)
nn6    c    d  2.0  POS)
nn6    e    f  2.0   Hi)

A: There are other options, like slicing columns and appending, but this is pretty straightforward.
output = []
for index, row in df.iterrows():
    r = row.dropna().values
    if len(r) <= 4:
        output.append([index,*r])
    else:
        for x in np.reshape(r, (int(len(r)/4),4)):
            output.append([index,*x])

pd.DataFrame(output).set_index(0)


text:
Q: How do I "Enable Wi-Fi" on my toolbar if the option disappeared? Hi so yesterday I was trying to update my wifi drivers but when I rebooted, the option to "Enable wi-fi" disappeared on my toolbar? How do I make it show up again?
I have Qualcomm Atheros QC6174a btw.
Thanks.


text:
Q: How to encrypt and write RSA private key to file with PEM_Write_RSA_PrivateKey The function:
int PEM_write_RSAPrivateKey(FILE *fp, RSA *x, const EVP_CIPHER *enc,
                                        unsigned char *kstr, int klen,
                                        pem_password_cb *cb, void *u);

The way I call the function :
PEM_write_RSAPrivateKey(pFile, pRSA,NULL,0,NULL,NULL,(void*)passphrase);

In openssl's documents,it says the last parameter is passphrase,but I find the context in the output file is not encrypted。

A: Obviously, because you set the cipher to NULL you won't get any encryption.
Go with something like:
PEM_write_RSAPrivateKey(pFile,pRSA,EVP_des_ede3_cbc(),passphrase, passphraseLength,NULL,NULL);

And of course change the cipher as you please, better option would be to use AES-128-CBC, but it's up to your specific goal and performance requirements.
Don't forget to initialize the OpenSSL library with something like
OpenSSL_add_all_algorithms()


text:
Q: how to make a Venn plot of several groups I have a data like this
df<- structure(list(X1 = c(37L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, NA,
11L, 12L), X2 = c(40L, NA, 35L, 35L, 35L, 34L, 29L, 28L, 28L,
NA, 25L, 24L), X3 = c(60L, 44L, 49L, 41L, NA, NA, NA, 25L, 26L,
NA, NA, 22L), T1 = c(19L, 55L, 47L, 46L, 36L, 42L, 25L, NA, 33L,
42L, 50L, 22L), T2 = c(75L, NA, 32L, 44L, 27L, 31L, 17L, NA,
18L, 45L, 10L, 11L), T3 = c(5L, 6L, 7L, 8L, 9L, 10L, 11L, NA,
46L, 36L, 42L, NA), P1 = c(2L, 2L, 3L, 4L, 2L, 6L, 7L, 8L, 9L,
NA, 1L, 12L), P2 = c(40L, 44L, 4L, 2L, 1L, 1L, 29L, 1L, 1L, 1L,
5L, 55L), P3 = c(1L, 44L, 49L, 3L, NA, NA, NA, 25L, 26L, NA,
NA, 66L)), class = "data.frame", row.names = c(NA, -12L))

group1 is X1,X2,X3
group2 is T1,T2,T3
group3 is P1,P2,P3
I am trying to make a Venn plot but I cannot figure out how to do it. I have read a number of questions here and also a very good tutorial here
https://rstudio-pubs-static.s3.amazonaws.com/13301_6641d73cfac741a59c0a851feb99e98b.html
The first group has three replicate , the second group has 3 replicate and the third group has three replicate.

A: If you want to treat your replicates as a single group, you can use my nVennR package:
library(nVennR)
nonas <- function(x) {unlist(as.list(na.exclude(x)))}
myV2 <- plotVenn(list(X=unique(c(nonas(df$X1), nonas(df$X2), nonas(df$X3))),  P=unique(c(nonas(df$P1), nonas(df$P2), nonas(df$P3))), T=unique(c(nonas(df$T1), nonas(df$T2), nonas(df$T3)))), nCycles = 20)
myV2 <- plotVenn(nVennObj = myV2)

This will give you a quasi-proportional Venn diagram:

You can then examine each region:
>listVennRegions(myV2, na.rm = F)
$`0, 0, 0 ()`
[1] NA

$`0, 0, 1 (T)`
 [1] 19 47 46 36 42 33 50 75 32 27 31 17 18 45 10

$`0, 1, 0 (P)`
[1]  1 66

$`0, 1, 1 (P, T)`
[1] 55

$`1, 0, 0 (X)`
[1] 37 35 34 28 24 60 41

$`1, 0, 1 (X, T)`
[1] 11 22

$`1, 1, 0 (X, P)`
[1]  2  3  4 12 40 29 49 26

$`1, 1, 1 (X, P, T)`
[1]  5  6  7  8  9 25 44

As a curiosity, the nVenn algorithm has no limit for set numbers. You might perform the nine-set diagram, but it would be slow and give little information. It might go like this:
nonas <- function(x) {unlist(as.list(na.exclude(x)))}
myV <- plotVenn(list(X1=nonas(df$X1), X2=nonas(df$X2), X3=nonas(df$X3), T1=nonas(df$T1), T2=nonas(df$T2), T3=nonas(df$T3), P1=nonas(df$P1), P2=nonas(df$P2), P3=nonas(df$P3)))
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- plotVenn(nVennObj = myV)
myV <- showSVG(myV, opacity = 0.2, borderWidth = 0.5, setColors = c('#ff0044', '#ff4400', '#ff2222', '#44ff00', '#00ff44', '#22ff22', '#4400ff', '#0044ff', '#2222ff'))

Probably not very useful. If you want to know more, you can read the vignette for the package.


text:
Q: An example of an endomorphism Could someone suggest a simple $\phi\in $End$_R(A)$ where $A$ is a finitely generated module over ring $R$ where $\phi$ is injective but not surjective? I have a hunch that it exists but I can't construct an explicit example. Thanks.

A: Let $R=K$ be a field, and let $A=K[x]$ be the polynomial ring in one variable over $K$ (with the module structure coming from multiplication). Then let $\phi(f)=xf$. It is injective, but has image $xK[x]\ne K[x]$.

A: Consider the morphism of $\mathbb{R}$-modules:
$$
\varphi : \mathbb{R}^\infty \longrightarrow \mathbb{R}^\infty
$$
defined by
$$
\varphi (x_1, x_2, \dots , x_n, \dots ) = (0, x_1, x_2 , \dots , x_n , \dots ) \ .
$$
This example is not possible with finite dimension vector spaces, because then, with endomorphisms, you have
$$
\text{isomorphism} \quad \Longleftrightarrow \quad \text{monomorphism} \quad \Longleftrightarrow \quad \text{epimorphism} \ .
$$
EDIT. Now I see you've added the finitely generated condition. So, this example doesn't apply any more obviously.


text:
Q: Safe to override save method in ActiveRecord? In a particular class that extends ActiveRecord::Base, I need to update a different ActiveRecord object whenever this one is created. Is it safe to override the save method and do the following in the save?
def save
  super
  other = self.other
  other.name = self.name
  other.save!
end

I'm worried about potential transaction related issues. I assume this would all be 1 transaction, if any part fails, everything is rolled back?

A: Is there a particular reason why you wouldn't use the hooks provided for this purpose?
You've got after_create, after_save, after_update, before_create, before_save, before_update - and a bunch of others. Wouldn't one of those be suitable?
In fact, given what you've said, it sounds like before_save is what you want, as you can catch any errors that occur whilst saving the second model and prevent the first one from being saved (by returning false from the before_save call).


text:
Q: JavaScript - Combine and Add Values in Multiple Same Length Object Arrays I'm looking to reduce an array of objects by matching identical date strings and add the totals together of those matching dates and combine them into a single object.  I could have an array several thousand items long so I'm trying to increase (where ever possible) and complexity.
// before
let objArr = [
    {
        date: '01/01/2018',
        total: 1
    },
    {
        date: '01/01/2018',
        total: 2
    },
    {
        date: '01/02/2018',
        total: 3
    },
    {
        date: '01/02/2018',
        total: 4
    },
    ...
]

// final result
let finalArr = [
    {
        date: '01/01/2018',
        total: 3
    },
    {
        date: '01/02/2018',
        total: 7
    },
    ...
]

I couldn't seem to get the hang of reducing them using reduce:
objArr.reduce((acc, obj) => {
      acc.set(obj.date, (acc.get([obj.date]) || 0) + obj.total);
      return acc;
    }, new Map())

The result always ends up with the wrong totals or the last several array objects look like:
// bad output
badArray = [
    ...,
    {
        date: '01/02/2018',
        total: 4
    },
    {
        date: undefined,
        total: NaN
    },
    {
        date: undefined,
        total: NaN
    }
]

I wrote a script to check to ensure all the values in the date and total properties existed the way they needed to but I still end up with a bad array.  The assumption here is my reduce function isn't right.

A: Your code is almost right. The problem is that you are setting the Map key to the date but trying to get the item by passing an array with the date rather than the date alone.
You are using: acc.get([obj.date]), when you probably want: acc.get(obj.date) (without the [ ])

let objArr = [{date: '01/01/2018',total: 1},{date: '01/01/2018',total: 2},{date: '01/02/2018',total: 3},{date: '01/02/2018',total: 4},]

let s = objArr.reduce((acc, obj) => {
    // not acc.get([obj.date]) !
    acc.set(obj.date, (acc.get(obj.date) || 0) + obj.total);
    return acc;
  }, new Map())

// turn the Map into something that will display:
console.log([...s.entries()].map(([date, total]) => ({date, total})))

A: I think Mark Meyer's answer is good, but this is also another option that uses an empty array as the initial value instead of a Map (maintaining the original structure of your input throughout):

 let objArr = [{date: '01/01/2018',total: 1},{date: '01/01/2018',total: 2},{date: '01/02/2018',total: 3},{date: '01/02/2018',total: 4},];

 const result = objArr.reduce((acc, obj) => {
     const existingObj = acc.find((o) => o.date === obj.date);
     if (existingObj) {
       existingObj.total += obj.total;
     } else {
       acc.push(obj);
     }
     return acc;
 }, []);

 console.log(result);

Note that the benefit of using an empty array as your initial value is that it maintains the original structure of your input (so you wouldn't have to iterate through the generated Map afterwards and convert it into an array of objects). :)


text:
Q: Why doesn't concurrency speed up my fibonacci function? Here is the following concurrency example from A Tour of Go
package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
    }
    close(c)
}

func main() {
    c := make(chan int, 10)
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}

I modified it to not use goroutines:
package main

import (
    "fmt"
)

func fibonacci(n int) int{

    if(n==0||n==1){
        return 1
    }
    x:= 1
    y:= 1
    for i := 0; i < n; i++ {
        tmp := x
        x = y
        y = tmp + y
        fmt.Println(x)
    }
    return x
}

func main(){

    fibonacci2(100)

}

However, the time it takes are both nearly instant at n = 100000.
Does anyone have an example where goroutines does speed up calculations? I am wondering if perhaps there are some compiler settings that is limiting the number of cores my program can use.
Why doesn't the goroutines speed up the calculations?

A: These 2 versions take almost exactly the same time because most of the work is in the Fibonacci function, so it doesn't matter whether it runs on the main goroutine, or a separate goroutine. When n is large, the concurrent version can be slower, because of the communication overhead over channels.

You can see from the above diagram, the only work running on the main thread are 'Println' calls, which take very little time to run.
But if the processing of the number on the main thread takes more time, using a goroutine to generate fibonacci number may be faster.


text:
Q: Cocoa Webkit - Disable text selection, but allow textfield selection Thanks to this answer I know how to completely disable user selection on a WebView.
I would like to prevent users from selecting text/graphics in the WebView but still be able to select a text field to input text. With the above solution selecting text fields is not allowed.

A: It appears the changing the delegate to return [[proposedRange startContainer] isContentEditable] will allow selection on editable elements, i.e. form fields.
- (BOOL)webView:(WebView *)webView shouldChangeSelectedDOMRange:
    (DOMRange *)currentRange
    toDOMRange:(DOMRange *)proposedRange
    affinity:(NSSelectionAffinity)selectionAffinity
    stillSelecting:(BOOL)flag
{
    return [[proposedRange startContainer] isContentEditable];
}


text:
Q: how to make validation more than one field in laravel? How to validate more than one field in laravel? for example: I want corporate_id, brand_id or hotel_id not to have the same catalog name. that is, hotel_id 1 cannot have 2 catalog names "Default".
how to make such validation in laravel? thank you

A: I think you can use Custom Validation Rules.
It's easy to handle
https://laravel.com/docs/8.x/validation#using-rule-objects
/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  array  $value
 * @return bool
 */
public function passes($attribute, $catalogName)
{
    $catalog = Catalog::where('title', $catalogName);
    // corporate_id, brand_id or hotel_id
    if (Input::get('corporate_id')) {
       $catalog->where('corporate_id', Input::get('corporate_id'));
    }
    if (Input::get('brand_id')) {
       $catalog->where('brand_id', Input::get('brand_id'));
    }
    if (Input::get('hotel_id')) {
       $catalog->where('corporate_id', Input::get('hotel_id'));
    }

    if ($catalog->first()) {
       return false;
    }
    else {
       return true;
    }

}


text:
Q: .net lucene Multifield search I have created a index as
Document doc = new Document();
        doc.Add(new Field("SearchKey", (item.FullTextColumn ?? item.Code), Field.Store.NO, Field.Index.TOKENIZED));
        doc.Add(new Field("Type", item.Type.ToString(), Field.Store.YES, Field.Index.TOKENIZED));
        doc.Add(new Field("Name", item.Name, Field.Store.YES, Field.Index.UN_TOKENIZED));
        doc.Add(new Field("Code", item.Code ?? string.Empty, Field.Store.YES, Field.Index.UN_TOKENIZED));

etc
and I am trying to search a term like "Kansas City" in "SearchKey" field and another filed "Type" must be "Airport"
for that I am writing
QueryParser parser = new QueryParser("SearchKey", analyzer);
        Query searchQuery = parser.Parse(text);
 TermQuery typeQuery = new TermQuery(new Term("Type", "Airport"));
 BooleanQuery filterQuery = new BooleanQuery();
        filterQuery.Add(typeQuery, BooleanClause.Occur.MUST);
        Filter f = new QueryFilter(filterQuery);
 Hits results = searcher.Search(searchQuery,f);

but it  gives me NO result ,
if I remove 'f' from
Hits results = searcher.Search(searchQuery,f);

then it gives result but "Type" field contain values other then "Airport" .
any Idea  where I am going wrong ?

A: Looking at your code I think you need to add each query (one for the SearchKey and one for the Type) to the BooleanQuery like below.
var standardLuceneAnalyzer = new StandardAnalyzer();

var query1 = new QueryParser("SearchKey", standardLuceneAnalyzer).Parse("Kansas City*");
var query2 = new QueryParser("Type", standardLuceneAnalyzer).Parse("Airport");

BooleanQuery filterQuery = new BooleanQuery();
filterQuery.Add(query1, BooleanClause.Occur.MUST);
filterQuery.Add(query1, BooleanClause.Occur.MUST);

TopDocs results = searcher.Search(filterQuery);

I haven't tested the code but it should work.


text:
Q: Move the label from left to right and right to left My question is very simple.
My Label1 should move continuously from left to right.
(Start from the left part of the form and go to the right part of the form. When it reaches the right part of the Form, go to the left and so on.) I have 2 timers(one for right and one for left)
I have the following code, it starts at the left and goes to the right, but when it reaches the right of the Form, it doesn't return.
Can anyone help me?
 enum Position
    {
        Left,Right
    }
    System.Windows.Forms.Timer timerfirst = new System.Windows.Forms.Timer();

    private int _x;
    private int _y;
    private Position _objPosition;
  public Form1()
    {
        InitializeComponent();
        if (label1.Location == new Point(0,180))
        {
            _objPosition = Position.Right;
        }
        if (label1.Location == new Point(690,0))
        {
            _objPosition = Position.Left;
        }
    }
private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Label1.SetBounds(_x, _y, 0, 180);
    }

private void tmrMoving_Tick(object sender, EventArgs e)
    {
        tmrMoving.Start();

        if (_objPosition == Position.Right && _x < 710)
        {
          _x +=10;
        }

        if(_x == 710)
        {
            tmrMoving.Stop();
        }
    Invalidate();
    }

private void tmrMoving2_Tick(object sender, EventArgs e)
    {
        tmrMoving2.Start();
        if (_objPosition == Position.Right && _x > 690)
        {
            _x -= 10;
        }
        if(_x == 1)
        {
            tmrMoving2.Stop();
        }
        Invalidate();
    }

Thanks.

A: I think you've overcomplicated things. Let's just have one timer, a step number of pixels that we sometimes flip negative, and some time later flip back to positive. We can move the label by repeatedly setting its Left:
public partial class Form1 : Form
{
    private int _step = 10;

    public Form1()
    {
        InitializeComponent();

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (label1.Right > this.Width) _step = -10;
        if (label1.Left < 0) _step = 10;
        label1.Left += _step;
    }
}

You might want to fine tune it, but the basic motion is there


text:
Q: Find All Possible Outcomes of all Matches in a Football Tournament I am working on a problem statement, where I need to return a list of all the possible combinations of outcomes in Football tournaments.
Let us assume the result of a match can be 1 - The first team won, 0 - the second team won
public ArrayList<Result> calculate(List<Matches> list){

    if(list.size == 0){
    return;
  } else {
    Match M = list.get(0);
    list.remove(0);
    calculate(list);

  }
 }

I am trying to use a recursive approach.
The output should be a list of all the possible outcomes of all the matches. That means if there are total 4 matches to be played then total all the possible combinations of outcomes in those four matched

A: I'm not sure on your question, but if you're trying to return a list using a recursive approach, the general idea is:
public ArrayList<Result> calculate(List<Matches> list){

  if(list.size == 0){
    return new ArrayList<Result>();
  } else {
    Match m1 = list.get(0);
    list.remove(0); // If you want to include a team against itself, move this to after the for loop
    ArrayList<Result> res = new ArrayList<Result>();
    for(Match m2 : list){
      //I'm not sure how you're comparing matches, but just as an example:
      res.add(m1.compare(m2));
    }
    return res.addAll(calculate(list));
  }
}

Here we're taking the top match from the list, and comparing it against all other matches in the list before recursively calling on the remainder. I'm really not sure what exactly your question is, as it's not very clearly worded, but I'm hoping this helps at least.


text:
Q: NSIS concatenate string with slash I'm trying to build a string with this expression bla://${foo}/bar where ${foo} == "hostname". The expected result is bla://hostname/bar but I get http://${foo}/bar instead.
So I figure there is something special about the combination /$ but I can't figure it out.
Thanks for your help

A: /$ is not special but a define that does not exist ends up as ${definename}.
DetailPrint "${foo}" ; Prints ${foo}
!define foo example.com
DetailPrint "${foo}" ; Prints example.com

All defines are resolved at compile time, if this hostname is something the user could configure on a custom page you need to use a NSIS variable...


text:
Q: Crash passing values between activities - what have I missed? I am trying to pass several values between 2 activities but my code is crashing and I have no idea why.  The code is called from an image button, but the app just stops.
if(v==image1){
    try {
        Calendar c = Calendar.getInstance();
        System.out.println("Current time => "+c.getTime());

        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        String formattedDate = df.format(c.getTime());
        //now we have the time lets write it to the file
        File myFile = new File("/sdcard/.working/mx.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile, true);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(formattedDate);
        myOutWriter.append(" :");
        myOutWriter.append(tv1.getText());
        myOutWriter.append(" ,  ");
        myOutWriter.close();
        fOut.close();
    }catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    mx=mx++;
    Intent startabout = new Intent(RTO.this, RTOShooting.class); //this is about screen
    startabout.putExtra("mx", mx);
    startabout.putExtra("Callsign", tv1.getText());
    final int result=1;
    startActivityForResult(startabout, result);
    overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
}

The receiving code looks like this (not that I ever get that far...)
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rtoshooting);
    Bundle extras = getIntent().getExtras();
    if (extras !=null){
        int mx = extras.getInt("mx");
    }
}

Can someone steer me to what I am clearly missing please?
LOGCAT output is
02-27 11:44:46.461: W/dalvikvm(20231): threadid=1: thread exiting with uncaught exception (group=0x41053930)
02-27 11:44:46.471: E/AndroidRuntime(20231): FATAL EXCEPTION: main
02-27 11:44:46.471: E/AndroidRuntime(20231): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nexgen.threedashone.trainer/com.nexgen.threedashone.trainer.RTOShooting}: java.lang.NullPointerException
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2304)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2354)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.ActivityThread.access$600(ActivityThread.java:150)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.os.Looper.loop(Looper.java:137)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.ActivityThread.main(ActivityThread.java:5191)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at java.lang.reflect.Method.invokeNative(Native Method)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at java.lang.reflect.Method.invoke(Method.java:511)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at dalvik.system.NativeStart.main(Native Method)
02-27 11:44:46.471: E/AndroidRuntime(20231): Caused by: java.lang.NullPointerException
02-27 11:44:46.471: E/AndroidRuntime(20231):    at com.nexgen.threedashone.trainer.RTOShooting.onCreate(RTOShooting.java:40)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.Activity.performCreate(Activity.java:5104)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-27 11:44:46.471: E/AndroidRuntime(20231):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
02-27 11:44:46.471: E/AndroidRuntime(20231):    ... 11 more

I have also tried creating my own bundle like this:
        Bundle b = new Bundle();
        b.putString("Callsign", tv1.getText().toString());
        b.putInt("mx", mx);
        startabout.putExtras(b);

receiving like this:
    Bundle b = getIntent().getExtras();

    String callsign = b.getString("Callsign");

    int mx = b.getInt("mx");

But it still crashes with very similar logcat output.
        tvcallsign.setText(callsign);
EDIT:  Here is the full code from each activity, its not pretty but i am just getting into java and android:
    package com.test.trainer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.res.AssetManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class RTO extends Activity implements Chronometer.OnChronometerTickListener, OnClickListener {

     //define buttons etc
     private Button babout;
     private Button bhome;
    private ImageButton image1;
    private ImageButton image2;
    private ImageButton image3;
    private ImageButton image4;
    private ImageButton image5;
    private ImageButton image6;
    private ImageButton image7;
    private ImageButton image8;
    private ImageButton image9;
    private ImageButton image10;
    private ImageButton image11;
    private ImageButton image12;
    private ImageButton image13;
    private ImageButton image14;
    private ImageButton image15;
    private ImageButton image16;
    private ImageButton imagesetup;
    private ImageButton imageevent;
    private ImageButton imageend;

        TextView tv1;
        TextView tv2;
        TextView tv3;
        TextView tv4;
        TextView tv5;
        TextView tv6;
        TextView tv7;
        TextView tv8;
        TextView tv9;
        TextView tv10;
        TextView tv11;
        TextView tv12;
        TextView tv13;
        TextView tv14;
        TextView tv15;
        TextView tv16;

    public ListView lv1;
    public Chronometer mchrono;

    //define logic
    public int mx = 0;
    public int configured = 0;
    public int side = 0; //int to handle which colour buttons to use
    public int prijettype = 0; //int for primary  type
    public int secjettype = 0; //int for sec  type

    public int prijetnumber = 0; //int for primary  numbers
    public int secjetnumber = 0; //int for sec  numbers

    //hint array strings
    public String loadeddata;
    public String[] splitdata;

    public String callsign;

    ContextWrapper mContext = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rto);
        getActionBar().setDisplayHomeAsUpEnabled(true);

     //define the buttons etc for use
        babout = (Button)findViewById(R.id.babout);   //about button
        bhome = (Button)findViewById(R.id.bhome);   //home button
        image1 = (ImageButton)findViewById(R.id.image1);
        image2 = (ImageButton)findViewById(R.id.image2);
        image3 = (ImageButton)findViewById(R.id.image3);
        image4 = (ImageButton)findViewById(R.id.image4);
        image5 = (ImageButton)findViewById(R.id.image5);
        image6 = (ImageButton)findViewById(R.id.image6);
        image7 = (ImageButton)findViewById(R.id.image7);
        image8 = (ImageButton)findViewById(R.id.image8);
        image9 = (ImageButton)findViewById(R.id.image9);
        image10 = (ImageButton)findViewById(R.id.image10);
        image11 = (ImageButton)findViewById(R.id.image11);
        image12 = (ImageButton)findViewById(R.id.image12);
        image13 = (ImageButton)findViewById(R.id.image13);
        image14 = (ImageButton)findViewById(R.id.image14);
        image15 = (ImageButton)findViewById(R.id.image15);
        image16 = (ImageButton)findViewById(R.id.image16);
        imageend = (ImageButton)findViewById(R.id.imageend);  //end mission
        imagesetup = (ImageButton)findViewById(R.id.imagesetup); //setup button
        imageevent = (ImageButton)findViewById(R.id.imageevent); //event button

   tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        tv3 = (TextView) findViewById(R.id.tv3);
        tv4 = (TextView) findViewById(R.id.tv4);
        tv5 = (TextView) findViewById(R.id.tv5);
        tv6 = (TextView) findViewById(R.id.tv6);
        tv7 = (TextView) findViewById(R.id.tv7);
        tv8 = (TextView) findViewById(R.id.tv8);
        tv9 = (TextView) findViewById(R.id.tv9);
        tv10 = (TextView) findViewById(R.id.tv10);
        tv11 = (TextView) findViewById(R.id.tv11);
        tv12 = (TextView) findViewById(R.id.tv12);
        tv13 = (TextView) findViewById(R.id.tv13);
        tv14 = (TextView) findViewById(R.id.tv14);
        tv15 = (TextView) findViewById(R.id.tv15);
        tv16 = (TextView) findViewById(R.id.tv16);

        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);
        image4.setOnClickListener(this);
        image5.setOnClickListener(this);
        image6.setOnClickListener(this);
        image7.setOnClickListener(this);
        image8.setOnClickListener(this);
        image9.setOnClickListener(this);
        image10.setOnClickListener(this);
        image11.setOnClickListener(this);
        image12.setOnClickListener(this);
        image13.setOnClickListener(this);
        image14.setOnClickListener(this);
        image15.setOnClickListener(this);
        image16.setOnClickListener(this);
        imageend.setOnClickListener(this);
        imagesetup.setOnClickListener(this);
        imageevent.setOnClickListener(this);

        settextviews();
            setimageviews();
            hidethem();
            arrayload();

 }//end oncreate

public void arrayload() {
}

public void settextviews() {

                    //load the asset files themselves
                    StringBuilder text = new StringBuilder();
                    try {
                         BufferedReader br = new BufferedReader(new FileReader("/sdcard/NexGen/RTOLOGS/.working/1.txt"));
                            String line;

                            while ((line = br.readLine()) != null) {
                                text.append(line);
                                text.append('\n');
                            }
                                //set the text we recovered to the TextView
                                tv1.setText(text);

                //load progress info
                StringBuilder text2 = new StringBuilder();
                     BufferedReader br2 = new BufferedReader(new FileReader("/sdcard/NexGen/RTOLOGS/.working/2.txt"));
                            String line2;
                                while ((line2 = br2.readLine()) != null) {
                                text2.append(line2);
                                text2.append('\n');
                            }
                            tv2.setText(new String(text2));
} //end try
                    catch (IOException ex) {
                        return;
                    }

public void setimageviews() {
//nothing here yet

}

    public void hidethem() {
        //nothing here yet

}

  public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v==bhome) {
            // TODO Auto-generated method stub
            Intent starthome = new Intent(RTO.this, Main.class); //this is about screen
        startActivity(starthome);
        overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        }

        if (v==babout) {
            Intent startabout = new Intent(RTO.this, AboutScreen.class); //this is about screen
            startActivity(startabout);
            overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        if(v==image1){
            mx=mx++;
            try {
                Calendar c = Calendar.getInstance();
                System.out.println("Current time => "+c.getTime());

                SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                String formattedDate = df.format(c.getTime());
                //now we have the time lets write it to the file
                String fileName = String.valueOf(mx) +".txt";
                File myFile = new File("/sdcard/test/LOGS/.working/mx/" +fileName);
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile, true);
                OutputStreamWriter myOutWriter =
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(formattedDate);
                myOutWriter.append(" :");
                myOutWriter.append(tv1.getText());
                myOutWriter.append(" ,  ");
                myOutWriter.close();
                fOut.close();
            }
            catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }

            Bundle b = new Bundle();
            String callsign = (String)tv1.getText().toString();
            b.putString("Callsign", callsign);
            b.putInt("mx", mx);
            Intent startabout = new Intent(RTO.this, RTOShooting.class); //this is next screen
            startabout.putExtras(b);
            startActivity(startabout);
            overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }

 } //end onClick

//nothing below here yet
  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_rto, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onChronometerTick(Chronometer chronometer) {
        // TODO Auto-generated method stub

    }

}

The receiving activity looks like this:
package com.test.trainer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class RTOShooting extends Activity implements OnClickListener {

    private ImageButton image1;
    private ImageButton image2;
    private ImageButton image3;
    private ImageButton image3close;
    private ImageButton image3medium;
    private ImageButton image3short;

    public int MX;

TextView tvcallsign;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rtoshooting);
        Bundle b = getIntent().getExtras();
         String callsign = b.getString("Callsign");
          int mx = b.getInt("mx");
        MX = mx;
        tvcallsign.setText(callsign);

 tvcallsign = (TextView) findViewById(R.id.tvcallsign);

 } //end on create

 public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v==image1) {

        }
}

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_rtoshooting, menu);
        return true;
    }

A: Assuming your code and the StackTrace are aligned, you see the following line in the trace:

at com.nexgen.threedashone.trainer.RTOShooting.onCreate(RTOShooting.java:40)

Simply counting rows in RTOShooting I end up here:
tvcallsign.setText(callsign);
tvcallsign = (TextView) findViewById(R.id.tvcallsign);

You are trying to set the text of an object you are trying to find in the next row. Swap them and all should probably go well.


text:
Q: how to show php validations error on page I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php

if ((isset($_POST['submit']))){

    $email = strip_tags($_POST['email']);
    $fullname = strip_tags($_POST['fullname']);
    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);

    $fullname_valid = $email_valid = $username_valid = $password_valid = false;

if(!empty($fullname)){

  if (strlen($fullname) > 2 && strlen($fullname)<=30) {
    if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
      $fullname_valid = true;

      # code...
    }else {$fmsg .="fullname can contain only alphabets
";}
 }else{$fmsg1 .="fullname must be 2 to 30 char long
";}
  }else{$fmsg2 .="fullname can not be blank
";}

if (!empty($email)) {
  if (filter_var($email , FILTER_VALIDATE_EMAIL)) {

     $query2 = "SELECT email FROM users WHERE email = '$email'";
      $fire2 = mysqli_query($con,$query2) or die("can not fire  query".mysqli_error($con));
      if (mysqli_num_rows($fire2)>0) {
      $msg .=$email."is already taken please try another one
 ";
      }else{
        $email_valid=true;
      }
    # code...
  }else{$msg .=$email."is an invalid email address
 ";}
  # code...
}else{$msg .="email can not be blank
";}

if(!empty($username)){

  if (strlen($username) > 4 && strlen($username)<=15) {
    if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {

      $query = "SELECT username FROM users WHERE username = '$username'";
      $fire = mysqli_query($con,$query) or die("can not fire  query".mysqli_error($con));

        if(mysqli_num_rows($fire)> 0){
          $umsg ='
username already taken
';
        }else{
          $username_valid = true;
        }
        # code...

      # code...
    }else {$msg.= "username can contain only alphabets
";}
 }else{$msg.= "username must be 4 to 15 char long
";}
  }else{$msg.="username can not be blank
";}

if (!empty($password)) {
  if (strlen($password) >=5 && strlen($password) <= 15 ) {
    $password_valid = true;
    $password = md5($password);

    # code...
  }else{$msg .= $password."password must be between 5 to 15 character long
";}
  # code...
}else{$msg .= "password can not be blank
";}

if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
  $query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
  $fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){

 header("Location: dashboard.php");}

}else{
  header("Location: createaccount.php?msg=".$msg);
}

}

  ?>

and this is my html code:

      <form  name="signup" id="signup" method="POST">

sign up

      <input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">

      <input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">

      <input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">

    <input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">

    <input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">

      <input type="submit" name="submit" id="submit"
         value="sign up" class="btn btn-primary btn-block">

         forgot password?

have an account? log in

      </form>

How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>

A: send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");

and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>

and in html show $errors

A: By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field  I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php

$emailError    = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors        = 0;

if ((isset($_POST['submit']))) {

    $email    = strip_tags($_POST['email']);
    $fullname = strip_tags($_POST['fullname']);
    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);

    $fullname_valid = $email_valid = $username_valid = $password_valid = false;

    if (!empty($fullname)) {

        if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
            if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
                $fullname_valid = true;

                # code...
            } else {
                $fullnameError = "fullname can contain only alphabets
";
                $errors++;
            }
        } else {
            $fullnameError = "fullname must be 2 to 30 char long
";
            $errors++;
        }
    } else {
        $fullnameError = "fullname can not be blank
";
        $errors++;
    }

    if (!empty($email)) {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $query2 = "SELECT email FROM users WHERE email = '$email'";
            $fire2 = mysqli_query($con, $query2) or die("can not fire  query" . mysqli_error($con));
            if (mysqli_num_rows($fire2) > 0) {
                $emailError = $email . "is already taken please try another one
 ";
            } else {
                $email_valid = true;
            }
            # code...
        } else {
            $emailError = $email . "is an invalid email address
 ";
            $errors++;
        }
        # code...
    } else {
        $emailError = "email can not be blank
";
    }

    if (!empty($username)) {

        if (strlen($username) > 4 && strlen($username) <= 15) {
            if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {

                $query = "SELECT username FROM users WHERE username = '$username'";
                $fire = mysqli_query($con, $query) or die("can not fire  query" . mysqli_error($con));

                if (mysqli_num_rows($fire) > 0) {
                    $usernameError = '
username already taken
';
                    $errors++;
                } else {
                    $username_valid = true;
                }

            } else {
                $usernameError = "username can contain only alphabets
";
                $errors++;
            }
        } else {
            $usernameError = "username must be 4 to 15 char long
";
            $errors++;
        }
    } else {
        $usernameError = "username can not be blank
";
        $errors++;
    }

    if (!empty($password)) {
        if (strlen($password) >= 5 && strlen($password) <= 15) {
            $password_valid = true;
            $password       = md5($password);

            # code...
        } else {
            $passwordError = $password . "password must be between 5 to 15 character long
";
            $errors++;
        }
        # code...
    } else {
        $passwordError = "password can not be blank
";
        $errors++;
    }

    //if there's no errors insert into database
    if ($errors <= 0) {
        if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
            $query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
            $fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
            if ($fire) {

                header("Location: dashboard.php");
            }
        }

    }
}
?>

<form  name="signup" id="signup" method="POST">

sign up

        <input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">

        <?php echo $emailError?>

    <input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">

        <input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
        <?php echo $fullnameError?>

        <input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
        <?php echo $usernameError?>

        <input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
        <?php echo $passwordError?>

        <input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
        forgot password?

have an account? log in

</form>

NB: I would advice that you look into password_hash() and
  password_verify()to hash your passwords, they provide better
  security as compared tomd5()` and make sure your database column is
  atleast 60 characters in length.. I would also advice to look into
  prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function

A: I think the best way is include from template in result
if ($fire){
    header("Location: dashboard.php");
}else{
    include("createaccount.php");
}

And in createaccount.php

    <form  name="signup" id="signup" method="POST">

sign up

<?= $msg ?>

...


text:
Q: if $|AB|=0$, $A$ and $B$ are not zero matrix. what can i say about their ranks? as the title suggests.
$|AB|=0$ and i know that both $A$ and $B$ are not the the zero matrix.
i want to prove that $Rank(A)$ and $Rank(B)$ cannot be full. specificly that their $Det$ is $0$.
is it even true? i will appriciate and help.

A: Well, you might have $A$ an $n \times m$ matrix and $B$ an $m \times n$ matrix, where $m < n$.  $A$ and $B$ could have rank $m$ (so both "full" in the sense of the largest possible rank for matrices of their dimensions), but $AB$ has rank at most $m$ and thus determinant $0$.
It's also possible in the case where $m > n$.  For example,
$$ A = \pmatrix{1 & 0 & 0\cr 0 & 1 & 1\cr},\ B = \pmatrix{1 & 0\cr 0 & 1\cr 0 & -1\cr},\ AB = \pmatrix{1 & 0\cr 0 & 0\cr} $$
But it's true if you're talking about square matrices ($n \times n$).

A: Well, if $A$ and $B$ are both square, than since
$$\det(AB)=\det(A)\det(B),$$ at least one of the determinants will be zero.
If one of these has determinant zero, the other could have any rank, even full rank.  Here is an example:
$$A=\pmatrix{0 &0\\1&0}, \quad B=\pmatrix{1&0\\0&1}.$$


text:
Q: Spring boot whitelabel 406 error I am facing this peculiar issue.
First, I have this as my Controller.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.opus.storeconfigurables.model.Config;
import io.opus.storeconfigurables.service.StoreConfigurablesService;

@RestController
public class StoreConfigurablesController extends BaseEndpoint {
    @Autowired
    private StoreConfigurablesService service;

    @RequestMapping(
            value = "/{mode}/{id}",
            method = RequestMethod.GET,
            headers="Accept=*/*",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin(origins="*", maxAge=3600)
    public ResponseEntity<List<Config>> listAllUsers(
            @PathVariable("mode") String mode,
            @PathVariable("id") String id) {
        List<Config> configs = service.findAllConfigs(mode, id);
        if(configs.isEmpty()){
            return new ResponseEntity<List<Config>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<Config>>(configs, HttpStatus.OK);
    }

and everything worked like a charm. http://localhost:8080/Store/XY29 gave me the response I was expecting in JSON format.
Finally, I added another controller method as this:
@RequestMapping(
            value = "/{mode}/{id}/{rlNumber}",
            method = RequestMethod.GET,
            headers="Accept=*/*",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin(origins="*", maxAge=3600)
    public ResponseEntity<List<Config>> listAllPermissions(
            @PathVariable("mode") String mode,
            @PathVariable("id") String id,
            @PathVariable("rlNumber") String rlNumber) {
        List<Config> configs = service.listAllPermissions(mode, id, rlNumber);
        if(configs.isEmpty()){
            return new ResponseEntity<List<Config>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<Config>>(configs, HttpStatus.OK);
    }

and my previous request from browser - http://localhost:8080/Store/XY29 - as well as my new request to the new controller method also failed with Whitelabel 406 error. What could be the reason?
I read adding jackson jars to maven pom.xml could solve these issues but no luck there either.


text:
Q: Why when adding two scores together, which go up in 0.5 steps, does the total box only produce integers without the half marks? Two scores go up in 0.5 steps yet the total box only produces integers when one of the scores my be e.g. 3.5? Any reason and can it be corrected?

<form action="trial.php" method="post" name="trial" target="_top">
Score1<input id = "scorebox1" type="number" value="0" max="20" min="0" step="0.5" size="5"
maxlength="5" oninput="totalscore()"/>
Score 2<input id = "scorebox2" type="number" value="0" max="20" min="0" step="0.5" size="5"
maxlength="5" oninput="totalscore()"/>
Total<input id = "totals" type="number" value="0" step="0.5" size="5" maxlength="5"
oninput="totalscore()" disabled="disabled"/>

</form>

A: I think it may be the parseInt may only deal with Integers. By doubling up the values before and then halving them before displaying in the Total box gives the correct output. So this amendment to the Javascript gives what is wanted.

I suppose if dealing with money you could multiply by 100 and then divided by 100 to get it to work.


text:
Q: using nHibernate QueryOver to join a subset I am using nHibernate for our database access. I need to do a complicated query to find all member journal entries after a certain date with certain value, PreviousId, set for each member. I can easily write the SQL for it:
SELECT J.MemberId, J.PreviousId
FROM tblMemMemberStatusJournal J
INNER JOIN (
    SELECT MemberId,
        MIN(EffectiveDate) AS EffectiveDate
    FROM tblMemMemberStatusJournal
    WHERE EffectiveDate > @StartOfMonth
        AND (PreviousId is NOT null)
    GROUP BY MemberId
) AS X ON (X.EffectiveDate = J.EffectiveDate AND X.MemberId = J.MemberId)

However I am having a lot of trouble trying to get nHibernate to generate this information. There is not a lot of (any) documentation for how to use QueryOver.
I have been seeing information in other places, but none of it is very clear and very little has an actual explanation as to why things are done in certain ways. The answer for Selecting on Sub Queries in NHibernate with Critieria API did not give an adequate example as to what it is doing, so I haven't been able to replicate it.
I've gotten the inner part of the query created with this:
IList<object[]> result = session.QueryOver<MemberStatusJournal>()
        .SelectList(list => list
            .SelectGroup(a => a.Member.ID)
            .SelectMin(a => a.EffectiveDate))
        .Where(j => (j.EffectiveDate > firstOfMonth) && (j.PreviousId != null))
        .List<object[]>();

Which, according to the profiler, makes this SQL:
SELECT this_.MemberId           as y0_,
   min(this_.EffectiveDate) as y1_
FROM   tblMemMemberStatusJournal this_
WHERE  (this_.EffectiveDate > '2014-08-01T00:00:00' /* @p0 */
    and not (this_.PreviousLocalId is null))
GROUP  BY this_.MemberId

But I am not finding a good example of how to actually do join this subset with a parent query. Does anyone have any suggestions?

A: You aren't actually joining on a subset, you're filtering on a subset. Knowing this, you have the option of filtering via other means, in this case, a correlated subquery.
The solution below first creates a detatched query to act as the inner subquery. We can correlate properties of the inner query with properties of the outer query through the use of an alias.
MemberStatusJournal memberStatusJournalAlias = null; // This will represent the
                                                     // object of the outer query

var subQuery = QueryOver.Of<MemberStatusJournal>()
                  .Select(Projections.GroupProperty(Projections.Property<MemberStatusJournal>(m => m.Member.ID)))
                  .Where(j => (j.EffectiveDate > firstOfMonth) && (j.PreviousId != null))
                  .Where(Restrictions.EqProperty(
                             Projections.Min<MemberStatusJournal>(j => j.EffectiveDate),
                             Projections.Property(() => memberStatusJournalAlias.EffectiveDate)
                         )
                        )
                  .Where(Restrictions.EqProperty(
                            Projections.GroupProperty(Projections.Property<MemberStatusJournal>(m => m.Member.Id)),
                            Projections.Property(() => memberStatusJournalAlias.Member.Id)
                       ));

var results = session.QueryOver<MemberStatusJournal>(() => memberStatusJournalAlias)
                     .WithSubquery
                     .WhereExists(subQuery)
                     .List();

This would produce an SQL query like the following:
SELECT blah
FROM tblMemMemberStatusJournal J
WHERE EXISTS (
    SELECT J2.MemberId
     FROM tblMemberStatusJournal J2
    WHERE J2.EffectiveDate > @StartOfMonth
        AND (J2.PreviousId is NOT null)
    GROUP BY J2.MemberId
    HAVING MIN(J2.EffectiveDate) = J.EffectiveDate
    AND J2.MemberId = J.MemberId
)

This looks less efficient than the inner join query you opened the question with. But my experience is that the SQL Query Optimizer is clever enough to convert this into an inner join. If you want to confirm this, you can use SQL Studio to generate and compare the execution plans of both queries.


text:
Q: AngularJS update shared data in a Service from $http Please see this Plunker. I have a myApp.common.sharedata module to share data between two modules myApp.interactive.layout.menu and myApp.interactive.layout.chart.
If you click the checkbox in the  menu module, it will call service sharedata.check(key); to update the shared data.
In common/sharedata/sharedata.service.js function sharedata.check. I use sharedata.series = response.data.data; to update the data from $http, it is not working. The data is not synchronized to module myApp.interactive.layout.menu and myApp.interactive.layout.chart. I also tried sharedata.series = angular.copy(response.data.data);, it is not working too. I have to do
for(var i=0; i<response.data.data.length;i++){
    sharedata.series[i] = response.data.data[i];
}

Any suggestions? My ultimate goal is to use $http to initialize the shared data in module myApp.common.sharedata. Now I'm using the static code. If I use
$http.get("https://reqres.in/api/users")
  .then(function(response) {
  sharedata.series = (response.data.data);
});

The data does not synchronized to module myApp.interactive.layout.menu and myApp.interactive.layout.chart too.

A: There is a small issue which you need to fix.
Change your InteractiveChartCtrl as following.
'use strict';

angular.module('myApp.interactive.layout.chart', ['myApp.common.sharedata'])

.controller('InteractiveChartCtrl', ['$scope', 'sharedata',function($scope,sharedata) {

        $scope.menuSeries = sharedata; //MODIFIED HERE

        $scope.$watch('menuSeries', function(newValue, oldValue) {
            console.log('menuSeries changed');
            console.log(newValue);
        },true);

}]);

I have changed  $scope.menuSeries = sharedata; //MODIFIED HERE
And your chart.html as following.

                            <input type="checkbox" class="metrics" id="{{item.id}}" ng-click="seriesMenuClick($event,checkStatus)" ng-model='checkStatus' ng-checked ="item.selected" alt="{{item.first_name}}"> {{item.first_name}}

        {{menuSeries}}

I have changed here

This will fix the issue.
Check the plnkr.
Updated for Menu


text:
Q: Golang creating resource-efficient emailer I've made a simple scheduler in Go that is meant to be long-running and using channels, when the ticker's channel is ready, I poll my database for emails to be sent out, which sends the email to the send channel and when it is ready, the email is sent out. For now the tick interval is every 10 minutes. This scheduler connects to the pg database once on startup.
Example:
for {
    select {
     case <-s.ticker.C:
      // query db, sends each email to s.send channel. Could just send them
      // without the channel though.
      go poll()
     case email := s.send:
      send(email) // sends the email via some email service
    }
}

My question is if would it be more safe/efficient to use this Go program which connects to the database once, or setup a Lambda function as a cronjob every 10 minutes? I've never used Lambda, but I believe there would be a new database connection every time it is run, which also involves fetching credentials.
Cost-wise assume that it doesn't matter, I'm only curious as to which would be more safe/efficient. Any information is appreciated!


text:
Q: find the equation of a line from bezier curve control points I would like to find the equation of a curve in the form y = ax2 + bx + c
from the following svg path:
<path id="curve1"  d="M100,200 C100,100 400,100 400,200" />

this gives me 4 points that can be seen on the attached image.

*

*100,200 (start point in purple)

*100,100 (control point 1 in red)

*400,100 (control point 2 in green)

*400,200 (end point in blue)

wikipedia has a great article explaining bezier curves however I am not sure how to apply the maths shown there to get equation of the curve.
http://en.wikipedia.org/wiki/B%C3%A9zier_curve
plotted curve, click to see image

A: You can't.
The SVG you're showing uses a cubic path, which uses a third order parametric curve, meaning it has the form:
fx(t) = x1 * (1-t)³ + x2 * 3 * (1-t)²t + x3 * 3 * (1-t)t² + x4 * t³
fy(t) = y1 * (1-t)³ + y2 * 3 * (1-t)²t + y3 * 3 * (1-t)t² + y4 * t³

(which is plotted for t going from 0, inclusive, to 1, inclusive).
So there are two reasons why you can't express that curve as a form y=ax²+b:

*

*you'd need, at the very least, a form ax³+bx²+c instead, and

*this is a parametric curve, not a simple function graph; for Bezier curves it is not the case that y is expressed in terms of x at all, but instead both the x and y values are controlled by a "master parameter" t.

We know that second degree functions like y=ax²+b can only model parabola, and looking at the image we can see that the plotted curve looks nothing like one of those (not even a squashed parabola) so we can't even "kind of sort of" approximate the curve with a second degree function in this case.
(sometimes you can get away with that, but definitely not in this case)


text:
Q: C# List inside class and namespace, accessing it from another class Please excuse my little knowledge in C#, as this question may be very easy for some of you but I cannot get my head around it.
I have tried and searched many examples and tutorials, but all of them are only partial examples so I could not understand it properly.
I have this class "FilesDataStruct":
namespace MYPROJECT.FilesListData
{
    class FilesDataStruct
    {
        public int ID;
        public string Name;
    }
}

And the class "FilesDataClass":
namespace MYPROJECT.FilesListData
{
    class FilesDataClass
    {
        public List<FilesDataStruct> Files;

        public FilesDataClass()
        {
            Files = new List<FilesDataStruct>();
        }
    }
}

The namespace they are using is "FilesListData".
So I go to Class "B" in MYPROJECT and declare:
private FilesDataClass m_ListWorker;

And then add items to my list:
m_ListWorker = new FilesDataClass();

FilesDataStruct item = new FilesDataStruct();

for (int i = 0; i < 10; i++)
{
    item.ID = i;
    item.Name = "Just_Testing";

    m_ListWorker.Files.Add(item);
}

Debugging this I can see the items are added properly.
Now I need to access this list in the "Form1" class ( or any other .. ):
So I declare again:
 private FilesDataClass m_ListWorker;

But reading the examples and tutorials I found, I have done this:
m_ListWorker = new FilesDataClass(); // this is weird, if I call the class again it's normal to be empty

for (int i = 0; i < m_ListWorker.Files.Count; i++)
{
    Console.WriteLine(m_ListWorker.Files[i].ID);
    Console.WriteLine(m_ListWorker.Files[i].Name);
}

And of course, nothing is there. I am guessing the problem is the constructor of "FilesDataClass" because each time you call "new" it will become a new empty class...
Please explain to me what in the world I am doing wrong, and how should I access my class to retrieve the items in ANY class that I want...

A: You need to pass a reference to the existing class, not create a new instance of it.
public class Form1 : Form
{
    FilesDataClass m_ListWorker = null;

    public Form1(FilesDataClass f)
    {
        this.m_ListWorker = f;
    }
}

var newForm = new Form1(m_ListWorker);

You have a second issue too. That for loop will not work like you expect. You're simply adding the same instance of FilesDataStruct 10 times... in the end, you have 10 references that will all have the same values (the values you assigned in the last iteration of the loop).
m_ListWorker = new FilesDataClass();

FilesDataStruct item = new FilesDataStruct();

for (int i = 0; i < 10; i++)
{
    item.ID = i;
    item.Name = "Just_Testing";

    m_ListWorker.Files.Add(item);
}

Instantiate the class inside the loop instead:
m_ListWorker = new FilesDataClass();

for (int i = 0; i < 10; i++)
{
    FilesDataStruct item = new FilesDataStruct();
    item.ID = i;
    item.Name = "Just_Testing";

    m_ListWorker.Files.Add(item);
}

A: You need to make B.m_ListWorker public (or better, a public property).Then you can access it as someInstanceOfB.ListWorker if it's an instance property or as B.ListWorker if it's static.


text:
Q: http request in javascript pdf api I'm trying to do a get request with the javascript api to adobe reader. I'm using the Net.http object with the following code:
get =  app.trustedFunction (function(cURL)
{
    app.beginPriv();
    var params =
     {
        cVerb: "GET",
        cURL: "HTTP://ip_addr/checker/comments/1",
        oHandler:
        {
            response: function(msg, uri, e)
                {
                    if(e != undefined && e.error != 405) {
                        app.alert("Failed to get: "+ e);
                    } else app.alert("connected");
                }
              }
        };
        Net.HTTP.request(params);
    app.endPriv();
 });

When I call the function in my code, the first time the program opens its working fine and can connect.
The problem is that when I call the function again using a submenu like this:
  app.addMenuItem ({cName: "connect", cParent: "Edit", cExec: "get()"});

I get an error, I also tried adding this PDF file to my privileged locations because I think it's a security related issue
Any idea?


text:
Q: How can I make it so the Tkinter button can only be pressed once? I have this code where I am trying to have it so I can only press the button once and then it becomes disabled, but I keep getting the error TypeError: 'NoneType' object is not subscriptable, I'm not so sure what I am doing incorrect. Any help is appreciated. Here is my code:
import tkinter as tk
from tkinter import *
from tkinter import ttk

team_array = []
team_dict = {}

def score_event1_team():
    global team_array
    global team_dict

    #First Event, 1st Team, Adding 15 points.
    event1T = str(input("What team was first place?"))

    #ADDING 15 POINTS TO FIRST TEAM IN THE DICTIONARY WITH GET METHOD.
    team_dict[event1T] = team_dict.get(event1T, 0) + 15
    print(team_dict)
    print(f"Team {event1T} has been added 15 points.")

    if (button_event_1['state'] == NORMAL):
        button_event_1['state'] = DISABLED

root = Tk()
root.title("Sports Event Organiser!")
root.geometry("600x500")

button_event_1 = Button(root,
    text="Event Pending",
    bg="white",
    height = 1,
    command=(score_event1_team),
    state = NORMAL,
).pack(pady = 10)

root.mainloop()

A: The problem is in your following code segment, where you are creating a button
button_event_1 = Button(root,
    text="Event Pending",
    bg="white",
    height = 1,
    command=(score_event1_team),
    state = NORMAL,
).pack(pady = 10)

You are calling pack(pady = 10) immediately on the button due to which your button_event_1 object is not referring to the button but None returned by pack()
the solution is simple, remove it from there and then pack the button separately, after button initialization
button_event_1 = Button(root,
    text="Event Pending",
    bg="white",
    height = 1,
    command=(score_event1_team),
    state = NORMAL,
)

button_event_1.pack()

A: The thing you are doing wrong is this line button_event_1 = Button(....).pack() as you are packing it with the button and pack returns a nontype object you need to do button_event_1 = Button(....) and than button_event_1.pack() both in separate lines. The pack function returns a none type object and in your question thus button_event_1 is None


text:
Q: AngularJS Controller submit form I have a problem with a controller
 .factory('Auth', function($firebaseAuth){
  var auth = $firebaseAuth();
  return auth;
 })

.controller('authCtrl', function() {
  var authCtrl = this;

  authCtrl.user = {
    email: '',
    password: ''
  };

  console.log('hoi1');

  authCtrl.login = function (){
    console.log('hoi2');
  };
});

-

    <form ng-submit="authCtrl.login()">

Login

      <input type="email" name="loginEmail" value="" placeholder="email" class="input" ng-model="authCtrl.user.email">

      <input type="password" name="loginPassword" value="" placeholder="******" class="input" ng-model="password" ng-model="authCtrl.user.password">

      <input type="submit" value="Login">
    </form>

The controller is always in my body, but I see hoi1 in the console, but when I submit the form, I don't get hoi2
What's wrong?
Sincerely,
Jur

A: Use $scope in your controller
.controller('authCtrl', function( $scope) {
   $scope.user = {
      email: '',
      password: ''
   };

   console.log('hoi1');

   $scope.login = function (){
    console.log('hoi2');
   };
});

A: Change

to

If you want to use controller this then you have to add ng-controller as ng-controller="authCtrl as authCtrl"
Check this tutorial for more info on Controller as
Working Fiddle Example

A: It is because when your $scope execute in controller to view, it execute console.log('hoi1') as it do not wait for any event to happen. You just write "debugger;" in your code and need to check its execution part


text:
Q: Strange behaviour with strings and arrays

Here I assign the value of an array to a variable, I then alter the variable, the array changes also.
$TestArray = @{ "ValueA" = "A" ; "ValueB" = "B" ; "Number" = "" }
$TestNumbers = 1..10

foreach ($number in $testnumbers) {

    $results = $TestArray
    $results.Number = $number
    Write-Host $TestArray.Number

}

I thought that $results = $TestArray would take a copy of $TestArray but this test shows that modifying $results also changes the corresponding value in $TestArray
Can anyone help me understand this behavior?

A: Doing:
$results = $TestArray

will make $results a reference to the same object referred to by TestArray. So, if you change one, the other will also be affected because they are the same object.

To instead make $results a copy of $TestArray, you can use its Clone method:
$results = $TestArray.Clone()

Also, just for the record, $TestArray is not actually an array.  It is a hashtable (also called a hashmap) where keys are paired with values.  An array would be something like:
$TestArray = (1, 2, 3)


text:
Q: drag and drop conversion with FFMPEG in multiple formats i'm looking for a script that can convert a video in 2 formats for my website :
mp4 and Webm
i also want it to create a jpeg of the first frame and make all at 640*360
I'm a begginer with ffmpeg so i don't really know where to start. this is what i have for the moment, but that doesn't work
 ffmpeg -i /tmp/video.off /tmp/video.webm /tmp/video.mp4

the ideal situation is to have a drag and drop conversion tool, but a folder based can do the trick too
Thank you


text:
Q: Printing multiple pages of smaller format on one page I know it is easily possible to let the printer drivers shrink your page so that multiple of them fit on one page.
I want to do the same thing, but in a slightly different version. I have a Word document with a very special width and height. Because it's much smaller than DIN A4, I want to print multiple of them on one page. How can I do that whilst keeping the width and height the same?

A: I've never been able to do this from Word natively but I have used FinePrint which will fit multiple document pages onto one page for printing.
It's a paid for application (it costs $49.95), but there is a free version which does have some limitations and include "Printed by Fine Print" (or something similar) in the footer, but might be OK for you.

A: Word can do this natively. In the lower right of the print dialog there is the option to print multiple pages on a single one as well as scaling options (which might come in handy to prevent scaling down the pages even further if they are smaller than A5).
Note: It seems that Word won't scale down the pages as long as they aren't larger than the portion of the tiles page they should occupy.


text:
Q: Upload from IOS picture to .net app: Rotate I have below code for uploading and resize pictures from IOS Devices to my .net application. Users use to take picture in portrait orientation and then all pictures show up in my app with wrong rotation. Any suggestion how to fix this?
            string fileName = Server.HtmlEncode(FileUploadFormbilde.FileName);
            string extension = System.IO.Path.GetExtension(fileName);
            System.Drawing.Image image_file = System.Drawing.Image.FromStream(FileUploadFormbilde.PostedFile.InputStream);
            int image_height = image_file.Height;
            int image_width = image_file.Width;
            int max_height = 300;
            int max_width = 300;

            image_height = (image_height * max_width) / image_width;
            image_width = max_width;

            if (image_height > max_height)
            {
                image_width = (image_width * max_height) / image_height;
                image_height = max_height;
            }

            Bitmap bitmap_file = new Bitmap(image_file, image_width, image_height);
            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            bitmap_file.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Position = 0;

            byte[] data = new byte[stream.Length + 1];
            stream.Read(data, 0, data.Length);

A: Here you go my friend:
Image originalImage = Image.FromStream(data);

 if (originalImage.PropertyIdList.Contains(0x0112))
        {
            int rotationValue = originalImage.GetPropertyItem(0x0112).Value[0];
            switch (rotationValue)
            {
                case 1: // landscape, do nothing
                    break;

                case 8: // rotated 90 right
                    // de-rotate:
                    originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone);
                    break;

                case 3: // bottoms up
                    originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone);
                    break;

                case 6: // rotated 90 left
                    originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone);
                    break;
            }
        }

A: You must read the image's Orientation value from the EXIF data in the Image.PropertyItems collection, and rotate it accordingly.

A: Here is a better solution answer posted  Here  He  wrote a simple helper class that does all that:
 you can check the full source code here.
    private System.Drawing.Image ResizeAndDraw(System.Drawing.Image objTempImage)
        {
          // call image helper to fix the orientation issue
            var temp = ImageHelper.RotateImageByExifOrientationData(objTempImage, true);
            Size objSize = new Size(150, 200);
            Bitmap objBmp;
            objBmp = new Bitmap(objSize.Width, objSize.Height);

            Graphics g = Graphics.FromImage(objBmp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            //Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
            Rectangle rect = new Rectangle(0,0,150,200);
            //g.DrawImage(objTempImage, rect, 0, 0, objTempImage.Width, objTempImage.Height, GraphicsUnit.Pixel);
            g.DrawImage(objTempImage, rect);
            return objBmp;
        }

using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;

public static class ImageHelper
{
    /// <summary>
    /// Rotate the given image file according to Exif Orientation data
    /// </summary>
    /// <param name="sourceFilePath">path of source file</param>
    /// <param name="targetFilePath">path of target file</param>
    /// <param name="targetFormat">target format</param>
    /// <param name="updateExifData">set it to TRUE to update image Exif data after rotation (default is TRUE)</param>
    /// <returns>The RotateFlipType value corresponding to the applied rotation. If no rotation occurred, RotateFlipType.RotateNoneFlipNone will be returned.</returns>
    public static RotateFlipType RotateImageByExifOrientationData(string sourceFilePath, string targetFilePath, ImageFormat targetFormat, bool updateExifData = true)
    {
        // Rotate the image according to EXIF data
        var bmp = new Bitmap(sourceFilePath);
        RotateFlipType fType = RotateImageByExifOrientationData(bmp, updateExifData);
        if (fType != RotateFlipType.RotateNoneFlipNone)
        {
            bmp.Save(targetFilePath, targetFormat);
        }
        return fType;
    }

    /// <summary>
    /// Rotate the given bitmap according to Exif Orientation data
    /// </summary>
    /// <param name="img">source image</param>
    /// <param name="updateExifData">set it to TRUE to update image Exif data after rotation (default is TRUE)</param>
    /// <returns>The RotateFlipType value corresponding to the applied rotation. If no rotation occurred, RotateFlipType.RotateNoneFlipNone will be returned.</returns>
    public static RotateFlipType RotateImageByExifOrientationData(Image img, bool updateExifData = true)
    {
        int orientationId = 0x0112;
        var fType = RotateFlipType.RotateNoneFlipNone;
        if (img.PropertyIdList.Contains(orientationId))
        {
            var pItem = img.GetPropertyItem(orientationId);
            fType = GetRotateFlipTypeByExifOrientationData(pItem.Value[0]);
            if (fType != RotateFlipType.RotateNoneFlipNone)
            {
                img.RotateFlip(fType);
                // Remove Exif orientation tag (if requested)
                if (updateExifData) img.RemovePropertyItem(orientationId);
            }
        }
        return fType;
    }

    /// <summary>
    /// Return the proper System.Drawing.RotateFlipType according to given orientation EXIF metadata
    /// </summary>
    /// <param name="orientation">Exif "Orientation"</param>
    /// <returns>the corresponding System.Drawing.RotateFlipType enum value</returns>
    public static RotateFlipType GetRotateFlipTypeByExifOrientationData(int orientation)
    {
        switch (orientation)
        {
            case 1:
            default:
                return RotateFlipType.RotateNoneFlipNone;
            case 2:
                return RotateFlipType.RotateNoneFlipX;
            case 3:
                return RotateFlipType.Rotate180FlipNone;
            case 4:
                return RotateFlipType.Rotate180FlipX;
            case 5:
                return RotateFlipType.Rotate90FlipX;
            case 6:
                return RotateFlipType.Rotate90FlipNone;
            case 7:
                return RotateFlipType.Rotate270FlipX;
            case 8:
                return RotateFlipType.Rotate270FlipNone;
        }
    }
}


text:
Q: Efficient way of finding subsets and supersets in a collection of sets Is there any efficient algorithm or data structure for looking up supersets and subsets on a collection of sets?
Example:
# collection of sets
>>> col = [{1,2,3},{2,3,4},{4,5,6,7}]

>>> subsets_of({1,2,3,4}, col)
[{1,2,3},{2,3,4}]

>>> supersets_of({4}, col)
[{2,3,4},{4,5,6,7}]

A: In the general case, no, other than brute force search methods.
However, there are various techniques for doing linear time searches depending on the type of data you have. For example, if the element values were always less than 32 (or 64) then you could create an integer with the bits set for the values present and OR them to find out if the set was a subset. If the values are less than a 100 million or so you can create a giant boolean array where each array element is 1 if the set contains the value, or 0 if it does not. Then the subset lookup is linear time. A similar method is possible for solving the superset problem in linear time.

A: You can create hash method for subsets and then store it in HashMap.
Then you can find it even in constant time (if you have enough memory).


text:
Q: TypeError: 'Weather' object is not callable I'm very new to programming so please excuse me if I lack the correct terminology.
I'm trying to retrieve an image from a website and post it onto a GUI with tkinter. It works, insofar as it posts the image on the GUI; however it still produces an error as per the title of this post.
The section of code that's causing the error is as follows:
    raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
    image = raw_data("img", ("class", "si"))[0]
    image = image["src"]
    if image == ("/images/icons/5.gif"):
        URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
        b64_data = base64.encodestring(URL)
        image = PhotoImage(data = b64_data)
        label = Label(self, image = image).grid(row = 1, column = 2)
        self(image)

Narrowed down further it seems line 39 is causing the error.
self(image)

Full program as follows:
#!/usr/bin/env python
from tkinter import *
import sys
import urllib.request
from urllib.request import urlopen
import base64
from bs4 import BeautifulSoup

class Weather(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.configure(bg = "#ededed")
        self.grid()
        self.heading = Label(self, bg = "#ededed", text = "       Temperature      ").grid(row = 0, column = 1, pady = 5)
        self.heading = Label(self, bg = "#ededed", text = "        Picture        ").grid(row = 0, column = 2, pady = 5)

        button = Button(self, bg = "#ededed", text = "Canberra", command = self.canberra_data).grid(row = 3, column = 0, sticky = EW)

        self.obsVar1 = StringVar()
        label = Label(self, textvariable = self.obsVar1, bg = "#e5e5e5", fg = "#751974").grid(row = 1, column = 1)
        self.obsVar1.set("")

    def canberra_data(self):
        soup = BeautifulSoup(urllib.request.urlopen("http://www.bom.gov.au/act/observations/canberra.shtml").read())
        table = soup.find("table", {"id" : "tCANBERRA"}).tbody("tr", "rowleftcolumn")
        for row in soup("th", {"id" : "obs-station-canberra"}):
            for temp in soup("td", {"headers" : "obs-temp obs-station-canberra"}):
               self.obsVar1.set(temp.text)

        raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
        image = raw_data("img", ("class", "si"))[0]
        image = image["src"]
        if image == ("/images/icons/5.gif"):
            URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
            b64_data = base64.encodestring(URL)
            image = PhotoImage(data = b64_data)
            label = Label(self, image = image).grid(row = 1, column = 2)
            self(image)

master = Tk()
master.title("Weather Program")
app = Weather(master)
master.mainloop()

I should add that if the website has updated its image and it's no longer '5.gif' (being a weather icon it's highly likely) then a picture won't show up.
Any help or direction would be much appreciated. I've looked high and low but to no avail. Thank you in advance.

A: The line containing self(image) is not correct. The 'self' is not a class, it's an object. So, if you want to create an object of type Weather and pass something to its constructor, just call Weather(image).

A: You cannot call an object like a function. When you say self(image) in your code, you are trying to call the object. If you want to do that you need to implement the __call__ method. However, I have coded your example and made changes to it. Kindly run it. I hope it helps
#!/usr/bin/env python
from tkinter import *
import sys
import urllib.request
from urllib.request import urlopen
import base64
from bs4 import BeautifulSoup

class Weather(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.configure(bg = "#ededed")
        self.grid()
        self.heading = Label(self, bg = "#ededed", text = "       Temperature      ").grid(row = 0, column = 1, pady = 5)
        self.heading = Label(self, bg = "#ededed", text = "        Picture        ").grid(row = 0, column = 2, pady = 5)

        button = Button(self, bg = "#ededed", text = "Canberra", command = self.canberra_data).grid(row = 3, column = 0, sticky = EW)

        self.obsVar1 = StringVar()
        label = Label(self, textvariable = self.obsVar1, bg = "#e5e5e5", fg = "#751974").grid(row = 1, column = 1)
        self.obsVar1.set("")

    def canberra_data(self):
        soup = BeautifulSoup(urllib.request.urlopen("http://www.bom.gov.au/act/observations/canberra.shtml").read())
        table = soup.find("table", {"id" : "tCANBERRA"}).tbody("tr", "rowleftcolumn")
        for row in soup("th", {"id" : "obs-station-canberra"}):
            for temp in soup("td", {"headers" : "obs-temp obs-station-canberra"}):
               self.obsVar1.set(temp.text)

        raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
        image = raw_data("img", ("class", "si"))[0]
        image = image["src"]
        if image == ("/images/icons/5.gif"):
            URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
            b64_data = base64.encodestring(URL)
            image = PhotoImage(data = b64_data)
            label = Label(self, image = image)
            label.image = image
            label.grid(row=1,column=2)

master = Tk()
master.title("Weather Program")
app = Weather(master)
master.mainloop()

The diff of your and my version is as follows:
<             label = Label(self, image = image).grid(row = 1, column = 2)
<             self(image)
---
>             label = Label(self, image = image)
>             label.image = image
>             label.grid(row=1,column=2)


text:
Q: Transfering data from Rails 3 app to C# desktop app It's one of those questions that I think I know how to solve, but if I don't look it up - I can end up reinventing the wheel.
Here's the task.
I have a C# app, that needs to contact my Rails 3 app every minute, and get information from there.
I would do it like so:

*

*Make a POST request from C# app to Rails website (containing secret key or username / password of some sort)

*website makes sure password is correct

*makes some requests to the database

*gets an object (model), and

*responds with a string, maybe something like this:
@response = ""

if secretkey == '123'

@item = Item.find(1)
@response = @item.name + "|" + @item.price + ...

end

and then just return @response in a view or render :text back to C# app.
Is this a smart way to do it?
Or is there a better way?

A: What you are describing is creating a service (with API) in Rails and accessing it via a networked client.
The proper approach would be to implement:

*

*Authentication: preferably OAUTH2

*API: define your Resources. Look into RESTful APIs, you also may decide to use RABL gem to describe your APIs

*Implement controllers that serialize your data to something consumable. I'd suggest JSON or XML, not TEXT.


text:
Q: Word that could use for " reaching to the point where one is referring quickly" I am looking for a word which could give the meaning of

"reaching to the point where one is referring quickly"

like if some one saying something with an intention which is not know if we go by their words, like they are referring some hidden/indirect meaning

A: I don't know if there's one word for that. To someone who seems like they mean something other than what they're saying, I might intensely look them in the eye and say:

What are you implying?

or

What are you suggesting?

or

What do you mean to say?

If I wanted to be a little more direct, I might say:

Hey, be straight with me.


text:
Q: Auto complete box for movies Is it possible to make an auto-complete box using data from www.omdbapi.com(xml or json)? Or do you know any other way to make a movie auto-complete box?
I would be grateful if you could find me a solution.
Thank you.

A: See this tutorial about how to create such an autocomplete functionality:
http://tutorialzine.com/2010/08/simple-movie-search-app-jquery-ajax/
Although the demo doesn't work anymore (probably because they have updated the API), the principles about how to do it are still the same and you can apply this to omdb api.
Try to do it yourself and if you have any troubles, you can ask it on stackoverflow. Don't expect stackoverflow to write the whole solution for you.


text:
Q: How to get src="" from html image tag $str = "html code here and img tag";
preg_match_all('~<img ([^>]+)>~i', $str, $matches);
$images = array();
foreach ($matches[1] as $str) {
    preg_match_all('~([a-z]([a-z0-9]*)?)=("|\')(.*?)("|\')~is', $str, $pairs);
}

I can't get SRC from IMG, how to ideas ?

A: I would recommend you consider using simplehtmldom instead of parsing out your img src tags with regular expressions.
$html = file_get_html('...html...');

// Find all images & echo src
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

A: You can use an XML parser in PHP like Simple HTML Dom, or a regex for something like this should also work.
/src="([^"]*)"/i


text:
Q: Google maps marker clustering for array I know there are a bunch of questions on this subject already - but I have read many of them but can't seem to get anything working in my particular case. I want to make a map with a bunch of custom markers with info windows showing store locations across Australia (<-- this part i have working)...
When zoomed out the markers should group by city with a number shown... also I would like a html list of links that when clicked zoom to an particular marker on the map. Much like the example shown here: https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/examples/speed_test_example.html
Below is my code (at the moment I have just added locations in 2 cities as example, later to have many cities nationwide):
<!DOCTYPE html>

    <title>Locations</title>
    <meta charset="utf-8">

So in summary, I need help with getting the clustering working and html links...

A: The array "sites" was undefined in your code, I wonder why though... but I'm no expert in javascript...
If you move it inside your initialize() function, it works correctly.
The declaration of the MarkerClusterer doesn't include any markers, which doesn't make sense at all. Based on the examples in here https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/docs/examples.html you can see that you need to first declare your markers, then include them in the declaration of the MarkerClusterer.
Also in your setMarkers() function you declare a local variable "sites", this is dangerous as you also have a global one with the same name. (it's not the case anymore since I moved it within initialize())
Finally, I don't know what you intent to do with the infowindow, right now, nothing is displayed, but if you write infowindow.setContent('Hello Marker'); instead of "this.html", it will work.
You can find a working example of your code here: http://jsfiddle.net/839dV/