问:
TypeError when using iloc to create dummy variables
Source data is from the book  Python_for_Data_Analysis, chp 2.
The data for movies is as follows and can also be found here:

```<code>movies.head(n=10)
Out[3]:
   movie_id                               title                        genres
0         1                    Toy Story (1995)   Animation|Children's|Comedy
1         2                      Jumanji (1995)  Adventure|Children's|Fantasy
2         3             Grumpier Old Men (1995)                Comedy|Romance
3         4            Waiting to Exhale (1995)                  Comedy|Drama
4         5  Father of the Bride Part II (1995)                        Comedy
5         6                         Heat (1995)         Action|Crime|Thriller
6         7                      Sabrina (1995)                Comedy|Romance
7         8                 Tom and Huck (1995)          Adventure|Children's
8         9                 Sudden Death (1995)                        Action
9        10                    GoldenEye (1995)     Action|Adventure|Thriller
</code>```

The following code has trouble when I use iloc:

```<code>import pandas as pd
import numpy as np
from pandas import Series,DataFrame

mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table( 'movies.dat', sep='::',
                       engine='python', header=None, names=mnames)
movies.head(n=10)
genre_iter = (set(x.split('|')) for x in movies['genres'])
genres = sorted(set.union(*genre_iter))
dummies = DataFrame(np.zeros((len(movies), len(genres))), columns=genres)

for i, gen in enumerate(movies['genres']):
# the following code report error
# TypeError: '['Animation', "Children's", 'Comedy']' is an invalid key
    dummies.iloc[i,dummies.columns.get_loc(gen.split('|'))] = 1
# while loc can run successfully
    dummies.loc[dummies.index[[i]],gen.split('|')] = 1
movies_windic = movies.join(dummies.add_prefix('Genre_'))
movies_windic.iloc[0]
</code>```

I have some understanding of why Children's is error, but why Animation,Comedy are error? I have tried:

```<code>dummies.columns.get_loc('Animation')
</code>```

and the result is 2.

答:
Try</p>

```<code>dummies = movies.genres.str.get_dummies()
</code>```

Body:
Source data is from the book  Python_for_Data_Analysis, chp 2.
The data for movies is as follows and can also be found here:

movies.head(n=10)
Out[3]:
   movie_id                               title                        genres
0         1                    Toy Story (1995)   Animation|Children's|Comedy
1         2                      Jumanji (1995)  Adventure|Children's|Fantasy
2         3             Grumpier Old Men (1995)                Comedy|Romance
3         4            Waiting to Exhale (1995)                  Comedy|Drama
4         5  Father of the Bride Part II (1995)                        Comedy
5         6                         Heat (1995)         Action|Crime|Thriller
6         7                      Sabrina (1995)                Comedy|Romance
7         8                 Tom and Huck (1995)          Adventure|Children's
8         9                 Sudden Death (1995)                        Action
9        10                    GoldenEye (1995)     Action|Adventure|Thriller

The following code has trouble when I use iloc:

import pandas as pd
import numpy as np
from pandas import Series,DataFrame

mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table( 'movies.dat', sep='::',
                       engine='python', header=None, names=mnames)
movies.head(n=10)
genre_iter = (set(x.split('|')) for x in movies['genres'])
genres = sorted(set.union(*genre_iter))
dummies = DataFrame(np.zeros((len(movies), len(genres))), columns=genres)

for i, gen in enumerate(movies['genres']):
# the following code report error
# TypeError: '['Animation', "Children's", 'Comedy']' is an invalid key
    dummies.iloc[i,dummies.columns.get_loc(gen.split('|'))] = 1
# while loc can run successfully
    dummies.loc[dummies.index[[i]],gen.split('|')] = 1
movies_windic = movies.join(dummies.add_prefix('Genre_'))
movies_windic.iloc[0]

I have some understanding of why Children's is error, but why Animation,Comedy are error? I have tried:

dummies.columns.get_loc('Animation')

and the result is 2.

Body:
Try

dummies = movies.genres.str.get_dummies()


来源: stackexchange

问:
SQL query for duplicate customers
I want number of customers (count) and duplicate phone_no from a table. I have to remove dashes in phone number and then check the length is equal to 10. Please can anyone help with this SQL query?

My query is like below :

```<code>select
    COUNT(Cust_ID) cnt, Phone_no
from
    tbl_Customers
where
    Cust_Type = 3
group by
    Phone_no
having
    COUNT(Cust_ID) > 1
order by
    cnt desc
</code>```

答:
Adding LEN(REPLACE(Phone_no,'-','')) = 10 in your WHERE clause should be what your looking for.

```<code>select COUNT(Cust_ID) cnt,Phone_no
from tbl_Customers
where Cust_Type = 3
      and
      LEN(REPLACE(Phone_no,'-','')) = 10
group by Phone_no
having COUNT(Cust_ID) > 1
order by cnt desc
</code>```

Here is the Microsoft documentation for those functions.

REPLACE

LEN

ContentLicense: CC BY-SA 3.0

Title: SQL query for duplicate customers

Body:
I want number of customers (count) and duplicate phone_no from a table. I have to remove dashes in phone number and then check the length is equal to 10. Please can anyone help with this SQL query?

My query is like below :

select
    COUNT(Cust_ID) cnt, Phone_no
from
    tbl_Customers
where
    Cust_Type = 3
group by
    Phone_no
having
    COUNT(Cust_ID) > 1
order by
    cnt desc

Body:
Adding LEN(REPLACE(Phone_no,'-','')) = 10 in your WHERE clause should be what your looking for.

select COUNT(Cust_ID) cnt,Phone_no
from tbl_Customers
where Cust_Type = 3
      and
      LEN(REPLACE(Phone_no,'-','')) = 10
group by Phone_no
having COUNT(Cust_ID) > 1
order by cnt desc

Here is the Microsoft documentation for those functions.

REPLACE

LEN


问:
how to properly wrap C API in python using ctypes?
I have wrapped two API's from a C library in Python using ctypes. One works and the other doesn't. My question is: how do I properly wrap API from from a C library in Python using ctypes?

some background info:

```<code>import ctypes
from ctypes import *

MF = (b'path_to_file')
beginTime = (-Value)
endTime = (Value)
PN = (b'path_to_String')
DT_RETURNGMT = 0x0100
DT_FLOAT = 0x0001
convert = DT_RETURNGMT|DT_FLOAT
</code>```

This one works:

```<code>#read functions
dll.openFile.argtypes = c_char_p,
dll.openFile.restype = POINTER(File)

dll.freeFile.argtypes = POINTER(File),
dll.freeFile.restype = None
f = dll.openFile(MF)
print(f[0].fileInfo[0].items)
</code>```

This one does not:

```<code>#retrieve data
dll.readSP.argtypes = POINTER(File), c_char_p(PN),
c_double(beginTime), c_double(endTime),
0, 0,
c_ushort(convert),
dll.readSP.restype = POINTER(SP)
#pointer to the SP file structure
g = dll.readSP(f, MF)
print(g)
print(g[0].points)
pint(g[0].tStamp[0].data[0].TTag)
</code>```

I think the pointer is correct because when I tell the code to print(g) it returns the location of my SP object like this:

```<code><__main__.LP_SP object at 0x000001D1EAB862C8>
</code>```

but it cant return the location of anything else in the SP file structure. Which leads me to believe it is how I wrapped the API that is the problem. But i'm not sure where I went wrong with it.

I think that I must not have wrapped the API correctly but i'm not sure where I went wrong.  double *refTIME, and struct TimeTage *refGMT are NULL in the C code so I have them as 0 in my script.

答:
You've defined instances instead of types in the non-working code. Instead of:

```<code>dll.readSP.argtypes = POINTER(File), c_char_p(PN), c_double(beginTime), c_double(endTime), 0, 0, c_ushort(convert),
</code>```

You need:

```<code>dll.readSP.argtypes = POINTER(File), c_char_p, c_double, c_double, c_double, POINTER(TTag), c_ushort
</code>```

Body:
I have wrapped two API's from a C library in Python using ctypes. One works and the other doesn't. My question is: how do I properly wrap API from from a C library in Python using ctypes?

some background info:

import ctypes
from ctypes import *

MF = (b'path_to_file')
beginTime = (-Value)
endTime = (Value)
PN = (b'path_to_String')
DT_RETURNGMT = 0x0100
DT_FLOAT = 0x0001
convert = DT_RETURNGMT|DT_FLOAT

This one works:

#read functions
dll.openFile.argtypes = c_char_p,
dll.openFile.restype = POINTER(File)

dll.freeFile.argtypes = POINTER(File),
dll.freeFile.restype = None
f = dll.openFile(MF)
print(f[0].fileInfo[0].items)

This one does not:

#retrieve data
dll.readSP.argtypes = POINTER(File), c_char_p(PN),
c_double(beginTime), c_double(endTime),
0, 0,
c_ushort(convert),
dll.readSP.restype = POINTER(SP)
#pointer to the SP file structure
g = dll.readSP(f, MF)
print(g)
print(g[0].points)
pint(g[0].tStamp[0].data[0].TTag)

I think the pointer is correct because when I tell the code to print(g) it returns the location of my SP object like this:

<__main__.LP_SP object at 0x000001D1EAB862C8>

but it cant return the location of anything else in the SP file structure. Which leads me to believe it is how I wrapped the API that is the problem. But i'm not sure where I went wrong with it.

I think that I must not have wrapped the API correctly but i'm not sure where I went wrong.  double *refTIME, and struct TimeTage *refGMT are NULL in the C code so I have them as 0 in my script.

Body:
You've defined instances instead of types in the non-working code. Instead of:

dll.readSP.argtypes = POINTER(File), c_char_p(PN), c_double(beginTime), c_double(endTime), 0, 0, c_ushort(convert),

You need:

dll.readSP.argtypes = POINTER(File), c_char_p, c_double, c_double, c_double, POINTER(TTag), c_ushort


问:
Looping through all posts shows duplicates in Wordpress
Myself and an SEO guy I am working with want to generate our own sitemaps(for certain reasons). To do so, obviously I need to loop through all of the posts and pages within the wordpress installation. I wrote a quick function and uploaded it to the server on a live site to see if it worked, and it does.

The strange thing however, is when I attempt to test this same function on a local install of wordpress(using WAMP), it prints out some post names multiple times(aka duplicates). I just wanted to know if someone here knew of a bug that might be occurring, or if my code needs to change. For example, my code might work on the live site now, but I'd rather not be faced with this issue later on when more posts are added, and I start seeing duplicates in the XML file.

Anyways, here's my code:

```<code><?php
$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;

// Loop through each post, and echo out the url and it's amp extension.
foreach($posts as $post) {

    if($post->post_type == 'post') {
       $permalink = get_permalink($post->ID);
       echo "\n\t<url>\n\t\t<loc>{$permalink}</loc>\n\t</url>";
       echo "\n\t<url>\n\t\t<loc>{$permalink}amp/</loc>\n\t</url>";
    }
}
</code>```

As I mentioned, it works on a live site, and does not print duplicates. So you don't have to worry yourself with the syntax of the echo statements, here's what will print for each post on the site:

```<code><url>
   <loc>https://www.somedomain.com/post1/</loc>
</url>

<url>
   <loc>https://www.somedomain.com/post1/amp/</loc>
</url>
</code>```

Anyone have an opinion on this?

答:
Figured out a solution that uses WP query for the data I need to retrieve, then I just use regular PHP to handle the rest. Might be unnecessary, but I did not feel like wasting any more of my time roaming through the useless Wordpress docs.

I instantiate an empty array at the beginning of the function, and then loop through all of the posts, extracting their ids, and pushing them into to the array I created.

Once the while loop ends, I loop through my array, and print out the xml needed for each post. Pretty simple, and does NOT create duplicates.

```<code>$xml = "";
$posts = array();

$q = new WP_Query(array(
    'post_type' => 'any',
    'post_status' => 'publish',
    'posts_per_page' => 50000,
    'has_password' => false,
));

// Loop through all posts, and push each id to the new posts array
if ($q->have_posts()) {
    while ($q->have_posts()) {
        $q->the_post();

        if(get_post_type() == 'post') {
          $id = get_the_ID();
          array_push($posts, $id);
        }
    }
}

// Loop through posts array and append the posts info into xml format
foreach($posts as $post) {
  $xml .= "<url>\n";
  $xml .= "\t<loc>\t\n";
  $xml .= "\t\t" . esc_url(get_permalink($post));
  $xml .= "\n\t</loc>\t";
  $xml .= "\n</url>\n\n";
}
</code>```

I left out the amp part here, but yeah, in my code I also print out an amp extension for each post as well. Final results print out like so.

```<code><url>
    <loc>
        http://www.domainname.com/blog/article1
    </loc>
</url>

<url>
    <loc>
        http://www.domainname.com/blog/article2
    </loc>
</url>
</code>```

Body:
Myself and an SEO guy I am working with want to generate our own sitemaps(for certain reasons). To do so, obviously I need to loop through all of the posts and pages within the wordpress installation. I wrote a quick function and uploaded it to the server on a live site to see if it worked, and it does.

The strange thing however, is when I attempt to test this same function on a local install of wordpress(using WAMP), it prints out some post names multiple times(aka duplicates). I just wanted to know if someone here knew of a bug that might be occurring, or if my code needs to change. For example, my code might work on the live site now, but I'd rather not be faced with this issue later on when more posts are added, and I start seeing duplicates in the XML file.

Anyways, here's my code:

<?php
$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;

// Loop through each post, and echo out the url and it's amp extension.
foreach($posts as $post) {

    if($post->post_type == 'post') {
       $permalink = get_permalink($post->ID);
       echo "\n\t<url>\n\t\t<loc>{$permalink}</loc>\n\t</url>";
       echo "\n\t<url>\n\t\t<loc>{$permalink}amp/</loc>\n\t</url>";
    }
}

As I mentioned, it works on a live site, and does not print duplicates. So you don't have to worry yourself with the syntax of the echo statements, here's what will print for each post on the site:

<url>
   <loc>https://www.somedomain.com/post1/</loc>
</url>

<url>
   <loc>https://www.somedomain.com/post1/amp/</loc>
</url>

Anyone have an opinion on this?

Body:
Figured out a solution that uses WP query for the data I need to retrieve, then I just use regular PHP to handle the rest. Might be unnecessary, but I did not feel like wasting any more of my time roaming through the useless Wordpress docs.

I instantiate an empty array at the beginning of the function, and then loop through all of the posts, extracting their ids, and pushing them into to the array I created.

Once the while loop ends, I loop through my array, and print out the xml needed for each post. Pretty simple, and does NOT create duplicates.

$xml = "";
$posts = array();

$q = new WP_Query(array(
    'post_type' => 'any',
    'post_status' => 'publish',
    'posts_per_page' => 50000,
    'has_password' => false,
));

// Loop through all posts, and push each id to the new posts array
if ($q->have_posts()) {
    while ($q->have_posts()) {
        $q->the_post();

        if(get_post_type() == 'post') {
          $id = get_the_ID();
          array_push($posts, $id);
        }
    }
}

// Loop through posts array and append the posts info into xml format
foreach($posts as $post) {
  $xml .= "<url>\n";
  $xml .= "\t<loc>\t\n";
  $xml .= "\t\t" . esc_url(get_permalink($post));
  $xml .= "\n\t</loc>\t";
  $xml .= "\n</url>\n\n";
}

I left out the amp part here, but yeah, in my code I also print out an amp extension for each post as well. Final results print out like so.

<url>
    <loc>
        http://www.domainname.com/blog/article1
    </loc>
</url>

<url>
    <loc>
        http://www.domainname.com/blog/article2
    </loc>
</url>


问:
Regex exclude word from matches
Does anyone know what am I doing wrong?
I have this sentence:

```<code>hi [user=1234]John Jack[/user] take me home
</code>```

and I need regex which select only John Jack

My regex:

```<code>(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))
</code>```

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

答:
Alternative to the answer from @matoni with "lookahead" and "lookbehind" syntax, you can use grouping (which are already defined in your pattern) and extract an appropriate group:</p>

```<code>    String s = "hi [user=1234]John Jack[/user] take me home ...";
    Pattern p = Pattern.compile("\\[user=\\d+\\](.+)\\[/user\\]");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
    }
</code>```

Title: Regex exclude word from matches

Body:
Does anyone know what am I doing wrong?
I have this sentence:

hi [user=1234]John Jack[/user] take me home

and I need regex which select only John Jack

My regex:

(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

Body:
Alternative to the answer from @matoni with "lookahead" and "lookbehind" syntax, you can use grouping (which are already defined in your pattern) and extract an appropriate group:

    String s = "hi [user=1234]John Jack[/user] take me home ...";
    Pattern p = Pattern.compile("\\[user=\\d+\\](.+)\\[/user\\]");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
    }


问:
HttpClient StreamContent append filename twice
I am using Microsoft Http Client Libraries to make a multipart request from Windows Phone 8 to the server. It contains a String content having json string and a Stream Content having image stream.
Now i get the status OK and request hits on the server. but the logs says the server is not able to get the file name of the image.

```<code>content.Add(new StreamContent(photoStream), "files", fileName);
</code>```

where the photoStream is the image stream, "files" is the name of content and file name is the name of the image file.

So the header value must be:

```<code>Content-Disposition: form-data; name=files; filename=image123.jpg
</code>```

but actually it is:

```<code>Content-Disposition: form-data; name=files; filename=image123.jpg; filename*=utf-8''image123.jpg
</code>```

Why it is appending the "; filename*=utf-8''image123.jpg" part.
Is it an issue?

Please let me know any reasons/possibility that i am not able to upload image from WP8.

答:
For me, using HttpStringContent instead of StreamContent, Damith's solution did not work out but at the end I found this one:

var fd = new Windows.Web.Http.HttpMultipartFormDataContent();
var file = new Windows.Web.Http.HttpStringContent(fs);
file.headers.contentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream");
fd.add(file);
file.headers.contentDisposition = new Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.parse("form-data; name=\"your_form_name\"; filename=\"your_file_name\"");```

Attention: it is abolute essential that you set contentDisposition after adding the file, otherwise the header will be overwritten by "form-data".

Body:
I am using Microsoft Http Client Libraries to make a multipart request from Windows Phone 8 to the server. It contains a String content having json string and a Stream Content having image stream.
Now i get the status OK and request hits on the server. but the logs says the server is not able to get the file name of the image.

content.Add(new StreamContent(photoStream), "files", fileName);

where the photoStream is the image stream, "files" is the name of content and file name is the name of the image file.

So the header value must be:

Content-Disposition: form-data; name=files; filename=image123.jpg

but actually it is:

Content-Disposition: form-data; name=files; filename=image123.jpg; filename*=utf-8''image123.jpg

Why it is appending the "; filename*=utf-8''image123.jpg" part.
Is it an issue?

Please let me know any reasons/possibility that i am not able to upload image from WP8.

Body:
For me, using HttpStringContent instead of StreamContent, Damith's solution did not work out but at the end I found this one:

var fd = new Windows.Web.Http.HttpMultipartFormDataContent();
var file = new Windows.Web.Http.HttpStringContent(fs);
file.headers.contentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream");
fd.add(file);
file.headers.contentDisposition = new Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.parse("form-data; name=\"your_form_name\"; filename=\"your_file_name\"");

Attention: it is abolute essential that you set contentDisposition after adding the file, otherwise the header will be overwritten by "form-data".


问:
Oracle SQL: Replace all non-numeric values, such as NULL, blank or empty strings
I have a column that is formatted as number but seems to contain some other values as well that are causing trouble with my other functions (Rtrim, Xmlagg, Xmlelement, Extract), leading the whole query to fail (which works well if I take this column out).

Can someone tell me the best way to replace anything in a column that is not a valid number by 0 (or alternatively a placeholder number like 99999) ?

I tried the following but guess this only covers NULL values, not empty strings or blank strings which I think I have to replace first.

```<code>TO_CHAR(NVL(a.mycolumn, 0))
</code>```

Many thanks in advance,

Mike

答:
Use REGEXP_LIKE

For Numeric:

```<code>REGEXP_LIKE (numeric_value, '^\d+(\.\d+)?$')
</code>```

or with null

```<code>REGEXP_LIKE(NVL(value, 'NULL'), '^\d+(\.\d+)?$|NULL$')
</code>```

Body:
I have a column that is formatted as number but seems to contain some other values as well that are causing trouble with my other functions (Rtrim, Xmlagg, Xmlelement, Extract), leading the whole query to fail (which works well if I take this column out).

Can someone tell me the best way to replace anything in a column that is not a valid number by 0 (or alternatively a placeholder number like 99999) ?

I tried the following but guess this only covers NULL values, not empty strings or blank strings which I think I have to replace first.

TO_CHAR(NVL(a.mycolumn, 0))

Many thanks in advance,

Mike

Body:
Use REGEXP_LIKE

For Numeric:

REGEXP_LIKE (numeric_value, '^\d+(\.\d+)?$')

or with null

REGEXP_LIKE(NVL(value, 'NULL'), '^\d+(\.\d+)?$|NULL$')


问:
Disable radio button depending on date
I'm a novice in Javascript, and trying to figure out how to using Javascript to disable radio button attribute

In my form, I have a date picker and 10 radio buttons below. I want some radio buttons turn to gray if specific date is selected, and some another radio buttons turn gray if another date is chosen.

It's a bit complicated for me, so please help me.

Thank you very much

答: For learning something new, I suggest trying to solve the same kind of problem in a simpler situation.  Try making a form with just a textfield, and 2 radio buttons, and one of them is disabled when text is entered.  </p>

ContentLicense: CC BY-SA 2.5

Title: Disable radio button depending on date


问:
Manipulating big array in a more memory-efficient way
I'm currently writing an API for an app that interfaces with a large database and need to retrieve large amounts of data from it, then spit it out as JSON.

I'm using CodeIgniter (CI) as a database interface but I don't think it's relevant here. I'm running into memory limits and I have unfortunately no way of increasing the limit because the shared hosting service won't do it.

I get about 56k rows from the database, which get put into an array by CI (zero-indexed, pretty standard). Each row has 7 fields.

All is well until I start looping through the array to modify data. The script runs into a memory limit error after a few loop iterations even though I'm just modifying the original array, and not allocating new variables, I think.

```<code>Allowed memory size of 134217728 bytes exhausted
</code>```

Below is the code I'm using:

```<code>$query = $this->db->get('table');
if ($query->num_rows() > 0) {
    $result = $query->result_array();
    foreach ($result as $k => $v) {
        foreach($v as $key => $value) {
            if ($key === 'column_name') {
                $result[$k][$key] = json_decode($value);
                continue;
            }
            if ($value == null) {
                $result[$k][$key] = '';
            } else if (ctype_digit($value)) {
                $result[$k][$key] = (int) $result[$k][$key];
            }
        }
    }
    return $result;
}
</code>```

Just decoding some json and casting to integers or empty strings, nothing fancy. But I will get memory limit errors on any line that mutates the $result array. Even if I remove the (memory-intensive) json_decode I will still get an error on line that simply casts to an int.

What's more, even if I remove the whole foreach, I get a memory limit error later on when I use json_encode to generate the API response.

I'm totally lost, and I really need this amount of data to be output all at once, no idea how to make this more memory-efficient (maybe with like buffers or something? never dived into this).

EDIT: for anyone interested, I managed to cut down on memory usage somewhat by making an unbuffered query to the database. This way, only 1 copy of the data is stored in the array. I also removed the foreach and treat each field specifically. The main problem, however, is probably how PHP stores arrays. Here's the new code:

```<code>$query = $this->db->get('table');
$result = [];
while ($row = $query->unbuffered_row('array')) {
    if ($row['column1'] == '[]') {
        $row['column1'] = [];
    } else {
        $row['column1'] = json_decode($row['column1']);
    }
    $row['column2'] = (int) $row['column2'];
    $row['column3'] = (int) $row['column3'];
    $row['column4'] = is_null($row['column4']) ? '' : (int) $row['column4'];
    $row['column5'] = is_null($row['column5']) ? '' : (int) $row['column5'];

    $result[] = $row;
}

return $result;
</code>```

答:
There are so many ways to tackle this, the real question would be what are your priorities?

Does it have to be fast? can it be slow?

Is that low-memory server is the absolute only resource available?

The ideal solution would obviously be upgrading your server, assuming you have tasks that consume a lot of memory, that should be a concern for whoever is running this project.

There is obviously the modern way to do it using micro services, each one of them processing a chunk of the data. They could be either written by you, or you could use cloud services such as AWS.

Having said that, assuming that you are indeed limited to the current constellation and you simply have no other option but to use a limited memory server for processing big data, I would recommend using local file I/O - it's not the fastest solution, but if you read chunks of data and keep writing them into a temporary file you will save the memory issue, and you could then flush that file to the client.

Body:
I'm currently writing an API for an app that interfaces with a large database and need to retrieve large amounts of data from it, then spit it out as JSON.

I'm using CodeIgniter (CI) as a database interface but I don't think it's relevant here. I'm running into memory limits and I have unfortunately no way of increasing the limit because the shared hosting service won't do it.

I get about 56k rows from the database, which get put into an array by CI (zero-indexed, pretty standard). Each row has 7 fields.

All is well until I start looping through the array to modify data. The script runs into a memory limit error after a few loop iterations even though I'm just modifying the original array, and not allocating new variables, I think.

Allowed memory size of 134217728 bytes exhausted

Below is the code I'm using:

$query = $this->db->get('table');
if ($query->num_rows() > 0) {
    $result = $query->result_array();
    foreach ($result as $k => $v) {
        foreach($v as $key => $value) {
            if ($key === 'column_name') {
                $result[$k][$key] = json_decode($value);
                continue;
            }
            if ($value == null) {
                $result[$k][$key] = '';
            } else if (ctype_digit($value)) {
                $result[$k][$key] = (int) $result[$k][$key];
            }
        }
    }
    return $result;
}

Just decoding some json and casting to integers or empty strings, nothing fancy. But I will get memory limit errors on any line that mutates the $result array. Even if I remove the (memory-intensive) json_decode I will still get an error on line that simply casts to an int.

What's more, even if I remove the whole foreach, I get a memory limit error later on when I use json_encode to generate the API response.

I'm totally lost, and I really need this amount of data to be output all at once, no idea how to make this more memory-efficient (maybe with like buffers or something? never dived into this).

EDIT: for anyone interested, I managed to cut down on memory usage somewhat by making an unbuffered query to the database. This way, only 1 copy of the data is stored in the array. I also removed the foreach and treat each field specifically. The main problem, however, is probably how PHP stores arrays. Here's the new code:

$query = $this->db->get('table');
$result = [];
while ($row = $query->unbuffered_row('array')) {
    if ($row['column1'] == '[]') {
        $row['column1'] = [];
    } else {
        $row['column1'] = json_decode($row['column1']);
    }
    $row['column2'] = (int) $row['column2'];
    $row['column3'] = (int) $row['column3'];
    $row['column4'] = is_null($row['column4']) ? '' : (int) $row['column4'];
    $row['column5'] = is_null($row['column5']) ? '' : (int) $row['column5'];

    $result[] = $row;
}

return $result;


问:
HTML Javascript dynamic changes to a button
Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:

var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
    validUser = true;
    document.getElementById("btnSignIn").outerHTML = "Sign out";
    document.getElementById("btnSignIn").style.backgroundColor = "pink";
    document.getElementById("results").innnerHTML = "Welcome " + user +"!";
    document.getElementById("txtUserName").style.visibility = "hidden";
    document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
  validUser = false;
}
}

function signin() {

if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

    validUser = false;
    document.getElementById("btnSignIn").innerHTML = "Sign in";
    document.getElementById("btnSignIn").style.backgroundColor = "orange";
    document.getElementById("results").innerHTML = "Welcome stranger";
    document.getElementById("txtUserName").style.visibility = "visible";
    document.getElementById("txtPassword").style.visibility = "visible";
    setCookie("txtUserName", null, "txtPassword", null, 365);
}
else {
    var user = document.getElementById("txtUserName").value;
    var pwd = document.getElementById("txtPassword").value;
    if (user.text === "" && user === null &&
        pwd.text === "" && pwd === null) {
        validUser = false;
    }

    else if (user === "john@me.com" && pwd === "snow") {
        validUser = true;
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("btnSignIn").outerHTML = "Sign out";
        document.getElementById("results").innerHTML = "Welcome "+ user      + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
        var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
        if (!myCookie) {
             validUser = false;
        }
    }
    return false;
}
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = uname + "=" + uvalue + "; " + expires;
    document.cookie = pname + "=" + pvalue + "; " + expires;
    return true;
}
else {
    return false;
}
}

function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
   var user = getCookie("username");
   if (user !== "") {
    return user;
   }else {
        return false;
    }
}
else {
    return false;
}
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav navbar-nav navbar-right">
                <li>
                    <form id="loginform" class="navbar-form navbar-right">
                        <div class="form-group">
                            <input type="text"  id="txtUserName" placeholder="Email" class="form-control">
                        </div>
                        <div class="form-group">
                            <input type="password" id="txtPassword" placeholder="Password" class="form-control">
                        </div>
                        <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();"  >Sign in</button>
                    </form>
                </li>
            </ul></code>```

The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.

答:
You messed up with replacing the text.

Try to use innerHTML, cause you have text inside the tag.
So inside init() it goes like this:

document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";

Body:
Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:

var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
    validUser = true;
    document.getElementById("btnSignIn").outerHTML = "Sign out";
    document.getElementById("btnSignIn").style.backgroundColor = "pink";
    document.getElementById("results").innnerHTML = "Welcome " + user +"!";
    document.getElementById("txtUserName").style.visibility = "hidden";
    document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
  validUser = false;
}
}

function signin() {

if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

    validUser = false;
    document.getElementById("btnSignIn").innerHTML = "Sign in";
    document.getElementById("btnSignIn").style.backgroundColor = "orange";
    document.getElementById("results").innerHTML = "Welcome stranger";
    document.getElementById("txtUserName").style.visibility = "visible";
    document.getElementById("txtPassword").style.visibility = "visible";
    setCookie("txtUserName", null, "txtPassword", null, 365);
}
else {
    var user = document.getElementById("txtUserName").value;
    var pwd = document.getElementById("txtPassword").value;
    if (user.text === "" && user === null &&
        pwd.text === "" && pwd === null) {
        validUser = false;
    }

    else if (user === "john@me.com" && pwd === "snow") {
        validUser = true;
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("btnSignIn").outerHTML = "Sign out";
        document.getElementById("results").innerHTML = "Welcome "+ user      + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
        var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
        if (!myCookie) {
             validUser = false;
        }
    }
    return false;
}
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = uname + "=" + uvalue + "; " + expires;
    document.cookie = pname + "=" + pvalue + "; " + expires;
    return true;
}
else {
    return false;
}
}

function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
   var user = getCookie("username");
   if (user !== "") {
    return user;
   }else {
        return false;
    }
}
else {
    return false;
}
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}

                    <form id="loginform" class="navbar-form navbar-right">

                            <input type="text"  id="txtUserName" placeholder="Email" class="form-control">

                            <input type="password" id="txtPassword" placeholder="Password" class="form-control">

                        <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();"  >Sign in</button>
                    </form>

The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.


问:
How do i architect automatic update of my clients
I have a distributed application written in C# (4.0). It has become a substantial task to update all clients each time i create a new release. I do not want to go the ClickOnce way, since organisations that has bought my software in some cases do not wish to upgrade their clients.

How do i build such an update mechanism, for my clients? My thoughts are to implement a kind of launcher application that checks a server for newest version, updates that if required, and starts the new one. If no updates are available it simple starts the client application. Then i see a problem of updating the launcher application, should the client then be the one responsible for this?

How do I solve this in a proper and robust way, that ensures that the customer can configurate their clients for updates or not, and then allow the clients to function completely autonomically? That is, without user supervision.

Cheers,

答: You could use ClickOnce and simply disable the CheckForUpdate : MSDN : Disable Clickonce Default Updater.</p>


答:
(.+?) is group indexed as 2 and it should hold John Jack so you should be able to obtain it via matcher.group(2).

Demo:

```<code>String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("(\\[user=\\d\\d\\d\\d](.+?)\\[\\/user\\])(?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\]))");
Matcher m = p.matcher(text);
if(m.find()){
    System.out.println(m.group(2));
}
</code>```

Output: John Jack

If you wanted to find more users you need to change if to while and fix your regex because

currently you are searching for users with 4 digit IDs so it will fail to match [user=12] or [user=1]. So instead of \d\d\d\d you can use \d+.

you are using [user=ID]..[/user] but also [user=ID]..[\user] (both / and \].

BTW since Java doesn't use /regex/flags syntax, / is not considered as special character so you don't need to escape it.

Also I am not sure why you need (?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\])) at the end of your regex, it doesn't really do anything in example you showed so it looks like it can be removed. Also we don't need to surround earlier part with parenthesis because look-ahead doesn't add anything to whole match which is already placed in group 0, so we don't need separate group which will duplicate that match. After removing those those extra parenthesis (.+?) will be indexed as group 1.

Modified and simplified solution can look like:

```<code>String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("\\[user=\\d+](.+?)\\[(/|\\\\)user]");
Matcher m = p.matcher(text);
while(m.find()){
    System.out.println(m.group(1).trim());
}
</code>```

Output:

```<code>John Jack
Jonno Ha
Danny Di
</code>```

Title: Regex exclude word from matches

Body:
(.+?) is group indexed as 2 and it should hold John Jack so you should be able to obtain it via matcher.group(2).

Demo:

String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("(\\[user=\\d\\d\\d\\d](.+?)\\[\\/user\\])(?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\]))");
Matcher m = p.matcher(text);
if(m.find()){
    System.out.println(m.group(2));
}

Output: John Jack

If you wanted to find more users you need to change if to while and fix your regex because

currently you are searching for users with 4 digit IDs so it will fail to match [user=12] or [user=1]. So instead of \d\d\d\d you can use \d+.

you are using [user=ID]..[/user] but also [user=ID]..[\user] (both / and \].

BTW since Java doesn't use /regex/flags syntax, / is not considered as special character so you don't need to escape it.

Also I am not sure why you need (?!(\\[user=\\d\\d\\d\\d\\])|(\\[\\/user\\])) at the end of your regex, it doesn't really do anything in example you showed so it looks like it can be removed. Also we don't need to surround earlier part with parenthesis because look-ahead doesn't add anything to whole match which is already placed in group 0, so we don't need separate group which will duplicate that match. After removing those those extra parenthesis (.+?) will be indexed as group 1.

Modified and simplified solution can look like:

String text = "hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\\user]";
Pattern p = Pattern.compile("\\[user=\\d+](.+?)\\[(/|\\\\)user]");
Matcher m = p.matcher(text);
while(m.find()){
    System.out.println(m.group(1).trim());
}

Output:

John Jack
Jonno Ha
Danny Di


问:
Django list ordering by date
I want to display in the same page all the results of this 2 queries and ordering them by date. The goal is to mix both results to just display a unique list ordering by date.

```<code>articles = Articles.objects.all()

statut = Statut.objects.all()
</code>```

I have this idea but I don't know :

```<code>articles = list(Articles.objects.all())

statut = list(Statut.objects.all())

all = articles + statut
</code>```

So I have a unique list and it's working. It displays every results.

Now I wonder how to order by date for the template rendering?

May be there is a simpler way to do it ?

Thank you

答: Hmm..., my suggestion is sorting them on front-end with some js framework, e.g., jquery.</p>

Title: Django list ordering by date

Body:
I want to display in the same page all the results of this 2 queries and ordering them by date. The goal is to mix both results to just display a unique list ordering by date.

articles = Articles.objects.all()

statut = Statut.objects.all()

I have this idea but I don't know :

articles = list(Articles.objects.all())

statut = list(Statut.objects.all())

all = articles + statut

So I have a unique list and it's working. It displays every results.

Now I wonder how to order by date for the template rendering?

May be there is a simpler way to do it ?

Thank you


问:
using sudo inside jupyter notebook's cell
I'm trying to make a tutorial for a platform inside a jupyter notebook

at some point I need to run a linux command inside a cell like this :

```<code>!sudo apt-get install blah
</code>```

but cant figure out how to enter the sudo pass , and I dont want to run jupyter notebook with sudo, any idea how to do this ?

答:
You can

```<code>subprocess.Pope(['sudo', 'apt-get', 'install', 'bla'])
</code>```

If you want to avoid the python syntax, you can define your own cell magic that does that for you (e.g. %sudo apt-get install bla).

Body:
I'm trying to make a tutorial for a platform inside a jupyter notebook

at some point I need to run a linux command inside a cell like this :

!sudo apt-get install blah

but cant figure out how to enter the sudo pass , and I dont want to run jupyter notebook with sudo, any idea how to do this ?

Body:
You can

subprocess.Pope(['sudo', 'apt-get', 'install', 'bla'])

If you want to avoid the python syntax, you can define your own cell magic that does that for you (e.g. %sudo apt-get install bla).


问:
How to update Php web page when db data changes from another device with android app?
Which is the correct way to do this: I have a pc with a php web application (as admin user) to "control" data (for example notes) but the notes are inserted in the db through a web service(APiRest) from android devices(using a simple app) which other users inserts in real time, but these notes must be checked by the admin in the pc(with a boolean value, e.g. "checked" or not). So, how to automatically update the admin web page when a user from the android app inserts a new note? Should I use triggers? What is the correct technique? Any suggestions are welcome, thanks in advance.</p>

答: You can achieve this using Websockets, Polling or a Forever Frame, if you want the admin to update automatically. Or you can use a server send event from the back-end towards the browser.</p>


问:
Not getting values from XML with C#
I have a XML like this.

```<code><language code="eng">
  <label lang="tr">İngilizce</label>
  <label lang="en">English</label>
</language>
</code>```

This is example. I have a 402 nodes.

I'm trying to parse this XML file with C# like on the code and I just can get language code values.

Here is the code.

```<code>var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                          })
                          .ToList();
</code>```

But I need to get label lang="tr" and label lang="en" inner texts (Ingilizce,English) in same code. I didn't do it.

How can I change my code ? Thanks for your helps. :)

EDIT :

```<code> var languageCodeAndValue = doc.Root
                  .Elements("language")
                  .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string>(item.Attribute("lang").Value, item.Value)))
                  .ToList();
</code>```

This code give me a list like this :

```<code>tr,Turkce
en,Turkish
tr,Ingilizce
en,English
</code>```

But I need

```<code>tur,tr,Turkce
tur,en,Turkish
eng,tr,Ingilizce
eng,en,English
</code>```

答:
Another way to parse xml is with XmlSerializer. Visual Studio can create classes for you based on your xml if you copy it to the clipboard and and choose Past Special > Paste XML as Classes.
Then you can deserialize the xml and you will have a language object with an array of labels.

```<code>void Main()
{
    string xml = @"<language code=""eng"">
      <label lang=""tr"">İngilizce</label>
       <label lang=""en"">English</label>
      </language>";

    XmlSerializer ser = new XmlSerializer(typeof(language));
    using (MemoryStream ms = new MemoryStream())
    {
        XDocument.Parse(xml).Save(ms);
        ms.Position = 0;
        var lang = (language)ser.Deserialize(ms);

        Console.WriteLine(lang.code);
        foreach (languageLabel lbl in lang.label)
        {
            Console.WriteLine(lbl.lang);
            Console.WriteLine(lbl.Value);
        }
    }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class language
{

    private languageLabel[] labelField;

    private string codeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("label")]
    public languageLabel[] label
    {
        get
        {
            return this.labelField;
        }
        set
        {
            this.labelField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string code
    {
        get
        {
            return this.codeField;
        }
        set
        {
            this.codeField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class languageLabel
{

    private string langField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string lang
    {
        get
        {
            return this.langField;
        }
        set
        {
            this.langField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value
    {
        get
        {
            return this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }
}
</code>```

Title: Not getting values from XML with C#

Body:
I have a XML like this.

<language code="eng">
  İngilizce
  English
</language>

This is example. I have a 402 nodes.

I'm trying to parse this XML file with C# like on the code and I just can get language code values.

Here is the code.

var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                          })
                          .ToList();

But I need to get label lang="tr" and label lang="en" inner texts (Ingilizce,English) in same code. I didn't do it.

How can I change my code ? Thanks for your helps. :)

EDIT :

 var languageCodeAndValue = doc.Root
                  .Elements("language")
                  .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string>(item.Attribute("lang").Value, item.Value)))
                  .ToList();

This code give me a list like this :

tr,Turkce
en,Turkish
tr,Ingilizce
en,English

But I need

tur,tr,Turkce
tur,en,Turkish
eng,tr,Ingilizce
eng,en,English

Body:
Another way to parse xml is with XmlSerializer. Visual Studio can create classes for you based on your xml if you copy it to the clipboard and and choose Past Special > Paste XML as Classes.
Then you can deserialize the xml and you will have a language object with an array of labels.

void Main()
{
    string xml = @"<language code=""eng"">
      <label lang=""tr"">İngilizce</label>
       <label lang=""en"">English</label>
      </language>";

    XmlSerializer ser = new XmlSerializer(typeof(language));
    using (MemoryStream ms = new MemoryStream())
    {
        XDocument.Parse(xml).Save(ms);
        ms.Position = 0;
        var lang = (language)ser.Deserialize(ms);

        Console.WriteLine(lang.code);
        foreach (languageLabel lbl in lang.label)
        {
            Console.WriteLine(lbl.lang);
            Console.WriteLine(lbl.Value);
        }
    }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class language
{

    private languageLabel[] labelField;

    private string codeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("label")]
    public languageLabel[] label
    {
        get
        {
            return this.labelField;
        }
        set
        {
            this.labelField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string code
    {
        get
        {
            return this.codeField;
        }
        set
        {
            this.codeField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class languageLabel
{

    private string langField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string lang
    {
        get
        {
            return this.langField;
        }
        set
        {
            this.langField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value
    {
        get
        {
            return this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }
}


问:
combine two -filter_complex command together
Below, I have two ffmpeg commands (1, 2) to be combined into (3).

add sounds from 1.mp3 and 1.3gp into muted 1.mp4

code works without error:

```<code>ffmpeg -i 1.mp3 -i 1.3gp -i 1.mp4 \
  -filter_complex "[1]adelay=640|640[s1];[0][s1]amix=2[mixout];" \
  -map 2:v -map [mixout] -c:v copy result.mp4
</code>```

add watermark to top-right of 1.mp4

code works without error:

```<code>ffmpeg -i 1.mp4 -i logo.png \
  -filter_complex "overlay=x=main_w-overlay_w:y=1" \
   result.mp4
</code>```

combine above two commands into one

My code fails

```<code>ffmpeg -i 1.mp3 -i 1.3gp -i 1.mp4 -i logo.png \
  -filter_complex "[1]adelay=640|640[s1];[0][s1]amix=2[mixout];[2:v][3]overlay=x=main_w-overlay_w:y=1[outv]" \
  -map [outv] -map [mixout] -c:v copy result.mp4
</code>```

What am I doing wrong here?

答:
Use

```<code>ffmpeg -i 1.mp3 -i 1.3gp -i 1.mp4 -i logo.png \
  -filter_complex "[1]adelay=640|640[s1];[0][s1]amix=2[mixout];
                   [2:v][3]overlay=x=main_w-overlay_w:y=1[outv]" \
  -map [outv] -map [mixout] result.mp4
</code>```

If you're filtering the video stream e.g. adding an overlay, then you can't copy that video stream.

Body:
Below, I have two ffmpeg commands (1, 2) to be combined into (3).

add sounds from 1.mp3 and 1.3gp into muted 1.mp4

code works without error:

ffmpeg -i 1.mp3 -i 1.3gp -i 1.mp4 \
  -filter_complex "[1]adelay=640|640[s1];[0][s1]amix=2[mixout];" \
  -map 2:v -map [mixout] -c:v copy result.mp4

add watermark to top-right of 1.mp4

code works without error:

ffmpeg -i 1.mp4 -i logo.png \
  -filter_complex "overlay=x=main_w-overlay_w:y=1" \
   result.mp4

combine above two commands into one

My code fails

ffmpeg -i 1.mp3 -i 1.3gp -i 1.mp4 -i logo.png \
  -filter_complex "[1]adelay=640|640[s1];[0][s1]amix=2[mixout];[2:v][3]overlay=x=main_w-overlay_w:y=1[outv]" \
  -map [outv] -map [mixout] -c:v copy result.mp4

What am I doing wrong here?

Body:
Use

ffmpeg -i 1.mp3 -i 1.3gp -i 1.mp4 -i logo.png \
  -filter_complex "[1]adelay=640|640[s1];[0][s1]amix=2[mixout];
                   [2:v][3]overlay=x=main_w-overlay_w:y=1[outv]" \
  -map [outv] -map [mixout] result.mp4

If you're filtering the video stream e.g. adding an overlay, then you can't copy that video stream.


问:
Is this better approach of creating Objects in Java than this?
Approach of creating objects

At present,

I have the following
structure

```<code>Abstract Class A{

public abstract void B();
public abstract void C();
public abstract void D();

public void E(){
 sample Statements;

}
}

public class Z extends A{

    public void B() {
        // TODO Auto-generated method stub

    }

    public void C() {
        // TODO Auto-generated method stub

    }

    public void D() {
        // TODO Auto-generated method stub

    }

    public void X() {
        Sample Statements;;
        Whcih is very specific to this Class;

    }

}
</code>```

My Question in the above class Z, I dont want to impl
I will define only method X which is very specific to

in the Same Way I will define a new Class P, which im
but other 2 methods are not implemented.

Is this the right way to implement the way of Creatin
suit my requirements to create an object?

Or is there any better approach to go about to create

I am worried in Class Z, since methods C & D are not
be any unforeseen effects during my programing later

One More Thought I have Got

Shall I Use the factory Design Pattern to implement the Same Objects?

答:
When some or all of the abstract methods in an abstract class are unimplemented in all child classes, you're almost certainly doing something wrong. Since you didn't describe what you're trying to model, it's hard to suggest specific implementation alternatives.

Ask yourself: why did you write this abstract class in the first place? Could you accomplish the same thing with a set of interfaces?

Body:
Approach of creating objects

At present,

I have the following
structure

Abstract Class A{

public abstract void B();
public abstract void C();
public abstract void D();

public void E(){
 sample Statements;

}
}

public class Z extends A{

    public void B() {
        // TODO Auto-generated method stub

    }

    public void C() {
        // TODO Auto-generated method stub

    }

    public void D() {
        // TODO Auto-generated method stub

    }

    public void X() {
        Sample Statements;;
        Whcih is very specific to this Class;

    }

}

My Question in the above class Z, I dont want to impl
I will define only method X which is very specific to

in the Same Way I will define a new Class P, which im
but other 2 methods are not implemented.

Is this the right way to implement the way of Creatin
suit my requirements to create an object?

Or is there any better approach to go about to create

I am worried in Class Z, since methods C & D are not
be any unforeseen effects during my programing later

One More Thought I have Got

Shall I Use the factory Design Pattern to implement the Same Objects?


问:
Failed query in mysql Database
Good afternoon,
I dont get to see any error in my code and i have been getting Mysql Errors along the line.

My code looks like this

```<code><?php
include 'account_numgen.php';
require_once('inc/config.php');

$con = mysqli_connect($host,$user,$pass, $db)or die ('Cannot Connect :'.mysqli_error());

$account_number = mysqli_real_escape_string($con,$_POST['account_number']);
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$mi = mysqli_real_escape_string($con,$_POST['mi']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$address = mysqli_real_escape_string($con,$_POST['address']);
$address2 = mysqli_real_escape_string($con,$_POST['address2']);
$city = mysqli_real_escape_string($con,$_POST['city']);
$tel = mysqli_real_escape_string($con,$_POST['tel']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$nok_1 = mysqli_real_escape_string($con,$_POST['nok_1']);
$nok1_address = mysqli_real_escape_string($con,$_POST['nok1_address']);
$nok1_address2 = mysqli_real_escape_string($con,$_POST['nok1_address2']);
$nok1_city = mysqli_real_escape_string($con,$_POST['nok1_city']);
$nok_2 = mysqli_real_escape_string($con,$_POST['nok_2']);
$nok2_address = mysqli_real_escape_string($con,$_POST['nok2_address']);
$nok2_address2 = mysqli_real_escape_string($con,$_POST['nok2_address2']);
$nok2_city = mysqli_real_escape_string($con,$_POST['nok2_city']);
$id_type = mysqli_real_escape_string($con,$_POST['id_type']);
$id_number = mysqli_real_escape_string($con,$_POST['id_number']);
$open_bal = mysqli_real_escape_string($con,$_POST['open_bal']);
$passport_name = $_FILES['passport']['name'];
$passport_size = $_FILES['passport']['size'];
$passport_type = $_FILES['passport']['type'];
$passporttmp_name = $_FILES['passport']['tmp_name'];

$signature_name = $_FILES['signature']['name'];
$signature_size = $_FILES['signature']['size'];
$signature_type = $_FILES['signature']['type'];
$signaturetmp_name = $_FILES['signature']['tmp_name'];

$sql = "insert into bank_details(account_number,first_name,mi,last_name,address,address2,city,tel,email,nok_1,nok1_address,nok1_address2,nok1_city,nok_2,nok2_address,nok2_address2,nok2_city,id_type,id_number,open_bal,passport_name,passport_size,passport_type,passporttmp_name,signature_name,signature_size,signature_type,signaturetmp_name) values ('".$account_number."','".$first_name."','".$mi."','".$last_name."','".$address."','".$address2."','".$city."','".$tel."','".$email."','".$nok_1."','".$nok1_address."','".$nok1_address2."','".$nok1_city."','".$nok_2."','".$nok2_address."','".$nok2_address2."','".$nok2_city."','".$id_type."','".$id_number."','".$open_bal."','".$passport_name."','".$passport_size."','".$passport_type."','".$passporttmp_name."','".$signature_name."','".$signature_size."','".$signature_type."','".$signaturetmp_name."')";
mysqli_query($con,$sql) or die ('Failed Query: '.mysqli_error($con));

$passport_dir = 'passport/';
$signature_dir = 'signature/';

$filePath1 = $passport_dir . $passport_name;
$filePath2 = $signature_dir . $signature_name;

$result1 = move_uploaded_file($passporttmp_name,$filePath1);
$result2 = move_uploaded_file($signaturetmp_name,$filePath2);

echo ('
<SCRIPT LANGUAGE="JavaScript">
   window.alert("Account Information \n Account Number: '.$account_number.'\n First Name: '.$first_name.'\n Last Name: '.$last_name.'\n Last Name: '.$open_bal.'")
   window.location.href="index.html";
</SCRIPT>
');

?>
</code>```

Now i get this Error

```<code>Failed Query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's_Signature.png','78716','image/png','C:\xampp\tmp\phpD784.tmp')' at line 1
</code>```

Why is this so? i dont get to see any errors in My code, How ever it has stopped posting to the database on My Local host.

Edit

When i add mysqli_real_escape_string($con, $_FILES[....]) it works fine, but it doesnt send the images from the application to the localhost server what exactly can be the case?

答:
$signature_name has an apostrophe ('). You need to escape it too with mysqli_real_escape_string.

I recommend to escape all parameters of a query besides use prepared statements. Check this out https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Edit: As sugested by Accountant

Escape all parameters OR use prepared statements. In fact, you should always use prepared statements, they escape the parameters for you, amongst other things.

Title: Failed query in mysql Database

Body:
Good afternoon,
I dont get to see any error in my code and i have been getting Mysql Errors along the line.

My code looks like this

<?php
include 'account_numgen.php';
require_once('inc/config.php');

$con = mysqli_connect($host,$user,$pass, $db)or die ('Cannot Connect :'.mysqli_error());

$account_number = mysqli_real_escape_string($con,$_POST['account_number']);
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$mi = mysqli_real_escape_string($con,$_POST['mi']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$address = mysqli_real_escape_string($con,$_POST['address']);
$address2 = mysqli_real_escape_string($con,$_POST['address2']);
$city = mysqli_real_escape_string($con,$_POST['city']);
$tel = mysqli_real_escape_string($con,$_POST['tel']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$nok_1 = mysqli_real_escape_string($con,$_POST['nok_1']);
$nok1_address = mysqli_real_escape_string($con,$_POST['nok1_address']);
$nok1_address2 = mysqli_real_escape_string($con,$_POST['nok1_address2']);
$nok1_city = mysqli_real_escape_string($con,$_POST['nok1_city']);
$nok_2 = mysqli_real_escape_string($con,$_POST['nok_2']);
$nok2_address = mysqli_real_escape_string($con,$_POST['nok2_address']);
$nok2_address2 = mysqli_real_escape_string($con,$_POST['nok2_address2']);
$nok2_city = mysqli_real_escape_string($con,$_POST['nok2_city']);
$id_type = mysqli_real_escape_string($con,$_POST['id_type']);
$id_number = mysqli_real_escape_string($con,$_POST['id_number']);
$open_bal = mysqli_real_escape_string($con,$_POST['open_bal']);
$passport_name = $_FILES['passport']['name'];
$passport_size = $_FILES['passport']['size'];
$passport_type = $_FILES['passport']['type'];
$passporttmp_name = $_FILES['passport']['tmp_name'];

$signature_name = $_FILES['signature']['name'];
$signature_size = $_FILES['signature']['size'];
$signature_type = $_FILES['signature']['type'];
$signaturetmp_name = $_FILES['signature']['tmp_name'];

$sql = "insert into bank_details(account_number,first_name,mi,last_name,address,address2,city,tel,email,nok_1,nok1_address,nok1_address2,nok1_city,nok_2,nok2_address,nok2_address2,nok2_city,id_type,id_number,open_bal,passport_name,passport_size,passport_type,passporttmp_name,signature_name,signature_size,signature_type,signaturetmp_name) values ('".$account_number."','".$first_name."','".$mi."','".$last_name."','".$address."','".$address2."','".$city."','".$tel."','".$email."','".$nok_1."','".$nok1_address."','".$nok1_address2."','".$nok1_city."','".$nok_2."','".$nok2_address."','".$nok2_address2."','".$nok2_city."','".$id_type."','".$id_number."','".$open_bal."','".$passport_name."','".$passport_size."','".$passport_type."','".$passporttmp_name."','".$signature_name."','".$signature_size."','".$signature_type."','".$signaturetmp_name."')";
mysqli_query($con,$sql) or die ('Failed Query: '.mysqli_error($con));

$passport_dir = 'passport/';
$signature_dir = 'signature/';

$filePath1 = $passport_dir . $passport_name;
$filePath2 = $signature_dir . $signature_name;

$result1 = move_uploaded_file($passporttmp_name,$filePath1);
$result2 = move_uploaded_file($signaturetmp_name,$filePath2);

echo ('

');

?>

Now i get this Error

Failed Query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's_Signature.png','78716','image/png','C:\xampp\tmp\phpD784.tmp')' at line 1

Why is this so? i dont get to see any errors in My code, How ever it has stopped posting to the database on My Local host.

Edit

When i add mysqli_real_escape_string($con, $_FILES[....]) it works fine, but it doesnt send the images from the application to the localhost server what exactly can be the case?


问:
access on screen keyboard from windev
In Windows 8 and Windows 10 before Anniversary update (summer 2016) it was possible to show touch keyboard by using (french version) :

```<code>LanceAppliAssociée("C:\Program Files\Common Files\microsoft shared\ink\TabTip32.exe")
</code>```

Since the anniversary update, it does not work anymore. Some people have found a workaround by simulating a clic on the tabtip icon on the systray.
I thank them for this solution. You can find the original post here.

This is just the translation in windev code (french version):

```<code>EXTERNE "KeyConst.WL"
Handle_Systray,Handle_SystrayZoneNotif,Handle_BtnTabTip sont des entiers
Handle_Systray=API("User32","FindWindowA","Shell_TrayWnd",Null) //récupère le handle systray
SI Handle_Systray<>0 ALORS
    Handle_SystrayZoneNotif=API("User32","FindWindowExA",Handle_Systray,Null,"TrayNotifyWnd",Null) //récupère le handle de zone de notification du systray
    SI Handle_SystrayZoneNotif<>0 ALORS
        Handle_BtnTabTip = API("User32","FindWindowExA",Handle_SystrayZoneNotif,Null,"TIPBand",Null) //récupère le handle du bouton du clavier virtuel
        API("User32","PostMessageA",Handle_BtnTabTip,WM_LBUTTONDOWN,0,0) //simule le clic
        API("User32","PostMessageA",Handle_BtnTabTip,WM_LBUTTONUP,0,0)
    FIN
FIN
</code>```

答:
You can try this:</p>

```<code>LanceAppliAssociée("osk.exe")
</code>```

Title: access on screen keyboard from windev

Body:
In Windows 8 and Windows 10 before Anniversary update (summer 2016) it was possible to show touch keyboard by using (french version) :

LanceAppliAssociée("C:\Program Files\Common Files\microsoft shared\ink\TabTip32.exe")

Since the anniversary update, it does not work anymore. Some people have found a workaround by simulating a clic on the tabtip icon on the systray.
I thank them for this solution. You can find the original post here.

This is just the translation in windev code (french version):

EXTERNE "KeyConst.WL"
Handle_Systray,Handle_SystrayZoneNotif,Handle_BtnTabTip sont des entiers
Handle_Systray=API("User32","FindWindowA","Shell_TrayWnd",Null) //récupère le handle systray
SI Handle_Systray<>0 ALORS
    Handle_SystrayZoneNotif=API("User32","FindWindowExA",Handle_Systray,Null,"TrayNotifyWnd",Null) //récupère le handle de zone de notification du systray
    SI Handle_SystrayZoneNotif<>0 ALORS
        Handle_BtnTabTip = API("User32","FindWindowExA",Handle_SystrayZoneNotif,Null,"TIPBand",Null) //récupère le handle du bouton du clavier virtuel
        API("User32","PostMessageA",Handle_BtnTabTip,WM_LBUTTONDOWN,0,0) //simule le clic
        API("User32","PostMessageA",Handle_BtnTabTip,WM_LBUTTONUP,0,0)
    FIN
FIN

Body:
You can try this:

LanceAppliAssociée("osk.exe")


问:
"Show More" Link for buttons inside div (multiple show more buttons)
Here is the fiddle And this is my code here:

$(document).ready(function(){
  $( "button.playtrailer" ).eq(2).after('....Show More');//add a unique id to link
  $( "button.playtrailer:gt(2)" ).addClass('hide');
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $('button.playtrailer').removeClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide
{
  display:none;
}</code>```

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

```

What I want?

In this code, There is only 1 Show More Link for all buttons inside a div.

I want different show more buttons for each div, something like this:

div1

Trailer 1   Trailer 2   Trailer HD...Show more

div2

Trailer 1   Trailer 2   Trailer HD...Show more

div3

Trailer 1   Trailer 2   Trailer HD...Show more

I want to do this without changing the class (both in div and button). What changes should, I make in my Jquery code?

答:
I think something like this would be acceptable

$(document).ready(function(){
  $('div').each(function(){
    $(this).children().slice(2).addClass('hide');
  });
  $('div').append('....Show More');
});

$(document).on('click','a',function(e){
  e.preventDefault();
  $(this).parent().children().removeClass('hide');
  $(this).addClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide
{
  display:none;
}</code>```

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

```

What i changed :
I add hide class to all buttons in each div exept first 2,
and each a tag opens only his div's buttons

Also you wrote //add a unique id to link but each link is same as previous, so they are not unique

Body:
Here is the fiddle And this is my code here:

$(document).ready(function(){
  $( "button.playtrailer" ).eq(2).after('....Show More');//add a unique id to link
  $( "button.playtrailer:gt(2)" ).addClass('hide');
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $('button.playtrailer').removeClass('hide');
});

.hide
{
  display:none;
}

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

What I want?

In this code, There is only 1 Show More Link for all buttons inside a div.

I want different show more buttons for each div, something like this:

div1

Trailer 1   Trailer 2   Trailer HD...Show more

div2

Trailer 1   Trailer 2   Trailer HD...Show more

div3

Trailer 1   Trailer 2   Trailer HD...Show more

I want to do this without changing the class (both in div and button). What changes should, I make in my Jquery code?

Body:
I think something like this would be acceptable

$(document).ready(function(){
  $('div').each(function(){
    $(this).children().slice(2).addClass('hide');
  });
  $('div').append('<a href="">....Show More</a>');
});

$(document).on('click','a',function(e){
  e.preventDefault();
  $(this).parent().children().removeClass('hide');
  $(this).addClass('hide');
});

.hide
{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>div1</p>
<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

<p>div2</p>

<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

<p>div3</p>

<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

What i changed :
I add hide class to all buttons in each div exept first 2,
and each a tag opens only his div's buttons

Also you wrote //add a unique id to link but each link is same as previous, so they are not unique


问:
Rails custom font does not work for both firefox & IE
I am trying to use the SegoePrint font on my rails app. I have in app/assets/fonts both files

SegoePrint.ttf

SegoePrint.eot

In my stylesheets if I have

```<code>@font-face {
font-family: "SegoePrint";
src: url(SegoePrint.ttf) format("truetype");
}
</code>```

It works only for firefox, not for IE but if I have

```<code>@font-face {
font-family: "SegoePrint";
src: url(SegoePrint.ttf) format("truetype");
src: url(SegoePrint.eot);
src: url(SegoePrint.eot?#iefix) format("embedded-opentype");
}
</code>```

I works only for IE and not for firefox anymore. What is the right syntax to have it work for both browsers please? Thanks.

答:
how about if you using this syntax below</p>

```<code>@font-face {
    font-family: 'SegoePrint';
    src: asset-url('SegoePrint.eot');
    src: asset-url('SegoePrint.eot') format('embedded-opentype'),
         asset-url('SegoePrint.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
</code>```

Body:
I am trying to use the SegoePrint font on my rails app. I have in app/assets/fonts both files

SegoePrint.ttf

SegoePrint.eot

In my stylesheets if I have

@font-face {
font-family: "SegoePrint";
src: url(SegoePrint.ttf) format("truetype");
}

It works only for firefox, not for IE but if I have

@font-face {
font-family: "SegoePrint";
src: url(SegoePrint.ttf) format("truetype");
src: url(SegoePrint.eot);
src: url(SegoePrint.eot?#iefix) format("embedded-opentype");
}

I works only for IE and not for firefox anymore. What is the right syntax to have it work for both browsers please? Thanks.

Body:
how about if you using this syntax below

@font-face {
    font-family: 'SegoePrint';
    src: asset-url('SegoePrint.eot');
    src: asset-url('SegoePrint.eot') format('embedded-opentype'),
         asset-url('SegoePrint.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}


问:
Encrypt with Node.js AES CTR and decrypt with PyCrypto
Okay, so basically I am having issues decrypting with Python.

I've managed to encrypt/decrypt data with Node.js - using "aes-128-ctr", the same goes for PyCrypto, but when I try to encrypt with Node.js and decrypt with Python I get invalid deciphered text.

Node.js code:

```<code>var key = "1234567890123456";
var cipher = crypto.createCipher("aes-128-ctr",key)
var ctext = cipher.update('asasasa','utf8','hex') +  cipher.final('hex')
console.log(ctext) // outputs: "f2cf6ecd8f"
</code>```

Python code:

```<code>counter = Counter.new(128)
cipher = AES.new("1234567890123456", AES.MODE_CTR, counter=counter)
cipher.decrypt("f2cf6ecd8f") // outputs: weird encoding characters
</code>```

By the way, I don't care about the level of security of this encryption, I care about performance more.

答:
crypto.createCipher takes a password and uses EVP_BytesToKey internally to derive a key and IV from that. Contrary to that, pycrypto directly expects a key and IV. You need to use exactly the same procedure on both sides.

crypto.createCipher must never be used with CTR-mode, because the key and IV generation are not randomized. Since the CTR-mode is a streaming mode, it will always produce the same key stream which might enable an attacker who only observes multiple ciphertexts that are encrypted with the same password to deduce the plaintext. This is possible because of the resulting many-time pad issue.

If you must use CTR-mode, then you have to use crypto.createCipheriv. If you use the same key, you have to use a different IV every time. This is why this is actually called a nonce for CTR-mode. For AES-CTR, a nonce of 96 bit is a good compromise between security and size of possibly encryptable plaintexts.

```<code>var plaintext = 'asasasa'
var key = "1234567890123456" # don't use this one!
var nonce = crypto.randomBytes(12)
var iv = Buffer.concat([nonce, Buffer.alloc(4, 0)])
var cipher = crypto.createCipheriv("aes-128-ctr", key, iv)
var ciphertext = nonce.toString('hex') + cipher.update(plaintext,'utf8','hex') +  cipher.final('hex')
console.log(ciphertext)
</code>```

Example output:

```
5b88aeb265712b6c8bfa8dbd63012d1e52eb42
```

The IV is not secret and you have to use the exact same IV during decryption. Usually, it is sent along with the ciphertext by being prefixed to it. It is then sliced off before decryption:

```<code>ct = codecs.decode('5b88aeb265712b6c8bfa8dbd63012d1e52eb42', 'hex') # I'm using Python 3
counter = Counter.new(32, prefix=ct[:12], initial_value=0)
cipher = AES.new("1234567890123456", AES.MODE_CTR, counter=counter)
cipher.decrypt(ct[12:])
</code>```

Output:

```<code>b'asasasa'
</code>```

Keep in mind that a key needs to be randomly chosen. You can generate a random key and keep it in an encoded form in the source code (i.e. as Hex). If you do that, you must not give the source code or the bytecode to anyone that you wouldn't trust the key with.

Body:
Okay, so basically I am having issues decrypting with Python.

I've managed to encrypt/decrypt data with Node.js - using "aes-128-ctr", the same goes for PyCrypto, but when I try to encrypt with Node.js and decrypt with Python I get invalid deciphered text.

Node.js code:

var key = "1234567890123456";
var cipher = crypto.createCipher("aes-128-ctr",key)
var ctext = cipher.update('asasasa','utf8','hex') +  cipher.final('hex')
console.log(ctext) // outputs: "f2cf6ecd8f"

Python code:

counter = Counter.new(128)
cipher = AES.new("1234567890123456", AES.MODE_CTR, counter=counter)
cipher.decrypt("f2cf6ecd8f") // outputs: weird encoding characters

By the way, I don't care about the level of security of this encryption, I care about performance more.

Body:
crypto.createCipher takes a password and uses EVP_BytesToKey internally to derive a key and IV from that. Contrary to that, pycrypto directly expects a key and IV. You need to use exactly the same procedure on both sides.

crypto.createCipher must never be used with CTR-mode, because the key and IV generation are not randomized. Since the CTR-mode is a streaming mode, it will always produce the same key stream which might enable an attacker who only observes multiple ciphertexts that are encrypted with the same password to deduce the plaintext. This is possible because of the resulting many-time pad issue.

If you must use CTR-mode, then you have to use crypto.createCipheriv. If you use the same key, you have to use a different IV every time. This is why this is actually called a nonce for CTR-mode. For AES-CTR, a nonce of 96 bit is a good compromise between security and size of possibly encryptable plaintexts.

var plaintext = 'asasasa'
var key = "1234567890123456" # don't use this one!
var nonce = crypto.randomBytes(12)
var iv = Buffer.concat([nonce, Buffer.alloc(4, 0)])
var cipher = crypto.createCipheriv("aes-128-ctr", key, iv)
var ciphertext = nonce.toString('hex') + cipher.update(plaintext,'utf8','hex') +  cipher.final('hex')
console.log(ciphertext)

Example output:

5b88aeb265712b6c8bfa8dbd63012d1e52eb42

The IV is not secret and you have to use the exact same IV during decryption. Usually, it is sent along with the ciphertext by being prefixed to it. It is then sliced off before decryption:

ct = codecs.decode('5b88aeb265712b6c8bfa8dbd63012d1e52eb42', 'hex') # I'm using Python 3
counter = Counter.new(32, prefix=ct[:12], initial_value=0)
cipher = AES.new("1234567890123456", AES.MODE_CTR, counter=counter)
cipher.decrypt(ct[12:])

Output:

b'asasasa'

Keep in mind that a key needs to be randomly chosen. You can generate a random key and keep it in an encoded form in the source code (i.e. as Hex). If you do that, you must not give the source code or the bytecode to anyone that you wouldn't trust the key with.

ContentLicense: CC BY-SA 4.0


问:
How to include dependencies targeting JDK 1.8 in jenkins plugin?
I have followed the official tutorial for creating Jenkins plugins: I have run mvn -U org.jenkins-ci.tools:maven-hpi-plugin:create to generate initial POM

Then I added guava as a dependency.

However, when I perform mvn package I get:

```<code>[INFO] --- maven-enforcer-plugin:1.4.2.jenkins-1:enforce (display-info) @ flaky-tests ---
[INFO] Restricted to JDK 1.7 yet com.google.guava:guava:jar:22.0:compile contains com/google/common/annotations/Beta.class targeted to JDK 1.8
...
[WARNING] Rule 2: org.apache.maven.plugins.enforcer.EnforceBytecodeVersion failed with message:
Found Banned Dependency: com.google.guava:guava:jar:22.0
Use 'mvn dependency:tree' to locate the source of the banned dependencies.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
</code>```

How can I include dependencies targeting JDK 1.8 in my Jenkins plugin?

Here's my full POM:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.jenkins-ci.plugins</groupId>
        <artifactId>plugin</artifactId>
        <version>2.32</version>
        <relativePath/>
    </parent>

    <groupId>com.github.dzieciou.testing</groupId>
    <artifactId>flaky-tests</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>hpi</packaging>

    <properties>
        <jenkins.version>2.68</jenkins.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <repositories>
        <repository>
            <id>repo.jenkins-ci.org</id>
            <url>https://repo.jenkins-ci.org/public/</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>repo.jenkins-ci.org</id>
            <url>https://repo.jenkins-ci.org/public/</url>
        </pluginRepository>
    </pluginRepositories>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>
    </dependencies>

</project>
</code>```

答:
It was enough to add the following property to POM:</p>

```<code><java.level>8</java.level>
</code>```

Body:
I have followed the official tutorial for creating Jenkins plugins: I have run mvn -U org.jenkins-ci.tools:maven-hpi-plugin:create to generate initial POM

Then I added guava as a dependency.

However, when I perform mvn package I get:

[INFO] --- maven-enforcer-plugin:1.4.2.jenkins-1:enforce (display-info) @ flaky-tests ---
[INFO] Restricted to JDK 1.7 yet com.google.guava:guava:jar:22.0:compile contains com/google/common/annotations/Beta.class targeted to JDK 1.8
...
[WARNING] Rule 2: org.apache.maven.plugins.enforcer.EnforceBytecodeVersion failed with message:
Found Banned Dependency: com.google.guava:guava:jar:22.0
Use 'mvn dependency:tree' to locate the source of the banned dependencies.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

How can I include dependencies targeting JDK 1.8 in my Jenkins plugin?

Here's my full POM:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.jenkins-ci.plugins</groupId>
        <artifactId>plugin</artifactId>
        <version>2.32</version>
        <relativePath/>
    </parent>

    <groupId>com.github.dzieciou.testing</groupId>
    <artifactId>flaky-tests</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>hpi</packaging>

    <properties>
        <jenkins.version>2.68</jenkins.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <repositories>
        <repository>
            <id>repo.jenkins-ci.org</id>
            <url>https://repo.jenkins-ci.org/public/</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>repo.jenkins-ci.org</id>
            <url>https://repo.jenkins-ci.org/public/</url>
        </pluginRepository>
    </pluginRepositories>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>
    </dependencies>

</project>

Body:
It was enough to add the following property to POM:

<java.level>8</java.level>


问:
silverlight draw on bitmap
```<code>Image img = new Bitmap(Image.FromFile(file.FullName));

using (Graphics g = Graphics.FromImage(img)){
    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}
</code>```

like this

how to do in sliverlight?

答:
Use WriteableBitmap class.

References:

Rendering XAML to a JPEG using Silverlight 3

Silverlight 3.0: WriteableBitmap

Silverlight 3's New Writeable Bitmap

Example:

With WritableBitmap, you can just draw something on a Control or Canvas and then save it to a bitmap using it's public WriteableBitmap(UIElement element,Transform transform) constructor.

Title: silverlight draw on bitmap

Body:
Image img = new Bitmap(Image.FromFile(file.FullName));

using (Graphics g = Graphics.FromImage(img)){
    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}

like this

how to do in sliverlight?


问:
cakephp 2.X Connection timed out on redirect on a live server
I have a "register" page that accepts the username, password and confirm password data from the user. on my local machine it just redirects just fine. I think the problem is on php's max execution time but i've talked with my hosting's support and was told that the max execution time of the hosting company is not subject to be changed.

Here is my code. I don't think there is any problem with my code because it works fine with my local machine.

```<code>public function register($role = null){
    $this->reg_status();
    if($this->Auth->user()){
        return $this->redirect(array('action' => 'dashboard'));
    }

    if ($this->request->is('post')) {

        $this->User->create();
        $existing = $this->User->find('first', array(
        'conditions' => array('email' => $this->request->data['User']['email'])
        ));
        if($existing){
            $this->Session->setFlash(__('Email is already used.'), 'default', array('class' => 'alert alert-danger'));
        } else{
            if($this->request->data['User']['password']==$this->request->data['User']['conf_password']){

                if($role){
                    $role = ($role == 'as_adviser') ? 'adviser' : 'client';
                    $this->request->data['User']['role'] = $role;
                }
                if ($this->User->save($this->request->data)) {
                    $id = $this->User->getLastInsertId();
                    $this->sendMail($this->request->data['User']['email'], $id, 'verify');
                    return $this->redirect(array('action' => 'confirm_email', $id, urlencode(base64_encode($this->request->data['User']['email']))));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
                }
            } else{
                $this->Session->setFlash(__("Password did not match."), 'default', array('class' => 'alert alert-danger'));
            }
        }
    }

    $this->set('role', $role);
}
</code>```

this is the error i am having on the live server.

i am currently out of clue because even if i turned "on" the debug on cakephp's config/core the error still seems vague.

edit
had to change Email config smtp settings. made sure they were correct and the error disappeared.

答: had to change Email config smtp settings. made sure they were correct and the error disappeared</p>

Body:
I have a "register" page that accepts the username, password and confirm password data from the user. on my local machine it just redirects just fine. I think the problem is on php's max execution time but i've talked with my hosting's support and was told that the max execution time of the hosting company is not subject to be changed.

Here is my code. I don't think there is any problem with my code because it works fine with my local machine.

public function register($role = null){
    $this->reg_status();
    if($this->Auth->user()){
        return $this->redirect(array('action' => 'dashboard'));
    }

    if ($this->request->is('post')) {

        $this->User->create();
        $existing = $this->User->find('first', array(
        'conditions' => array('email' => $this->request->data['User']['email'])
        ));
        if($existing){
            $this->Session->setFlash(__('Email is already used.'), 'default', array('class' => 'alert alert-danger'));
        } else{
            if($this->request->data['User']['password']==$this->request->data['User']['conf_password']){

                if($role){
                    $role = ($role == 'as_adviser') ? 'adviser' : 'client';
                    $this->request->data['User']['role'] = $role;
                }
                if ($this->User->save($this->request->data)) {
                    $id = $this->User->getLastInsertId();
                    $this->sendMail($this->request->data['User']['email'], $id, 'verify');
                    return $this->redirect(array('action' => 'confirm_email', $id, urlencode(base64_encode($this->request->data['User']['email']))));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
                }
            } else{
                $this->Session->setFlash(__("Password did not match."), 'default', array('class' => 'alert alert-danger'));
            }
        }
    }

    $this->set('role', $role);
}

this is the error i am having on the live server.

i am currently out of clue because even if i turned "on" the debug on cakephp's config/core the error still seems vague.

edit
had to change Email config smtp settings. made sure they were correct and the error disappeared.


问:
Prism VM binding with View within Page code behind
Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

using this block

```<code>xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"
</code>```

And what if I want to bind the view model within the page code behind (Page.cs).

答:
In my case

I removed from page.xaml

```<code>     xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
  prism:ViewModelLocator.AutowireViewModel="True"
</code>```

and inside the code Behind (page.cs)

i added

```<code>    public Page()
    {
          InitializeComponent();
          this.BindingContext = new pageViewModel(null,null);
    }
</code>```

and it worked for me

Body:
Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

using this block

xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"

And what if I want to bind the view model within the page code behind (Page.cs).

Body:
In my case

I removed from page.xaml

     xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
  prism:ViewModelLocator.AutowireViewModel="True"

and inside the code Behind (page.cs)

i added

    public Page()
    {
          InitializeComponent();
          this.BindingContext = new pageViewModel(null,null);
    }

and it worked for me